sweepbatcher

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: 37 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Open is the state in which the batch is able to accept new sweeps.
	Open batchState = 0

	// Closed is the state in which the batch is no longer able to accept
	// new sweeps.
	Closed batchState = 1

	// Confirmed is the state in which the batch transaction has reached the
	// configured conf height.
	Confirmed batchState = 2
)
View Source
const (

	// MaxSweepsPerBatch is the maximum number of sweeps in a single batch.
	// It is needed to prevent sweep tx from becoming non-standard. Max
	// standard transaction is 400k wu, a non-cooperative input is 393 wu.
	MaxSweepsPerBatch = 1000
)

Variables

View Source
var (
	ErrBatchShuttingDown = errors.New("batch shutting down")
)
View Source
var (
	ErrBatcherShuttingDown = errors.New("batcher shutting down")
)

Functions

func NewBatch

func NewBatch(cfg batchConfig, bk batchKit) *batch

NewBatch creates a new batch.

func NewBatchFromDB

func NewBatchFromDB(cfg batchConfig, bk batchKit) (*batch, error)

NewBatchFromDB creates a new batch that already existed in storage.

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 interface {
	Querier

	// ExecTx allows for executing a function in the context of a database
	// transaction.
	ExecTx(ctx context.Context, txOptions loopdb.TxOptions,
		txBody func(Querier) error) error
}

BaseDB is the interface that contains all the queries generated by sqlc for sweep batcher and transaction functionality.

type Batcher

type Batcher struct {

	// VerifySchnorrSig is a function that can be used to verify a schnorr
	// signature.
	VerifySchnorrSig VerifySchnorrSig
	// contains filtered or unexported fields
}

Batcher is a system that is responsible for accepting sweep requests and placing them in appropriate batches. It will spin up new batches as needed.

func NewBatcher

func NewBatcher(wallet lndclient.WalletKitClient,
	chainNotifier lndclient.ChainNotifierClient,
	signerClient lndclient.SignerClient, musig2ServerSigner MuSig2SignSweep,
	verifySchnorrSig VerifySchnorrSig, chainparams *chaincfg.Params,
	store BatcherStore, sweepStore SweepFetcher,
	opts ...BatcherOption) *Batcher

NewBatcher creates a new Batcher instance.

func (*Batcher) AddSweep

func (b *Batcher) AddSweep(sweepReq *SweepRequest) error

AddSweep adds a sweep request to the batcher for handling. This will either place the sweep in an existing batch or create a new one.

func (*Batcher) FetchUnconfirmedBatches

func (b *Batcher) FetchUnconfirmedBatches(ctx context.Context) ([]*batch,
	error)

FetchUnconfirmedBatches fetches all the batches from the database that are not in a confirmed state.

func (*Batcher) Run

func (b *Batcher) Run(ctx context.Context) error

Run starts the batcher and processes incoming sweep requests.

type BatcherConfig

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

BatcherConfig holds batcher configuration.

type BatcherOption

type BatcherOption func(*BatcherConfig)

BatcherOption configures batcher behaviour.

func WithClock

func WithClock(clock clock.Clock) BatcherOption

WithClock sets the clock used by sweepbatcher and its batches. It is needed to manipulate time in tests.

func WithCustomFeeRate

func WithCustomFeeRate(customFeeRate FeeRateProvider) BatcherOption

WithCustomFeeRate instructs sweepbatcher not to fee bump itself and rely on external source of fee rates (FeeRateProvider). To apply a fee rate change, the caller should re-add the sweep by calling AddSweep.

func WithCustomSignMuSig2

func WithCustomSignMuSig2(customMuSig2Signer SignMuSig2) BatcherOption

WithCustomSignMuSig2 instructs sweepbatcher to use a custom function to produce MuSig2 signatures. If it is set, it is used to create musig2 signatures instead of musig2SignSweep and signerClient. Note that musig2SignSweep must be nil in this case, however signerClient must still be provided, as it is used for non-coop spendings.

func WithInitialDelay

func WithInitialDelay(initialDelay time.Duration) BatcherOption

