loopdb

package
v0.29.0-beta.rc1 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2024 License: MIT Imports: 50 Imported by: 2

Documentation

Index

Constants

View Source
const (
	// DefaultLoopOutHtlcConfirmations is the default number of
	// confirmations we set for a loop out htlc.
	DefaultLoopOutHtlcConfirmations uint32 = 1

	// DefaultLoopDBTimeout is the default maximum time we wait for the
	// Loop bbolt database to be opened. If the database is already opened
	// by another process, the unique lock cannot be obtained. With the
	// timeout we error out after the given time instead of just blocking
	// for forever.
	DefaultLoopDBTimeout = 5 * time.Second
)
View Source
const (
	// StateTypePending indicates that the swap is still pending.
	StateTypePending SwapStateType = 0

	// StateTypeSuccess indicates that the swap has completed successfully.
	StateTypeSuccess = 1

	// StateTypeFail indicates that the swap has failed.
	StateTypeFail = 2
)
View Source
const (
	PostgresTag = "11"
)

Variables

View Source
var (
	ErrLoopOutsNotEqual        = errors.New("loop outs not equal")
	ErrLoopInsNotEqual         = errors.New("loop ins not equal")
	ErrLiquidityParamsNotEqual = errors.New("liquidity params not equal")
)
View Source
var (
	// DefaultPostgresFixtureLifetime is the default maximum time a Postgres
	// test fixture is being kept alive. After that time the docker
	// container will be terminated forcefully, even if the tests aren't
	// fully executed yet. So this time needs to be chosen correctly to be
	// longer than the longest expected individual test run time.
	DefaultPostgresFixtureLifetime = 10 * time.Minute
)
View Source
var (

	// ErrDBReversion is returned when detecting an attempt to revert to a
	// prior database version.
	ErrDBReversion = fmt.Errorf("channel db cannot revert to prior version")
)

Functions

func CurrentRPCProtocolVersion

func CurrentRPCProtocolVersion() swapserverrpc.ProtocolVersion

CurrentRPCProtocolVersion returns the RPC protocol version selected to be used for new swaps.

func EnableExperimentalProtocol

func EnableExperimentalProtocol()

EnableExperimentalProtocol sets the current protocol version to include all experimental features. Do not call this function directly: used in loopd and unit tests only.

func MapSQLError

func MapSQLError(err error) error

MapSQLError attempts to interpret a given error as a database agnostic SQL error.

func MarshalKeyLocator

func MarshalKeyLocator(keyLocator keychain.KeyLocator) ([]byte, error)

MarshalKeyLocator marshals a keychain.KeyLocator to a byte slice.

func MarshalProtocolVersion

func MarshalProtocolVersion(version ProtocolVersion) []byte

MarshalProtocolVersion marshals a ProtocolVersion value to a byte slice.

func NewBoltSwapStore

func NewBoltSwapStore(dbPath string, chainParams *chaincfg.Params) (
	*boltSwapStore, error)

NewBoltSwapStore creates a new client swap store.

func NewMigrationError

func NewMigrationError(err error) *migrationError

func ResetCurrentProtocolVersion

func ResetCurrentProtocolVersion()

ResetCurrentProtocolVersion resets the current protocol version to the stable protocol. Note: used in integration tests only!

func UnmarshalKeyLocator

func UnmarshalKeyLocator(data []byte) (keychain.KeyLocator, error)

UnmarshalKeyLocator unmarshals a keychain.KeyLocator from a byte slice.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

Types

type BaseDB

type BaseDB struct {
	*sql.DB

	*sqlc.Queries
	// contains filtered or unexported fields
}

BaseDB is the base database struct that each implementation can embed to gain some common functionality.

func (*BaseDB) BatchCreateLoopIn

func (db *BaseDB) BatchCreateLoopIn(ctx context.Context,
	swaps map[lntypes.Hash]*LoopInContract) error

BatchCreateLoopIn adds multiple initiated swaps to the store.

func (*BaseDB) BatchCreateLoopOut

func (db *BaseDB) BatchCreateLoopOut(ctx context.Context,
	swaps map[lntypes.Hash]*LoopOutContract) error

BatchCreateLoopOut adds multiple initiated swaps to the store.

func (*BaseDB) BatchInsertUpdate

func (db *BaseDB) BatchInsertUpdate(ctx context.Context,
	updateData map[lntypes.Hash][]BatchInsertUpdateData) error

BatchInsertUpdate inserts multiple swap updates to the store.

func (*BaseDB) BatchUpdateLoopOutSwapCosts

func (db *BaseDB) BatchUpdateLoopOutSwapCosts(ctx context.Context,
	costs map[lntypes.Hash]SwapCost) error

BatchUpdateLoopOutSwapCosts updates the swap costs for a batch of loop out swaps.

func (*BaseDB) BeginTx

func (db *BaseDB) BeginTx(ctx context.Context,
	opts TxOptions) (*sql.Tx, error)

