bux

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2022 License: MIT Imports: 45 Imported by: 2

README

BUX

Bitcoin UTXO & xPub Management Suite

Release Build Status Report codecov Mergify Status Go
Gitpod Ready-to-Code standard-readme compliant Makefile Included Sponsor Donate


Table of Contents


About

TLDR;

Application developers should focus on their applications and should not be bogged down with managing UTXOs or XPubs. Developers should be able to use an open-source, easy to install solution to rapidly build full-featured Bitcoin applications.



DISCLAIMER

BUX is still considered "ALPHA" and should not be used in production until v1.0.0



BUX: Out-of-the-box Features:
  • xPub & UTXO State Management (state, tip, balance, utxos, destinations)
  • Bring your own Database (MySQL, PostgreSQL, SQLite, Mongo or interface your own)
  • Caching (Ristretto, mCache, Redis or custom)
  • Task Management (TaskQ, Machinery or custom)
  • Transaction Processing (queue, broadcast, update state of xpubs)
  • Plugins using BRFC standards
Project Assumptions: MVP
  • No private keys are used, only the xPub (or access key) is given to bux
  • (BYOX) Bring your own xPub
  • Signing a transaction is outside this application (IE: buxServer or buxWallet)
  • All transactions need to be submitted to the bux service to effectively track utxo states
  • Database can be backed up, but not regenerated from chain
    • Certain data is not on chain, plus re-scanning xPub is expensive and not easily possible with WOC and limitations with blockchair

Installation

go-template requires a supported release of Go.

go get -u github.com/BuxOrg/bux

Documentation

View the generated documentation

GoDoc


Repository Features

This repository was created using MrZ's go-template

Built-in Features
Package Dependencies
Library Deployment

Releases are automatically created when you create a new git tag!

If you want to manually make releases, please install GoReleaser:

goreleaser for easy binary or library deployment to Github and can be installed:

  • using make: make install-releaser
  • using brew: brew install goreleaser

The .goreleaser.yml file is used to configure goreleaser.


Automatic releases via Github Actions from creating a new tag:

make tag version=1.2.3

Manual Releases (optional)

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production (manually).


Makefile Commands

View all makefile commands

make help

List of all current commands:

all                           Runs multiple commands
clean                         Remove previous builds and any cached data
clean-mods                    Remove all the Go mod cache
coverage                      Shows the test coverage
diff                          Show the git diff
generate                      Runs the go generate command in the base of the repo
godocs                        Sync the latest tag with GoDocs
help                          Show this help message
install                       Install the application
install-all-contributors      Installs all contributors locally
install-go                    Install the application (Using Native Go)
install-releaser              Install the GoReleaser application
lint                          Run the golangci-lint application (install if not found)
release                       Full production release (creates release in Github)
release                       Runs common.release then runs godocs
release-snap                  Test the full release (build binaries)
release-test                  Full production test release (everything except deploy)
replace-version               Replaces the version in HTML/JS (pre-deploy)
tag                           Generate a new tag and push (tag version=0.0.0)
tag-remove                    Remove a tag if found (tag-remove version=0.0.0)
tag-update                    Update an existing tag to current commit (tag-update version=0.0.0)
test                          Runs lint and ALL tests
test-all-db                   Runs all tests including embedded database tests
test-all-db-ci                Runs all tests including embedded database tests (CI)
test-ci                       Runs all tests via CI (exports coverage)
test-ci-no-race               Runs all tests via CI (no race) (exports coverage)
test-ci-short                 Runs unit tests via CI (exports coverage)
test-no-lint                  Runs just tests
test-short                    Runs vet, lint and tests (excludes integration tests)
test-unit                     Runs tests and outputs coverage
uninstall                     Uninstall the application (and remove files)
update-contributors           Regenerates the contributors html/list
update-linter                 Update the golangci-lint package (macOS only)
vet                           Run the Go vet application

Examples & Tests

All unit tests and examples run via Github Actions and uses Go version 1.17.x. View the configuration file.


Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

Checkout all the examples!


Contributing

View the contributing guidelines and follow the code of conduct.


How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀

Stars


Contributors ✨

Thank you to these wonderful people (emoji key):


Mr. Z

🚇 💻 🚧 🛡️

Siggi

🚇 💻 🛡️

Dylan

🚇 💻

This project follows the all-contributors specification.


License

License

Documentation

Overview

Package bux is the Bitcoin UTXO & xPub Management Suite

If you have any suggestions or comments, please feel free to open an issue on this GitHub repository!

