tbtcpg

package
v0.0.0-...-369a1d7 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2024 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const MovedFundsSweepLookBackBlocks = uint64(216000)

MovedFundsSweepLookBackBlocks is the look-back period in blocks used when searching for submitted moving funds-related events. It's equal to 30 days assuming 12 seconds per block.

View Source
const MovingFundsCommitmentLookBackBlocks = uint64(216000)

MovingFundsCommitmentLookBackBlocks is the look-back period in blocks used when searching for submitted moving funds commitment events. It's equal to 30 days assuming 12 seconds per block.

Variables

View Source
var (
	// ErrMaxBtcTransferZero is the error returned when wallet max BTC transfer
	// parameter is zero.
	ErrMaxBtcTransferZero = fmt.Errorf(
		"wallet max BTC transfer must be positive",
	)

	// ErrNotEnoughTargetWallets is the error returned when the number of
	// gathered target wallets does not match the required target wallets count.
	ErrNotEnoughTargetWallets = fmt.Errorf("not enough target wallets")

	// ErrWrongCommitmentHash is the error returned when the hash calculated
	// from retrieved target wallets does not match the committed hash.
	ErrWrongCommitmentHash = fmt.Errorf(
		"target wallets hash must match commitment hash",
	)

	// ErrNoExecutingOperator is the error returned when the task executing
	// operator is not found among the wallet operator IDs.
	ErrNoExecutingOperator = fmt.Errorf(
		"task executing operator not found among wallet operators",
	)

	// ErrTransactionNotIncluded is the error returned when the commitment
	// submission transaction was not included in the Ethereum blockchain.
	ErrTransactionNotIncluded = fmt.Errorf(
		"transaction not included in blockchain",
	)

	// ErrFeeTooHigh is the error returned when the estimated fee exceeds the
	// maximum fee allowed for the moving funds transaction.
	ErrFeeTooHigh = fmt.Errorf("estimated fee exceeds the maximum fee")
)
View Source
var ErrNoPendingMovedFundsSweepRequests = fmt.Errorf(
	"could not find any pending moved funds sweep request",
)

ErrNoPendingMovedFundsSweepRequests is the error returned when no pending moved funds sweep requests.

View Source
var ErrSweepTxFeeTooHigh = fmt.Errorf(
	"estimated fee exceeds the maximum fee",
)

ErrSweepTxFeeTooHigh is the error returned when the estimated fee exceeds the maximum fee allowed for the moved funds sweep transaction.

Functions

func EstimateDepositsSweepFee

func EstimateDepositsSweepFee(
	chain Chain,
	btcChain bitcoin.Chain,
	depositsCount int,
) (
	map[int]struct {
		TotalFee       int64
		SatPerVByteFee int64
	},
	error,
)

EstimateDepositsSweepFee computes the total fee for the Bitcoin deposits sweep transaction for the given depositsCount. If the provided depositsCount is 0, this function computes the total fee for Bitcoin deposits sweep transactions containing a various number of input deposits, from 1 up to the maximum count allowed by the WalletProposalValidator contract. Computed fees for specific deposits counts are returned as a map.

While making estimations, this function assumes a sweep transaction consists of:

  • 1 P2WPKH input being the current wallet main UTXO. That means the produced fees may be overestimated for the very first sweep transaction of each wallet.
  • N P2WSH inputs representing the deposits. Worth noting that real transactions may contain legacy P2SH deposits as well so produced fees may be underestimated in some rare cases.
  • 1 P2WPKH output

If any of the estimated fees exceed the maximum fee allowed by the Bridge contract, an error is returned as result.

func EstimateMovedFundsSweepFee

func EstimateMovedFundsSweepFee(
	btcChain bitcoin.Chain,
	hasMainUtxo bool,
	sweepTxMaxTotalFee uint64,
) (int64, error)

EstimateMovedFundsSweepFee estimates fee for the moved funds sweep transaction that merges the received main UTXO from the source wallets with the current wallet's main UTXO.

func EstimateMovingFundsFee

func EstimateMovingFundsFee(
	btcChain bitcoin.Chain,
	targetWalletsCount int,
	txMaxTotalFee uint64,
) (int64, error)