BeginTx wraps the normal sql specific BeginTx method with the TxOptions interface. This interface is then mapped to the concrete sql tx options struct.

func (*BaseDB) CreateLoopIn

func (db *BaseDB) CreateLoopIn(ctx context.Context, hash lntypes.Hash,
	swap *LoopInContract) error

CreateLoopIn adds an initiated swap to the store.

func (*BaseDB) CreateLoopOut

func (db *BaseDB) CreateLoopOut(ctx context.Context, hash lntypes.Hash,
	swap *LoopOutContract) error

CreateLoopOut adds an initiated swap to the store.

func (*BaseDB) ExecTx

func (db *BaseDB) ExecTx(ctx context.Context, txOptions TxOptions,
	txBody func(*sqlc.Queries) error) error

ExecTx is a wrapper for txBody to abstract the creation and commit of a db transaction. The db transaction is embedded in a `*sqlc.Queries` that txBody needs to use when executing each one of the queries that need to be applied atomically.

func (*BaseDB) FetchLiquidityParams

func (db *BaseDB) FetchLiquidityParams(ctx context.Context) ([]byte,
	error)

FetchLiquidityParams reads the serialized `manager.Parameters` bytes from the bucket.

NOTE: it's the caller's responsibility to decode the param. Atm, it's decoding using the proto package's `Unmarshal` method.

func (*BaseDB) FetchLoopInSwaps

func (db *BaseDB) FetchLoopInSwaps(ctx context.Context) (
	[]*LoopIn, error)

FetchLoopInSwaps returns all swaps currently in the store.

func (*BaseDB) FetchLoopOutSwap

func (db *BaseDB) FetchLoopOutSwap(ctx context.Context,
	hash lntypes.Hash) (*LoopOut, error)

FetchLoopOutSwap returns the loop out swap with the given hash.

func (*BaseDB) FetchLoopOutSwaps

func (db *BaseDB) FetchLoopOutSwaps(ctx context.Context) ([]*LoopOut,
	error)

FetchLoopOutSwaps returns all swaps currently in the store.

func (*BaseDB) FixFaultyTimestamps

func (db *BaseDB) FixFaultyTimestamps(ctx context.Context) error

FixFaultyTimestamps fixes faulty timestamps in the database, caused by using milliseconds instead of seconds as the publication deadline.

func (*BaseDB) GetNetwork

func (db *BaseDB) GetNetwork() *chaincfg.Params

GetNetwork returns the network(mainnet, testnet...) that the database is running on.

func (*BaseDB) HasMigration

func (db *BaseDB) HasMigration(ctx context.Context, migrationID string) (
	bool, error)

HasMigration returns true if the migration with the given ID has been done.

func (*BaseDB) PutLiquidityParams

func (db *BaseDB) PutLiquidityParams(ctx context.Context,
	params []byte) error

PutLiquidityParams writes the serialized `manager.Parameters` bytes into the bucket.

NOTE: it's the caller's responsibility to encode the param. Atm, it's encoding using the proto package's `Marshal` method.

func (*BaseDB) SetMigration

func (db *BaseDB) SetMigration(ctx context.Context, migrationID string) error

SetMigration marks the migration with the given ID as done.

func (*BaseDB) UpdateLoopIn

func (db *BaseDB) UpdateLoopIn(ctx context.Context, hash lntypes.Hash,
	time time.Time, state SwapStateData) error

UpdateLoopIn stores a new event for a target loop in swap. This appends to the event log for a particular swap as it goes through the various stages in its lifetime.

func (*BaseDB) UpdateLoopOut

func (db *BaseDB) UpdateLoopOut(ctx context.Context, hash lntypes.Hash,
	time time.Time, state SwapStateData) error

UpdateLoopOut stores a new event for a target loop out swap. This appends to the event log for a particular swap as it goes through the various stages in its lifetime.

type BatchInsertUpdateData

type BatchInsertUpdateData struct {
	Time  time.Time
	State SwapStateData
}

BatchInsertUpdateData is a struct that holds the data for the BatchInsertUpdate function.

type BatchedQuerier

type BatchedQuerier interface {
	sqlc.Querier

	// ExecTx is a wrapper for txBody to abstract the creation and commit of
	// a db transaction. The db transaction is embedded in a `*sqlc.Queries`
	// that txBody needs to use when executing each one of the queries that
	// need to be applied atomically.
	ExecTx(ctx context.Context, txOptions TxOptions,
		txBody func(*sqlc.Queries) error) error
}

BatchedQuerier implements all DB queries and ExecTx on *sqlc.Queries. It is implemented by BaseDB, SqliteSwapStore, etc.

type ChannelSet

type ChannelSet []uint64

ChannelSet stores a set of channels.

func ConvertOutgoingChanSet

func ConvertOutgoingChanSet(outgoingChanSet string) (ChannelSet, error)