By BuxOrg (https://github.com/BuxOrg)

Index

Constants

View Source
const (
	// AuthHeader is the header to use for authentication (raw xPub)
	AuthHeader = "auth_xpub"

	// AuthSignature is the given signature (body + timestamp)
	AuthSignature = "auth_signature"

	// AuthHeaderHash hash of the body coming from the request
	AuthHeaderHash = "auth_hash"

	// AuthHeaderNonce random nonce for the request
	AuthHeaderNonce = "auth_nonce"

	// AuthHeaderTime the time of the request, only valid for 30 seconds
	AuthHeaderTime = "auth_time"

	// AuthSignatureTTL is the max TTL for a signature to be valid
	AuthSignatureTTL = 20 * time.Second
)
View Source
const (
	// ResolutionTypeBasic is for the "deprecated" way to resolve an address from a Paymail
	ResolutionTypeBasic = "basic_resolution"

	// ResolutionTypeP2P is the current way to resolve a Paymail (prior to P4)
	ResolutionTypeP2P = "p2p"
)

Types of resolution methods

View Source
const (
	// ReferenceIDField is used for Paymail
	ReferenceIDField = "reference_id"
)
View Source
const ValueTypeString = "string"

ValueTypeString is the value type "string"

Variables

View Source
var (

	// BaseModels is the list of models for loading the engine and AutoMigration (defaults)
	BaseModels = []interface{}{

		&Xpub{
			Model: *NewBaseModel(ModelXPub),
		},

		&AccessKey{
			Model: *NewBaseModel(ModelAccessKey),
		},

		&DraftTransaction{
			Model: *NewBaseModel(ModelDraftTransaction),
		},

		&IncomingTransaction{
			Model: *NewBaseModel(ModelIncomingTransaction),
		},

		&Transaction{
			Model: *NewBaseModel(ModelTransaction),
		},

		&SyncTransaction{
			Model: *NewBaseModel(ModelSyncTransaction),
		},

		&Destination{
			Model: *NewBaseModel(ModelDestination),
		},

		&Utxo{
			Model: *NewBaseModel(ModelUtxo),
		},
	}
)
View Source
var ErrAccessKeyRevoked = errors.New("access key has been revoked")

ErrAccessKeyRevoked is when the access key has been revoked

View Source
var ErrAuhHashMismatch = errors.New("auth hash and body hash do not match")

ErrAuhHashMismatch is when the auth hash does not match the body hash

View Source
var ErrCannotConvertToIDs = errors.New("cannot convert value to type IDs")

ErrCannotConvertToIDs is the error when the conversion fails from interface into type IDs

View Source
var ErrChangeStrategyNotImplemented = errors.New("change strategy nominations not implemented yet")

ErrChangeStrategyNotImplemented is a temporary error until the feature is supported

View Source
var ErrDatastoreRequired = errors.New("datastore is required")

ErrDatastoreRequired is when a datastore function is called without a datastore present

View Source
var ErrDraftIDMismatch = errors.New("transaction draft id does not match utxo draft reservation id")

ErrDraftIDMismatch is when the reference ID does not match the reservation id

View Source
var ErrDraftNotFound = errors.New("corresponding draft transaction not found")

ErrDraftNotFound is when the requested draft transaction was not found

View Source
var ErrInvalidLockingScript = errors.New("invalid locking script")

ErrInvalidLockingScript is when a locking script cannot be decoded

View Source
var ErrInvalidOpReturnOutput = errors.New("invalid op_return output")

ErrInvalidOpReturnOutput is when a locking script is not a valid op_return

View Source
var ErrInvalidTransactionID = errors.New("invalid transaction id")

ErrInvalidTransactionID is when a transaction id cannot be decoded

View Source
var ErrMissingAddressResolutionURL = errors.New("missing address resolution url from capabilities")

ErrMissingAddressResolutionURL is when the paymail resolution url is missing from capabilities

View Source
var ErrMissingAuthHeader = errors.New("missing authentication header")

ErrMissingAuthHeader is when the authentication header is missing from the request

View Source
var ErrMissingBody = errors.New("missing body")

ErrMissingBody is when the body is missing

View Source
var ErrMissingFieldHex = errors.New("missing required field: hex")

ErrMissingFieldHex is an error when missing the hex field of a transaction

View Source
var ErrMissingFieldID = errors.New("missing required field: id")

ErrMissingFieldID is an error when missing the id field

View Source
var ErrMissingFieldSatoshis = errors.New("missing required field: satoshis")

ErrMissingFieldSatoshis is when the field is required but missing

View Source
var ErrMissingFieldScriptPubKey = errors.New("missing required field: script_pub_key")

ErrMissingFieldScriptPubKey is when the field is required but missing

View Source
var ErrMissingFieldTransactionID = errors.New("missing required field: transaction_id")

ErrMissingFieldTransactionID is when the field is required but missing

View Source
var ErrMissingFieldXpubID = errors.New("missing required field: xpub_id")

ErrMissingFieldXpubID is when the field is required but missing

View Source
var ErrMissingLockingScript = errors.New("could not find locking script")

ErrMissingLockingScript is when the field is required but missing

View Source
var ErrMissingRequiredXpub = errors.New("xpub was not found but was expected")

ErrMissingRequiredXpub is when the xpub should exist but was not found

View Source
var ErrMissingSignature = errors.New("signature missing")

ErrMissingSignature is when the signature is missing from the request

View Source
var ErrMissingTransactionOutputs = errors.New("draft transaction configuration has no outputs")

ErrMissingTransactionOutputs is when the draft transaction has not outputs

View Source
var ErrMissingTxHex = errors.New("transaction hex is empty or id is missing")

ErrMissingTxHex is when the hex is missing or invalid and creates an empty id

View Source
var ErrMissingXPriv = errors.New("missing xPriv key")

ErrMissingXPriv is when the xPriv is missing

View Source
var ErrMissingXpub = errors.New("could not find xpub")

ErrMissingXpub is when the field is required but missing

View Source
var ErrNoMatchingOutputs = errors.New("transaction outputs do not match any known destinations")

ErrNoMatchingOutputs is when the transaction does not match any known destinations

View Source
var ErrNotAdminKey = errors.New("xpub provided is not an admin key")

ErrNotAdminKey is when the xpub being used is not considered an admin key

View Source
var ErrNotEnoughUtxos = errors.New("could not select enough outputs to satisfy transaction")

ErrNotEnoughUtxos is when a draft transaction cannot be created because of lack of utxos

View Source
var ErrOutputValueNotRecognized = errors.New("output value is unrecognized")

ErrOutputValueNotRecognized is when there is an invalid output value given, or missing value

View Source
var ErrOutputValueTooLow = errors.New("output value is too low")

ErrOutputValueTooLow is when the satoshis output is too low on a transaction

View Source
var ErrOutputValueUnSpendable = errors.New("output value un-spendable")

ErrOutputValueUnSpendable is when the satoshis output is set on an op_return and is un-spendable

View Source
var ErrPaymailAddressIsInvalid = errors.New("paymail address is invalid")

ErrPaymailAddressIsInvalid is when the paymail address is NOT alias@domain.com

View Source
var ErrResolutionFailed = errors.New("failed to return a resolution for paymail address")

ErrResolutionFailed is when the paymail resolution failed unexpectedly

View Source
var ErrSignatureExpired = errors.New("signature has expired")

ErrSignatureExpired is when the signature TTL expired

View Source
var ErrSignatureInvalid = errors.New("signature invalid")

ErrSignatureInvalid is when the signature failed to be valid

View Source
var ErrTaskManagerNotLoaded = errors.New("taskmanager must be loaded")

ErrTaskManagerNotLoaded is when the taskmanager was not loaded

View Source
var ErrTransactionNotParsed = errors.New("transaction is not parsed")

ErrTransactionNotParsed is when the transaction is not parsed but was expected

View Source
var ErrUnknownAccessKey = errors.New("unknown access key")

ErrUnknownAccessKey is when the access key is unknown or not found

View Source
var ErrUnsupportedDestinationType = errors.New("unsupported destination type")

ErrUnsupportedDestinationType is a destination type that is not currently supported

View Source
var ErrUtxoAlreadySpent = errors.New("utxo has already been spent")

ErrUtxoAlreadySpent is when the utxo is already spent, but is trying to be used

View Source
var ErrUtxoNotReserved = errors.New("transaction utxo has not been reserved for spending")

ErrUtxoNotReserved is when the utxo is not reserved, but a transaction tries to spend it

View Source
var ErrXpubIDMisMatch = errors.New("xpub_id mismatch")

ErrXpubIDMisMatch is when the xPubID does not match

Functions

func CreateSignature

func CreateSignature(xPriv *bip32.ExtendedKey, bodyString string) (string, error)

CreateSignature will create a signature for the given key & body contents

func DisplayModels

func DisplayModels(models interface{}) interface{}

DisplayModels process the (slice) of model(s) for display

func Get

func Get(
	ctx context.Context,
	model ModelInterface,
	conditions map[string]interface{},
	_ bool,
	timeout time.Duration,
) error

Get will retrieve a model from the Cachestore or Datastore using the provided conditions

use bypassCache to skip checking the Cachestore for the record

func GetXpubFromRequest

func GetXpubFromRequest(req *http.Request) (string, bool)

GetXpubFromRequest gets the stored xPub from the request if found

func GetXpubHashFromRequest

func GetXpubHashFromRequest(req *http.Request) (string, bool)

GetXpubHashFromRequest gets the stored xPub hash from the request if found

func Greet

func Greet() string

Greet will say hi!

func IncrementField

func IncrementField(ctx context.Context, model ModelInterface, fieldName string,
	increment int64) (int64, error)

IncrementField will increment the given field atomically in the datastore

func MarshalIDs

func MarshalIDs(i IDs) graphql.Marshaler

MarshalIDs will unmarshal the custom type

func MarshalMetadata

func MarshalMetadata(m Metadata) graphql.Marshaler

MarshalMetadata will marshal the custom type

func Save

func Save(ctx context.Context, model ModelInterface) (err error)

Save will Save the model(s) into the Datastore

func SetSignature

func SetSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString string) error

SetSignature will set the signature on the header for the request

func TaskBroadcastTransactions

func TaskBroadcastTransactions(ctx context.Context, logClient logger.Interface, opts ...ModelOps) error

TaskBroadcastTransactions will broadcast any transactions

func TaskCleanupDraftTransactions

func TaskCleanupDraftTransactions(ctx context.Context, logClient logger.Interface, opts ...ModelOps) error

TaskCleanupDraftTransactions will clean up all old expired draft transactions

func TaskProcessIncomingTransactions

func TaskProcessIncomingTransactions(ctx context.Context, logClient logger.Interface, opts ...ModelOps) error

TaskProcessIncomingTransactions will process any incoming transactions found

func TaskSyncTransactions

func TaskSyncTransactions(ctx context.Context, logClient logger.Interface, opts ...ModelOps) error

TaskSyncTransactions will sync any transactions

func UnReserveUtxos

func UnReserveUtxos(ctx context.Context, xPubID, draftID string, opts ...ModelOps) error

UnReserveUtxos remove the reservation on the utxos for the given draft ID

Types

type AccessKey

type AccessKey struct {
	// Base model
	Model `bson:",inline"`

	// Model specific fields
	ID        string         `json:"id" toml:"id" yaml:"id" gorm:"<-:create;type:char(64);primaryKey;comment:This is the unique access key id" bson:"_id"`
	XpubID    string         `` /* 129-byte string literal not displayed */
	RevokedAt utils.NullTime `json:"revoked_at" toml:"revoked_at" yaml:"revoked_at" gorm:"<-;comment:When the key was revoked" bson:"revoked_at,omitempty"`

	// Private fields
	Key string `gorm:"-" bson:"-"` // Used on "CREATE", shown to the user "once" only
}

AccessKey is an object representing the access key

An AccessKey is a private key with a corresponding public key The public key is hashed and saved in this model for retrieval. When a request is made with an access key, the public key is sent in the headers, together with a signature (like normally done with xPriv signing)

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func GetAccessKey

func GetAccessKey(ctx context.Context, id string, opts ...ModelOps) (*AccessKey, error)

GetAccessKey will get the model with a given ID

func (*AccessKey) BeforeCreating

func (m *AccessKey) BeforeCreating(_ context.Context) error

BeforeCreating will fire before the model is being inserted into the Datastore

func (*AccessKey) GetID

func (m *AccessKey) GetID() string

GetID will get the ID

func (*AccessKey) GetModelName

func (m *AccessKey) GetModelName() string

GetModelName will get the name of the current model

func (*AccessKey) GetModelTableName

