order

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2021 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultBatchVersion is the first implemented version of the batch
	// verification protocol.
	DefaultBatchVersion BatchVersion = 0

	// CurrentBatchVersion must point to the latest implemented version of the
	// batch verification protocol. Both server and client should always
	// refer to this constant. If a client's binary is not updated in time
	// it will point to a previous version than the server and the mismatch
	// will be detected during the OrderMatchPrepare call.
	CurrentBatchVersion = DefaultBatchVersion

	// LegacyLeaseDurationBucket is the single static duration bucket that
	// was used for orders before dynamic duration buckets were added.
	LegacyLeaseDurationBucket uint32 = 2016
)
View Source
const (
	// BaseSupplyUnit is the smallest channel that can be bought or sold in
	// the system. These units are expressed in satoshis.
	BaseSupplyUnit btcutil.Amount = 100_000
)
View Source
const DefaultMinNodeTier = NodeTier1

DefaultMinNodeTier is the default node tier. With this current value, Bids will default to only matching with nodes in the first tier and above.

View Source
const (
	// MaxBatchIDHistoryLookup is the maximum number of iterations we do
	// when iterating batch IDs. It's unlikely to happen but in case we
	// start from an invalid value we want to avoid an endless loop. If we
	// ever have more than that many batches, we need to handle them in
	// multiple steps anyway.
	MaxBatchIDHistoryLookup = 10_000
)
View Source
const (

	// MinimumOrderDurationBlocks is the minimum for a bid's MinDuration or
	// an ask's MaxDuration.
	MinimumOrderDurationBlocks = 144
)
View Source
const Subsystem = "ORDR"

Variables

View Source
var (
	// FeeRateTotalParts defines the granularity of the fixed rate used to
	// compute the per-block interest rate.  Throughout the codebase, we'll
	// use fix based arithmetic to compute fees.
	FeeRateTotalParts = 1e9

	// MinNoDustAccountSize is the minimum number of satoshis an account
	// output value needs to be to not be considered a dust output. This is
	// the cost of a spend TX at 1 sat/byte plus the minimum non-dust output
	// size.
	MinNoDustAccountSize = minNoDustAccountSize()
)
View Source
var (
	// DefaultBatchStepTimeout is the default time we allow an action that
	// blocks the batch conversation (like peer connection establishment or
	// channel open) to take. If any action takes longer, we might reject
	// the order from that slow peer. This value SHOULD be lower than the
	// defaultMsgTimeout on the server side otherwise nodes might get kicked
	// out of the match making process for timing out even though it was
	// their peer's fault.
	DefaultBatchStepTimeout = 15 * time.Second
)
View Source
var (
	// ErrMismatchErr is the wrapped error that is returned if the batch
	// verification fails.
	ErrMismatchErr = errors.New("batch verification result mismatch")
)
View Source
var (
	// ErrVersionMismatch is the error that is returned if we don't
	// implement the same batch verification version as the server.
	ErrVersionMismatch = fmt.Errorf("version %d mismatches server version",
		CurrentBatchVersion)
)

Functions

func ChannelOutput

func ChannelOutput(batchTx *wire.MsgTx, wallet lndclient.WalletKitClient,
	ourOrder Order, otherOrder *MatchedOrder) (*wire.TxOut, uint32, error)

ChannelOutput returns the transaction output and output index of the channel created for an order of ours that was matched with another one in a batch.

func EstimateTraderFee

func EstimateTraderFee(numTraderChans uint32,
	feeRate chainfee.SatPerKWeight) btcutil.Amount

EstimateTraderFee calculates the chain fees a trader has to pay for their part of a batch transaction. The more outputs a trader creates (channels), the higher fee they will pay.

func PendingChanKey

func PendingChanKey(askNonce, bidNonce Nonce) [32]byte

PendingChanKey calculates the pending channel ID to be used for funding purposes for a given bid and ask. The pending channel ID must be unique, so we use the hash of the concatenation of the two nonces: sha256(askNonce || bidNonce).

func PerBlockPremium

func PerBlockPremium(amt btcutil.Amount, fixedRate uint32) float64