ConvertOutgoingChanSet converts a comma separated string of channel IDs into a ChannelSet.

func NewChannelSet

func NewChannelSet(set []uint64) (ChannelSet, error)

NewChannelSet instantiates a new channel set and verifies that there are no duplicates present.

func (ChannelSet) String

func (c ChannelSet) String() string

String returns the human-readable representation of a channel set.

type ErrSqlUniqueConstraintViolation

type ErrSqlUniqueConstraintViolation struct {
	DbError error
}

ErrSqlUniqueConstraintViolation is an error type which represents a database agnostic SQL unique constraint violation.

func (ErrSqlUniqueConstraintViolation) Error

type HtlcKeys

type HtlcKeys struct {
	// SenderScriptKey is the sender's public key that is used in the HTLC,
	// specifically when constructing the script spend scripts.
	SenderScriptKey [33]byte

	// SenderInternalPubKey is the sender's internal pubkey that is used in
	// taproot HTLCs as part of the aggregate internal key.
	SenderInternalPubKey [33]byte

	// ReceiverScriptKey is the receiver's public key that is used in the
	// HTLC, specifically when constructing the script spend scripts.
	ReceiverScriptKey [33]byte

	// ReceiverInternalPubKey is the sender's internal pubkey that is used
	// in taproot HTLCs as part of the aggregate internal key.
	ReceiverInternalPubKey [33]byte

	// ClientScriptKeyLocator is the client's key locator for the key used
	// in the HTLC script spend scripts.
	ClientScriptKeyLocator keychain.KeyLocator
}

HtlcKeys is a holder of all keys used when constructing the swap HTLC. Since it's used for both loop in and loop out swaps it may hold partial information about the sender or receiver depending on the swap type.

type Loop

type Loop struct {
	Hash   lntypes.Hash
	Events []*LoopEvent
}

Loop contains fields shared between LoopIn and LoopOut.

func (*Loop) LastUpdate

func (s *Loop) LastUpdate() *LoopEvent

LastUpdate returns the most recent update of this swap.

func (*Loop) State

func (s *Loop) State() SwapStateData

State returns the most recent state of this swap.

type LoopEvent

type LoopEvent struct {
	SwapStateData

	// Time is the time that this swap had its state changed.
	Time time.Time
}

LoopEvent contains the dynamic data of a swap.

type LoopIn

type LoopIn struct {
	Loop

	Contract *LoopInContract
}

LoopIn is a combination of the contract and the updates.

func (*LoopIn) LastUpdateTime

func (s *LoopIn) LastUpdateTime() time.Time

LastUpdateTime returns the last update time of this swap.

type LoopInContract

type LoopInContract struct {
	SwapContract

	// SweepConfTarget specifies the targeted confirmation target for the
	// client sweep tx.
	HtlcConfTarget int32

	// LastHop is the last hop to use for the loop in swap (optional).
	LastHop *route.Vertex

	// ExternalHtlc specifies whether the htlc is published by an external
	// source.
	ExternalHtlc bool
}

LoopInContract contains the data that is serialized to persistent storage for pending loop in swaps.

type LoopOut

type LoopOut struct {
	Loop

	// Contract is the active contract for this swap. It describes the
	// precise details of the swap including the final fee, CLTV value,
	// etc.
	Contract *LoopOutContract
}

LoopOut is a combination of the contract and the updates.

func ConvertLoopOutRow

func ConvertLoopOutRow(network *chaincfg.Params, row sqlc.GetLoopOutSwapRow,
	updates []sqlc.SwapUpdate) (*LoopOut, error)

ConvertLoopOutRow converts a database row containing a loop out swap to a LoopOut struct.

func (*LoopOut) LastUpdateTime

func (s *LoopOut) LastUpdateTime() time.Time

LastUpdateTime returns the last update time of this swap.

type LoopOutContract

type LoopOutContract struct {
	// SwapContract contains basic information pertaining to this swap.
	// Each swap type has a base contract, then swap specific information
	// on top of it.
	SwapContract

	// DestAddr is the destination address of the loop out swap.
	DestAddr btcutil.Address

	// IsExternalAddr indicates whether the destination address does not
	// belong to the backing lnd node.
	IsExternalAddr bool

	// SwapInvoice is the invoice that is to be paid by the client to
	// initiate the loop out swap.
	SwapInvoice string

	// MaxSwapRoutingFee is the maximum off-chain fee in msat that may be
	// paid for the swap payment to the server.
	MaxSwapRoutingFee btcutil.Amount

	// SweepConfTarget specifies the targeted confirmation target for the
	// client sweep tx.
	SweepConfTarget int32

	// HtlcConfirmations is the number of confirmations we require the on
	// chain htlc to have before proceeding with the swap.
	HtlcConfirmations uint32

	// OutgoingChanSet is the set of short ids of channels that may be used.
	// If empty, any channel may be used.
	OutgoingChanSet ChannelSet

	// PrepayInvoice is the invoice that the client should pay to the
	// server that will be returned if the swap is complete.
	PrepayInvoice string

	// MaxPrepayRoutingFee is the maximum off-chain fee in msat that may be
	// paid for the prepayment to the server.
	MaxPrepayRoutingFee btcutil.Amount

	// SwapPublicationDeadline is a timestamp that the server commits to
	// have the on-chain swap published by. It is set by the client to
	// allow the server to delay the publication in exchange for possibly
	// lower fees.
	SwapPublicationDeadline time.Time

	// PaymentTimeout is the timeout for any individual off-chain payment
	// attempt.
	PaymentTimeout time.Duration
}