func (m *AccessKey) GetModelTableName() string

GetModelTableName will get the db table name of the current model

func (*AccessKey) Migrate

func (m *AccessKey) Migrate(client datastore.ClientInterface) error

Migrate model specific migration on startup

func (*AccessKey) RegisterTasks

func (m *AccessKey) RegisterTasks() error

RegisterTasks will register the model specific tasks on client initialization

func (*AccessKey) Save

func (m *AccessKey) Save(ctx context.Context) error

Save will Save the model into the Datastore

type AuthPayload

type AuthPayload struct {
	AuthHash     string `json:"auth_hash"`
	AuthNonce    string `json:"auth_nonce"`
	AuthTime     int64  `json:"auth_time"`
	BodyContents string `json:"body_contents"`
	Signature    string `json:"signature"`
	// contains filtered or unexported fields
}

AuthPayload is the authentication payload for checking or creating a signature

type ChangeStrategy

type ChangeStrategy string

ChangeStrategy strategy to use for change

const (
	// ChangeStrategyDefault Change strategy just dividing the satoshis among the change destinations
	ChangeStrategyDefault ChangeStrategy = "default"

	// ChangeStrategyRandom Change strategy randomizing the output of satoshis among the change destinations
	ChangeStrategyRandom ChangeStrategy = "random"

	// ChangeStrategyNominations Change strategy using coin nominations for the outputs (10, 25, 50, 100, 250 etc.)
	ChangeStrategyNominations ChangeStrategy = "nominations"
)

Types of change destination strategies

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the bux client & options

func (*Client) AddModels

func (c *Client) AddModels(ctx context.Context, autoMigrate bool, models ...interface{}) error

AddModels will add additional models to the client

func (*Client) AuthenticateRequest

func (c *Client) AuthenticateRequest(ctx context.Context, req *http.Request, adminXPubs []string,
	adminRequired, requireSigning, signingDisabled bool) (*http.Request, error)

AuthenticateRequest will parse the incoming request for the associated authentication header, and it will check the Key/Signature

Sets req.Context(xpub) and req.Context(xpub_hash)

func (*Client) Cachestore

func (c *Client) Cachestore() cachestore.ClientInterface

Cachestore will return the Cachestore IF: exists and is enabled

func (*Client) Chainstate

func (c *Client) Chainstate() chainstate.ClientInterface

Chainstate will return the Chainstate service IF: exists and is enabled

func (*Client) Close

func (c *Client) Close(ctx context.Context) error

Close will safely close any open connections (cache, datastore, etc.)

func (*Client) Datastore

func (c *Client) Datastore() datastore.ClientInterface

Datastore will return the Datastore if it exists

func (*Client) Debug

func (c *Client) Debug(on bool)

Debug will toggle the debug mode (for all resources)

func (*Client) DefaultModelOptions

func (c *Client) DefaultModelOptions(opts ...ModelOps) []ModelOps

DefaultModelOptions will set any default model options (from Client options->model)

func (*Client) EnableNewRelic

func (c *Client) EnableNewRelic()

EnableNewRelic will enable NewRelic tracing

func (*Client) GetDestinationByAddress

func (c *Client) GetDestinationByAddress(ctx context.Context, xPubKey, address string) (*Destination, error)

GetDestinationByAddress will get a destination for an address

func (*Client) GetDestinationByLockingScript

func (c *Client) GetDestinationByLockingScript(ctx context.Context, xPubKey, lockingScript string) (*Destination, error)

GetDestinationByLockingScript will get a destination for a locking script

func (*Client) GetDestinations

func (c *Client) GetDestinations(ctx context.Context, xPubKey string, usingMetadata *Metadata) ([]*Destination, error)

GetDestinations will get destinations based on an xPub

func (*Client) GetFeeUnit

func (c *Client) GetFeeUnit(_ context.Context, _ string) *utils.FeeUnit

GetFeeUnit get the fee from a miner todo: move into it's own Service / package

func (*Client) GetOrStartTxn

func (c *Client) GetOrStartTxn(ctx context.Context, name string) context.Context

GetOrStartTxn will check for an existing NewRelic transaction, if not found, it will make a new transaction

func (*Client) GetTaskPeriod

func (c *Client) GetTaskPeriod(name string) time.Duration

GetTaskPeriod will return the period for a given task name

func (*Client) GetTransaction

func (c *Client) GetTransaction(ctx context.Context, rawXpubKey, txID string) (*Transaction, error)

GetTransaction will get a transaction from the Datastore

ctx is the context testTxID is the transaction ID

func (*Client) GetTransactions

func (c *Client) GetTransactions(ctx context.Context, rawXpubKey string, metadata *Metadata,
	conditions *map[string]interface{}) ([]*Transaction, error)

GetTransactions will get all transactions for a given xpub from the Datastore

ctx is the context rawXpubKey is the raw xPub key metadata is added to the request for searching

func (*Client) GetUtxo

func (c *Client) GetUtxo(ctx context.Context, xPubKey, txID string, outputIndex uint32) (*Utxo, error)

GetUtxo will get a single utxo based on an xPub, the tx ID and the outputIndex

func (*Client) GetUtxos

func (c *Client) GetUtxos(ctx context.Context, xPubKey string) ([]*Utxo, error)

GetUtxos will get utxos based on an xPub

func (*Client) GetXpub

func (c *Client) GetXpub(ctx context.Context, xPubKey string) (*Xpub, error)

GetXpub will get an existing xPub from the Datastore

xPubKey is the raw public xPub

func (*Client) GetXpubByID

func (c *Client) GetXpubByID(ctx context.Context, xPubID string) (*Xpub, error)

GetXpubByID will get an existing xPub from the Datastore

func (*Client) IsDebug

func (c *Client) IsDebug() bool

IsDebug will return the debug flag (bool)

func (*Client) IsITCEnabled

func (c *Client) IsITCEnabled() bool

IsITCEnabled will return the flag (bool)

func (*Client) IsNewRelicEnabled

func (c *Client) IsNewRelicEnabled() bool

IsNewRelicEnabled will return the flag (bool)

func (*Client) Logger

func (c *Client) Logger() glogger.Interface

Logger will return the Logger if it exists

func (*Client) ModifyPaymailConfig

func (c *Client) ModifyPaymailConfig(config *server.Configuration,
	defaultFromPaymail, defaultNote string)

ModifyPaymailConfig will set the new values if found

func (*Client) ModifyTaskPeriod

func (c *Client) ModifyTaskPeriod(name string, period time.Duration) error

ModifyTaskPeriod will modify a cron task's duration period from the default

func (*Client) NewAccessKey

func (c *Client) NewAccessKey(ctx context.Context, xPubKey string, opts ...ModelOps) (*AccessKey, error)

NewAccessKey will create a new access key for the given xpub

opts are options and can include "metadata"

func (*Client) NewDestination

func (c *Client) NewDestination(ctx context.Context, xPubKey string, chain uint32,
	destinationType string, metadata *map[string]interface{}) (*Destination, error)

NewDestination will get a new destination for an existing xPub

xPubKey is the raw public xPub

func (*Client) NewDestinationForLockingScript

func (c *Client) NewDestinationForLockingScript(ctx context.Context, xPubKey, lockingScript, destinationType string,
	metadata map[string]interface{}) (*Destination, error)

NewDestinationForLockingScript will create a new destination based on a locking script

func (*Client) NewTransaction

func (c *Client) NewTransaction(ctx context.Context, rawXpubKey string, config *TransactionConfig,
	metadata map[string]interface{}, opts ...ModelOps) (*DraftTransaction, error)

NewTransaction will create a new draft transaction and return it

ctx is the context rawXpubKey is the raw xPub key config is the TransactionConfig metadata is added to the model opts are additional model options to be applied

func (*Client) NewXpub

func (c *Client) NewXpub(ctx context.Context, xPubKey string, opts ...ModelOps) (*Xpub, error)

NewXpub will parse the xPub and Save it into the Datastore

xPubKey is the raw public xPub opts are options and can include "metadata"

func (*Client) PaymailClient

func (c *Client) PaymailClient() paymail.ClientInterface

PaymailClient will return the Paymail if it exists

func (*Client) PaymailServerConfig

func (c *Client) PaymailServerConfig() *paymailServerOptions

PaymailServerConfig will return the Paymail server config if it exists

func (*Client) RecordTransaction

func (c *Client) RecordTransaction(ctx context.Context, xPubKey, txHex, draftID string,
	opts ...ModelOps) (*Transaction, error)

RecordTransaction will parse the transaction and Save it into the Datastore