PerBlockPremium calculates the absolute premium in fractions of satoshis for a one block duration from the amount and the specified fee rate in parts per billion.

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 AccountDiff

type AccountDiff struct {
	// AccountKeyRaw is the raw serialized account public key this diff
	// refers to.
	AccountKeyRaw [33]byte

	// AccountKey is the parsed account public key this diff refers to.
	AccountKey *btcec.PublicKey

	// EndingState is the ending on-chain state of the account after the
	// executed batch as the auctioneer calculated it.
	EndingState auctioneerrpc.AccountDiff_AccountState

	// EndingBalance is the ending balance for a trader's account.
	EndingBalance btcutil.Amount

	// OutpointIndex is the index of the re-created account output in the
	// batch transaction. This is set to -1 if no account output has been
	// created because the leftover value was considered to be dust.
	OutpointIndex int32
}

AccountDiff represents a matching+clearing event for a trader's account. This diff shows the total balance delta along with a breakdown for each item for a trader's account.

type AccountTally

type AccountTally struct {
	// EndingBalance is the ending balance for a trader's account.
	EndingBalance btcutil.Amount

	// TotalExecutionFeesPaid is the total amount of fees a trader paid to
	// the venue.
	TotalExecutionFeesPaid btcutil.Amount

	// TotalTakerFeesPaid is the total amount of fees the trader paid to
	// purchase any channels in this batch.
	TotalTakerFeesPaid btcutil.Amount

	// TotalMakerFeesAccrued is the total amount of fees the trader gained
	// by selling channels in this batch.
	TotalMakerFeesAccrued btcutil.Amount

	// NumChansCreated is the number of new channels that were created for
	// one account in a batch. This is needed to calculate the chain fees
	// that need to be paid from that account.
	NumChansCreated uint32
}

AccountTally keeps track of an account's balance and fees for all orders in a batch that spend from/use that account.

func (*AccountTally) CalcMakerDelta

func (t *AccountTally) CalcMakerDelta(feeSchedule terms.FeeSchedule,
	price FixedRatePremium, totalSats btcutil.Amount,
	duration uint32) btcutil.Amount

CalcMakerDelta calculates an account's balance and fee difference for a single order where the account is involved on the maker side. It returns the execution fee that is collected by the auctioneer.

func (*AccountTally) CalcTakerDelta

func (t *AccountTally) CalcTakerDelta(feeSchedule terms.FeeSchedule,
	price FixedRatePremium, totalSats, selfChanBalance btcutil.Amount,
	duration uint32) btcutil.Amount

CalcTakerDelta calculates an account's balance and fee difference for a single order where the account is involved on the taker side. It returns the execution fee that is collected by the auctioneer.

func (*AccountTally) ChainFees

func (t *AccountTally) ChainFees(feeRate chainfee.SatPerKWeight)

ChainFees estimates the chain fees that need to be paid for the number of channels created for this account and subtracts that value from the ending balance.

type Ask

type Ask struct {
	// Kit contains all the common order parameters.
	Kit
}

Ask is the specific order type representing the willingness of an auction participant to lend out their funds by opening channels to other auction participants.

func (*Ask) Digest

func (a *Ask) Digest() ([sha256.Size]byte, error)

Digest returns a deterministic SHA256 hash over the contents of an ask order. Deterministic in this context means that if two orders have the same content, their digest have to be identical as well.

NOTE: This method is part of the Order interface.

func (*Ask) ReservedValue

func (a *Ask) ReservedValue(feeSchedule terms.FeeSchedule) btcutil.Amount

ReservedValue returns the maximum value that could be deducted from a single account if the ask is is matched under the worst case fee conditions.

func (*Ask) Type

func (a *Ask) Type() Type

Type returns the order type.

NOTE: This method is part of the Order interface.

type Batch