LoopOutContract contains the data that is serialized to persistent storage for pending swaps.

type MigratorManager

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

MigratorManager is a struct that handles migrating data from one SwapStore to another.

func NewMigratorManager

func NewMigratorManager(fromStore SwapStore,
	toStore SwapStore) *MigratorManager

NewMigratorManager creates a new MigratorManager.

func (*MigratorManager) RunMigrations

func (m *MigratorManager) RunMigrations(ctx context.Context) error

RunMigrations runs the migrations from the fromStore to the toStore.

type PostgresConfig

type PostgresConfig struct {
	SkipMigrations     bool   `long:"skipmigrations" description:"Skip applying migrations on startup."`
	Host               string `long:"host" description:"Database server hostname."`
	Port               int    `long:"port" description:"Database server port."`
	User               string `long:"user" description:"Database user."`
	Password           string `long:"password" description:"Database user's password."`
	DBName             string `long:"dbname" description:"Database name to use."`
	MaxOpenConnections int32  `long:"maxconnections" description:"Max open connections to keep alive to the database server."`
	RequireSSL         bool   `long:"requiressl" description:"Whether to require using SSL (mode: require) when connecting to the server."`
}

PostgresConfig holds the postgres database configuration.

func (*PostgresConfig) DSN

func (s *PostgresConfig) DSN(hidePassword bool) string

DSN returns the dns to connect to the database.

type PostgresStore

type PostgresStore struct {
	*BaseDB
	// contains filtered or unexported fields
}

PostgresStore is a database store implementation that uses a Postgres backend.

func NewPostgresStore

func NewPostgresStore(cfg *PostgresConfig,
	network *chaincfg.Params) (*PostgresStore, error)

NewPostgresStore creates a new store that is backed by a Postgres database backend.

func NewTestPostgresDB

func NewTestPostgresDB(t *testing.T) *PostgresStore

NewTestPostgresDB is a helper function that creates a Postgres database for testing.

type ProtocolVersion

type ProtocolVersion uint32

ProtocolVersion represents the protocol version (declared on rpc level) that the client declared to us.

const (
	// ProtocolVersionLegacy indicates that the client is a legacy version
	// that did not report its protocol version.
	ProtocolVersionLegacy ProtocolVersion = 0

	// ProtocolVersionMultiLoopOut indicates that the client supports multi
	// loop out.
	ProtocolVersionMultiLoopOut ProtocolVersion = 1

	// ProtocolVersionSegwitLoopIn indicates that the client supports segwit
	// loop in.
	ProtocolVersionSegwitLoopIn ProtocolVersion = 2

	// ProtocolVersionPreimagePush indicates that the client will push loop
	// out preimages to the sever to speed up claim.
	ProtocolVersionPreimagePush ProtocolVersion = 3

	// ProtocolVersionUserExpiryLoopOut indicates that the client will
	// propose a cltv expiry height for loop out.
	ProtocolVersionUserExpiryLoopOut ProtocolVersion = 4

	// ProtocolVersionHtlcV2 indicates that the client will use the new
	// HTLC v2 scripts for swaps.
	ProtocolVersionHtlcV2 ProtocolVersion = 5

	// ProtocolVersionMultiLoopIn indicates that the client creates a probe
	// invoice so that the server can perform a multi-path probe.
	ProtocolVersionMultiLoopIn ProtocolVersion = 6

	// ProtocolVersionLoopOutCancel indicates that the client supports
	// canceling loop out swaps.
	ProtocolVersionLoopOutCancel = 7

	// ProtocolVerionProbe indicates that the client is able to request
	// the server to perform a probe to test inbound liquidty.
	ProtocolVersionProbe ProtocolVersion = 8

	// The client may ask the server to use a custom routing helper plugin
	// in order to enhance off-chain payments corresponding to a swap.
	ProtocolVersionRoutingPlugin = 9

	// ProtocolVersionHtlcV3 indicates that the client will now use the new
	// HTLC v3 (P2TR) script for swaps.
	ProtocolVersionHtlcV3 = 10

	// ProtocolVersionMuSig2 will enable MuSig2 signature scheme for loops.
	ProtocolVersionMuSig2 ProtocolVersion = 11

	// ProtocolVersionUnrecorded is set for swaps were created before we
	// started saving protocol version with swaps.
	ProtocolVersionUnrecorded ProtocolVersion = math.MaxUint32
)