Internal (known) transactions: there is a corresponding `draft_transaction` via `draft_id` External (known) transactions: there are output(s) related to the destination `reference_id`, tx is valid (mempool/on-chain) External (unknown) transactions: no reference id but some output(s) match known outputs, tx is valid (mempool/on-chain) Unknown transactions: no matching outputs, tx will be disregarded

xPubKey is the raw public xPub txHex is the raw transaction hex draftID is the unique draft id from a previously started New() transaction (draft_transaction.ID) opts are model options and can include "metadata"

func (*Client) RevokeAccessKey

func (c *Client) RevokeAccessKey(ctx context.Context, xPubKey, id string, opts ...ModelOps) (*AccessKey, error)

RevokeAccessKey will revoke an access key

opts are options and can include "metadata"

func (*Client) Taskmanager

func (c *Client) Taskmanager() taskmanager.ClientInterface

Taskmanager will return the Taskmanager if it exists

func (*Client) UserAgent

func (c *Client) UserAgent() string

UserAgent will return the user agent

func (*Client) Version

func (c *Client) Version() string

Version will return the version

type ClientInterface

type ClientInterface interface {
	DestinationService
	TransactionService
	UTXOService
	XPubService
	AddModels(ctx context.Context, autoMigrate bool, models ...interface{}) error
	AuthenticateRequest(ctx context.Context, req *http.Request, adminXPubs []string, adminRequired, requireSigning, signingDisabled bool) (*http.Request, error)
	Cachestore() cachestore.ClientInterface
	Chainstate() chainstate.ClientInterface
	Close(ctx context.Context) error
	Datastore() datastore.ClientInterface
	Debug(on bool)
	DefaultModelOptions(opts ...ModelOps) []ModelOps
	EnableNewRelic()
	GetFeeUnit(_ context.Context, _ string) *utils.FeeUnit
	GetOrStartTxn(ctx context.Context, name string) context.Context
	GetTaskPeriod(name string) time.Duration
	IsDebug() bool
	IsITCEnabled() bool
	IsNewRelicEnabled() bool
	Logger() logger.Interface
	ModifyPaymailConfig(config *server.Configuration, defaultFromPaymail, defaultNote string)
	ModifyTaskPeriod(name string, period time.Duration) error
	PaymailClient() paymail.ClientInterface
	PaymailServerConfig() *paymailServerOptions
	Taskmanager() taskmanager.ClientInterface
	UserAgent() string
	Version() string
}

ClientInterface is the client (bux engine) interface

func NewClient

func NewClient(ctx context.Context, opts ...ClientOps) (ClientInterface, error)

NewClient creates a new client for all bux functionality

If no options are given, it will use the defaultClientOptions() ctx may contain a NewRelic txn (or one will be created)

type ClientOps

type ClientOps func(c *clientOptions)

ClientOps allow functional options to be supplied that overwrite default client options.

func WithAutoMigrate

func WithAutoMigrate(migrateModels ...interface{}) ClientOps

WithAutoMigrate will enable auto migrate database mode (given models)

Pointers of structs (IE: &models.Xpub{})

func WithCustomCachestore

func WithCustomCachestore(cacheStore cachestore.ClientInterface) ClientOps

WithCustomCachestore will set the cachestore

func WithCustomChainstate

func WithCustomChainstate(chainState chainstate.ClientInterface) ClientOps

WithCustomChainstate will set the chainstate

func WithCustomDatastore

func WithCustomDatastore(dataStore datastore.ClientInterface) ClientOps

WithCustomDatastore will set the datastore

func WithCustomTaskManager

func WithCustomTaskManager(taskManager taskmanager.ClientInterface) ClientOps

WithCustomTaskManager will set the taskmanager

func WithDebugging

func WithDebugging() ClientOps

WithDebugging will set debugging in any applicable configuration

func WithITCDisabled

func WithITCDisabled() ClientOps

WithITCDisabled will disable (ITC) incoming transaction checking

func WithLogger

func WithLogger(customLogger logger.Interface) ClientOps

WithLogger will set the custom logger interface

func WithMcache

func WithMcache() ClientOps

WithMcache will set the cache client for both Read & Write clients

func WithMcacheConnection

func WithMcacheConnection(driver *mcache.CacheDriver) ClientOps

WithMcacheConnection will set the cache client to an active mcache driver connection

func WithModels

func WithModels(models ...interface{}) ClientOps

WithModels will add additional models (will NOT migrate using datastore)

Pointers of structs (IE: &models.Xpub{})

func WithMongoConnection

func WithMongoConnection(database *mongo.Database, tablePrefix string) ClientOps

WithMongoConnection will set the Datastore to an existing connection for MongoDB

func WithMongoDB

func WithMongoDB(config *datastore.MongoDBConfig) ClientOps

WithMongoDB will set the Datastore to use MongoDB

func WithNewRelic

func WithNewRelic(app *newrelic.Application) ClientOps

WithNewRelic will set the NewRelic application client

func WithPaymailClient

func WithPaymailClient(client paymail.ClientInterface) ClientOps

WithPaymailClient will set a custom paymail client

func WithPaymailServer

func WithPaymailServer(config *server.Configuration, defaultFromPaymail, defaultNote string) ClientOps

WithPaymailServer will set the server configuration for Paymail

func WithRedis

func WithRedis(config *cachestore.RedisConfig) ClientOps

WithRedis will set the redis cache client for both Read & Write clients

This will load new redis connections using the given parameters

func WithRedisConnection

func WithRedisConnection(activeClient *cache.Client) ClientOps

WithRedisConnection will set the cache client to an active redis connection

func WithRistretto

func WithRistretto(config *ristretto.Config) ClientOps

WithRistretto will set the cache client for both Read & Write clients

func WithRistrettoConnection

func WithRistrettoConnection(client *ristretto.Cache) ClientOps

WithRistrettoConnection will set the cache client to an active Ristretto connection

func WithSQL

func WithSQL(engine datastore.Engine, config *datastore.SQLConfig) ClientOps

WithSQL will load a Datastore using either an SQL database config or existing connection

func WithSQLConnection

func WithSQLConnection(engine datastore.Engine, sqlDB *sql.DB, tablePrefix string) ClientOps

WithSQLConnection will set the Datastore to an existing connection for MySQL or PostgreSQL

func WithSQLite

func WithSQLite(config *datastore.SQLiteConfig) ClientOps

WithSQLite will set the Datastore to use SQLite

func WithTaskQ

func WithTaskQ(config *taskq.QueueOptions, factory taskmanager.Factory) ClientOps

WithTaskQ will set the task manager to use TaskQ & in-memory

func WithTaskQUsingRedis

func WithTaskQUsingRedis(config *taskq.QueueOptions, redisOptions *redis.Options) ClientOps

WithTaskQUsingRedis will set the task manager to use TaskQ & Redis

func WithUserAgent

func WithUserAgent(userAgent string) ClientOps

WithUserAgent will overwrite the default useragent

type Destination

type Destination struct {
	// Base model
	Model `bson:",inline"`

	// Model specific fields
	ID            string `` /* 129-byte string literal not displayed */
	XpubID        string `` /* 129-byte string literal not displayed */
	LockingScript string `` /* 159-byte string literal not displayed */
	Type          string `json:"type" toml:"type" yaml:"type" gorm:"<-:create;type:text;comment:Type of output" bson:"type"`
	Chain         uint32 `` /* 153-byte string literal not displayed */
	Num           uint32 `` /* 145-byte string literal not displayed */
	Address       string `` /* 135-byte string literal not displayed */
	DraftID       string `` /* 167-byte string literal not displayed */
}

Destination is an object representing the BitCoin destination table

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func (*Destination) BeforeCreating

func (m *Destination) BeforeCreating(_ context.Context) error

BeforeCreating will fire before the model is being inserted into the Datastore

func (*Destination) GetID

func (m *Destination) GetID() string

GetID will get the model ID

func (*Destination) GetModelName

func (m *Destination) GetModelName() string

GetModelName will get the name of the current model

func (*Destination) GetModelTableName

func (m *Destination) GetModelTableName() string

GetModelTableName will get the db table name of the current model

func (*Destination) Migrate

func (m *Destination) Migrate(client datastore.ClientInterface) error

Migrate model specific migration on startup

func (*Destination) Save

func (m *Destination) Save(ctx context.Context) (err error)

Save will Save the model into the Datastore

type DestinationService