EstimateMovingFundsFee estimates fee for the moving funds transaction that moves funds from the source wallet to target wallets.

func EstimateRedemptionFee

func EstimateRedemptionFee(
	btcChain bitcoin.Chain,
	redeemersOutputScripts []bitcoin.Script,
) (int64, error)

EstimateRedemptionFee estimates fee for the redemption transaction that pays the provided redeemers output scripts.

Types

type Chain

type Chain interface {
	tbtc.BridgeChain

	// PastNewWalletRegisteredEvents fetches past new wallet registered events
	// according to the provided filter or unfiltered if the filter is nil. Returned
	// events are sorted by the block number in the ascending order, i.e. the
	// latest event is at the end of the slice.
	PastNewWalletRegisteredEvents(
		filter *tbtc.NewWalletRegisteredEventFilter,
	) ([]*tbtc.NewWalletRegisteredEvent, error)

	// GetWalletParameters gets the current value of parameters relevant to
	// wallet.
	GetWalletParameters() (
		creationPeriod uint32,
		creationMinBtcBalance uint64,
		creationMaxBtcBalance uint64,
		closureMinBtcBalance uint64,
		maxAge uint32,
		maxBtcTransfer uint64,
		closingPeriod uint32,
		err error,
	)

	// GetLiveWalletsCount gets the current count of live wallets.
	GetLiveWalletsCount() (uint32, error)

	// BuildDepositKey calculates a deposit key for the given funding transaction
	// which is a unique identifier for a deposit on-chain.
	BuildDepositKey(fundingTxHash bitcoin.Hash, fundingOutputIndex uint32) *big.Int

	// GetDepositParameters gets the current value of parameters relevant
	// for the depositing process.
	GetDepositParameters() (
		dustThreshold uint64,
		treasuryFeeDivisor uint64,
		txMaxFee uint64,
		revealAheadPeriod uint32,
		err error,
	)

	// PastRedemptionRequestedEvents fetches past redemption requested events according
	// to the provided filter or unfiltered if the filter is nil. Returned
	// events are sorted by the block number in the ascending order, i.e. the
	// latest event is at the end of the slice.
	PastRedemptionRequestedEvents(
		filter *tbtc.RedemptionRequestedEventFilter,
	) ([]*tbtc.RedemptionRequestedEvent, error)

	// BuildRedemptionKey calculates a redemption key for the given redemption
	// request which is an identifier for a redemption at the given time
	// on-chain.
	BuildRedemptionKey(
		walletPublicKeyHash [20]byte,
		redeemerOutputScript bitcoin.Script,
	) (*big.Int, error)

	// GetRedemptionParameters gets the current value of parameters relevant
	// for the redemption process.
	GetRedemptionParameters() (
		dustThreshold uint64,
		treasuryFeeDivisor uint64,
		txMaxFee uint64,
		txMaxTotalFee uint64,
		timeout uint32,
		timeoutSlashingAmount *big.Int,
		timeoutNotifierRewardMultiplier uint32,
		err error,
	)

	// GetRedemptionMaxSize gets the maximum number of redemption requests that
	// can be a part of a redemption sweep proposal.
	GetRedemptionMaxSize() (uint16, error)

	// GetRedemptionRequestMinAge get the  minimum time that must elapse since
	// the redemption request creation before a request becomes eligible for
	// a processing.
	GetRedemptionRequestMinAge() (uint32, error)

	// ValidateDepositSweepProposal validates the given deposit sweep proposal
	// against the chain. It requires some additional data about the deposits
	// that must be fetched externally. Returns an error if the proposal is
	// not valid or nil otherwise.
	ValidateDepositSweepProposal(
		walletPublicKeyHash [20]byte,
		proposal *tbtc.DepositSweepProposal,
		depositsExtraInfo []struct {
			*tbtc.Deposit
			FundingTx *bitcoin.Transaction
		},
	) error

	// ValidateRedemptionProposal validates the given redemption proposal
	// against the chain. Returns an error if the proposal is not valid or
	// nil otherwise.
	ValidateRedemptionProposal(
		walletPublicKeyHash [20]byte,
		proposal *tbtc.RedemptionProposal,
	) error

	// GetDepositSweepMaxSize gets the maximum number of deposits that can
	// be part of a deposit sweep proposal.
	GetDepositSweepMaxSize() (uint16, error)

	BlockCounter() (chain.BlockCounter, error)

	AverageBlockTime() time.Duration

	// GetOperatorID returns the operator ID for the given operator address.
	GetOperatorID(operatorAddress chain.Address) (chain.OperatorID, error)

	// ValidateHeartbeatProposal validates the given heartbeat proposal
	// against the chain. Returns an error if the proposal is not valid or
	// nil otherwise.
	ValidateHeartbeatProposal(
		walletPublicKeyHash [20]byte,
		proposal *tbtc.HeartbeatProposal,
	) error

	// PastMovingFundsCommitmentSubmittedEvents fetches past moving funds
	// commitment submitted events according to the provided filter or
	// unfiltered if the filter is nil. Returned events are sorted by the block
	// number in the ascending order, i.e. the latest event is at the end of the
	// slice.
	PastMovingFundsCommitmentSubmittedEvents(
		filter *tbtc.MovingFundsCommitmentSubmittedEventFilter,
	) ([]*tbtc.MovingFundsCommitmentSubmittedEvent, error)

	// PastMovingFundsCompletedEvents fetches past moving funds completed events
	// according to the provided filter or unfiltered if the filter is nil.
	// Returned events are sorted by the block number in the ascending order,
	// i.e. the latest event is at the end of the slice.
	PastMovingFundsCompletedEvents(
		filter *tbtc.MovingFundsCompletedEventFilter,
	) ([]*tbtc.MovingFundsCompletedEvent, error)

	// ValidateMovingFundsProposal validates the given moving funds proposal
	// against the chain. Returns an error if the proposal is not valid or
	// nil otherwise.
	ValidateMovingFundsProposal(
		walletPublicKeyHash [20]byte,
		mainUTXO *bitcoin.UnspentTransactionOutput,
		proposal *tbtc.MovingFundsProposal,
	) error

	// Submits the moving funds target wallets commitment.
	SubmitMovingFundsCommitment(
		walletPublicKeyHash [20]byte,
		walletMainUTXO bitcoin.UnspentTransactionOutput,
		walletMembersIDs []uint32,
		walletMemberIndex uint32,
		targetWallets [][20]byte,
	) error

	// ValidateMovedFundsSweepProposal validates the given moved funds sweep
	// proposal against the chain. Returns an error if the proposal is not valid
	// or nil otherwise.
	ValidateMovedFundsSweepProposal(
		walletPublicKeyHash [20]byte,
		proposal *tbtc.MovedFundsSweepProposal,
	) error

	// Computes the moving funds commitment hash from the provided public key
	// hashes of target wallets.
	ComputeMovingFundsCommitmentHash(targetWallets [][20]byte) [32]byte

	// GetRedemptionDelay returns the processing delay for the given redemption.
	GetRedemptionDelay(
		walletPublicKeyHash [20]byte,
		redeemerOutputScript bitcoin.Script,
	) (time.Duration, error)

	// GetDepositMinAge get the minimum time that must elapse since
	// the deposit reveal before a deposit becomes eligible for
	// a processing.
	GetDepositMinAge() (uint32, error)
}