func CurrentProtocolVersion

func CurrentProtocolVersion() ProtocolVersion

CurrentProtocolVersion returns the internal protocol version selected to be used for new swaps.

func UnmarshalProtocolVersion

func UnmarshalProtocolVersion(b []byte) (ProtocolVersion, error)

UnmarshalProtocolVersion attempts to unmarshal a byte slice to a ProtocolVersion value. If the unmarshal fails, ProtocolVersionUnrecorded is returned along with an error.

func (ProtocolVersion) String

func (p ProtocolVersion) String() string

String returns the string representation of a protocol version.

func (ProtocolVersion) Valid

func (p ProtocolVersion) Valid() bool

Valid returns true if the value of the ProtocolVersion is valid.

type SqliteConfig

type SqliteConfig struct {
	// SkipMigrations if true, then all the tables will be created on start
	// up if they don't already exist.
	SkipMigrations bool `long:"skipmigrations" description:"Skip applying migrations on startup."`

	// DatabaseFileName is the full file path where the database file can be
	// found.
	DatabaseFileName string `long:"dbfile" description:"The full path to the database."`
}

SqliteConfig holds all the config arguments needed to interact with our sqlite DB.

type SqliteSwapStore

type SqliteSwapStore struct {
	*BaseDB
	// contains filtered or unexported fields
}

SqliteSwapStore is a sqlite3 based database for the loop daemon.

func NewSqliteStore

func NewSqliteStore(cfg *SqliteConfig, network *chaincfg.Params) (*SqliteSwapStore, error)

NewSqliteStore attempts to open a new sqlite database based on the passed config.

func NewTestDB

func NewTestDB(t *testing.T) *SqliteSwapStore

NewTestDB is a helper function that creates an SQLite database for testing.

func NewTestSqliteDB

func NewTestSqliteDB(t *testing.T) *SqliteSwapStore

NewTestSqliteDB is a helper function that creates an SQLite database for testing.

type SqliteTxOptions

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

SqliteTxOptions defines the set of db txn options the KeyStore understands.

func NewSqlReadOpts

func NewSqlReadOpts() *SqliteTxOptions

NewSqlReadOpts returns a new KeyStoreTxOptions instance that triggers a read transaction.

func NewSqlWriteOpts

func NewSqlWriteOpts() *SqliteTxOptions

NewSqlWriteOpts returns a new KeyStoreTxOptions instance that triggers a write (regular) transaction.

func (*SqliteTxOptions) ReadOnly

func (r *SqliteTxOptions) ReadOnly() bool

ReadOnly returns true if the transaction should be read only.

NOTE: This implements the TxOptions interface.

type StoreMock

type StoreMock struct {
	sync.RWMutex

	LoopOutSwaps   map[lntypes.Hash]*LoopOutContract
	LoopOutUpdates map[lntypes.Hash][]SwapStateData

	LoopInSwaps   map[lntypes.Hash]*LoopInContract
	LoopInUpdates map[lntypes.Hash][]SwapStateData
	// contains filtered or unexported fields
}

StoreMock implements a mock client swap store.

func NewStoreMock

func NewStoreMock(t *testing.T) *StoreMock

NewStoreMock instantiates a new mock store.

func (*StoreMock) AssertLoopInState

func (s *StoreMock) AssertLoopInState(
	expectedState SwapState) SwapStateData

assertLoopInState asserts that a specified state transition is persisted to disk.

func (*StoreMock) AssertLoopInStored

func (s *StoreMock) AssertLoopInStored()

AssertLoopInStored asserts that a loop-in swap is stored.

func (*StoreMock) AssertLoopOutState

func (s *StoreMock) AssertLoopOutState(expectedState SwapState)

AssertLoopOutState asserts that a specified state transition is persisted to disk.

func (*StoreMock) AssertLoopOutStored

func (s *StoreMock) AssertLoopOutStored()

AssertLoopOutStored asserts that a swap is stored.

func (*StoreMock) AssertStoreFinished

func (s *StoreMock) AssertStoreFinished(expectedResult SwapState)

AssertStoreFinished asserts that a swap is marked as finished.

func (*StoreMock) AssertStorePreimageReveal

func (s *StoreMock) AssertStorePreimageReveal()

AssertStorePreimageReveal asserts that a swap is marked as preimage revealed.

func (*StoreMock) BatchCreateLoopIn

func (b *StoreMock) BatchCreateLoopIn(ctx context.Context,
	swaps map[lntypes.Hash]*LoopInContract) error

BatchCreateLoopIn creates many loop in swaps in a batch.

func (*StoreMock) BatchCreateLoopOut

func (b *StoreMock) BatchCreateLoopOut(ctx context.Context,
	swaps map[lntypes.Hash]*LoopOutContract) error