type DestinationService interface {
	GetDestinationByAddress(ctx context.Context, xPubKey, address string) (*Destination, error)
	GetDestinationByLockingScript(ctx context.Context, xPubKey, lockingScript string) (*Destination, error)
	GetDestinations(ctx context.Context, xPubKey string, usingMetadata *Metadata) ([]*Destination, error)
	NewDestination(ctx context.Context, xPubKey string, chain uint32, destinationType string,
		metadata *map[string]interface{}) (*Destination, error)
	NewDestinationForLockingScript(ctx context.Context, xPubID, lockingScript, destinationType string,
		metadata map[string]interface{}) (*Destination, error)
}

DestinationService is the destination related requests

type DraftStatus

type DraftStatus string

DraftStatus draft transaction status

const (
	// DraftStatusDraft is when the transaction is a draft
	DraftStatusDraft DraftStatus = statusDraft

	// DraftStatusCanceled is when the draft is canceled
	DraftStatusCanceled DraftStatus = statusCanceled

	// DraftStatusExpired is when the draft has expired
	DraftStatusExpired DraftStatus = statusExpired

	// DraftStatusComplete is when the draft transaction is complete
	DraftStatusComplete DraftStatus = statusComplete
)

func (*DraftStatus) Scan

func (t *DraftStatus) Scan(value interface{}) error

Scan will scan the value into Struct, implements sql.Scanner interface

func (DraftStatus) Value

func (t DraftStatus) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type DraftTransaction

type DraftTransaction struct {
	// Base model
	Model `bson:",inline"`

	// Standard transaction model base fields
	TransactionBase `bson:",inline"`

	// Model specific fields
	XpubID        string            `` /* 129-byte string literal not displayed */
	ExpiresAt     time.Time         `json:"expires_at" toml:"expires_at" yaml:"expires_at" gorm:"<-:create;comment:Time when the draft expires" bson:"expires_at"`
	Configuration TransactionConfig `` /* 152-byte string literal not displayed */
	Status        DraftStatus       `` /* 128-byte string literal not displayed */
	FinalTxID     string            `` /* 157-byte string literal not displayed */
}

DraftTransaction is an object representing the draft BitCoin transaction prior to the final transaction

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func (*DraftTransaction) AfterUpdated

func (m *DraftTransaction) AfterUpdated(ctx context.Context) error

AfterUpdated will fire after a successful update into the Datastore

func (*DraftTransaction) BeforeCreating

func (m *DraftTransaction) BeforeCreating(ctx context.Context) (err error)

BeforeCreating will fire before the model is being inserted into the Datastore

func (*DraftTransaction) GetID

func (m *DraftTransaction) GetID() string

GetID will get the model ID

func (*DraftTransaction) GetModelName

func (m *DraftTransaction) GetModelName() string

GetModelName will get the name of the current model

func (*DraftTransaction) GetModelTableName

func (m *DraftTransaction) GetModelTableName() string

GetModelTableName will get the db table name of the current model

func (*DraftTransaction) Migrate

func (m *DraftTransaction) Migrate(client datastore.ClientInterface) error

Migrate model specific migration on startup

func (*DraftTransaction) RegisterTasks

func (m *DraftTransaction) RegisterTasks() error

RegisterTasks will register the model specific tasks on client initialization

func (*DraftTransaction) Save

func (m *DraftTransaction) Save(ctx context.Context) (err error)

Save will Save the model into the Datastore

type IDs

type IDs []string

IDs are string ids saved as an array

func UnmarshalIDs

func UnmarshalIDs(v interface{}) (IDs, error)

UnmarshalIDs will marshal the custom type

func (IDs) GormDBDataType

func (IDs) GormDBDataType(db *gorm.DB, _ *schema.Field) string

GormDBDataType the gorm data type for metadata

func (IDs) GormDataType

func (i IDs) GormDataType() string

GormDataType type in gorm

func (*IDs) Scan

func (i *IDs) Scan(value interface{}) error

Scan scan value into JSON, implements sql.Scanner interface

func (IDs) Value

func (i IDs) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type IncomingTransaction

type IncomingTransaction struct {
	// Base model
	Model `bson:",inline"`

	// Standard transaction model base fields
	TransactionBase `bson:",inline"`

	// Model specific fields
	Status        SyncStatus `` /* 145-byte string literal not displayed */
	StatusMessage string     `` /* 159-byte string literal not displayed */
}

IncomingTransaction is an object representing the incoming (external) transaction (for pre-processing)

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func (*IncomingTransaction) AfterCreated

func (m *IncomingTransaction) AfterCreated(ctx context.Context) error

AfterCreated will fire after the model is created

func (*IncomingTransaction) BeforeCreating

func (m *IncomingTransaction) BeforeCreating(ctx context.Context) error

BeforeCreating will fire before the model is being inserted into the Datastore

func (*IncomingTransaction) GetID

func (m *IncomingTransaction) GetID() string

GetID will get the ID

func (*IncomingTransaction) GetModelName

func (m *IncomingTransaction) GetModelName() string

GetModelName will get the name of the current model

func (*IncomingTransaction) GetModelTableName

func (m *IncomingTransaction) GetModelTableName() string

GetModelTableName will get the db table name of the current model

func (*IncomingTransaction) Migrate

Migrate model specific migration on startup

func (*IncomingTransaction) RegisterTasks

func (m *IncomingTransaction) RegisterTasks() error

RegisterTasks will register the model specific tasks on client initialization

func (*IncomingTransaction) Save

Save will Save the model into the Datastore

type MapProtocol

type MapProtocol struct {
	App  string                 `json:"app,omitempty"`
	Keys map[string]interface{} `json:"keys,omitempty"`
	Type string                 `json:"type,omitempty"`
}

MapProtocol is a specific MAP protocol interface for an op_return

type Metadata

type Metadata map[string]interface{}

Metadata is an object representing the metadata about the related record

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func UnmarshalMetadata

func UnmarshalMetadata(v interface{}) (Metadata, error)

UnmarshalMetadata will unmarshal the custom type

func (Metadata) GormDBDataType

func (Metadata) GormDBDataType(db *gorm.DB, _ *schema.Field) string

GormDBDataType the gorm data type for metadata

func (Metadata) GormDataType

func (m Metadata) GormDataType() string

GormDataType type in gorm

func (*Metadata) MarshalBSONValue

func (m *Metadata) MarshalBSONValue() (bsontype.Type, []byte, error)

MarshalBSONValue method is called by bson.Marshal in Mongo for type = Metadata

func (*Metadata) Scan

func (m *Metadata) Scan(value interface{}) error

Scan scan value into Json, implements sql.Scanner interface

func (*Metadata) UnmarshalBSONValue

func (m *Metadata) UnmarshalBSONValue(t bsontype.Type, data []byte) error

UnmarshalBSONValue method is called by bson.Unmarshal in Mongo for type = Metadata

func (Metadata) Value

func (m Metadata) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type Model

type Model struct {
	CreatedAt time.Time `` /* 134-byte string literal not displayed */
	UpdatedAt time.Time `` /* 138-byte string literal not displayed */
	Metadata  Metadata  `gorm:"type:json" json:"metadata,omitempty" bson:"metadata,omitempty"`

	// https://gorm.io/docs/indexes.html
	// DeletedAt gorm.DeletedAt `json:"deleted_at" toml:"deleted_at" yaml:"deleted_at" (@mrz: this was the original type)
	DeletedAt utils.NullTime `` /* 144-byte string literal not displayed */
	// contains filtered or unexported fields
}

Model is the generic model field(s) and interface(s)

gorm: https://gorm.io/docs/models.html

func NewBaseModel

func NewBaseModel(name ModelName, opts ...ModelOps) (m *Model)

NewBaseModel create an empty base model

func (*Model) AfterCreated

func (m *Model) AfterCreated(_ context.Context) error

AfterCreated will fire after the model is created in the Datastore

func (*Model) AfterDeleted

func (m *Model) AfterDeleted(_ context.Context) error

AfterDeleted will fire after a successful delete in the Datastore

func (*Model) AfterUpdated

func (m *Model) AfterUpdated(_ context.Context) error

AfterUpdated will fire after a successful update into the Datastore

func (*Model) BeforeUpdating

func (m *Model) BeforeUpdating(_ context.Context) error

BeforeUpdating will fire before updating a model in the Datastore

func (*Model) ChildModels

func (m *Model) ChildModels() []ModelInterface

ChildModels will return any child models

func (*Model) Client

func (m *Model) Client() ClientInterface

Client will return the current client

func (*Model) DebugLog

func (m *Model) DebugLog(text string)

DebugLog will display verbose logs

func (*Model) Display

func (m *Model) Display() interface{}

Display filter the model for display

func (*Model) GetOptions

func (m *Model) GetOptions(isNewRecord bool) (opts []ModelOps)