Chain represents the interface that the wallet maintainer module expects to interact with the anchoring blockchain on.

type Deposit

type Deposit struct {
	DepositReference

	WalletPublicKeyHash [20]byte
	DepositKey          string
	IsSwept             bool
	AmountBtc           float64
	Confirmations       uint
}

Deposit holds some detailed data about a deposit.

func FindDeposits

func FindDeposits(
	chain Chain,
	btcChain bitcoin.Chain,
	walletPublicKeyHash [20]byte,
	maxNumberOfDeposits int,
	skipSwept bool,
	skipUnconfirmed bool,
) ([]*Deposit, error)

FindDeposits finds deposits according to the given criteria.

type DepositReference

type DepositReference struct {
	FundingTxHash      bitcoin.Hash
	FundingOutputIndex uint32
	RevealBlock        uint64
}

DepositReference holds some data allowing to identify and refer to a deposit.

type DepositSweepTask

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

DepositSweepTask is a task that may produce a deposit sweep proposal.

func NewDepositSweepTask

func NewDepositSweepTask(
	chain Chain,
	btcChain bitcoin.Chain,
) *DepositSweepTask

func (*DepositSweepTask) ActionType

func (dst *DepositSweepTask) ActionType() tbtc.WalletActionType

func (*DepositSweepTask) FindDepositsToSweep