BatchCreateLoopOut creates many loop out swaps in a batch.

func (*StoreMock) BatchInsertUpdate

func (b *StoreMock) BatchInsertUpdate(ctx context.Context,
	updateData map[lntypes.Hash][]BatchInsertUpdateData) error

BatchInsertUpdate inserts many updates for a swap in a batch.

func (*StoreMock) BatchUpdateLoopOutSwapCosts

func (s *StoreMock) BatchUpdateLoopOutSwapCosts(ctx context.Context,
	costs map[lntypes.Hash]SwapCost) error

BatchUpdateLoopOutSwapCosts updates the swap costs for a batch of loop out swaps.

func (*StoreMock) Close

func (s *StoreMock) Close() error

Close closes the store.

func (*StoreMock) CreateLoopIn

func (s *StoreMock) CreateLoopIn(ctx context.Context, hash lntypes.Hash,
	swap *LoopInContract) error

CreateLoopIn adds an initiated loop in swap to the store.

NOTE: Part of the SwapStore interface.

func (*StoreMock) CreateLoopOut

func (s *StoreMock) CreateLoopOut(ctx context.Context, hash lntypes.Hash,
	swap *LoopOutContract) error

CreateLoopOut adds an initiated swap to the store.

NOTE: Part of the SwapStore interface.

func (*StoreMock) FetchLiquidityParams

func (s *StoreMock) FetchLiquidityParams(ctx context.Context) ([]byte, error)

FetchLiquidityParams reads the serialized `manager.Parameters` bytes from the bucket.

NOTE: Part of the SwapStore interface.

func (*StoreMock) FetchLoopInSwaps

func (s *StoreMock) FetchLoopInSwaps(ctx context.Context) ([]*LoopIn,
	error)

FetchLoopInSwaps returns all in swaps currently in the store.

func (*StoreMock) FetchLoopOutSwap

func (s *StoreMock) FetchLoopOutSwap(ctx context.Context,
	hash lntypes.Hash) (*LoopOut, error)

FetchLoopOutSwaps returns all swaps currently in the store.

NOTE: Part of the SwapStore interface.

func (*StoreMock) FetchLoopOutSwaps

func (s *StoreMock) FetchLoopOutSwaps(ctx context.Context) ([]*LoopOut, error)

FetchLoopOutSwaps returns all swaps currently in the store.

NOTE: Part of the SwapStore interface.

func (*StoreMock) HasMigration

func (s *StoreMock) HasMigration(ctx context.Context, migrationID string) (
	bool, error)

HasMigration returns true if the migration with the given ID has been done.

func (*StoreMock) IsDone

func (s *StoreMock) IsDone() error

isDone asserts that the store mock has no pending operations.

func (*StoreMock) PutLiquidityParams

func (s *StoreMock) PutLiquidityParams(ctx context.Context,
	params []byte) error

PutLiquidityParams writes the serialized `manager.Parameters` bytes into the bucket.

NOTE: Part of the SwapStore interface.

func (*StoreMock) SetMigration

func (s *StoreMock) SetMigration(ctx context.Context,
	migrationID string) error

SetMigration marks the migration with the given ID as done.

func (*StoreMock) UpdateLoopIn

func (s *StoreMock) UpdateLoopIn(ctx context.Context, hash lntypes.Hash,
	time time.Time, state SwapStateData) error

UpdateLoopIn stores a new event for a target loop in swap. This appends to the event log for a particular swap as it goes through the various stages in its lifetime.

NOTE: Part of the SwapStore interface.

func (*StoreMock) UpdateLoopOut

func (s *StoreMock) UpdateLoopOut(ctx context.Context, hash lntypes.Hash,
	time time.Time, state SwapStateData) error

UpdateLoopOut stores a new event for a target loop out swap. This appends to the event log for a particular swap as it goes through the various stages in its lifetime.

NOTE: Part of the SwapStore interface.

type SwapContract

type SwapContract struct {
	// Preimage is the preimage for the swap.
	Preimage lntypes.Preimage

	// AmountRequested is the total amount of the swap.
	AmountRequested btcutil.Amount

	// HtlcKeys holds all keys used in the swap HTLC construction.
	HtlcKeys HtlcKeys

	// CltvExpiry is the total absolute CLTV expiry of the swap.
	CltvExpiry int32

	// MaxSwapFee is the maximum we are willing to pay the server for the
	// swap.
	MaxSwapFee btcutil.Amount

	// MaxMinerFee is the maximum in on-chain fees that we are willing to
	// spend.
	MaxMinerFee btcutil.Amount

	// InitiationHeight is the block height at which the swap was
	// initiated.
	InitiationHeight int32

	// InitiationTime is the time at which the swap was initiated.
	InitiationTime time.Time

	// Label contains an optional label for the swap.
	Label string

	// ProtocolVersion stores the protocol version when the swap was
	// created.
	ProtocolVersion ProtocolVersion
}