GetOptions will get the options that are set on that model

func (*Model) IsNew

func (m *Model) IsNew() bool

IsNew returns true if the model is (or was) a new record

func (*Model) Name

func (m *Model) Name() string

Name will get the collection name (model)

func (*Model) New

func (m *Model) New()

New will set the record to new

func (*Model) NotNew

func (m *Model) NotNew()

NotNew sets newRecord to false

func (*Model) RawXpub

func (m *Model) RawXpub() string

RawXpub returns the rawXpubKey

func (*Model) RegisterTasks

func (m *Model) RegisterTasks() error

RegisterTasks will register the model specific tasks on client initialization

func (*Model) SetOptions

func (m *Model) SetOptions(opts ...ModelOps)

SetOptions will set the options on the model

func (*Model) SetRecordTime

func (m *Model) SetRecordTime(created bool)

SetRecordTime will set the record timestamps (created is true for a new record)

type ModelInterface

type ModelInterface interface {
	AfterCreated(ctx context.Context) (err error)
	AfterDeleted(ctx context.Context) (err error)
	AfterUpdated(ctx context.Context) (err error)
	BeforeCreating(ctx context.Context) (err error)
	BeforeUpdating(ctx context.Context) (err error)
	ChildModels() []ModelInterface
	Client() ClientInterface
	DebugLog(text string)
	Display() interface{}
	GetID() string
	GetModelName() string
	GetModelTableName() string
	GetOptions(isNewRecord bool) (opts []ModelOps)
	IsNew() bool
	Migrate(client datastore.ClientInterface) error
	Name() string
	New()
	NotNew()
	RawXpub() string
	RegisterTasks() error
	Save(ctx context.Context) (err error)
	SetOptions(opts ...ModelOps)
	SetRecordTime(bool)
}

ModelInterface is the interface that all models share

type ModelName

type ModelName string

ModelName is the model name type

const (
	ModelAccessKey           ModelName = "access_key"
	ModelDestination         ModelName = "destination"
	ModelDraftTransaction    ModelName = "draft_transaction"
	ModelIncomingTransaction ModelName = "incoming_transaction"
	ModelMetadata            ModelName = "metadata"
	ModelNameEmpty           ModelName = "empty"
	ModelSyncTransaction     ModelName = "sync_transaction"
	ModelTransaction         ModelName = "transaction"
	ModelUtxo                ModelName = "utxo"
	ModelXPub                ModelName = "xpub"
)

All the base models

func (ModelName) IsEmpty

func (n ModelName) IsEmpty() bool

IsEmpty tests if the model name is empty

func (ModelName) String

func (n ModelName) String() string

String is the string version of the name

type ModelOps

type ModelOps func(m *Model)

ModelOps allow functional options to be supplied that overwrite default model options

func New

func New() ModelOps

New set this model to a new record

func WithClient

func WithClient(client ClientInterface) ModelOps

WithClient will set the Client on the model

func WithMetadata

func WithMetadata(key string, value interface{}) ModelOps

WithMetadata will add the metadata record to the model

func WithMetadatas

func WithMetadatas(metadata map[string]interface{}) ModelOps

WithMetadatas will add multiple metadata records to the model

func WithXPub

func WithXPub(rawXpubKey string) ModelOps

WithXPub will set the xPub key on the model

type OpReturn

type OpReturn struct {
	Hex         string       `json:"hex,omitempty"`
	HexParts    []string     `json:"hex_parts,omitempty"`
	Map         *MapProtocol `json:"map,omitempty"`
	StringParts []string     `json:"string_parts,omitempty"`
}

OpReturn is the op_return definition for the output

type PaymailP4

type PaymailP4 struct {
	Alias           string `json:"alias" toml:"alias" yaml:"alias" bson:"alias,omitempty"`
	Domain          string `json:"domain" toml:"domain" yaml:"domain" bson:"domain,omitempty"`
	FromPaymail     string `json:"from_paymail,omitempty" toml:"from_paymail" yaml:"from_paymail" bson:"from_paymail,omitempty"`
	Note            string `json:"note,omitempty" toml:"note" yaml:"note" bson:"note,omitempty"`
	PubKey          string `json:"pub_key,omitempty" toml:"pub_key" yaml:"pub_key" bson:"pub_key,omitempty"`
	ReceiveEndpoint string `json:"receive_endpoint,omitempty" toml:"receive_endpoint" yaml:"receive_endpoint" bson:"receive_endpoint,omitempty"`
	ReferenceID     string `json:"reference_id,omitempty" toml:"reference_id" yaml:"reference_id" bson:"reference_id,omitempty"`
	ResolutionType  string `json:"resolution_type" toml:"resolution_type" yaml:"resolution_type" bson:"resolution_type,omitempty"`
}

PaymailP4 paymail configuration for the p2p payments on this output

type ScriptOutput

type ScriptOutput struct {
	Address    string `json:"address,omitempty"`  // Hex encoded locking script
	Satoshis   uint64 `json:"satoshis,omitempty"` // Number of satoshis for that output
	Script     string `json:"script"`             // Hex encoded locking script
	ScriptType string `json:"script_type"`        // The type of output
}

ScriptOutput is the actual script record (could be several for one output record)

type SyncAttempt

type SyncAttempt struct {
	Action        string    `json:"action"`         // type: broadcast, sync etc
	AttemptedAt   time.Time `json:"attempted_at"`   // Time it was attempted
	StatusMessage string    `json:"status_message"` // Success or failure message

}

SyncAttempt is the complete attempt to sync (multiple providers and strategies)

type SyncConfig

type SyncConfig struct {
	Broadcast   bool `json:"broadcast" toml:"broadcast" yaml:"broadcast"`             // Transaction should be broadcasted
	SyncOnChain bool `json:"sync_on_chain" toml:"sync_on_chain" yaml:"sync_on_chain"` // Transaction should be checked that it's on-chain

}

SyncConfig is the configuration used for syncing a transaction (on-chain)

func DefaultSyncConfig

func DefaultSyncConfig() *SyncConfig

DefaultSyncConfig will return a default broadcast config todo: these defaults should come from bux config and possible to change

func (*SyncConfig) Scan

func (t *SyncConfig) Scan(value interface{}) error

Scan will scan the value into Struct, implements sql.Scanner interface

func (SyncConfig) Value

func (t SyncConfig) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type SyncResults

type SyncResults struct {
	Attempts    []*SyncAttempt `json:"attempts"`     // Each attempt
	LastMessage string         `json:"last_message"` // Last message (success or failure)
}

SyncResults is the results from all sync attempts (broadcast or sync)

func (*SyncResults) Scan

func (t *SyncResults) Scan(value interface{}) error

Scan will scan the value into Struct, implements sql.Scanner interface

func (SyncResults) Value

func (t SyncResults) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type SyncStatus

type SyncStatus string

SyncStatus sync status

const (
	// SyncStatusPending is when the sync is pending (blocked by other constraints)
	SyncStatusPending SyncStatus = statusPending

	// SyncStatusReady is when the sync is ready (waiting for workers)
	SyncStatusReady SyncStatus = statusReady

	// SyncStatusProcessing is when the sync is processing (worker is running task)
	SyncStatusProcessing SyncStatus = statusProcessing

	// SyncStatusCanceled is when the sync is canceled
	SyncStatusCanceled SyncStatus = statusCanceled

	// SyncStatusSkipped is when the sync is skipped
	SyncStatusSkipped SyncStatus = statusSkipped

	// SyncStatusError is when the sync has an error
	SyncStatusError SyncStatus = statusError

	// SyncStatusComplete is when the sync is complete
	SyncStatusComplete SyncStatus = statusComplete
)

func (*SyncStatus) Scan

func (t *SyncStatus) Scan(value interface{}) error

Scan will scan the value into Struct, implements sql.Scanner interface

func (SyncStatus) String

func (t SyncStatus) String() string

String is the string version of the status

func (SyncStatus) Value

func (t SyncStatus) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type SyncTransaction

type SyncTransaction struct {
	// Base model
	Model `bson:",inline"`

	// Model specific fields
	ID              string         `json:"id" toml:"id" yaml:"id" gorm:"<-:create;type:char(64);primaryKey;comment:This is the unique transaction id" bson:"_id"`
	Configuration   SyncConfig     `` /* 152-byte string literal not displayed */
	LastAttempt     utils.NullTime `` /* 140-byte string literal not displayed */
	Results         SyncResults    `json:"results" toml:"results" yaml:"results" gorm:"<-;type:text;comment:This is the results struct in JSON" bson:"results"`
	BroadcastStatus SyncStatus     `` /* 172-byte string literal not displayed */
	SyncStatus      SyncStatus     `` /* 156-byte string literal not displayed */
}