func (dst *DepositSweepTask) FindDepositsToSweep(
	taskLogger log.StandardLogger,
	walletPublicKeyHash [20]byte,
	maxNumberOfDeposits uint16,
) ([]*DepositReference, error)

FindDepositsToSweep finds deposits that can be swept. maxNumberOfDeposits is used as a ceiling for the number of deposits in the result. If number of discovered deposits meets the maxNumberOfDeposits the function will stop fetching more deposits. This function will return a list of deposits from the wallet that can be swept. Deposits with insufficient number of funding transaction confirmations will not be taken into consideration for sweeping.

TODO: Cache immutable data

func (*DepositSweepTask) ProposeDepositsSweep

func (dst *DepositSweepTask) ProposeDepositsSweep(
	taskLogger log.StandardLogger,
	walletPublicKeyHash [20]byte,
	deposits []*DepositReference,
	fee int64,
) (*tbtc.DepositSweepProposal, error)

ProposeDepositsSweep returns a deposit sweep proposal.

func (*DepositSweepTask) Run

type HeartbeatTask

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

HeartbeatTask is a task that may produce a heartbeat proposal.

func NewHeartbeatTask

func NewHeartbeatTask(chain Chain) *HeartbeatTask

func (*HeartbeatTask) ActionType

func (ht *HeartbeatTask) ActionType() tbtc.WalletActionType

func (*HeartbeatTask) Run

type MovedFundsSweepTask

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

MovedFundsSweepTask is a task that may produce a moved funds sweep proposal.

func NewMovedFundsSweepTask

func NewMovedFundsSweepTask(
	chain Chain,
	btcChain bitcoin.Chain,
) *MovedFundsSweepTask

func (*MovedFundsSweepTask) ActionType

func (mfst *MovedFundsSweepTask) ActionType() tbtc.WalletActionType

func (*MovedFundsSweepTask) FindMovingFundsTxData

func (mfst *MovedFundsSweepTask) FindMovingFundsTxData(
	walletPublicKeyHash [20]byte,
) (
	txHash bitcoin.Hash,
	txOutputIdx uint32,
	err error,
)

FindMovingFundsTxData finds the transaction hash and output index for the unswept funds transferred from a source wallet to this wallet. It returns data for only one funds transfer. If there were more than one funds transfers the data for the first encountered unswept transfer is returned. If no pending moved funds sweep request could be found, the function returns error.

func (*MovedFundsSweepTask) ProposeMovedFundsSweep

func (mfst *MovedFundsSweepTask) ProposeMovedFundsSweep(
	taskLogger log.StandardLogger,
	walletPublicKeyHash [20]byte,
	movingFundsTxHash bitcoin.Hash,
	movingFundsTxOutputIndex uint32,
	hasMainUtxo bool,
	fee int64,
) (*tbtc.MovedFundsSweepProposal, error)

func (*MovedFundsSweepTask) Run

type MovingFundsTask

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

MovingFundsTask is a task that may produce a moving funds proposal.

func NewMovingFundsTask

func NewMovingFundsTask(
	chain Chain,
	btcChain bitcoin.Chain,
) *MovingFundsTask

func (*MovingFundsTask) ActionType

func (mft *MovingFundsTask) ActionType() tbtc.WalletActionType

func (*MovingFundsTask) FindTargetWallets

func (mft *MovingFundsTask) FindTargetWallets(
	taskLogger log.StandardLogger,
	sourceWalletPublicKeyHash [20]byte,
	targetWalletsCommitmentHash [32]byte,
	walletBalance uint64,
	liveWalletsCount uint32,
) ([][20]byte, bool, error)

FindTargetWallets returns a list of target wallets for the moving funds procedure. If the source wallet has not submitted moving funds commitment yet a new list of target wallets is prepared. If the source wallet has already submitted the commitment, the returned target wallet list is prepared based on the submitted commitment event.

func (*MovingFundsTask) GetWalletMembersInfo

func (mft *MovingFundsTask) GetWalletMembersInfo(
	walletOperators []chain.Address,
	executingOperator chain.Address,
) ([]uint32, uint32, error)

GetWalletMembersInfo returns the wallet member IDs based on the provided wallet operator addresses. Additionally, it returns the position of the moving funds task execution operator on the list.

func (*MovingFundsTask) ProposeMovingFunds

func (mft *MovingFundsTask) ProposeMovingFunds(
	taskLogger log.StandardLogger,
	walletPublicKeyHash [20]byte,
	mainUTXO *bitcoin.UnspentTransactionOutput,
	targetWallets [][20]byte,
	fee int64,
) (*tbtc.MovingFundsProposal, error)

ProposeMovingFunds returns a moving funds proposal.

func (*MovingFundsTask) Run

func (*MovingFundsTask) SubmitMovingFundsCommitment

func (mft *MovingFundsTask) SubmitMovingFundsCommitment(
	taskLogger log.StandardLogger,
	walletPublicKeyHash [20]byte,
	walletMainUTXO *bitcoin.UnspentTransactionOutput,
	walletMembersIDs []uint32,
	walletMemberIndex uint32,
	targetWallets [][20]byte,
) error

SubmitMovingFundsCommitment submits the moving funds commitment and waits until the transaction has entered the Ethereum blockchain.

type ProposalGenerator

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

ProposalGenerator is a component responsible for generating coordination proposals for tbtc wallets.

func NewProposalGenerator

func NewProposalGenerator(
	chain Chain,
	btcChain bitcoin.Chain,
) *ProposalGenerator

NewProposalGenerator returns a new proposal generator.

func (*ProposalGenerator) Generate

Generate generates a coordination proposal based on the given checklist of possible wallet actions. The checklist is a list of actions that should be checked for the given coordination window. This function returns a proposal for the first action from the checklist that is valid for the given wallet's state. If none of the actions are valid, the generator returns a no-op proposal.

type ProposalTask

type ProposalTask interface {
	// Run executes the task and returns a proposal, a boolean flag indicating
	// whether the proposal was generated and an error if any.
	Run(
		request *tbtc.CoordinationProposalRequest,
	) (tbtc.CoordinationProposal, bool, error)

	// ActionType returns the type of the action proposal.
	ActionType() tbtc.WalletActionType
}

ProposalTask encapsulates logic used to generate an action proposal of the given type.

type RedemptionRequest

type RedemptionRequest struct {
	WalletPublicKeyHash  [20]byte
	RedemptionKey        string
	RedeemerOutputScript bitcoin.Script
	RequestedAt          time.Time
	RequestedAmount      uint64
}

RedemptionRequest represents a redemption request.

type RedemptionTask

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

RedemptionTask is a task that may produce a redemption proposal.

func NewRedemptionTask

func NewRedemptionTask(
	chain Chain,
	btcChain bitcoin.Chain,
) *RedemptionTask

func (*RedemptionTask) ActionType

func (rt *RedemptionTask) ActionType() tbtc.WalletActionType

func (*RedemptionTask) FindPendingRedemptions

func (rt *RedemptionTask) FindPendingRedemptions(
	taskLogger log.StandardLogger,
	walletPublicKeyHash [20]byte,
	maxNumberOfRequests uint16,
) ([]bitcoin.Script, error)

FindPendingRedemptions finds pending redemptions requests for the provided wallet. The returned value is a list of redeemers output scripts that come from detected pending requests targeting this wallet. The maxNumberOfRequests parameter is used as a ceiling for the number of requests in the result. If number of discovered requests meets the maxNumberOfRequests the function will stop fetching more requests.

func (*RedemptionTask) ProposeRedemption

func (rt *RedemptionTask) ProposeRedemption(
	taskLogger log.StandardLogger,
	walletPublicKeyHash [20]byte,
	redeemersOutputScripts []bitcoin.Script,
	fee int64,
) (*tbtc.RedemptionProposal, error)

ProposeRedemption returns a redemption proposal.

func (*RedemptionTask) Run

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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