SwapContract contains the base data that is serialized to persistent storage for pending swaps.

type SwapCost

type SwapCost struct {
	// Swap is the amount paid to the server.
	Server btcutil.Amount

	// Onchain is the amount paid to miners for the onchain tx.
	Onchain btcutil.Amount

	// Offchain is the amount paid in routing fees.
	Offchain btcutil.Amount
}

SwapCost is a breakdown of the final swap costs.

func (SwapCost) Total

func (s SwapCost) Total() btcutil.Amount

Total returns the total costs represented by swap costs.

type SwapState

type SwapState uint8

SwapState indicates the current state of a swap. This enumeration is the union of loop in and loop out states. A single type is used for both swap types to be able to reduce code duplication that would otherwise be required.

const (
	// StateInitiated is the initial state of a swap. At that point, the
	// initiation call to the server has been made and the payment process
	// has been started for the swap and prepayment invoices.
	StateInitiated SwapState = 0

	// StatePreimageRevealed is reached when the sweep tx publication is
	// first attempted. From that point on, we should consider the preimage
	// to no longer be secret and we need to do all we can to get the sweep
	// confirmed. This state will mostly coalesce with StateHtlcConfirmed,
	// except in the case where we wait for fees to come down before we
	// sweep.
	StatePreimageRevealed SwapState = 1

	// StateSuccess is the final swap state that is reached when the sweep
	// tx has the required confirmation depth (SweepConfDepth) and the
	// server pulled the off-chain htlc.
	StateSuccess SwapState = 2

	// StateFailOffchainPayments indicates that it wasn't possible to find
	// routes for one or both of the off-chain payments to the server that
	// satisfied the payment restrictions (fee and timelock limits).
	StateFailOffchainPayments SwapState = 3

	// StateFailTimeout indicates that the on-chain htlc wasn't confirmed
	// before its expiry or confirmed too late (MinPreimageRevealDelta
	// violated).
	StateFailTimeout SwapState = 4

	// StateFailSweepTimeout indicates that the on-chain htlc wasn't swept
	// before the server revoked the htlc. The server didn't pull the
	// off-chain htlc (even though it could have) and we timed out the
	// off-chain htlc ourselves. No funds lost.
	StateFailSweepTimeout SwapState = 5

	// StateFailInsufficientValue indicates that the published on-chain htlc
	// had a value lower than the requested amount.
	StateFailInsufficientValue SwapState = 6

	// StateFailTemporary indicates that the swap cannot progress because
	// of an internal error. This is not a final state. Manual intervention
	// (like a restart) is required to solve this problem.
	StateFailTemporary SwapState = 7

	// StateHtlcPublished means that the client published the on-chain htlc.
	StateHtlcPublished SwapState = 8

	// StateInvoiceSettled means that the swap invoice has been paid by the
	// server.
	StateInvoiceSettled SwapState = 9

	// StateFailIncorrectHtlcAmt indicates that the amount of an externally
	// published loop in htlc didn't match the swap amount.
	StateFailIncorrectHtlcAmt SwapState = 10

	// StateFailAbandoned indicates that a swap has been abandoned. Its
	// execution has been canceled. It won't further be processed.
	StateFailAbandoned SwapState = 11

	// StateFailInsufficientConfirmedBalance indicates that the swap wasn't
	// published due to insufficient confirmed balance.
	StateFailInsufficientConfirmedBalance SwapState = 12

	// StateFailIncorrectHtlcAmtSwept indicates that the amount of an
	// externally published loop in htlc that didn't match the swap amount
	// has been swept back to the user after the htlc timeout period.
	StateFailIncorrectHtlcAmtSwept SwapState = 13
)

func (SwapState) IsFinal

func (s SwapState) IsFinal() bool

IsFinal returns true if the swap is in a final state.

func (SwapState) IsPending

func (s SwapState) IsPending() bool

IsPending returns true if the swap is in a pending state.

func (SwapState) String

func (s SwapState) String() string

String returns a string representation of the swap's state.

func (SwapState) Type

func (s SwapState) Type() SwapStateType

Type returns the type of the SwapState it is called on.

type SwapStateData

type SwapStateData struct {
	// SwapState is the state the swap is in.
	State SwapState

	// Cost are the accrued (final) costs so far.
	Cost SwapCost

	// HtlcTxHash is the tx id of the confirmed htlc.
	HtlcTxHash *chainhash.Hash
}

SwapStateData is all persistent data to describe the current swap state.

type SwapStateType

type SwapStateType uint8

SwapStateType defines the types of swap states that exist. Every swap state defined as type SwapState above, falls into one of these SwapStateType categories.

type SwapStore

type SwapStore interface {
	// FetchLoopOutSwaps returns all swaps currently in the store.
	FetchLoopOutSwaps(ctx context.Context) ([]*LoopOut, error)

	// FetchLoopOutSwap returns the loop out swap with the given hash.
	FetchLoopOutSwap(ctx context.Context, hash lntypes.Hash) (*LoopOut, error)

	// CreateLoopOut adds an initiated swap to the store.
	CreateLoopOut(ctx context.Context, hash lntypes.Hash,
		swap *LoopOutContract) error

	// BatchCreateLoopOut creates a batch of loop out swaps to the store.
	BatchCreateLoopOut(ctx context.Context,
		swaps map[lntypes.Hash]*LoopOutContract) error

	// UpdateLoopOut stores a new event for a target loop out swap. This
	// appends to the event log for a particular swap as it goes through
	// the various stages in its lifetime.
	UpdateLoopOut(ctx context.Context, hash lntypes.Hash, time time.Time,
		state SwapStateData) error

	// FetchLoopInSwaps returns all swaps currently in the store.
	FetchLoopInSwaps(ctx context.Context) ([]*LoopIn, error)

	// CreateLoopIn adds an initiated swap to the store.
	CreateLoopIn(ctx context.Context, hash lntypes.Hash,
		swap *LoopInContract) error

	// BatchCreateLoopIn creates a batch of loop in swaps to the store.
	BatchCreateLoopIn(ctx context.Context,
		swaps map[lntypes.Hash]*LoopInContract) error

	// UpdateLoopIn stores a new event for a target loop in swap. This
	// appends to the event log for a particular swap as it goes through
	// the various stages in its lifetime.
	UpdateLoopIn(ctx context.Context, hash lntypes.Hash, time time.Time,
		state SwapStateData) error

	// BatchInsertUpdate inserts batch of swap updates to the store.
	BatchInsertUpdate(ctx context.Context,
		updateData map[lntypes.Hash][]BatchInsertUpdateData) error

	// PutLiquidityParams writes the serialized `manager.Parameters` bytes
	// into the bucket.
	//
	// NOTE: it's the caller's responsibility to encode the param. Atm,
	// it's encoding using the proto package's `Marshal` method.
	PutLiquidityParams(ctx context.Context, params []byte) error

	// FetchLiquidityParams reads the serialized `manager.Parameters` bytes
	// from the bucket.
	//
	// NOTE: it's the caller's responsibility to decode the param. Atm,
	// it's decoding using the proto package's `Unmarshal` method.
	FetchLiquidityParams(ctx context.Context) ([]byte, error)

	// BatchUpdateLoopOutSwapCosts updates the swap costs for a batch of
	// loop out swaps.
	BatchUpdateLoopOutSwapCosts(ctx context.Context,
		swaps map[lntypes.Hash]SwapCost) error

	// HasMigration returns true if the migration with the given ID has
	// been done.
	HasMigration(ctx context.Context, migrationID string) (bool, error)

	// SetMigration marks the migration with the given ID as done.
	SetMigration(ctx context.Context, migrationID string) error

	// Close closes the underlying database.
	Close() error
}

SwapStore is the primary database interface used by the loopd system. It houses information for all pending completed/failed swaps.

type TestPgFixture

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

TestPgFixture is a test fixture that starts a Postgres 11 instance in a docker container.

func NewTestPgFixture

func NewTestPgFixture(t *testing.T, expiry time.Duration) *TestPgFixture

NewTestPgFixture constructs a new TestPgFixture starting up a docker container running Postgres 11. The started container will expire in after the passed duration.

func (*TestPgFixture) ClearDB

func (f *TestPgFixture) ClearDB(t *testing.T)

ClearDB clears the database.

func (*TestPgFixture) GetConfig

func (f *TestPgFixture) GetConfig() *PostgresConfig

GetConfig returns the full config of the Postgres node.

func (*TestPgFixture) GetDSN

func (f *TestPgFixture) GetDSN() string

GetDSN returns the DSN (Data Source Name) for the started Postgres node.

func (*TestPgFixture) TearDown

func (f *TestPgFixture) TearDown(t *testing.T)

TearDown stops the underlying docker container.

type TxOptions

type TxOptions interface {
	// ReadOnly returns true if the transaction should be read only.
	ReadOnly() bool
}

TxOptions represents a set of options one can use to control what type of database transaction is created. Transaction can whether be read or write.

type TypedStore

type TypedStore[Q any] struct {
	BatchedQuerier
}

TypedStore is similar to BaseDB but provides parameterized ExecTx. It is used in other packages expecting ExecTx operating on subset of methods.

func NewTypedStore

func NewTypedStore[Q any](db BatchedQuerier) *TypedStore[Q]

NewTypedStore wraps a db, replacing generic ExecTx method with the typed one.

func (*TypedStore[Q]) ExecTx

func (s *TypedStore[Q]) ExecTx(ctx context.Context,
	txOptions TxOptions, txBody func(Q) error) error

ExecTx will execute the passed txBody, operating upon generic parameter Q (usually a storage interface) in a single transaction. The set of TxOptions are passed in to allow the caller to specify if a transaction is read-only.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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