SyncTransaction is an object representing the chain-state sync configuration and results for a given transaction

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func (*SyncTransaction) BeforeCreating

func (m *SyncTransaction) BeforeCreating(_ context.Context) error

BeforeCreating will fire before the model is being inserted into the Datastore

func (*SyncTransaction) GetID

func (m *SyncTransaction) GetID() string

GetID will get the ID

func (*SyncTransaction) GetModelName

func (m *SyncTransaction) GetModelName() string

GetModelName will get the name of the current model

func (*SyncTransaction) GetModelTableName

func (m *SyncTransaction) GetModelTableName() string

GetModelTableName will get the db table name of the current model

func (*SyncTransaction) Migrate

func (m *SyncTransaction) Migrate(client datastore.ClientInterface) error

Migrate model specific migration on startup

func (*SyncTransaction) RegisterTasks

func (m *SyncTransaction) RegisterTasks() error

RegisterTasks will register the model specific tasks on client initialization

func (*SyncTransaction) Save

func (m *SyncTransaction) Save(ctx context.Context) error

Save will Save the model into the Datastore

type Transaction

type Transaction struct {
	// Base model
	Model `bson:",inline"`

	// Standard transaction model base fields
	TransactionBase `bson:",inline"`

	// Model specific fields
	XpubInIDs       IDs             `json:"xpub_in_ids,omitempty" toml:"xpub_in_ids" yaml:"xpub_in_ids" gorm:"<-:create;type:json" bson:"xpub_in_ids,omitempty"`
	XpubOutIDs      IDs             `` /* 126-byte string literal not displayed */
	BlockHash       string          `` /* 170-byte string literal not displayed */
	BlockHeight     uint64          `` /* 176-byte string literal not displayed */
	Fee             uint64          `json:"fee" toml:"fee" yaml:"fee" gorm:"<-create;type:bigint" bson:"fee,omitempty"`
	NumberOfInputs  uint32          `` /* 130-byte string literal not displayed */
	NumberOfOutputs uint32          `` /* 134-byte string literal not displayed */
	DraftID         string          `` /* 149-byte string literal not displayed */
	TotalValue      uint64          `json:"total_value" toml:"total_value" yaml:"total_value" gorm:"<-create;type:bigint" bson:"total_value,omitempty"`
	XpubMetadata    XpubMetadata    `json:"-" toml:"xpub_metadata" gorm:"<-;type:json;xpub_id specific metadata" bson:"xpub_metadata,omitempty"`
	XpubOutputValue XpubOutputValue `json:"-" toml:"xpub_output_value" gorm:"<-create;type:json;xpub_id specific value" bson:"xpub_output_value,omitempty"`

	// Virtual Fields
	OutputValue int64                `json:"-" toml:"-" bson:"-,omitempty"`
	Status      SyncStatus           `json:"-" toml:"-" yaml:"-" gorm:"-" bson:"-"`
	Direction   TransactionDirection `json:"-" toml:"-" yaml:"-" gorm:"-" bson:"-"`
	// contains filtered or unexported fields
}

Transaction is an object representing the BitCoin transaction table

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func (*Transaction) AfterCreated

func (m *Transaction) AfterCreated(ctx context.Context) error

AfterCreated will fire after the model is created in the Datastore

func (*Transaction) BeforeCreating

func (m *Transaction) BeforeCreating(ctx context.Context) error

BeforeCreating will fire before the model is being inserted into the Datastore

func (*Transaction) ChildModels

func (m *Transaction) ChildModels() (childModels []ModelInterface)

ChildModels will get any related sub models

func (*Transaction) Display

func (m *Transaction) Display() interface{}

Display filter the model for display

func (*Transaction) GetID

func (m *Transaction) GetID() string

GetID will get the ID

func (*Transaction) GetModelName

func (m *Transaction) GetModelName() string

GetModelName will get the name of the current model

func (*Transaction) GetModelTableName

func (m *Transaction) GetModelTableName() string

GetModelTableName will get the db table name of the current model

func (*Transaction) InputUtxoChecksOff

func (m *Transaction) InputUtxoChecksOff(check bool)

InputUtxoChecksOff will set the inputUtxoChecksOff option on the transaction

func (*Transaction) IsXpubAssociated

func (m *Transaction) IsXpubAssociated(rawXpubKey string) bool

IsXpubAssociated will check if this key is associated to this transaction

func (*Transaction) Migrate

func (m *Transaction) Migrate(client datastore.ClientInterface) error

Migrate model specific migration on startup

func (*Transaction) Save

func (m *Transaction) Save(ctx context.Context) (err error)

Save will Save the model into the Datastore

type TransactionBase

type TransactionBase struct {
	ID  string `` /* 142-byte string literal not displayed */
	Hex string `json:"hex" toml:"hex" yaml:"hex" gorm:"<-:create;type:text;comment:This is the raw transaction hex" bson:"hex"`
	// contains filtered or unexported fields
}

TransactionBase is the same fields share between multiple transaction models

type TransactionConfig

type TransactionConfig struct {
	// Conditions (utxo choices)
	// NlockTime uint32
	ChangeDestinations         []*Destination       `json:"change_destinations" toml:"change_destinations" yaml:"change_destinations"`
	ChangeDestinationsStrategy ChangeStrategy       `json:"change_destinations_strategy" toml:"change_destinations_strategy" yaml:"change_destinations_strategy"`
	ChangeMinimumSatoshis      uint64               `json:"change_minimum_satoshis" toml:"change_minimum_satoshis" yaml:"change_minimum_satoshis"`
	ChangeNumberOfDestinations int                  `json:"change_number_of_destinations" toml:"change_number_of_destinations" yaml:"change_number_of_destinations"`
	ChangeSatoshis             uint64               `json:"change_satoshis" toml:"change_satoshis" yaml:"change_satoshis"`
	ExpiresIn                  time.Duration        `json:"expires_in" toml:"expires_in" yaml:"expires_in"`
	Fee                        uint64               `json:"fee" toml:"fee" yaml:"fee"`
	FeeUnit                    *utils.FeeUnit       `json:"fee_unit" toml:"fee_unit" yaml:"fee_unit"`
	FromUtxos                  []*UtxoPointer       `json:"from_utxos" toml:"from_utxos" yaml:"from_utxos"`
	Inputs                     []*TransactionInput  `json:"inputs" toml:"inputs" yaml:"inputs"`
	Miner                      string               `json:"miner" toml:"miner" yaml:"miner"`
	Outputs                    []*TransactionOutput `json:"outputs" toml:"outputs" yaml:"outputs"`
	SendAllTo                  string               `json:"send_all_to" toml:"send_all_to" yaml:"send_all_to"`
	Sync                       *SyncConfig          `json:"sync" toml:"sync" yaml:"sync"`
}

TransactionConfig is the configuration used to start a transaction

func (*TransactionConfig) Scan

func (t *TransactionConfig) Scan(value interface{}) error

Scan will scan the value into Struct, implements sql.Scanner interface

func (TransactionConfig) Value

func (t TransactionConfig) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type TransactionDirection

type TransactionDirection string

TransactionDirection String describing the direction of the transaction (in / out)

const (
	// TransactionDirectionIn The transaction is coming in to the wallet of the xpub
	TransactionDirectionIn TransactionDirection = "incoming"

	// TransactionDirectionOut The transaction is going out of to the wallet of the xpub
	TransactionDirectionOut TransactionDirection = "outgoing"

	// TransactionDirectionReconcile The transaction is an internal reconciliation transaction
	TransactionDirectionReconcile TransactionDirection = "reconcile"
)

type TransactionInput

type TransactionInput struct {
	Utxo
	Destination Destination `json:"destination" toml:"destination" yaml:"destination" bson:"destination"`
}

TransactionInput is an input on the transaction config

type TransactionOutput

type TransactionOutput struct {
	PaymailP4 *PaymailP4      `json:"paymail_p4,omitempty" toml:"paymail_p4" yaml:"paymail_p4" bson:"paymail_p4,omitempty"`
	Satoshis  uint64          `json:"satoshis" toml:"satoshis" yaml:"satoshis" bson:"satoshis"`
	Scripts   []*ScriptOutput `json:"scripts" toml:"scripts" yaml:"scripts" bson:"scripts"`
	To        string          `json:"to,omitempty" toml:"to" yaml:"to" bson:"to,omitempty"`
	OpReturn  *OpReturn       `json:"op_return" toml:"op_return" yaml:"op_return" bson:"op_return,omitempty"`
}