WithInitialDelay instructs sweepbatcher to wait for the duration provided after new batch creation before it is first published. This facilitates better grouping. Defaults to 0s (no initial delay). If a sweep is about to expire (time until timeout is less that 2x initialDelay), then waiting is skipped.

func WithMixedBatch

func WithMixedBatch() BatcherOption

WithMixedBatch instructs sweepbatcher to create mixed batches with regard to cooperativeness. Such a batch can include both sweeps signed both cooperatively and non-cooperatively. If cooperative signing fails for a sweep, transaction is updated to sign that sweep non-cooperatively and another round of cooperative signing runs on the remaining sweeps. The remaining sweeps are signed in non-cooperative (more expensive) way. If the whole procedure fails for whatever reason, the batch is signed non-cooperatively (the fallback).

func WithPublishDelay

func WithPublishDelay(publishDelay time.Duration) BatcherOption

WithPublishDelay sets the delay of batch publishing that is applied in the beginning, after the appearance of a new block in the network or after the end of initial delay (see WithInitialDelay). It is needed to prevent unnecessary transaction publishments when a spend is detected on that block. Default value depends on the network: 5 seconds in mainnet, 0.5s in testnet. For batches recovered from DB this value is always 0s.

func WithPublishErrorHandler

func WithPublishErrorHandler(handler PublishErrorHandler) BatcherOption

WithPublishErrorHandler sets the callback used to handle publish errors. It can be used to filter out noisy messages.

func WithTxLabeler

func WithTxLabeler(txLabeler func(batchID int32) string) BatcherOption

WithTxLabeler sets a function generating a transaction label. It is called before publishing a batch transaction. Batch ID is passed to the function. By default, loop/labels.LoopOutBatchSweepSuccess is used.

type BatcherStore

type BatcherStore interface {
	// FetchUnconfirmedSweepBatches fetches all the batches from the
	// database that are not in a confirmed state.
	FetchUnconfirmedSweepBatches(ctx context.Context) ([]*dbBatch, error)

	// InsertSweepBatch inserts a batch into the database, returning the id
	// of the inserted batch.
	InsertSweepBatch(ctx context.Context, batch *dbBatch) (int32, error)

	// DropBatch drops a batch from the database. This should only be used
	// when a batch is empty.
	DropBatch(ctx context.Context, id int32) error

	// UpdateSweepBatch updates a batch in the database.
	UpdateSweepBatch(ctx context.Context, batch *dbBatch) error

	// ConfirmBatch confirms a batch by setting its state to confirmed.
	ConfirmBatch(ctx context.Context, id int32) error

	// FetchBatchSweeps fetches all the sweeps that belong to a batch.
	FetchBatchSweeps(ctx context.Context, id int32) ([]*dbSweep, error)

	// UpsertSweep inserts a sweep into the database, or updates an existing
	// sweep if it already exists.
	UpsertSweep(ctx context.Context, sweep *dbSweep) error

	// GetSweepStatus returns the completed status of the sweep.
	GetSweepStatus(ctx context.Context, swapHash lntypes.Hash) (bool, error)

	// GetParentBatch returns the parent batch of a (completed) sweep.
	GetParentBatch(ctx context.Context, swapHash lntypes.Hash) (*dbBatch,
		error)

	// TotalSweptAmount returns the total amount swept by a (confirmed)
	// batch.
	TotalSweptAmount(ctx context.Context, id int32) (btcutil.Amount, error)
}

type FeeRateProvider

type FeeRateProvider func(ctx context.Context,
	swapHash lntypes.Hash) (chainfee.SatPerKWeight, error)

FeeRateProvider is a function that returns min fee rate of a batch sweeping the UTXO of the swap.

type LoopOutFetcher

type LoopOutFetcher interface {
	// FetchLoopOutSwap returns the loop out swap with the given hash.
	FetchLoopOutSwap(ctx context.Context,
		hash lntypes.Hash) (*loopdb.LoopOut, error)
}

LoopOutFetcher is used to load LoopOut swaps from the database. It is implemented by loopdb.SwapStore.

type MuSig2SignSweep

type MuSig2SignSweep func(ctx context.Context,
	protocolVersion loopdb.ProtocolVersion, swapHash lntypes.Hash,
	paymentAddr [32]byte, nonce []byte, sweepTxPsbt []byte,
	prevoutMap map[wire.OutPoint]*wire.TxOut) (
	[]byte, []byte, error)

MuSig2SignSweep is a function that can be used to sign a sweep transaction cooperatively with the swap server.

type PublishErrorHandler

type PublishErrorHandler func(err error, errMsg string, log btclog.Logger)

PublishErrorHandler is a function that handles transaction publishing error.

type Purger

type Purger func(sweepReq *SweepRequest) error

Purger is a function that takes a sweep request and feeds it back to the batcher main entry point. The name is inspired by its purpose, which is to purge the batch from sweeps that didn't make it to the confirmed tx.

type Querier

type Querier interface {
	// ConfirmBatch confirms a batch by setting the state to confirmed.
	ConfirmBatch(ctx context.Context, id int32) error

	// GetBatchSweeps fetches all the sweeps that are part a batch.
	GetBatchSweeps(ctx context.Context, batchID int32) (
		[]sqlc.Sweep, error)

	// GetBatchSweptAmount returns the total amount of sats swept by a
	// (confirmed) batch.
	GetBatchSweptAmount(ctx context.Context, batchID int32) (int64, error)

	// GetSweepStatus returns true if the sweep has been completed.
	GetSweepStatus(ctx context.Context, swapHash []byte) (bool, error)

	// GetParentBatch fetches the parent batch of a completed sweep.
	GetParentBatch(ctx context.Context, swapHash []byte) (sqlc.SweepBatch,
		error)

	// GetUnconfirmedBatches fetches all the batches from the
	// database that are not in a confirmed state.
	GetUnconfirmedBatches(ctx context.Context) ([]sqlc.SweepBatch, error)

	// InsertBatch inserts a batch into the database, returning the id of
	// the inserted batch.
	InsertBatch(ctx context.Context, arg sqlc.InsertBatchParams) (
		int32, error)

	// DropBatch drops a batch from the database.
	DropBatch(ctx context.Context, id int32) error

	// UpdateBatch updates a batch in the database.
	UpdateBatch(ctx context.Context, arg sqlc.UpdateBatchParams) error

	// UpsertSweep inserts a sweep into the database, or updates an existing
	// sweep if it already exists.
	UpsertSweep(ctx context.Context, arg sqlc.UpsertSweepParams) error
}

Querier is the interface that contains all the queries generated by sqlc for sweep batcher.

type SQLStore

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

SQLStore manages the reservations in the database.

func NewSQLStore

func NewSQLStore(db BaseDB, network *chaincfg.Params) *SQLStore

NewSQLStore creates a new SQLStore.

func (*SQLStore) ConfirmBatch

func (s *SQLStore) ConfirmBatch(ctx context.Context, id int32) error

ConfirmBatch confirms a batch by setting the state to confirmed.

func (*SQLStore) DropBatch

func (s *SQLStore) DropBatch(ctx context.Context, id int32) error

DropBatch drops a batch from the database. Note that we only use this call for batches that have no sweeps and so we'd not be able to resume.

func (*SQLStore) FetchBatchSweeps

func (s *SQLStore) FetchBatchSweeps(ctx context.Context, id int32) (
	[]*dbSweep, error)

FetchBatchSweeps fetches all the sweeps that are part a batch.

func (*SQLStore) FetchUnconfirmedSweepBatches

func (s *SQLStore) FetchUnconfirmedSweepBatches(ctx context.Context) (
	[]*dbBatch, error)

FetchUnconfirmedSweepBatches fetches all the batches from the database that are not in a confirmed state.

func (*SQLStore) GetParentBatch

func (s *SQLStore) GetParentBatch(ctx context.Context, swapHash lntypes.Hash) (
	*dbBatch, error)

GetParentBatch fetches the parent batch of a completed sweep.

func (*SQLStore) GetSweepStatus

func (s *SQLStore) GetSweepStatus(ctx context.Context, swapHash lntypes.Hash) (
	bool, error)

GetSweepStatus returns true if the sweep has been completed.

func (*SQLStore) InsertSweepBatch

func (s *SQLStore) InsertSweepBatch(ctx context.Context, batch *dbBatch) (int32,
	error)

InsertSweepBatch inserts a batch into the database, returning the id of the inserted batch.

func (*SQLStore) TotalSweptAmount

func (s *SQLStore) TotalSweptAmount(ctx context.Context, id int32) (
	btcutil.Amount, error)

TotalSweptAmount returns the total amount swept by a (confirmed) batch.

func (*SQLStore) UpdateSweepBatch

func (s *SQLStore) UpdateSweepBatch(ctx context.Context, batch *dbBatch) error

UpdateSweepBatch updates a batch in the database.

func (*SQLStore) UpsertSweep

func (s *SQLStore) UpsertSweep(ctx context.Context, sweep *dbSweep) error

UpsertSweep inserts a sweep into the database, or updates an existing sweep if it already exists.

type SignMuSig2

type SignMuSig2 func(ctx context.Context, muSig2Version input.MuSig2Version,
	swapHash lntypes.Hash, rootHash chainhash.Hash, sigHash [32]byte,
) ([]byte, error)

SignMuSig2 is a function that can be used to sign a sweep transaction in a custom way.

type SpendDetail

type SpendDetail struct {
	// Tx is the transaction that spent the outpoint.
	Tx *wire.MsgTx

	// OnChainFeePortion is the fee portion that was paid to get this sweep
	// confirmed on chain. This is the difference between the value of the
	// outpoint and the value of all sweeps that were included in the batch
	// divided by the number of sweeps.
	OnChainFeePortion btcutil.Amount
}

type SpendNotifier

type SpendNotifier struct {
	// SpendChan is a channel where the spend details are received.
	SpendChan chan *SpendDetail

	// SpendErrChan is a channel where spend errors are received.
	SpendErrChan chan error

	// QuitChan is a channel that can be closed to stop the notifier.
	QuitChan chan bool
}

SpendNotifier is a notifier that is used to notify the requester of a sweep that the sweep was successful.

type StoreMock

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

StoreMock implements a mock client swap store.

func NewStoreMock

func NewStoreMock() *StoreMock

NewStoreMock instantiates a new mock store.

func (*StoreMock) AssertSweepStored

func (s *StoreMock) AssertSweepStored(id lntypes.Hash) bool

AssertSweepStored asserts that a sweep is stored.

func (*StoreMock) Close

func (s *StoreMock) Close() error

Close closes the store.

func (*StoreMock) ConfirmBatch

func (s *StoreMock) ConfirmBatch(ctx context.Context, id int32) error

ConfirmBatch confirms a batch.

func (*StoreMock) DropBatch

func (s *StoreMock) DropBatch(ctx context.Context, id int32) error

DropBatch drops a batch from the database.

func (*StoreMock) FetchBatchSweeps

func (s *StoreMock) FetchBatchSweeps(ctx context.Context,
	id int32) ([]*dbSweep, error)

FetchBatchSweeps fetches all the sweeps that belong to a batch.

func (*StoreMock) FetchUnconfirmedSweepBatches

func (s *StoreMock) FetchUnconfirmedSweepBatches(ctx context.Context) (
	[]*dbBatch, error)

FetchUnconfirmedSweepBatches fetches all the loop out sweep batches from the database that are not in a confirmed state.

func (*StoreMock) GetParentBatch

func (s *StoreMock) GetParentBatch(ctx context.Context, swapHash lntypes.Hash) (
	*dbBatch, error)

GetParentBatch returns the parent batch of a swap.

func (*StoreMock) GetSweepStatus

func (s *StoreMock) GetSweepStatus(ctx context.Context,
	swapHash lntypes.Hash) (bool, error)

GetSweepStatus returns the status of a sweep.

func (*StoreMock) InsertSweepBatch

func (s *StoreMock) InsertSweepBatch(ctx context.Context,
	batch *dbBatch) (int32, error)

InsertSweepBatch inserts a batch into the database, returning the id of the inserted batch.

func (*StoreMock) TotalSweptAmount

func (s *StoreMock) TotalSweptAmount(ctx context.Context, batchID int32) (
	btcutil.Amount, error)

TotalSweptAmount returns the total amount of BTC that has been swept from a batch.

func (*StoreMock) UpdateSweepBatch

func (s *StoreMock) UpdateSweepBatch(ctx context.Context,
	batch *dbBatch) error

UpdateSweepBatch updates a batch in the database.

func (*StoreMock) UpsertSweep

func (s *StoreMock) UpsertSweep(ctx context.Context, sweep *dbSweep) error

UpsertSweep inserts a sweep into the database, or updates an existing sweep.

type SwapStoreWrapper

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

SwapStoreWrapper is LoopOutFetcher wrapper providing SweepFetcher interface.

func NewSweepFetcherFromSwapStore

func NewSweepFetcherFromSwapStore(swapStore LoopOutFetcher,
	chainParams *chaincfg.Params) (*SwapStoreWrapper, error)

NewSweepFetcherFromSwapStore accepts swapStore (e.g. loopdb) and returns a wrapper implementing SweepFetcher interface (suitable for NewBatcher).

func (*SwapStoreWrapper) FetchSweep

func (f *SwapStoreWrapper) FetchSweep(ctx context.Context,
	swapHash lntypes.Hash) (*SweepInfo, error)

FetchSweep returns details of the sweep with the given hash. Implements SweepFetcher interface.

type SweepFetcher

type SweepFetcher interface {
	// FetchSweep returns details of the sweep with the given hash.
	FetchSweep(ctx context.Context, hash lntypes.Hash) (*SweepInfo, error)
}

SweepFetcher is used to get details of a sweep.

type SweepInfo

type SweepInfo struct {
	// ConfTarget is the confirmation target of the sweep.
	ConfTarget int32

	// Timeout is the timeout of the swap that the sweep belongs to.
	Timeout int32

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

	// HTLC is the HTLC that is being swept.
	HTLC swap.Htlc

	// Preimage is the preimage of the HTLC that is being swept.
	Preimage lntypes.Preimage

	// SwapInvoicePaymentAddr is the payment address of the swap invoice.
	SwapInvoicePaymentAddr [32]byte

	// HTLCKeys is the set of keys used to sign the HTLC.
	HTLCKeys loopdb.HtlcKeys

	// HTLCSuccessEstimator is a function that estimates the weight of the
	// HTLC success script.
	HTLCSuccessEstimator func(*input.TxWeightEstimator) error

	// ProtocolVersion is the protocol version of the swap that the sweep
	// belongs to.
	ProtocolVersion loopdb.ProtocolVersion

	// IsExternalAddr is true if the sweep spends to a non-wallet address.
	IsExternalAddr bool

	// DestAddr is the destination address of the sweep.
	DestAddr btcutil.Address

	// NonCoopHint is set, if the sweep can not be spent cooperatively and
	// has to be spent using preimage. This is only used in fee estimations
	// when selecting a batch for the sweep to minimize fees.
	NonCoopHint bool
}

SweepInfo stores any data related to sweeping a specific outpoint.

type SweepRequest

type SweepRequest struct {
	// SwapHash is the hash of the swap that is being swept.
	SwapHash lntypes.Hash

	// Outpoint is the outpoint that is being swept.
	Outpoint wire.OutPoint

	// Value is the value of the outpoint that is being swept.
	Value btcutil.Amount

	// Notifier is a notifier that is used to notify the requester of this
	// sweep that the sweep was successful.
	Notifier *SpendNotifier
}

SweepRequest is a request to sweep a specific outpoint.

type VerifySchnorrSig

type VerifySchnorrSig func(pubKey *btcec.PublicKey, hash, sig []byte) error

VerifySchnorrSig is a function that can be used to verify a schnorr signature.

Jump to

Keyboard shortcuts

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