type Batch struct {
	// ID is the batch's unique ID. If multiple messages come in with the
	// same ID, they are to be considered to be the _same batch_ with
	// updated matches. Any previous version of a batch with that ID should
	// be discarded in that case.
	ID BatchID

	// BatchVersion is the version of the batch verification protocol.
	Version BatchVersion

	// MatchedOrders is a map between all trader's orders and the other
	// orders that were matched to them in the batch.
	MatchedOrders map[Nonce][]*MatchedOrder

	// AccountDiffs is the calculated difference for each trader's account
	// that was involved in the batch.
	AccountDiffs []*AccountDiff

	// ExecutionFee is the FeeSchedule that was used by the server to
	// calculate the execution fee.
	ExecutionFee terms.FeeSchedule

	// ClearingPrices is a map of the lease duration markets and the fixed
	// rate the orders were cleared at within that market.
	ClearingPrices map[uint32]FixedRatePremium

	// BatchTX is the complete batch transaction with all non-witness data
	// fully populated.
	BatchTX *wire.MsgTx

	// BatchTxFeeRate is the miner fee rate in sat/kW that was chosen for
	// the batch transaction.
	BatchTxFeeRate chainfee.SatPerKWeight

	// FeeRebate is the rebate that was offered to the trader if another
	// batch participant wanted to pay more fees for a faster confirmation.
	FeeRebate btcutil.Amount
}

Batch is all the information the auctioneer sends to each trader for them to validate a batch execution.

func ParseRPCBatch

func ParseRPCBatch(prepareMsg *auctioneerrpc.OrderMatchPrepare) (*Batch,
	error)

ParseRPCBatch parses the incoming raw RPC batch into the go native data types used by the order manager.

type BatchID

type BatchID [33]byte

BatchID is a 33-byte point that uniquely identifies this batch. This ID will be used later for account key derivation when constructing the batch execution transaction.

func DecrementingBatchIDs

func DecrementingBatchIDs(startKey, endKey *btcec.PublicKey) []BatchID

DecrementingBatchIDs lists all possible batch IDs that can exist between a start and end key. Start key must be the larger/higher key, decrementing it a given number of times should finally result in the end key. If the keys aren't related or are too far apart, we return a maximum number of IDs that corresponds to our safety net parameter and the end key won't be contained in the list. The returned list is in descending order, meaning the first entry is the start key, the last entry is the end key.

func NewBatchID

func NewBatchID(pub *btcec.PublicKey) BatchID

NewBatchID returns a new batch ID for the given public key.

type BatchSignature

type BatchSignature map[[33]byte]*btcec.Signature

BatchSignature is a map type that is keyed by a trader's account key and contains the multi-sig signature for the input that spends from the current account in a batch.

type BatchSigner

type BatchSigner interface {
	// Sign returns the witness stack of all account inputs in a batch that
	// belong to the trader.
	Sign(*Batch) (BatchSignature, error)
}

BatchSigner is an interface that can sign for a trader's account inputs in a batch.

type BatchStorer

type BatchStorer interface {
	// StorePendingBatch makes sure all changes executed by a pending batch
	// are correctly and atomically stored to the database.
	StorePendingBatch(_ *Batch, bestHeight uint32) error

	// MarkBatchComplete marks a pending batch as complete, allowing a
	// trader to participate in a new batch.
	MarkBatchComplete() error
}

BatchStorer is an interface that can store a batch to the local database by applying all the diffs to the orders and accounts.

type BatchVerifier

type BatchVerifier interface {
	// Verify makes sure the batch prepared by the server is correct and
	// can be accepted by the trader.
	Verify(*Batch) error
}

BatchVerifier is an interface that can verify a batch from the point of view of the trader.

type BatchVersion

type BatchVersion uint32

BatchVersion is the type for the batch verification protocol.

type Bid

type Bid struct {
	// Kit contains all the common order parameters.
	Kit

	// MinNodeTier is the minimum node tier that this order should be
	// matched with. Only Asks backed by nodes on this tier or above will
	// be matched with this bid.
	MinNodeTier NodeTier

	// SelfChanBalance is the initial outbound balance that should be added
	// to the channel resulting from matching this bid by moving additional
	// funds from the taker's account into the channel.
	SelfChanBalance btcutil.Amount

	// SidecarTicket indicates, if non-nil, that the channel being purchased
	// with this bid should be opened to a node other than the caller's
	// node. The lease recipient is another Pool (light) node that
	// authenticates itself to the auctioneer using the information in this
	// ticket (the information exchange between bidder and lease recipient
	// happens out of band). This will only be used if the order version is
	// VersionSidecarChannel or greater.
	SidecarTicket *sidecar.Ticket
}

Bid is the specific order type representing the willingness of an auction participant to pay for inbound liquidity provided by other auction participants.

func (*Bid) Digest

func (b *Bid) Digest() ([sha256.Size]byte, error)

Digest returns a deterministic SHA256 hash over the contents of a bid order. Deterministic in this context means that if two orders have the same content, their digest have to be identical as well.

NOTE: This method is part of the Order interface.

func (*Bid) ReservedValue

func (b *Bid) ReservedValue(feeSchedule terms.FeeSchedule) btcutil.Amount

ReservedValue returns the maximum value that could be deducted from a single account if the bid is is matched under the worst case fee conditions.

func (*Bid) Type

func (b *Bid) Type() Type

Type returns the order type.

NOTE: This method is part of the Order interface.

func (*Bid) ValidateSelfChanBalance

func (b *Bid) ValidateSelfChanBalance() error

ValidateSelfChanBalance makes sure that all conditions to use the SelfChanBalance field on a bid order are met.

type Fetcher

type Fetcher func(Nonce) (Order, error)

Fetcher describes a function that's able to fetch the latest version of an order based on its nonce.

type FixedRatePremium

type FixedRatePremium uint32

FixedRatePremium is the unit that we'll use to express the "lease" rate of the funds within a channel. This value is compounded every N blocks. As a result, a trader will pay for the longer they wish to allocate liquidity to another agent in the market. In other words, this is our period interest rate.

func (FixedRatePremium) LumpSumPremium

func (f FixedRatePremium) LumpSumPremium(amt btcutil.Amount,
	durationBlocks uint32) btcutil.Amount

LumpSumPremium calculates the total amount that will be paid out to lease an asset at the target FixedRatePremium, for the specified amount. This computes the total amount that will be paid over the lifetime of the asset. We'll use this to compute the total amount that a taker needs to set aside once they're matched.

type Kit

type Kit struct {

	// Preimage is the randomly generated preimage to the nonce hash. It is
	// only known to the trader client.
	Preimage lntypes.Preimage

	// Version is the feature version of this order. Can be used to
	// distinguish between certain feature sets or to signal feature flags.
	Version Version

	// State is the current state the order is in as it was last seen by the
	// client. The real state is tracked on the auction server, so this can
	// be out of sync if there was no connection for a while.
	State State

	// FixedRate is the fixed order rate expressed in parts per million.
	FixedRate uint32

	// Amt is the order amount in satoshis.
	Amt btcutil.Amount

	// Units the total amount of units that the target amount maps to.
	Units SupplyUnit

	// UnitsUnfulfilled is the number of units that have not been filled yet
	// and are still available for matching against other orders.
	UnitsUnfulfilled SupplyUnit

	// MultiSigKeyLocator is the key locator used to obtain the multi sig
	// key. This will be needed for operations that require a signature
	// under said key and will therefore only be known to the trader client.
	// This key will only be derived from the connected lnd after the order
	// has been formally validated.
	MultiSigKeyLocator keychain.KeyLocator

	// MaxBatchFeeRate is is the maximum fee rate the trader is willing to
	// pay for the batch transaction, in sat/kW.
	MaxBatchFeeRate chainfee.SatPerKWeight

	// AcctKey is key of the account the order belongs to.
	AcctKey [33]byte

	// LeaseDuration identifies how long this order wishes to acquire or
	// lease out capital in the Lightning Network for.
	LeaseDuration uint32

	// MinUnitsMatch signals the minimum number of units that must be
	// matched against an order.
	MinUnitsMatch SupplyUnit
	// contains filtered or unexported fields
}

Kit stores all the common fields that are used to express the decision to participate in the auction process. A kit is always wrapped by either a bid or an ask.

func NewKit

func NewKit(nonce Nonce) *Kit

NewKit creates a new kit from a nonce in case the preimage is not known.

func NewKitWithPreimage

func NewKitWithPreimage(preimage lntypes.Preimage) *Kit

NewKitWithPreimage creates a new kit by hashing the preimage to generate the unique nonce.

func ParseRPCOrder

func ParseRPCOrder(version, leaseDuration uint32,
	details *poolrpc.Order) (*Kit, error)

ParseRPCOrder parses the incoming raw RPC order into the go native data types used in the order struct.

func ParseRPCServerOrder

func ParseRPCServerOrder(version uint32, details *auctioneerrpc.ServerOrder,
	orderIsAsk bool, leaseDuration uint32) (*Kit, [33]byte, []net.Addr,
	[33]byte, error)

ParseRPCServerOrder parses the incoming raw RPC server order into the go native data types used in the order struct.

func (*Kit) Details

func (k *Kit) Details() *Kit

Details returns the Kit of the order.

NOTE: This method is part of the Order interface.

func (*Kit) Nonce

func (k *Kit) Nonce() Nonce

Nonce is the unique identifier of each order and MUST be created by hashing a new random preimage for each new order. The nonce is what is signed in the order signature.

NOTE: This method is part of the Order interface.

type Manager

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

Manager is responsible for the management of orders.

func NewManager

func NewManager(cfg *ManagerConfig) *Manager

NewManager instantiates a new Manager backed by the given config.

func (*Manager) BatchFinalize

func (m *Manager) BatchFinalize(batchID BatchID) error

BatchFinalize marks a batch as complete upon receiving the finalize message from the auctioneer.

func (*Manager) BatchSign

func (m *Manager) BatchSign(bestHeight uint32) (BatchSignature, error)

BatchSign returns the witness stack of all account inputs in a batch that belong to the trader. Before sending off the signature to the auctioneer, we'll also persist the batch to disk as pending to ensure we can recover after a crash.

func (*Manager) HasPendingBatch

func (m *Manager) HasPendingBatch() bool

HasPendingBatch returns whether a pending batch is currently being processed.

func (*Manager) OrderMatchValidate

func (m *Manager) OrderMatchValidate(batch *Batch) error

OrderMatchValidate verifies an incoming batch is sane before accepting it.

func (*Manager) OurNodePubkey

func (m *Manager) OurNodePubkey() ([33]byte, error)

OurNodePubkey returns our lnd node's public identity key or an error if the manager wasn't fully started yet.

func (*Manager) PendingBatch

func (m *Manager) PendingBatch() *Batch

PendingBatch returns the current pending batch being validated.

func (*Manager) PrepareOrder

func (m *Manager) PrepareOrder(ctx context.Context, order Order,
	acct *account.Account,
	terms *terms.AuctioneerTerms) (*ServerOrderParams, error)

PrepareOrder validates an order, signs it and then stores it locally.

func (*Manager) Start

func (m *Manager) Start() error

Start starts all concurrent tasks the manager is responsible for.

func (*Manager) Stop

func (m *Manager) Stop()

Stop stops all concurrent tasks the manager is responsible for.

type ManagerConfig

type ManagerConfig struct {
	// Store is responsible for storing and retrieving order information.
	Store Store

	AcctStore account.Store

	// Lightning is used to access the main RPC to get information about the
	// lnd node that poold is connected to.
	Lightning lndclient.LightningClient

	// Wallet is responsible for deriving new keys we need to sign orders.
	Wallet lndclient.WalletKitClient

	// Signer is used to sign orders before submitting them to the server.
	Signer lndclient.SignerClient
}

ManagerConfig contains all of the required dependencies for the Manager to carry out its duties.

type MatchState

type MatchState uint8

MatchState describes the distinct phases an order goes through as seen by the trader daemon. These states are not persisted on the orders themselves but rather as events with timestamps so a user can track what's happening to their orders.

const (
	// MatchStatePrepare is the state an order is in after the
	// OrderMatchPrepare message was received initially.
	MatchStatePrepare MatchState = 0

	// MatchStatePrepare is the state an order is in after the
	// OrderMatchPrepare message was processed successfully and the batch
	// was accepted.
	MatchStateAccepted MatchState = 1

	// MatchStateRejected is the state an order is in after the trader
	// rejected it, either as an answer to a OderMatchSignBegin or
	// OrderMatchFinalize message from the auctioneer.
	MatchStateRejected MatchState = 2

	// MatchStateSigned is the state an order is in after the
	// OrderMatchSignBegin message was processed successfully.
	MatchStateSigned MatchState = 3

	// MatchStateFinalized is the state an order is in after the
	// OrderMatchFinalize message was processed successfully.
	MatchStateFinalized MatchState = 4
)

func (MatchState) String

func (s MatchState) String() string

String returns a human readable string representation of the match state.

type MatchedOrder

type MatchedOrder struct {
	// Order contains the details of the other order as sent by the server.
	Order Order

	// MultiSigKey is a key of the node creating the order that will be used
	// to craft the channel funding TX's 2-of-2 multi signature output.
	MultiSigKey [33]byte

	// NodeKey is the identity public key of the node creating the order.
	NodeKey [33]byte

	// NodeAddrs is the list of network addresses of the node creating the
	// order.
	NodeAddrs []net.Addr

	// UnitsFilled is the number of units that were matched by this order.
	UnitsFilled SupplyUnit
}

MatchedOrder is the other side to one of our matched orders. It contains all the information that is needed to validate the match and to start negotiating the channel opening with the matched trader's node.

func ParseRPCMatchedOrders

func ParseRPCMatchedOrders(orders *auctioneerrpc.MatchedOrder) ([]*MatchedOrder,
	error)

ParseRPCMatchedOrders parses the incoming raw RPC matched orders into the go native structs used by the order manager.

func ParseRPCServerAsk

func ParseRPCServerAsk(details *auctioneerrpc.ServerAsk) (*MatchedOrder, error)

ParseRPCServerAsk parses the incoming raw RPC server ask into the go native data types used in the order struct.

func ParseRPCServerBid

func ParseRPCServerBid(details *auctioneerrpc.ServerBid) (*MatchedOrder, error)

ParseRPCServerBid parses the incoming raw RPC server bid into the go native data types used in the order struct.

type MismatchErr

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

MismatchErr is an error type that is returned if the batch verification on the client does not come up with the same result as the server.

func (*MismatchErr) Error

func (m *MismatchErr) Error() string

Error returns the underlying error message.

NOTE: This method is part of the error interface.

func (*MismatchErr) Unwrap

func (m *MismatchErr) Unwrap() error

Unwrap returns the underlying error cause. This is always ErrMismatchErr so we can compare any error returned by the batch verifier with errors.Is() but still retain the context what exactly went wrong.

type Modifier

type Modifier func(*Kit)

Modifier abstracts the modification of an account through a function.

func StateModifier

func StateModifier(state State) Modifier

StateModifier is a functional option that modifies the state of an order.

func UnitsFulfilledModifier

func UnitsFulfilledModifier(newUnfulfilledUnits SupplyUnit) Modifier

UnitsFulfilledModifier is a functional option that modifies the number of unfulfilled units of an order.

type NodeTier

type NodeTier uint32

NodeTier an enum-like variable that presents which "tier" a node is in. A higher tier is better. Node tiers are used to allow clients to express their preference w.r.t the "quality" of a node they wish to buy channels from.

const (
	// NodeTierDefault only exists in-memory as allows users to specify
	// that they want to opt-into the default "node tier". The
	// DefaultMinNodeTier constant should point to what the current default
	// node tier is.
	NodeTierDefault NodeTier = 0

	// NodeTier0 is the tier for nodes which may not be explicitly ranked.
	// Orders submitted with this min tier express that they don't care
	// about the "quality" of the node they're matched with.
	NodeTier0 NodeTier = 1

	// NodeTier1 is the "base" node tier. Nodes on this tier are considered
	// to be relatively good. We have this be the first value in the enum
	// so it can be the default within the codebase and for order
	// submission/matching.
	NodeTier1 NodeTier = 2
)

func (NodeTier) String

func (n NodeTier) String() string

String returns the string representation of the target NodeTier.

type Nonce

type Nonce [32]byte

Nonce is a 32 byte pseudo randomly generated unique order ID.

var (
	// ErrInsufficientBalance is the error that is returned if an account
	// has insufficient balance to perform a requested action.
	ErrInsufficientBalance = errors.New("insufficient account balance")

	// ZeroNonce is used to find out if a user-provided nonce is empty.
	ZeroNonce Nonce
)

func (Nonce) String

func (n Nonce) String() string

String returns the hex encoded representation of the nonce.

type Order

type Order interface {
	// Nonce is the unique identifier of each order and MUST be created by
	// hashing a new random preimage for each new order. The nonce is what
	// is signed in the order signature.
	Nonce() Nonce

	// Details returns the Kit of the order.
	Details() *Kit

	// Type returns the order type.
	Type() Type

	// Digest returns a deterministic SHA256 hash over the contents of an
	// order. Deterministic in this context means that if two orders have
	// the same content, their digest have to be identical as well.
	Digest() ([sha256.Size]byte, error)

	// ReservedValue returns the maximum value that could be deducted from
	// the account if the order is is matched, and therefore has to be
	// reserved to ensure the trader can afford it.
	ReservedValue(feeSchedule terms.FeeSchedule) btcutil.Amount
}

Order is an interface to allow generic handling of both ask and bid orders by both store and manager.

type Quote

type Quote struct {
	// TotalPremium is the total order premium in satoshis for filling the
	// entire order.
	TotalPremium btcutil.Amount

	// RatePerBlock is the fixed order rate expressed as a fraction instead
	// of parts per billion.
	RatePerBlock float64

	// TotalExecutionFee is the total execution fee in satoshis that needs
	// to be paid to the auctioneer for executing the entire order.
	TotalExecutionFee btcutil.Amount

	// WorstCaseChainFee is the chain fees that have to be paid in the worst
	// case scenario where fees spike up to the given max batch fee rate and
	// the order is executed in the maximum parts possible (amount divided
	// by minimum channel amount).
	WorstCaseChainFee btcutil.Amount
}

Quote is a struct holding the result of an order quote calculation.

func NewQuote

func NewQuote(amt, minChanAmt btcutil.Amount, rate FixedRatePremium,
	leaseDuration uint32, maxBatchFeeRate chainfee.SatPerKWeight,
	schedule terms.FeeSchedule) *Quote

NewQuote returns a new quote for an order with the given parameters.

type ServerOrderParams

type ServerOrderParams struct {
	// MultiSigKey is a key of the node creating the order that will be used
	// to craft the channel funding TX's 2-of-2 multi signature output.
	MultiSigKey [33]byte

	// NodePubkey is the identity public key of the node submitting the
	// order.
	NodePubkey [33]byte

	// Addrs is a list of network addresses through which the node
	// submitting the order can be reached.
	Addrs []net.Addr

	// RawSig is the raw signature over the order digest signed with the
	// trader's account key.
	RawSig []byte
}

ServerOrderParams is the list of values that we have to send to the server when submitting an order that doesn't need to be persisted in the local DB.

type State

type State uint8

State describes the different possible states of an order. We don't use iota for the constants due to the order state being persisted to disk.

const (
	// StateSubmitted is the state an order has after it's been submitted
	// successfully.
	StateSubmitted State = 0

	// StateCleared is the state an order has after it's been accepted as
	// part of a batch but has not been executed yet.
	StateCleared State = 1

	// StatePartiallyFilled is the state an order has after some but not all
	// parts of it have been filled.
	StatePartiallyFilled State = 2

	// StateExecuted is the state an order has after it has been matched
	// with another order in the order book and fully processed.
	StateExecuted State = 3

	// StateCanceled is the state an order has after a user cancels the
	// order manually.
	StateCanceled State = 4

	// StateExpired is the state an order has after it's maximum lifetime
	// has passed.
	StateExpired State = 5

	// StateFailed is the state an order has if any irrecoverable error
	// happens in its lifetime.
	StateFailed State = 6
)

func (State) Archived

func (s State) Archived() bool

Archived returns true if the order is in a state that is considered to be fully executed and no more modifications will be done to it.

func (State) String

func (s State) String() string

String returns a human readable string representation of the order state.

type Store