TransactionOutput is an output on the transaction config

type TransactionService

type TransactionService interface {
	GetTransaction(ctx context.Context, rawXpubKey, txID string) (*Transaction, error)
	GetTransactions(ctx context.Context, rawXpubKey string, metadata *Metadata, conditions *map[string]interface{}) ([]*Transaction, error)
	NewTransaction(ctx context.Context, rawXpubKey string, config *TransactionConfig,
		metadata map[string]interface{}, opts ...ModelOps) (*DraftTransaction, error)
	RecordTransaction(ctx context.Context, xPubKey, txHex, draftID string,
		opts ...ModelOps) (*Transaction, error)
}

TransactionService is the transaction related requests

type UTXOService

type UTXOService interface {
	GetUtxo(ctx context.Context, xPubKey, txID string, outputIndex uint32) (*Utxo, error)
	GetUtxos(ctx context.Context, xPubKey string) ([]*Utxo, error)
}

UTXOService is the utxo related requests

type Utxo

type Utxo struct {
	// Base model
	Model `bson:",inline"`

	// Model specific fields
	ID            string           `` /* 135-byte string literal not displayed */
	TransactionID string           `` /* 174-byte string literal not displayed */
	XpubID        string           `` /* 129-byte string literal not displayed */
	OutputIndex   uint32           `` /* 165-byte string literal not displayed */
	Satoshis      uint64           `` /* 143-byte string literal not displayed */
	ScriptPubKey  string           `` /* 149-byte string literal not displayed */
	Type          string           `json:"type" toml:"type" yaml:"type" gorm:"<-:create;type:text;comment:Type of output" bson:"type"`
	DraftID       utils.NullString `` /* 148-byte string literal not displayed */
	ReservedAt    utils.NullTime   `json:"reserved_at" toml:"reserved_at" yaml:"reserved_at" gorm:"<-;comment:When it was reserved" bson:"reserved_at,omitempty"`
	SpendingTxID  utils.NullString `` /* 172-byte string literal not displayed */
}

Utxo is an object representing the BitCoin UTXO table

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func GetSpendableUtxos

func GetSpendableUtxos(ctx context.Context, xPubID, utxoType string, fromUtxos []*UtxoPointer, opts ...ModelOps) ([]*Utxo, error)

GetSpendableUtxos Get all spendable utxos - yes really!

func ReserveUtxos

func ReserveUtxos(ctx context.Context, xPubID, draftID string,
	satoshis uint64, feePerByte float64, fromUtxos []*UtxoPointer, opts ...ModelOps) ([]*Utxo, error)

ReserveUtxos reserve utxos for the given draft ID and amount

func (*Utxo) BeforeCreating

func (m *Utxo) BeforeCreating(_ context.Context) error

BeforeCreating will fire before the model is being inserted into the Datastore

func (*Utxo) GenerateID

func (m *Utxo) GenerateID() string

GenerateID will generate the id of the UTXO record based on the format: <txid>|<output_index>

func (*Utxo) GetID

func (m *Utxo) GetID() string

GetID will get the ID

func (*Utxo) GetModelName

func (m *Utxo) GetModelName() string

GetModelName will get the name of the current model

func (*Utxo) GetModelTableName

func (m *Utxo) GetModelTableName() string

GetModelTableName will get the db table name of the current model

func (*Utxo) Migrate

func (m *Utxo) Migrate(client datastore.ClientInterface) error

Migrate model specific migration on startup

func (*Utxo) Save

func (m *Utxo) Save(ctx context.Context) (err error)

Save will Save the model into the Datastore

type UtxoPointer

type UtxoPointer struct {
	TransactionID string `` /* 174-byte string literal not displayed */
	OutputIndex   uint32 `` /* 165-byte string literal not displayed */
}

UtxoPointer is a pointer to a utxo

type XPubService

type XPubService interface {
	GetXpub(ctx context.Context, xPubKey string) (*Xpub, error)
	GetXpubByID(ctx context.Context, xPubID string) (*Xpub, error)
	NewXpub(ctx context.Context, xPubKey string, opts ...ModelOps) (*Xpub, error)
}

XPubService is the xPub related requests

type Xpub

type Xpub struct {
	// Base model
	Model `bson:",inline"`

	// Model specific fields
	ID              string `json:"id" toml:"id" yaml:"hash" gorm:"<-:create;type:char(64);primaryKey;comment:This is the sha256(xpub) hash" bson:"_id"`
	CurrentBalance  uint64 `` /* 149-byte string literal not displayed */
	NextInternalNum uint32 `` /* 181-byte string literal not displayed */
	NextExternalNum uint32 `` /* 181-byte string literal not displayed */
	// contains filtered or unexported fields
}

Xpub is an object representing the BitCoin xPub table

Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html

func (*Xpub) AfterCreated

func (m *Xpub) AfterCreated(ctx context.Context) error

AfterCreated will fire after the model is created in the Datastore

func (*Xpub) AfterUpdated

func (m *Xpub) AfterUpdated(ctx context.Context) error

AfterUpdated will fire after a successful update into the Datastore

func (*Xpub) BeforeCreating

func (m *Xpub) BeforeCreating(_ context.Context) error

BeforeCreating will fire before the model is being inserted into the Datastore

func (*Xpub) ChildModels

func (m *Xpub) ChildModels() (childModels []ModelInterface)

ChildModels will get any related sub models

func (*Xpub) GetID

func (m *Xpub) GetID() string

GetID will get the ID

func (*Xpub) GetModelName

func (m *Xpub) GetModelName() string

GetModelName will get the name of the current model

func (*Xpub) GetModelTableName

func (m *Xpub) GetModelTableName() string

GetModelTableName will get the db table name of the current model

func (*Xpub) IncrementBalance

func (m *Xpub) IncrementBalance(ctx context.Context, balanceIncrement int64) error

IncrementBalance will atomically update the balance of the xPub

func (*Xpub) IncrementNextNum

func (m *Xpub) IncrementNextNum(ctx context.Context, chain uint32) (uint32, error)

IncrementNextNum will atomically update the num of the given chain of the xPub and return it

func (*Xpub) Migrate

func (m *Xpub) Migrate(client datastore.ClientInterface) error

Migrate model specific migration on startup

func (*Xpub) Save

func (m *Xpub) Save(ctx context.Context) error

Save will Save the model into the Datastore

type XpubMetadata

type XpubMetadata map[string]Metadata

XpubMetadata XpubId specific metadata

func (XpubMetadata) GormDBDataType

func (XpubMetadata) GormDBDataType(db *gorm.DB, _ *schema.Field) string

GormDBDataType the gorm data type for metadata

func (*XpubMetadata) MarshalBSONValue

func (x *XpubMetadata) MarshalBSONValue() (bsontype.Type, []byte, error)

MarshalBSONValue method is called by bson.Marshal in Mongo for type = XpubMetadata

func (*XpubMetadata) Scan

func (x *XpubMetadata) Scan(value interface{}) error

Scan scan value into Json, implements sql.Scanner interface

func (*XpubMetadata) UnmarshalBSONValue

func (x *XpubMetadata) UnmarshalBSONValue(t bsontype.Type, data []byte) error

UnmarshalBSONValue method is called by bson.Unmarshal in Mongo for type = XpubMetadata

func (XpubMetadata) Value

func (x XpubMetadata) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type XpubOutputValue

type XpubOutputValue map[string]int64

XpubOutputValue Xpub specific output value of the transaction

func (XpubOutputValue) GormDBDataType

func (XpubOutputValue) GormDBDataType(db *gorm.DB, _ *schema.Field) string

GormDBDataType the gorm data type for metadata

func (*XpubOutputValue) Scan

func (x *XpubOutputValue) Scan(value interface{}) error

Scan scan value into Json, implements sql.Scanner interface

func (XpubOutputValue) Value

func (x XpubOutputValue) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

Directories

Path Synopsis
Package cachestore is the caching (key->value) service abstraction layer
Package cachestore is the caching (key->value) service abstraction layer
Package chainstate is the on-chain data service abstraction layer
Package chainstate is the on-chain data service abstraction layer
Package datastore is the database service abstraction layer
Package datastore is the database service abstraction layer
Package taskmanager is the task/job management service layer for concurrent and asynchronous tasks
Package taskmanager is the task/job management service layer for concurrent and asynchronous tasks
Package tester is a generic testing package with helpful methods for all packages
Package tester is a generic testing package with helpful methods for all packages
Package utils is used for generic methods and values that are used across all packages
Package utils is used for generic methods and values that are used across all packages

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL