payd

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2022 License: ISC Imports: 18 Imported by: 0

README

payd

Release Build Status Report codecov Go Sponsor Donate

Payd is a basic dummy wallet (do not use this) for demonstrating the BIP 270 / Payment Protocol flow.

It has a random master key, created at startup and a single user support for now and no authentication. Seriously, don't use this wallet at the moment expect for demonstration purposes.

This wallet has an Invoice interface with CRUD operations for creating payment invoices and also implements the Wallet Payment Protocol Interface, used to integration with payment protocol servers.

This is written in go and integrates with servers running the Payment Protocol Interface.

Exploring Endpoints

To explore the endpoints and functionality, run the server using go run cmd/rest-server/main.go and navigate to Swagger where the endpoints and their models are described in detail.

Configuring PayD

The server has a series of environment variables that allow you to configure the behaviours and integrations of the server. Values can also be passed at build time to provide information such as build information, region, version etc.

Server
Key Description Default
SERVER_PORT Port which this server should use :8443
SERVER_HOST Host name under which this server is found payd:8443
SERVER_SWAGGER_ENABLED If set to true we will expose an endpoint hosting the Swagger docs true
SERVER_SWAGGER_HOST The host that swagger will point its api requests to localhost:8443
Environment / Deployment Info
Key Description Default
ENV_ENVIRONMENT What enviornment we are running in, for example 'production' dev
ENV_REGION Region we are running in, for example 'eu-west-1' local
ENV_COMMIT Commit hash for the current build test
ENV_VERSION Semver tag for the current build, for example v1.0.0 v0.0.0
ENV_BUILDDATE Date the code was build Current UTC time
Logging
Key Description Default
LOG_LEVEL Level of logging we want within the server (debug, error, warn, info) info
DB
Key Description Default
DB_TYPE Type of db you're connecting to (sqlite, postgres,mysql) sqlite only supported currently sqlite
DB_DSN Connection string for the db file:data/wallet.db?_foreign_keys=true&pooled=true
DB_SCHEMA_PATH Location of the data base migration scripts data/sqlite/migrations
DB_MIGRATE If true we will check the db version and apply missing migrations true
Headers Client

If validating using SPV you will need to run a Headers Client, this will sync headers as they are mined and provide block and merkle proof information.

Key Description Default
HEADERSCLIENT_ADDRESS Uri for the headers client you are using http://headersv:8080
HEADERSCLIENT_TIMEOUT Timeout in seconds for headers client queries 30
Wallet
Key Description Default
WALLET_NETWORK Bitcoin network we're connected to (regtest, stn, testnet,regtest) regtest
WALLET_SPVREQUIRED If true we will require full SPV envelopes to be sent as part of payments true
WALLET_PAYMENTEXPIRY Duration in hours that invoices will be valid for 24

Working with PayD

There are a set of makefile commands listed under the Makefile which give some useful shortcuts when working with the repo.

Some of the more common commands are listed below:

make pre-commit - ensures dependencies are up to date and runs linter and unit tests.

make build-image - builds a local docker image, useful when testing PayD in docker.

make run-compose - runs PayD in compose.

Releases

You can view the latest releases on our Github Releases page.

We also publish docker images which can be found on Docker Hub.

CI / CD

We use github actions to test and build the code.

If a new release is required, after your PR is approved and code added to master, simply add a new semver tag and a GitHub action will build and publish your code as well as create a GitHub release.

Documentation

Index

Constants

View Source
const (
	// DustLimit is the minimum amount a miner will accept from an output.
	DustLimit = 136
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Ack added in v0.1.1

type Ack struct {
	Failed bool
	Reason string
}

Ack contains the status of the payment.

type AckArgs added in v0.1.1

type AckArgs struct {
	InvoiceID   string
	TxID        string
	PeerChannel *PeerChannel
}

AckArgs are used to identify a payment we are acknowledging.

type Balance

type Balance struct {
	Satoshis uint64 `json:"satoshis" db:"satoshis"`
}

Balance contains the current balance of unspent outputs.

type BalanceReader

type BalanceReader interface {
	Balance(ctx context.Context) (*Balance, error)
}

BalanceReader is used to read balance info from a datastore.

type BalanceService

type BalanceService interface {
	Balance(ctx context.Context) (*Balance, error)
}

BalanceService is used to enforce balance buiness rules.

type BroadcastArgs added in v0.1.1

type BroadcastArgs struct {
	InvoiceID   string
	CallbackURL string
	Token       string
}

BroadcastArgs sends some meta identifying the invoice used when broadcasting.

type BroadcastWriter

type BroadcastWriter interface {
	// Broadcast will submit a tx to a blockchain network.
	Broadcast(ctx context.Context, args BroadcastArgs, tx *bt.Tx) error
}

BroadcastWriter is used to submit a transaction for public broadcast to nodes.

type ClientError

type ClientError struct {
	ID      string `json:"id" example:"e97970bf-2a88-4bc8-90e6-2f597a80b93d"`
	Code    string `json:"code" example:"N01"`
	Title   string `json:"title" example:"not found"`
	Message string `json:"message" example:"unable to find foo when loading bar"`
}

ClientError defines an error type that can be returned to handle client errors.

type ConnectArgs added in v0.1.1

type ConnectArgs struct {
	InvoiceID string `param:"invoiceId"`
}

ConnectArgs identify the invoiceId / channelID to connect to.

func (*ConnectArgs) Validate added in v0.1.1

func (c *ConnectArgs) Validate() error

Validate will check that invoice arguments match expectations.

type ConnectService added in v0.1.1

type ConnectService interface {
	Connect(ctx context.Context, args ConnectArgs) error
}

ConnectService is used to connect this wallet to an async channel server, this could be sockets, peer channels or something else.

type ConnectWriter added in v0.1.1

type ConnectWriter interface {
	Connect(ctx context.Context, args ConnectArgs) error
}

ConnectWriter handles data writes when creating a new async connection.

type CreateUserArgs added in v0.1.3

type CreateUserArgs struct {
	Name         string                 `json:"name"`
	Email        string                 `json:"email"`
	Avatar       string                 `json:"avatar"`
	Address      string                 `json:"address"`
	PhoneNumber  string                 `json:"phoneNumber"`
	ExtendedData map[string]interface{} `json:"extendedData"`
}

CreateUserArgs is what we expect to be sent to create a new user in the payd user store.

type CreateUserResponse added in v0.1.3

type CreateUserResponse struct {
	ID uint64 `json:"userId" db:"user_id"`
}

CreateUserResponse is what we expect to receive once a new user is created.

type DerivationExistsArgs

type DerivationExistsArgs struct {
	KeyName string `db:"key_name"`
	UserID  uint64 `db:"user_id"`
	Path    string `db:"derivation_path"`
}

DerivationExistsArgs are used to check a derivation path exists for a specific master key and path.

type DerivationReader

type DerivationReader interface {
	DerivationPathExists(ctx context.Context, args DerivationExistsArgs) (bool, error)
}

DerivationReader can be used to read derivation path data from a data store.

type Destination

type Destination struct {
	SPVRequired bool      `json:"spvRequired"`
	Network     string    `json:"network"`
	Outputs     []Output  `json:"outputs"`
	CreatedAt   time.Time `json:"createdAt"`
	ExpiresAt   time.Time `json:"expiresAt"`
}

Destination contains outputs and current fees required to construct a transaction.

type DestinationCreate

type DestinationCreate struct {
	Script         string `db:"locking_script"`
	DerivationPath string `db:"derivation_path"`
	Satoshis       uint64 `db:"satoshis"`
	UserID         uint64 `db:"user_id"`
	KeyName        string `db:"key_name"`
}

DestinationCreate can be used to create a single Output for storage.

type DestinationsArgs

type DestinationsArgs struct {
	InvoiceID string `param:"invoiceID"`
}

DestinationsArgs are used to get a set of Denominations for an existing InvoiceID.

func (DestinationsArgs) Validate

func (d DestinationsArgs) Validate() error

Validate will ensure arguments to get destinations are as expected.

type DestinationsCreate

type DestinationsCreate struct {
	InvoiceID     null.String
	Satoshis      uint64
	Denominations uint64
	UserID        uint64
}

DestinationsCreate will create new destinations.

func (DestinationsCreate) Validate

func (d DestinationsCreate) Validate() error

Validate will ensure arguments for destinationsCreate are valid, otherwise an error is returned.

type DestinationsCreateArgs

type DestinationsCreateArgs struct {
	// InvoiceID, this is optional, if not supplied destinations
	// will not be associated with an invoice.
	InvoiceID null.String `db:"invoice_id"`
}

DestinationsCreateArgs are used when adding destinations to a datastore and can be sued to group them.

type DestinationsReader

type DestinationsReader interface {
	// Destinations will return destination outputs.
	Destinations(ctx context.Context, args DestinationsArgs) ([]Output, error)
}

DestinationsReader will return destination outputs.

type DestinationsReaderWriter

type DestinationsReaderWriter interface {
	DestinationsReader
	DestinationsWriter
}

DestinationsReaderWriter combines the reader and writer interfaces for convenience.

type DestinationsService

type DestinationsService interface {
	// InvoiceCreate will split satoshis into multiple denominations and store
	// as denominations waiting to be fulfilled in a tx.
	DestinationsCreate(ctx context.Context, req DestinationsCreate) (*Destination, error)
	// Destinations given the args, will return a set of Destinations.
	Destinations(ctx context.Context, args DestinationsArgs) (*Destination, error)
}

DestinationsService enforces business rules and validation for Destinations.

type DestinationsWriter

type DestinationsWriter interface {
	// DestinationsCreate will add a set of destinations to a data store.
	DestinationsCreate(ctx context.Context, args DestinationsCreateArgs, req []DestinationCreate) ([]Output, error)
}

DestinationsWriter can be implemented to store new destinations in a data store.

type EnvelopeArgs added in v0.1.1

type EnvelopeArgs struct {
	PayToURL string `json:"payToURL"`
}

EnvelopeArgs identify where an envelope is being paid to.

func (EnvelopeArgs) Validate added in v0.1.1

func (e EnvelopeArgs) Validate() error

Validate will ensure that the args supplied are valid.

type EnvelopeService added in v0.1.1

type EnvelopeService interface {
	Envelope(ctx context.Context, args EnvelopeArgs, req p4.PaymentRequest) (*spv.Envelope, error)
}

EnvelopeService will create an spv envelope from a paymentRequest.

type FeeQuoteCreateArgs added in v0.1.3

type FeeQuoteCreateArgs struct {
	InvoiceID string
	FeeQuote  *bt.FeeQuote
}

FeeQuoteCreateArgs for store a fee quote.

type FeeQuoteFetcher added in v0.1.3

type FeeQuoteFetcher interface {
	// FeeQuote return fees from a fee quoter.
	FeeQuote(ctx context.Context) (*bt.FeeQuote, error)
}

FeeQuoteFetcher fetch a new fee quote.

type FeeQuoteReader added in v0.1.3

type FeeQuoteReader interface {
	// FeeQuote will return fees from a datastore.
	FeeQuote(ctx context.Context, invoiceID string) (*bt.FeeQuote, error)
}

FeeQuoteReader can be implemented to read fees from a datastore.

type FeeQuoteWriter added in v0.1.3

type FeeQuoteWriter interface {
	FeeQuoteCreate(ctx context.Context, args *FeeQuoteCreateArgs) error
}

FeeQuoteWriter writes fee quotes to a store.

type HealthCheck added in v0.1.5

type HealthCheck interface {
	Start() error
}

HealthCheck for checking the health of a specific component.

type HealthService added in v0.1.1

type HealthService interface {
	Health(ctx context.Context) error
}

HealthService for checking the overall health of payd.

type Invoice

type Invoice struct {
	// ID is a unique identifier for an invoice and can be used
	// to lookup a single invoice.
	ID string `json:"id" db:"invoice_id"`
	// Reference is an identifier that can be used to link the
	// PayD invoice with an external system.
	Reference null.String `json:"reference" db:"payment_reference"`
	// Description is an optional text field that can have some further info
	// like 'invoice for oranges'.
	Description null.String `json:"description" db:"description"`
	// Satoshis is the total amount this invoice is to pay.
	Satoshis uint64 `json:"satoshis" db:"satoshis"`
	// ExpiresAt is an optional param that can be passed to set an expiration
	// date on an invoice, after which, payments will not be accepted.
	ExpiresAt null.Time `json:"expiresAt" db:"expires_at"`
	// PaymentReceivedAt will be set when this invoice has been paid and
	// states when the payment was received in UTC time.
	PaymentReceivedAt null.Time `json:"paymentReceivedAt" db:"payment_received_at"`
	// RefundTo is an optional paymail address that can be used to refund the
	// customer if required.
	RefundTo null.String `json:"refundTo" db:"refund_to"`
	// RefundedAt if this payment has been refunded, this date will be set
	// to the UTC time of the refund.
	RefundedAt null.Time `json:"refundedAt" db:"refunded_at"`
	// State is the current status of the invoice.
	State InvoiceState `json:"state" db:"state" enums:"pending,paid,refunded,deleted"`
	// SPVRequired if true will mean this invoice requires a valid spvenvelope otherwise a rawTX will suffice.
	SPVRequired bool `json:"-" db:"spv_required"`
	MetaData
}

Invoice identifies a single payment request from this payd wallet, it states the amount, id and optional refund address. This indicate we are requesting n satoshis in payment.

type InvoiceArgs

type InvoiceArgs struct {
	InvoiceID string `param:"invoiceID" db:"invoice_id"`
}

InvoiceArgs contains argument/s to return a single invoice.

func (*InvoiceArgs) Validate

func (i *InvoiceArgs) Validate() error

Validate will check that invoice arguments match expectations.

type InvoiceCreate

type InvoiceCreate struct {
	InvoiceID string `json:"-" db:"invoice_id"`
	// Satoshis is the total amount this invoice is to pay.
	Satoshis uint64 `json:"satoshis" db:"satoshis"`
	// Reference is an identifier that can be used to link the
	// payd invoice with an external system.
	// MaxLength is 32 characters.
	Reference null.String `json:"reference" db:"payment_reference" swaggertype:"primitive,string"`
	// Description is an optional text field that can have some further info
	// like 'invoice for oranges'.
	// MaxLength is 1024 characters.
	Description null.String `json:"description" db:"description" swaggertype:"primitive,string"`
	// CreatedAt is the timestamp when the invoice was created.
	CreatedAt time.Time `json:"-" db:"created_at"`
	// ExpiresAt is an optional param that can be passed to set an expiration
	// date on an invoice, after which, payments will not be accepted.
	ExpiresAt null.Time `json:"expiresAt" db:"expires_at"`
	// SPVRequired if true will mean this invoice requires a valid spvenvelope otherwise a rawTX will suffice.
	SPVRequired bool `json:"-" db:"spv_required"`
}

InvoiceCreate is used to create a new invoice.

func (InvoiceCreate) Validate

func (i InvoiceCreate) Validate() error

Validate will check that InvoiceCreate params match expectations.

type InvoiceReader

type InvoiceReader interface {
	// Invoice will return an invoice that matches the provided args.
	Invoice(ctx context.Context, args InvoiceArgs) (*Invoice, error)
	// Invoices returns all currently stored invoices TODO: update to support search args
	Invoices(ctx context.Context) ([]Invoice, error)
	InvoicesPending(ctx context.Context) ([]Invoice, error)
}

InvoiceReader defines a data store used to read invoice data.

type InvoiceReaderWriter

type InvoiceReaderWriter interface {
	InvoiceWriter
	InvoiceReader
}

InvoiceReaderWriter can be implemented to support storing and retrieval of invoices.

type InvoiceService

type InvoiceService interface {
	Invoice(ctx context.Context, args InvoiceArgs) (*Invoice, error)
	Invoices(ctx context.Context) ([]Invoice, error)
	InvoicesPending(ctx context.Context) ([]Invoice, error)
	Create(ctx context.Context, req InvoiceCreate) (*Invoice, error)
	Delete(ctx context.Context, args InvoiceArgs) error
}

InvoiceService defines a service for managing invoices.

type InvoiceState

type InvoiceState string

InvoiceState enforces invoice states.

const (
	StateInvoicePending  InvoiceState = "pending"
	StateInvoicePaid     InvoiceState = "paid"
	StateInvoiceRefunded InvoiceState = "refunded"
	StateInvoiceDeleted  InvoiceState = "deleted"
)

contains states that an invocie can have.

func (InvoiceState) String

func (i InvoiceState) String() string

type InvoiceUpdateArgs

type InvoiceUpdateArgs struct {
	InvoiceID string
}

InvoiceUpdateArgs are used to identify the invoice to update.

type InvoiceUpdatePaid

type InvoiceUpdatePaid struct {
	PaymentReceivedAt time.Time `db:"payment_received_at"`
	RefundTo          string    `db:"refund_to"`
}

InvoiceUpdatePaid can be used to update an invoice after it has been created.

type InvoiceUpdateRefunded

type InvoiceUpdateRefunded struct {
	// RefundTo will set an invoice as refunded.
	RefundTo null.String `db:"refund_to"`
	// RefundedAt if this payment has been refunded, this date will be set
	// to the UTC time of the refund.
	RefundedAt null.Time `json:"refundedAt" db:"refunded_at"`
}

InvoiceUpdateRefunded can be used to update an invoice state to refunded.

type InvoiceWriter

type InvoiceWriter interface {
	// Create will persist a new Invoice in the data store.
	InvoiceCreate(ctx context.Context, req InvoiceCreate) (*Invoice, error)
	// Update will update an invoice matching the provided args with the requested changes.
	InvoiceUpdate(ctx context.Context, args InvoiceUpdateArgs, req InvoiceUpdatePaid) (*Invoice, error)
	// Delete will remove an invoice from the data store, depending on implementation this could
	// be a hard or soft delete.
	InvoiceDelete(ctx context.Context, args InvoiceArgs) error
}

InvoiceWriter defines a data store used to write invoice data.

type KeyArgs

type KeyArgs struct {
	// Name is the name of the key to return.
	Name string `db:"name"`
	// user id associated with this key.
	UserID uint64 `db:"user_id"`
}

KeyArgs defines all arguments required to get a key.

type MerchantData added in v0.1.1

type MerchantData struct {
	Avatar           string                 `json:"avatar"`
	Name             string                 `json:"name"`
	Email            string                 `json:"email"`
	Address          string                 `json:"address"`
	PaymentReference string                 `json:"paymentReference"`
	ExtendedData     map[string]interface{} `json:"extendedData"`
}

MerchantData p4 from a p4 server.

type MetaData

type MetaData struct {
	// CreatedAt is the UTC time the object was created.
	CreatedAt time.Time `json:"createdAt" db:"created_at"`
	// UpdatedAt is the UTC time the object was updated.
	UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`
	// DeletedAt is the date the object was removed.
	DeletedAt null.Time `json:"deletedAt,omitempty" db:"deleted_at"`
}

MetaData contains common meta info for objects.

type Output

type Output struct {
	ID uint64 `json:"-" db:"destination_id"`
	// LockingScript is the P2PKH locking script used.
	LockingScript *bscript.Script `json:"script" db:"locking_script"`
	Satoshis      uint64          `json:"satoshis" db:"satoshis"`
	// DerivationPath is the deterministic path for this destination.
	DerivationPath string `json:"-" db:"derivation_path"`
	// State will indicate if this destination is still waiting on a tx to fulfil it (pending)
	// has been paid to in a tx (received) or has been deleted.
	State string `json:"-" db:"state"  enums:"pending,received,deleted"`
}

Output contains a single locking script and satoshi amount and can be used to construct transaction outputs.

type OwnerService

type OwnerService interface {
	Owner(ctx context.Context) (*User, error)
}

OwnerService interfaces with owners.

type OwnerStore

type OwnerStore interface {
	Owner(ctx context.Context) (*User, error)
}

OwnerStore interfaces with an owner store.

type P2PCapabilityArgs

type P2PCapabilityArgs struct {
	Domain string
	BrfcID string
}

P2PCapabilityArgs is used to retrieve information from a p2p server. https://bsvalias.org/02-02-capability-discovery.html

type P2POutputCreateArgs

type P2POutputCreateArgs struct {
	Domain string
	Alias  string
}

P2POutputCreateArgs is used to locate a `signer when sending a p2p payment.

type P2PPayment

type P2PPayment struct {
	Satoshis uint64
}

P2PPayment contains the amount of satoshis to send peer to peer.

type P2PTransaction

type P2PTransaction struct {
	TxHex    string
	Metadata P2PTransactionMetadata
}

P2PTransaction defines a peer to peer transaction.

type P2PTransactionArgs

type P2PTransactionArgs struct {
	Alias     string
	Domain    string
	PaymentID string
	TxHex     string
}

P2PTransactionArgs is used to get a transaction.

type P2PTransactionMetadata

type P2PTransactionMetadata struct {
	Note      string // A human readable bit of information about the payment
	PubKey    string // Public key to validate the signature (if signature is given)
	Sender    string // The paymail of the person that originated the transaction
	Signature string
}

P2PTransactionMetadata contains potentially optional metadata that can be sent along with a p2p payment.

type P4Destination added in v0.0.7

type P4Destination struct {
	Outputs []P4Output `json:"outputs"`
}

P4Destination defines a P4 payment destination object.

type P4Output added in v0.0.2

type P4Output struct {
	Amount      uint64 `json:"amount"`
	Script      string `json:"script"`
	Description string `json:"description"`
}

P4Output an output matching what a p4 server expects.

type PayRequest added in v0.0.2

type PayRequest struct {
	PayToURL string `json:"payToURL"`
}

PayRequest a request for making a payment.

func (PayRequest) Validate added in v0.0.2

func (p PayRequest) Validate() error

Validate validates the request.

type PayService added in v0.0.2

type PayService interface {
	Pay(ctx context.Context, req PayRequest) (*p4.PaymentACK, error)
}

PayService for sending payments to another wallet.

type PayStrategy added in v0.1.1

type PayStrategy interface {
	PayService
	Register(svc PayService, names ...string) PayStrategy
}

PayStrategy for registering different payment strategies.

type PayWriter added in v0.1.1

type PayWriter interface {
	Pay(ctx context.Context, req PayRequest) error
}

PayWriter will send a payment to another wallet or p4 server.

type PaymailReader

type PaymailReader interface {
	Capability(ctx context.Context, args P2PCapabilityArgs) (string, error)
}

PaymailReader reads paymail information from a datastore.

type PaymailReaderWriter

type PaymailReaderWriter interface {
	PaymailReader
	PaymailWriter
}

PaymailReaderWriter combines the reader and writer interfaces.

type PaymailWriter

type PaymailWriter interface {
	OutputsCreate(ctx context.Context, args P2POutputCreateArgs, req P2PPayment) ([]*bt.Output, error)
}

PaymailWriter writes to a paymail datastore.

type Payment added in v0.0.2

type Payment struct {
	Transaction  string        `json:"transaction"`
	SPVEnvelope  *spv.Envelope `json:"spvEnvelope"`
	MerchantData User          `json:"merchantData"`
	Memo         string        `json:"memo"`
}

Payment is a payment.

type PaymentACK added in v0.0.2

type PaymentACK struct {
	Payment PaymentCreate `json:"payment"`
	Memo    string        `json:"memo,omitempty"`
	// A number indicating why the transaction was not accepted. 0 or undefined indicates no error.
	// A 1 or any other positive integer indicates an error. The errors are left undefined for now;
	// it is recommended only to use “1” and to fill the memo with a textual explanation about why
	// the transaction was not accepted until further numbers are defined and standardised.
	Error int `json:"error,omitempty"`
}

PaymentACK message used in BIP270. See https://github.com/moneybutton/bips/blob/master/bip-0270.mediawiki#paymentack

type PaymentCreate

type PaymentCreate struct {
	// MerchantData is copied from PaymentDetails.merchantData.
	// Payment hosts may use invoice numbers or any other data they require to match Payments to PaymentRequests.
	// Note that malicious clients may modify the merchantData, so should be authenticated
	// in some way (for example, signed with a payment host-only key).
	// Maximum length is 10000 characters.
	MerchantData User `json:"merchantData"`
	// RefundTo is a paymail to send a refund to should a refund be necessary.
	// Maximum length is 100 characters
	RefundTo null.String `json:"refundTo" swaggertype:"primitive,string" example:"me@paymail.com"`
	// Memo is a plain-text note from the customer to the payment host.
	Memo string `json:"memo" example:"for invoice 123456"`
	// SPVEnvelope which contains the details of previous transaction and Merkle proof of each input UTXO.
	// Should be available if SPVRequired is set to true in the paymentRequest.
	// See https://tsc.bitcoinassociation.net/standards/spv-envelope/
	SPVEnvelope *spv.Envelope `json:"spvEnvelope"`
	// ProofCallbacks are optional and can be supplied when the sender wants to receive
	// a merkleproof for the transaction they are submitting as part of the SPV Envelope.
	//
	// This is especially useful if they are receiving change and means when they use it
	// as an input, they can provide the merkle proof.
	ProofCallbacks map[string]ProofCallback `json:"proofCallbacks"`
}

PaymentCreate is submitted to validate and add a payment to the wallet.

func (PaymentCreate) Validate

func (p PaymentCreate) Validate(spvRequired bool) error

Validate will ensure the users request is correct.

type PaymentCreateArgs added in v0.1.1

type PaymentCreateArgs struct {
	InvoiceID string
}

PaymentCreateArgs are used to identify a payment.

type PaymentRequestArgs added in v0.1.1

type PaymentRequestArgs struct {
	InvoiceID string `param:"invoiceID"`
}

PaymentRequestArgs are used to create a new paymentRequest.

func (*PaymentRequestArgs) Validate added in v0.1.1

func (p *PaymentRequestArgs) Validate() error

Validate will check that invoice arguments match expectations.

type PaymentRequestResponse added in v0.0.2

type PaymentRequestResponse struct {
	Network             string        `json:"network"`
	Destinations        P4Destination `json:"destinations"`
	CreationTimestamp   time.Time     `json:"creationTimestamp"`
	ExpirationTimestamp time.Time     `json:"expirationTimestamp"`
	PaymentURL          string        `json:"paymentURL"`
	Memo                string        `json:"memo"`
	MerchantData        User          `json:"merchantData"`
	Fee                 *bt.FeeQuote  `json:"fees"`
	SPVRequired         bool          `json:"spvRequired" example:"true"`
}

PaymentRequestResponse a payment request from p4.

type PaymentRequestService added in v0.1.1

type PaymentRequestService interface {
	PaymentRequest(ctx context.Context, args PaymentRequestArgs) (*PaymentRequestResponse, error)
}

PaymentRequestService will create and return a paymentRequest using the args provided.

type PaymentSend added in v0.0.2

type PaymentSend struct {
	SPVEnvelope    *spv.Envelope            `json:"spvEnvelope"`
	ProofCallbacks map[string]ProofCallback `json:"proofCallbacks"`
	MerchantData   User                     `json:"merchantData"`
}

PaymentSend is a send request to p4.

type PaymentsService

type PaymentsService interface {
	// PaymentCreate will validate a new payment.
	PaymentCreate(ctx context.Context, args PaymentCreateArgs, req p4.Payment) (*p4.PaymentACK, error)
	// Ack will handle a payment acknowledgement and can set a transaction as broadcast or failed.
	Ack(ctx context.Context, args AckArgs, req Ack) error
}

PaymentsService is used for handling payments.

type PeerChannel added in v0.1.3

type PeerChannel struct {
	ID        string                 `db:"channel_id"`
	Token     string                 `db:"tok"`
	Host      string                 `db:"channel_host"`
	CreatedAt time.Time              `db:"created_at"`
	Type      PeerChannelHandlerType `db:"channel_type"`
}

PeerChannel data.

type PeerChannelAPITokenCreateArgs added in v0.1.3

type PeerChannelAPITokenCreateArgs struct {
	Role    string
	Persist bool
	Request spvchannels.TokenCreateRequest
}

PeerChannelAPITokenCreateArgs for creating a peer channel token.

type PeerChannelAPITokenStoreArgs added in v0.1.3

type PeerChannelAPITokenStoreArgs struct {
	PeerChannelsChannelID string `db:"peerchannels_channel_id"`
	Token                 string `db:"tok"`
	Role                  string `db:"role"`
	CanRead               bool   `db:"can_read"`
	CanWrite              bool   `db:"can_write"`
}

PeerChannelAPITokenStoreArgs for storing a peer channel token.

type PeerChannelAccount added in v0.1.3

type PeerChannelAccount struct {
	ID       int64
	Username string
	Password string
}

PeerChannelAccount a peer channel account.

type PeerChannelCreateArgs added in v0.1.3

type PeerChannelCreateArgs struct {
	PeerChannelAccountID int64                  `db:"peerchannels_account_id"`
	ChannelType          PeerChannelHandlerType `db:"channel_type"`
	ChannelHost          string                 `db:"channel_host"`
	ChannelID            string                 `db:"channel_id"`
	CreatedAt            time.Time              `db:"created_at"`
}

PeerChannelCreateArgs for creating a peer channel.

type PeerChannelHandlerType added in v0.1.3

type PeerChannelHandlerType string

PeerChannelHandlerType the type of function which a peer channels message should map to.

const (
	PeerChannelHandlerTypeProof PeerChannelHandlerType = "proof"
)

The types of message handlers.

type PeerChannelIDArgs added in v0.1.3

type PeerChannelIDArgs struct {
	UserID int64
}

PeerChannelIDArgs for getting a peerchannel account of a user.

type PeerChannelMessageArgs added in v0.1.3

type PeerChannelMessageArgs struct {
	ChannelID string
	Token     string
}

PeerChannelMessageArgs for quering a peer channel message.

type PeerChannelSubscription added in v0.1.3

type PeerChannelSubscription struct {
	ChannelID   string
	Token       string
	ChannelType PeerChannelHandlerType
	Conn        *websocket.Conn
}

PeerChannelSubscription for subscribing to channel notifications.

type PeerChannelsMessageHandler added in v0.1.3

type PeerChannelsMessageHandler interface {
	HandlePeerChannelsMessage(ctx context.Context, msgs spvchannels.MessagesReply) (bool, error)
}

PeerChannelsMessageHandler for handling peer channel messages.

type PeerChannelsNotifyService added in v0.1.3

type PeerChannelsNotifyService interface {
	RegisterHandler(ht PeerChannelHandlerType, hdlr PeerChannelsMessageHandler) PeerChannelsNotifyService
	Subscribe(ctx context.Context, args *PeerChannel) error
}

PeerChannelsNotifyService for interfacing with peer channel notifications.

type PeerChannelsService added in v0.1.3

type PeerChannelsService interface {
	PeerChannelCreate(ctx context.Context, req spvchannels.ChannelCreateRequest) (*PeerChannel, error)
	PeerChannelAPITokensCreate(ctx context.Context, reqs ...*PeerChannelAPITokenCreateArgs) ([]*spvchannels.TokenCreateReply, error)
	PeerChannelsMessage(ctx context.Context, args *PeerChannelMessageArgs) (spvchannels.MessagesReply, error)
	ActiveProofChannels(ctx context.Context) ([]PeerChannel, error)
	CloseChannel(ctx context.Context, channelID string) error
}

PeerChannelsService a service for interacting with peer channels.

type PeerChannelsStore added in v0.1.3

type PeerChannelsStore interface {
	PeerChannelAccount(ctx context.Context, args *PeerChannelIDArgs) (*PeerChannelAccount, error)
	PeerChannelCreate(ctx context.Context, args *PeerChannelCreateArgs) error
	PeerChannelCloseChannel(ctx context.Context, channelID string) error
	PeerChannelsOpened(ctx context.Context, channelType PeerChannelHandlerType) ([]PeerChannel, error)
	PeerChannelAPITokenCreate(ctx context.Context, args *PeerChannelAPITokenStoreArgs) error
	PeerChannelAPITokensCreate(ctx context.Context, args ...*PeerChannelAPITokenStoreArgs) error
}

PeerChannelsStore for interfacing with a peer channel data store.

type PrivateKey

type PrivateKey struct {
	UserID uint64 `db:"user_id"`
	// Name of the private key.
	Name string `db:"name"`
	// Xprv is the private key.
	Xprv string `db:"xprv"`
	// CreatedAt is the date/time when the key was stored.
	CreatedAt time.Time `db:"createdAt"`
}

PrivateKey describes a named private key.

type PrivateKeyReader

type PrivateKeyReader interface {
	// PrivateKey can be used to return an existing private key.
	PrivateKey(ctx context.Context, args KeyArgs) (*PrivateKey, error)
}

PrivateKeyReader reads private info from a data store.

type PrivateKeyReaderWriter

type PrivateKeyReaderWriter interface {
	PrivateKeyReader
	PrivateKeyWriter
}

PrivateKeyReaderWriter describes a data store that can be implemented to get and store private keys.

type PrivateKeyService

type PrivateKeyService interface {
	// Create will create a new private key if it doesn't exist already.
	Create(ctx context.Context, keyName string, userID uint64) error
	// PrivateKey will return a private key.
	PrivateKey(ctx context.Context, keyName string, userID uint64) (*bip32.ExtendedKey, error)
}

PrivateKeyService can be implemented to get and create PrivateKeys.

type PrivateKeyWriter

type PrivateKeyWriter interface {
	// PrivateKeyCreate will add a new private key to the data store.
	PrivateKeyCreate(ctx context.Context, req PrivateKey) (*PrivateKey, error)
}

PrivateKeyWriter will add private key to the datastore.

type ProofCallback

type ProofCallback struct {
	// Token to use for authentication when sending the proof to the destination. Optional.
	Token string
}

ProofCallback contains information relating to a merkleproof callback.

type ProofCallbackArgs

type ProofCallbackArgs struct {
	InvoiceID string `db:"invoice_id"`
}

ProofCallbackArgs are used to identify proofs for an invoice.

type ProofCallbackWriter

type ProofCallbackWriter interface {
	// ProofCallBacksCreate can be implemented to store merkle proof callback urls for an invoice.
	ProofCallBacksCreate(ctx context.Context, args ProofCallbackArgs, callbacks map[string]p4.ProofCallback) error
}

ProofCallbackWriter can be implemented to support writing proof callbacks.

type ProofCreateArgs

type ProofCreateArgs struct {
	// TxID will be used to validate the proof envelope.
	TxID string `json:"txId" param:"txid"`
}

ProofCreateArgs are used to create a proof.

type ProofWrapper

type ProofWrapper struct {
	CallbackPayload *bc.MerkleProof `json:"callbackPayload"`
	BlockHash       string          `json:"blockHash"`
	BlockHeight     uint32          `json:"blockHeight"`
	CallbackTxID    string          `json:"callbackTxID"`
	CallbackReason  string          `json:"callbackReason"`
}

ProofWrapper represents a mapi callback payload for a merkleproof. mAPI returns proofs in a JSONEnvelope with a payload. This represents the Payload format which contains a parent object with tx meta and a nested object which is the TSC format merkleProof.

func (ProofWrapper) Validate

func (p ProofWrapper) Validate(args ProofCreateArgs) error

Validate will ensure the ProofWrapper is valid.

type ProofsService

type ProofsService interface {
	// Create will store a JSONEnvelope that contains a merkleproof. The envelope should
	// be validated to not be tampered with and the Envelope should be opened to check the payload
	// is indeed a MerkleProof.
	Create(ctx context.Context, args p4.ProofCreateArgs, req envelope.JSONEnvelope) error
}

ProofsService enforces business rules and validation when handling merkle proofs.

type ProofsWriter

type ProofsWriter interface {
	// ProofCreate can be used to persist a merkle proof in TSC format.
	ProofCreate(ctx context.Context, req p4.ProofWrapper) error
}

ProofsWriter is used to persist a proof to a data store.

type SeedService added in v0.1.1

type SeedService interface {
	Uint64() (uint64, error)
}

SeedService for retrieve seeds.

type SpendTxo

type SpendTxo struct {
	SpentAt      *time.Time
	SpendingTxID string
}

SpendTxo can be used to update a transaction out with information on when it was spent and by what transaction.

type SpendTxoArgs

type SpendTxoArgs struct {
	Outpoint string
}

SpendTxoArgs are used to identify the transaction output to mark as spent.

type SpendingArgs added in v0.1.1

type SpendingArgs struct {
	InvoiceID string
}

SpendingArgs are used to identify the payment we are spending.

type SpendingCreate added in v0.1.1

type SpendingCreate struct {
	Tx string
}

SpendingCreate will wrap the request arguments.

type SpendingService added in v0.1.1

type SpendingService interface {
	// SpendTx will mark the txos as spent and insert the change txo.
	SpendTx(ctx context.Context, args SpendingArgs, req SpendingCreate) error
}

SpendingService is used to mark a transaction as spent on response from a payment ack. The sender wallet will insert their accepted transaction as broadcast and store the change txo if found.

type TimestampService added in v0.1.1

type TimestampService interface {
	Nanosecond() int
	NowUTC() time.Time
}

TimestampService for getting timestamps.

type Transacter

type Transacter interface {
	WithTx(ctx context.Context) context.Context
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
}

Transacter can be implemented to provide context based transactions.

type Transaction

type Transaction struct {
	PaymentID string    `db:"paymentid"`
	TxID      string    `db:"tx_id"`
	TxHex     string    `db:"tx_hex"`
	CreatedAt time.Time `db:"created_at"`
	Outputs   []Txo     `db:"-"`
	State     string    `enums:"pending,broadcast,failed,deleted"`
}

Transaction defines a single transaction.

type TransactionArgs

type TransactionArgs struct {
	TxID string `db:"tx_id"`
}

TransactionArgs are used to identify a specific tx.

type TransactionCreate

type TransactionCreate struct {
	InvoiceID string       `db:"invoice_id"`
	RefundTo  null.String  `db:"refund_to"`
	TxID      string       `db:"tx_id"`
	TxHex     string       `db:"tx_hex"`
	Outputs   []*TxoCreate `db:"-"`
}

TransactionCreate is used to insert a tx into the data store. To save calls, Txos can be included to also add in the same transaction.

type TransactionService added in v0.1.1

type TransactionService interface {
	// Submit is for testing only and allows a finalised tx to be stored.
	Submit(ctx context.Context, args TransactionSubmitArgs, req TransactionSubmit) error
}

TransactionService is used to handle transactions.

type TransactionStateUpdate

type TransactionStateUpdate struct {
	State      TxState     `db:"state"`
	FailReason null.String `db:"fail_reason"`
}

TransactionStateUpdate contains information to update a tx.

type TransactionSubmit added in v0.1.1

type TransactionSubmit struct {
	TxHex string `param:"txHex"`
}

TransactionSubmit contains the request to store the tx.

type TransactionSubmitArgs added in v0.1.1

type TransactionSubmitArgs struct {
	InvoiceID string `param:"invoiceid"`
}

TransactionSubmitArgs are used to identify a tx.

type TransactionWriter

type TransactionWriter interface {
	TransactionCreate(ctx context.Context, req TransactionCreate) error
	// TransactionUpdateState can be used to change a tx state (failed, broadcast).
	TransactionUpdateState(ctx context.Context, args TransactionArgs, req TransactionStateUpdate) error
}

TransactionWriter will add and update transaction data.

type TxState

type TxState string

TxState defines states a transaction can have.

const (
	StateTxBroadcast TxState = "broadcast"
	StateTxFailed    TxState = "failed"
	StateTxPending   TxState = "pending"
)

defines states a transaction can have.

type Txo

type Txo struct {
	Outpoint       string      `db:"outpoint"`
	TxID           string      `db:"tx_id"`
	Vout           int         `db:"vout"`
	KeyName        null.String `db:"key_name"`
	DerivationPath null.String `db:"derivation_path"`
	LockingScript  string      `db:"locking_script"`
	Satoshis       uint64      `db:"satoshis"`
	SpentAt        null.Time   `db:"spent_at"`
	SpendingTxID   null.String `db:"spending_txid"`
	CreatedAt      time.Time   `db:"created_at"`
	ModifiedAt     time.Time   `db:"updated_at"`
}

Txo defines a single txo and can be returned from the data store.

type TxoArgs

type TxoArgs struct {
	Outpoint string
}

TxoArgs is used to get a single txo.

type TxoCreate

type TxoCreate struct {
	Outpoint      string `db:"outpoint"`
	DestinationID uint64 `db:"destination_id"`
	TxID          string `db:"tx_id"`
	Vout          uint64 `db:"vout"`
}

TxoCreate will add utxos to our data store linked by a destinationId. These are added when a user submit a tx to pay an invoice.

type TxoWriter

type TxoWriter interface {
	// TxosCreate will add an array of txos to a data store.
	// TxosCreate(ctx context.Context, req []*TxoCreate) error
	UTXOReserve(ctx context.Context, req UTXOReserve) ([]UTXO, error)
	UTXOUnreserve(ctx context.Context, req UTXOUnreserve) error
	UTXOSpend(ctx context.Context, req UTXOSpend) error
}

TxoWriter is used to add transaction information to a data store.

type UTXO added in v0.0.2

type UTXO struct {
	Outpoint       string `db:"outpoint"`
	TxID           string `db:"tx_id"`
	Vout           uint32 `db:"vout"`
	Satoshis       uint64 `db:"satoshis"`
	LockingScript  string `db:"locking_script"`
	DerivationPath string `db:"derivation_path"`
}

UTXO an internal utxo.

type UTXOReserve added in v0.0.2

type UTXOReserve struct {
	ReservedFor string
	Satoshis    uint64
}

UTXOReserve takes args for marking a utxo in the db as reserved.

type UTXOSpend added in v0.0.2

type UTXOSpend struct {
	Timestamp    time.Time `db:"timestamp"`
	SpendingTxID string    `db:"spending_txid"`
	Reservation  string    `db:"reserved_for"`
}

UTXOSpend takes args for marking a utxo in the db as spent.

type UTXOUnreserve added in v0.0.2

type UTXOUnreserve struct {
	ReservedFor string
}

UTXOUnreserve takes args for unreserving reserved utxos in the db.

type User

type User struct {
	ID           uint64                 `json:"id" db:"user_id"`
	Name         string                 `json:"name" db:"name"`
	Email        string                 `json:"email" db:"email"`
	Avatar       string                 `json:"avatar" db:"avatar_url"`
	Address      string                 `json:"address" db:"address"`
	PhoneNumber  string                 `json:"phoneNumber" db:"phone_number"`
	ExtendedData map[string]interface{} `json:"extendedData"`
	MasterKey    *bip32.ExtendedKey     `json:"-"`
}

User information on wallet users.

type UserService added in v0.1.3

type UserService interface {
	CreateUser(context.Context, CreateUserArgs) (*User, error)
	ReadUser(context.Context, uint64) (*User, error)
	UpdateUser(context.Context, uint64, User) (*User, error)
	DeleteUser(context.Context, uint64) error
}

UserService interfaces with users.

type UserStore added in v0.1.3

type UserStore interface {
	CreateUser(context.Context, CreateUserArgs, PrivateKeyService) (*CreateUserResponse, error)
	ReadUser(context.Context, uint64) (*User, error)
	UpdateUser(context.Context, uint64, User) (*User, error)
	DeleteUser(context.Context, uint64) error
}

UserStore interfaces with a user store.

Directories

Path Synopsis
cmd
Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT This file was generated by swaggo/swag
Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT This file was generated by swaggo/swag
transports

Jump to

Keyboard shortcuts

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