type Store interface {
	// SubmitOrder stores an order by using the orders's nonce as an
	// identifier. If an order with the given nonce already exists in the
	// store, ErrOrderExists is returned.
	SubmitOrder(Order) error

	// UpdateOrder updates an order in the database according to the given
	// modifiers.
	UpdateOrder(Nonce, ...Modifier) error

	// UpdateOrders atomically updates a list of orders in the database
	// according to the given modifiers.
	UpdateOrders([]Nonce, [][]Modifier) error

	// GetOrder returns an order by looking up the nonce. If no order with
	// that nonce exists in the store, ErrNoOrder is returned.
	GetOrder(Nonce) (Order, error)

	// GetOrders returns all orders that are currently known to the store.
	GetOrders() ([]Order, error)

	// StorePendingBatch atomically stages all modified orders/accounts as a
	// result of a pending batch. If any single operation fails, the whole
	// set of changes is rolled back. Once the batch has been
	// finalized/confirmed on-chain, then the stage modifications will be
	// applied atomically as a result of MarkBatchComplete.
	StorePendingBatch(_ *Batch, orders []Nonce,
		orderModifiers [][]Modifier, accounts []*account.Account,
		accountModifiers [][]account.Modifier) error

	// MarkBatchComplete marks a pending batch as complete, applying any
	// staged modifications necessary, and allowing a trader to participate
	// in a new batch. If a pending batch is not found, ErrNoPendingBatch is
	// returned.
	MarkBatchComplete() error
}

Store is the interface a store has to implement to support persisting orders.

type SupplyUnit

type SupplyUnit uint64

SupplyUnit is a type that represents the smallest unit of an order that can be fulfilled. One unit corresponds to the smallest channel size that can be bought or sold in the system.

func NewSupplyFromSats

func NewSupplyFromSats(sats btcutil.Amount) SupplyUnit

NewSupplyFromSats calculates the number of supply units that can be bought or sold with a given amount in satoshis.

func RoundToNextSupplyUnit

func RoundToNextSupplyUnit(sats btcutil.Amount) SupplyUnit

RoundToNextSupplyUnit computes and rounds to the next whole number of supply units from the given amount in satoshis.

func (SupplyUnit) ToSatoshis

func (s SupplyUnit) ToSatoshis() btcutil.Amount

ToSatoshis maps a set number of supply units to the corresponding number of satoshis.

type Type

type Type uint8

Type is the type of an order. We don't use iota for the constants due to the order type being persisted to disk.

const (
	// TypeAsk is the constant to represent the "ask" order type.
	TypeAsk Type = 0

	// TypeBid is the constant to represent the "bid" order type.
	TypeBid Type = 1
)

func (Type) String

func (t Type) String() string

String returns a human read-able string describing the passed order type.

type UserError

type UserError struct {
	FailMsg string
	Details *auctioneerrpc.InvalidOrder
}

UserError is an error type that is returned if an action fails because of an invalid action or information provided by the user.

func (*UserError) Error

func (e *UserError) Error() string

Error returns the string representation of the underlying failure message.

type Version

type Version uint32

Version is the version of an order. We don't use iota for the constants due to the order type being persisted to disk.

const (
	// VersionDefault is the default initial version of orders.
	VersionDefault Version = 0

	// VersionNodeTierMinMatch is the order version that added recognition
	// of the new node tier and min matchable order size fields.
	VersionNodeTierMinMatch Version = 1

	// VersionLeaseDurationBuckets is the order version that added use of
	// multiple lease durations. Only orders with this version are allowed
	// to use lease durations outside of the default/legacy 2016 block
	// duration.
	VersionLeaseDurationBuckets Version = 2

	// VersionSelfChanBalance is the order version that added use of the
	// self channel balance field. Only orders with this version are allowed
	// to use the self channel balance field.
	VersionSelfChanBalance Version = 3

	// VersionSidecarChannel is the order version that added sidecar
	// channels for bid orders. Only orders with this version are allowed
	// to set the sidecar ticket field on bid orders. Since sidecar orders
	// also add the feature of push amounts on the leased channels, this
	// affects makers as well. Makers that don't want to support leasing out
	// channels with a push amount (because it might screw up their
	// accounting or whatever) can opt out by explicitly submitting their
	// ask orders with a version previous to this one.
	VersionSidecarChannel Version = 4
)

Jump to

Keyboard shortcuts

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