order

package
v0.6.4-beta Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2023 License: MIT Imports: 38 Imported by: 1

Documentation

Overview

Package order is a generated GoMock package.

Index

Constants

View Source
const (
	// LatestBatchVersion points to the most recent batch version.
	LatestBatchVersion = UpgradeAccountTaprootBatchVersion |
		ZeroConfChannelsFlag | UpgradeAccountTaprootV2Flag

	// 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 (
	// ErrInvalidBatchHeightHint is an error returned by a trader upon
	// verifying a batch when its proposed height hint is outside of the
	// trader's acceptable range.
	ErrInvalidBatchHeightHint = errors.New("proposed batch height hint is " +
		"outside of acceptable range")
)
View Source
var (
	// ErrMismatchErr is the wrapped error that is returned if the batch
	// verification fails.
	ErrMismatchErr = errors.New("batch verification result mismatch")
)

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 CheckOfferParams

func CheckOfferParams(auctionType AuctionType, capacity, pushAmt,
	baseSupplyUnit btcutil.Amount) error

CheckOfferParams makes sure the offer parameters of an offer are valid and sane.

func CheckOfferParamsForOrder

func CheckOfferParamsForOrder(auctionType AuctionType, offer sidecar.Offer,
	bidAmt, bidMinUnitsMatch, baseSupplyUnit btcutil.Amount) error

CheckOfferParamsForOrder makes sure that the order parameters in a sidecar offer are formally valid, sane and match the order parameters.

func EstimateTraderFee

func EstimateTraderFee(numTraderChans uint32, feeRate chainfee.SatPerKWeight,
	accountVersion account.Version) 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 IsNodeIDAValidMatch

func IsNodeIDAValidMatch(nodeID [33]byte, allowed, notAllowed [][33]byte) bool

IsNodeIDAValidMatch takes a nodeID and the list of allowed/not allowed node ids and returns if we are allowed to match with it.

func MarshalNodeIDSlice

func MarshalNodeIDSlice(nodeIDs [][33]byte) [][]byte

MarshalNodeIDSlice returns a flattened version of an slice of node ids to be used in rpc serialization.

func MatchAnnouncementConstraints

func MatchAnnouncementConstraints(asker ChannelAnnouncementConstraints,
	unannounced bool) bool

MatchAnnouncementConstraints returns true when the asker announcement constraints match the bidder announcement preferences.

func MatchZeroConfConstraints

func MatchZeroConfConstraints(asker ChannelConfirmationConstraints,
	zeroConf bool) bool

MatchZeroConfConstraints returns true when the asker confirmation constraints match the bidder confirmation preferences.

func NewManager

func NewManager(cfg *ManagerConfig) *manager

NewManager instantiates a new Manager backed by the given config.

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 UnmarshalNodeIDSlice

func UnmarshalNodeIDSlice(slice [][]byte) ([][33]byte, error)

UnmarshalNodeIDSlice returns a slice of node ids from a flatten version.

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

	// NewExpiry is the new expiry height for this account. This field
	// can be safely ignored if its value is 0.
	NewExpiry uint32

	// NewVersion is the version of the account that should be used after
	// the batch went through. This field influences the type of account
	// output that is created by this batch. If this differs from the
	// CurrentVersion, then the account was upgraded in this batch.
	NewVersion account.Version
}

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 AccountNonces

type AccountNonces map[[33]byte]poolscript.MuSig2Nonces

AccountNonces is a map of all server or client nonces for a batch signing session, keyed by the account key.

func ParseRPCSign

func ParseRPCSign(signMsg *auctioneerrpc.OrderMatchSignBegin) (AccountNonces,
	[]*wire.TxOut, error)

ParseRPCSign parses the incoming raw OrderMatchSignBegin into the go native structs used by the order manager.

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, makerAmt, premiumAmt 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, takerAmt, premiumAmt 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,
	accountVersion account.Version)

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

	// AnnouncementConstraints specifies the constraints for the matched
	// channels in terms of announced/unannounced.
	AnnouncementConstraints ChannelAnnouncementConstraints

	// ConfirmationConstraints specifies the constraints for the matched
	// channels in terms of confirmed/zero conf.
	ConfirmationConstraints ChannelConfirmationConstraints
}

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() ([hashSize]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,
	accountVersion account.Version) btcutil.Amount

ReservedValue returns the maximum value that could be deducted from a single account if the ask 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 AuctionType

type AuctionType uint32

AuctionType is a numerical type used to denote in what auction market should this order be considered in.

const (
	// BTCInboundLiquidity is an auction type where the bidder pays the
	// asker a premium to get btc inbound liquidity from him.
	BTCInboundLiquidity AuctionType = 0

	// BTCOutboundLiquidity is an auction type where the bidder pays the
	// asker a premium to accept a btc channel from the bidder.
	BTCOutboundLiquidity AuctionType = 1
)

func (AuctionType) String

func (a AuctionType) String() string

String returns a human readable string representation of the auction type.

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

	// HeightHint represents the earliest absolute height in the chain in
	// which the batch transaction can be found within. This will be used by
	// traders to base off their absolute channel lease maturity height.
	HeightHint uint32

	// ServerNonces is the map of all the auctioneer's public nonces for
	// each of the (Taproot enabled) accounts in the batch, keyed by the
	// account's trader key. This is volatile (in-memory only) information
	// that is _not_ persisted as part of the batch snapshot.
	ServerNonces AccountNonces

	// PreviousOutputs is the list of previous output scripts and amounts
	// (UTXO information) for all the inputs being spent by the batch
	// transaction. This is volatile (in-memory only) information that is
	// _not_ persisted as part of the batch snapshot.
	PreviousOutputs []*wire.TxOut
}

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][]byte

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, AccountNonces, 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) 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 *Batch, bestHeight uint32) 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.

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

	// ExtendAccountBatchVersion is the first version where accounts expiry
	// are extended after participating in a batch.
	ExtendAccountBatchVersion BatchVersion = 1

	// UnannouncedChannelsBatchVersion is the first version where orders
	// can set the flags to only match with announced/unannonced channels.
	//
	// NOTE: This feature requires the runtime support:
	// - The asker needs to open the channel with the right `private` value
	// - The bidder needs to be able to set the channel acceptor for the
	//   channel with the right `private` value.
	// For that reason this needs to be a batch version and not only an
	// order one.
	UnannouncedChannelsBatchVersion BatchVersion = 2

	// UpgradeAccountTaprootBatchVersion is the batch version where accounts
	// are automatically upgraded to Taproot accounts. We leave a gap up to
	// 10 on purpose to allow for in-between versions (that aren't dependent
	// on a lnd version) to be added. This version is used as the base
	// version when using a flag based versioning scheme, as this is now the
	// feature set that every lnd node supports.
	UpgradeAccountTaprootBatchVersion BatchVersion = 10

	// ZeroConfChannelsBatchVersion is the first version where orders can
	// set the flags to only match with confirmed/zeroconf channels.
	//
	// NOTE: This feature requires the runtime to support:
	// - The asker needs to open the channel with the right `zeroconf` bit.
	// - The bidder needs to be able to set the channel acceptor for the
	//   channel with the right  `Zeroconf` bool value && `MinDepth=0`.
	// The LND node should be running version v0.15.1-beta or newer.
	// Because this version already existed (in a deployed state) as a
	// config dependent version before we switched to a flag based version
	// scheme, this still has a linear version number. But the features
	// expressed by this version can also be expressed as
	// 	UpgradeAccountTaprootBatchVersion | ZeroConfChannelsFlag
	ZeroConfChannelsBatchVersion BatchVersion = 11
)
const (
	// LinearVersionEnd is the end of the linear version space. This is used
	// to determine whether a version is one of the old, linear ones or one
	// of the new, flag based ones.
	LinearVersionEnd BatchVersion = 0x0000_000F

	// ZeroConfChannelsFlag is the flag in the batch version that indicates
	// that orders can set the flags to only match with confirmed/zeroconf
	// channels.
	ZeroConfChannelsFlag BatchVersion = 0x0000_0010

	// UpgradeAccountTaprootV2Flag is the flag in the batch version that
	// indicates accounts can automatically be upgraded to Taproot v2 (using
	// the MuSig2 v1.0.0-rc2 spec).
	UpgradeAccountTaprootV2Flag BatchVersion = 0x0000_0020
)

func (BatchVersion) SupportsAccountExtension

func (bv BatchVersion) SupportsAccountExtension() bool

SupportsAccountExtension is a helper function to easily check if a version supports account extension after participating in a batch or not.

func (BatchVersion) SupportsAccountTaprootUpgrade

func (bv BatchVersion) SupportsAccountTaprootUpgrade() bool

SupportsAccountTaprootUpgrade is a helper function to easily check if a version supports upgrading SegWit v0 (p2wsh) accounts to Taproot (p2tr) or not.

func (BatchVersion) SupportsAccountTaprootV2Upgrade

func (bv BatchVersion) SupportsAccountTaprootV2Upgrade() bool

SupportsAccountTaprootV2Upgrade is a helper function to easily check if a version supports upgrading SegWit v0 (p2wsh) or Taproot v2 (p2tr) to Taproot v2 (p2tr) or not.

func (BatchVersion) SupportsUnannouncedChannels

func (bv BatchVersion) SupportsUnannouncedChannels() bool

SupportsUnannouncedChannels is a helper function to easily check if a version supports orders with unannounced channels or not.

func (BatchVersion) SupportsZeroConfChannels

func (bv BatchVersion) SupportsZeroConfChannels() bool

SupportsZeroConfChannels is the helper function to easily check if a version supports orders with zeroconf channels or not.

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

	// UnannouncedChannel signals if the resulting channel needs to be
	// announced or not.
	UnannouncedChannel bool

	// ZeroConfChannel signals if the resulting channels need to be zero
	// conf or not.
	ZeroConfChannel bool
}

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() ([hashSize]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,
	accountVersion account.Version) btcutil.Amount

ReservedValue returns the maximum value that could be deducted from a single account if the bid 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 ChanTypeSelector

type ChanTypeSelector func() ChannelType

ChanTypeSelector defines a function capable of selecting a channel type based on the version of an lnd node.

type ChannelAnnouncementConstraints

type ChannelAnnouncementConstraints uint8

ChannelAnnouncementConstraints is a numerical type used to denote if the channels created from a match can be announced or not.

const (
	// AnnouncementNoPreference denotes that the resulting channels can be
	// announced or not.
	AnnouncementNoPreference ChannelAnnouncementConstraints = 0

	// OnlyAnnounced denotes that the resulting channels must be announced
	// to the network.
	OnlyAnnounced ChannelAnnouncementConstraints = 1

	// OnlyUnannounced denotes that the resulting channels must not be
	// announced to the network.
	OnlyUnannounced ChannelAnnouncementConstraints = 2
)

type ChannelConfirmationConstraints

type ChannelConfirmationConstraints uint8

ChannelConfirmationConstraints is a numerical type used to denote if the channels created from a match is zero conf or not.

const (
	// ConfirmationNoPreference denotes that the resulting channel can be
	// zero conf or not.
	ConfirmationNoPreference ChannelConfirmationConstraints = 0

	// OnlyConfirmed denotes that the resulting channels must be confirmed
	// onchain before start routing.
	OnlyConfirmed ChannelConfirmationConstraints = 1

	// OnlyZeroConf denotes that the resulting channels can be used
	// without having to wait for onchain confirmations.
	OnlyZeroConf ChannelConfirmationConstraints = 2
)

type ChannelType

type ChannelType uint8

ChannelType is a numerical type that represents all possible channel types that are supported to be opened through the auction process.

const (
	// ChannelTypePeerDependent denotes that the resulting channel type from
	// an order match will depend on the shared features between its
	// participants.
	ChannelTypePeerDependent ChannelType = 0

	// ChannelTypeScriptEnforced represents a new channel type that builds
	// upon the anchors commitment format to enforce the maturity of a
	// leased channel in the commitment and HTLC outputs that pay directly
	// to the channel initiator.
	ChannelTypeScriptEnforced ChannelType = 1
)

NOTE: We avoid the use of iota as this type is stored on disk.

type ErrVersionMismatch

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

ErrVersionMismatch is the error that is returned if we don't implement the same batch verification version as the server.

func NewErrVersionMismatch

func NewErrVersionMismatch(clientVersion,
	serverVersion BatchVersion) *ErrVersionMismatch

NewErrVersionMismatch returns a new error.

func (*ErrVersionMismatch) Error

func (e *ErrVersionMismatch) Error() string

Error returns the underlying error message.

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

	// AuctionType is the market where this offer should be considered in.
	AuctionType AuctionType

	// 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 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

	// ChannelType denotes the channel type that must be used for the
	// resulting matched channels.
	ChannelType ChannelType

	// AllowedNodeIDs is the list of node ids this order is allowed to
	// match with.
	AllowedNodeIDs [][33]byte

	// NotAllowedNodeIDs is the list of node ids this order is not allowed
	// to match with.
	NotAllowedNodeIDs [][33]byte

	// IsPublic is the flag used to signal if the details of this order can
	// be shared in public marketplaces or not.
	IsPublic bool
	// 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, parseOpts ...ParseOption) (*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 interface {
	// Start starts all concurrent tasks the manager is responsible for.
	Start() error

	// Stop stops all concurrent tasks the manager is responsible for.
	Stop()

	// PrepareOrder validates an order, signs it and then stores it locally.
	PrepareOrder(ctx context.Context, order Order, acct *account.Account,
		terms *terms.AuctioneerTerms) (*ServerOrderParams, error)

	// OrderMatchValidate verifies an incoming batch is sane before
	// accepting it.
	OrderMatchValidate(batch *Batch, bestHeight uint32) error

	// HasPendingBatch returns whether a pending batch is currently being
	// processed.
	HasPendingBatch() bool

	// PendingBatch returns the current pending batch being validated.
	PendingBatch() *Batch

	// BatchSign returns the witness stack of all account inputs in a batch
	// that belong to the trader.
	BatchSign() (BatchSignature, AccountNonces, error)

	// BatchFinalize marks a batch as complete upon receiving the finalize
	// message from the auctioneer.
	BatchFinalize(batchID BatchID) error

	// OurNodePubkey returns our lnd node's public identity key or an error
	// if the manager wasn't fully started yet.
	OurNodePubkey() ([33]byte, error)
}

Manager is the interface a manager implements to deal with the orders.

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

	// BatchVersion is the batch version that we should use to verify new
	// batches against.
	BatchVersion BatchVersion
}

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 OrderMatchSignBegin 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 MockManager

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

MockManager is a mock of Manager interface.

func NewMockManager

func NewMockManager(ctrl *gomock.Controller) *MockManager

NewMockManager creates a new mock instance.

func (*MockManager) BatchFinalize

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

BatchFinalize mocks base method.

func (*MockManager) BatchSign

func (m *MockManager) BatchSign() (BatchSignature, AccountNonces, error)

BatchSign mocks base method.

func (*MockManager) EXPECT

func (m *MockManager) EXPECT() *MockManagerMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockManager) HasPendingBatch

func (m *MockManager) HasPendingBatch() bool

HasPendingBatch mocks base method.

func (*MockManager) OrderMatchValidate

func (m *MockManager) OrderMatchValidate(batch *Batch, bestHeight uint32) error

OrderMatchValidate mocks base method.

func (*MockManager) OurNodePubkey

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

OurNodePubkey mocks base method.

func (*MockManager) PendingBatch

func (m *MockManager) PendingBatch() *Batch

PendingBatch mocks base method.

func (*MockManager) PrepareOrder

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

PrepareOrder mocks base method.

func (*MockManager) Start

func (m *MockManager) Start() error

Start mocks base method.

func (*MockManager) Stop

func (m *MockManager) Stop()

Stop mocks base method.

type MockManagerMockRecorder

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

MockManagerMockRecorder is the mock recorder for MockManager.

func (*MockManagerMockRecorder) BatchFinalize

func (mr *MockManagerMockRecorder) BatchFinalize(batchID interface{}) *gomock.Call

BatchFinalize indicates an expected call of BatchFinalize.

func (*MockManagerMockRecorder) BatchSign

func (mr *MockManagerMockRecorder) BatchSign() *gomock.Call

BatchSign indicates an expected call of BatchSign.

func (*MockManagerMockRecorder) HasPendingBatch

func (mr *MockManagerMockRecorder) HasPendingBatch() *gomock.Call

HasPendingBatch indicates an expected call of HasPendingBatch.

func (*MockManagerMockRecorder) OrderMatchValidate

func (mr *MockManagerMockRecorder) OrderMatchValidate(batch, bestHeight interface{}) *gomock.Call

OrderMatchValidate indicates an expected call of OrderMatchValidate.

func (*MockManagerMockRecorder) OurNodePubkey

func (mr *MockManagerMockRecorder) OurNodePubkey() *gomock.Call

OurNodePubkey indicates an expected call of OurNodePubkey.

func (*MockManagerMockRecorder) PendingBatch

func (mr *MockManagerMockRecorder) PendingBatch() *gomock.Call

PendingBatch indicates an expected call of PendingBatch.

func (*MockManagerMockRecorder) PrepareOrder

func (mr *MockManagerMockRecorder) PrepareOrder(ctx, order, acct, terms interface{}) *gomock.Call

PrepareOrder indicates an expected call of PrepareOrder.

func (*MockManagerMockRecorder) Start

func (mr *MockManagerMockRecorder) Start() *gomock.Call

Start indicates an expected call of Start.

func (*MockManagerMockRecorder) Stop

func (mr *MockManagerMockRecorder) Stop() *gomock.Call

Stop indicates an expected call of Stop.

type MockOrder

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

MockOrder is a mock of Order interface.

func NewMockOrder

func NewMockOrder(ctrl *gomock.Controller) *MockOrder

NewMockOrder creates a new mock instance.

func (*MockOrder) Details

func (m *MockOrder) Details() *Kit

Details mocks base method.

func (*MockOrder) Digest

func (m *MockOrder) Digest() ([32]byte, error)

Digest mocks base method.

func (*MockOrder) EXPECT

func (m *MockOrder) EXPECT() *MockOrderMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockOrder) Nonce

func (m *MockOrder) Nonce() Nonce

Nonce mocks base method.

func (*MockOrder) ReservedValue

func (m *MockOrder) ReservedValue(feeSchedule terms.FeeSchedule, accountVersion account.Version) btcutil.Amount

ReservedValue mocks base method.

func (*MockOrder) Type

func (m *MockOrder) Type() Type

Type mocks base method.

type MockOrderMockRecorder

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

MockOrderMockRecorder is the mock recorder for MockOrder.

func (*MockOrderMockRecorder) Details

func (mr *MockOrderMockRecorder) Details() *gomock.Call

Details indicates an expected call of Details.

func (*MockOrderMockRecorder) Digest

func (mr *MockOrderMockRecorder) Digest() *gomock.Call

Digest indicates an expected call of Digest.

func (*MockOrderMockRecorder) Nonce

func (mr *MockOrderMockRecorder) Nonce() *gomock.Call

Nonce indicates an expected call of Nonce.

func (*MockOrderMockRecorder) ReservedValue

func (mr *MockOrderMockRecorder) ReservedValue(feeSchedule, accountVersion interface{}) *gomock.Call

ReservedValue indicates an expected call of ReservedValue.

func (*MockOrderMockRecorder) Type

func (mr *MockOrderMockRecorder) Type() *gomock.Call

Type indicates an expected call of Type.

type MockStore

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

MockStore is a mock of Store interface.

func NewMockStore

func NewMockStore(ctrl *gomock.Controller) *MockStore

NewMockStore creates a new mock instance.

func (*MockStore) DeleteOrder

func (m *MockStore) DeleteOrder(arg0 Nonce) error

DeleteOrder mocks base method.

func (*MockStore) EXPECT

func (m *MockStore) EXPECT() *MockStoreMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockStore) GetOrder

func (m *MockStore) GetOrder(arg0 Nonce) (Order, error)

GetOrder mocks base method.

func (*MockStore) GetOrders

func (m *MockStore) GetOrders() ([]Order, error)

GetOrders mocks base method.

func (*MockStore) MarkBatchComplete

func (m *MockStore) MarkBatchComplete() error

MarkBatchComplete mocks base method.

func (*MockStore) StorePendingBatch

func (m *MockStore) StorePendingBatch(arg0 *Batch, orders []Nonce, orderModifiers [][]Modifier, accounts []*account.Account, accountModifiers [][]account.Modifier) error

StorePendingBatch mocks base method.

func (*MockStore) SubmitOrder

func (m *MockStore) SubmitOrder(arg0 Order) error

SubmitOrder mocks base method.

func (*MockStore) UpdateOrder

func (m *MockStore) UpdateOrder(arg0 Nonce, arg1 ...Modifier) error

UpdateOrder mocks base method.

func (*MockStore) UpdateOrders

func (m *MockStore) UpdateOrders(arg0 []Nonce, arg1 [][]Modifier) error

UpdateOrders mocks base method.

type MockStoreMockRecorder

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

MockStoreMockRecorder is the mock recorder for MockStore.

func (*MockStoreMockRecorder) DeleteOrder

func (mr *MockStoreMockRecorder) DeleteOrder(arg0 interface{}) *gomock.Call

DeleteOrder indicates an expected call of DeleteOrder.

func (*MockStoreMockRecorder) GetOrder

func (mr *MockStoreMockRecorder) GetOrder(arg0 interface{}) *gomock.Call

GetOrder indicates an expected call of GetOrder.

func (*MockStoreMockRecorder) GetOrders

func (mr *MockStoreMockRecorder) GetOrders() *gomock.Call

GetOrders indicates an expected call of GetOrders.

func (*MockStoreMockRecorder) MarkBatchComplete

func (mr *MockStoreMockRecorder) MarkBatchComplete() *gomock.Call

MarkBatchComplete indicates an expected call of MarkBatchComplete.

func (*MockStoreMockRecorder) StorePendingBatch

func (mr *MockStoreMockRecorder) StorePendingBatch(arg0, orders, orderModifiers, accounts, accountModifiers interface{}) *gomock.Call

StorePendingBatch indicates an expected call of StorePendingBatch.

func (*MockStoreMockRecorder) SubmitOrder

func (mr *MockStoreMockRecorder) SubmitOrder(arg0 interface{}) *gomock.Call

SubmitOrder indicates an expected call of SubmitOrder.

func (*MockStoreMockRecorder) UpdateOrder

func (mr *MockStoreMockRecorder) UpdateOrder(arg0 interface{}, arg1 ...interface{}) *gomock.Call

UpdateOrder indicates an expected call of UpdateOrder.

func (*MockStoreMockRecorder) UpdateOrders

func (mr *MockStoreMockRecorder) UpdateOrders(arg0, arg1 interface{}) *gomock.Call

UpdateOrders indicates an expected call of UpdateOrders.

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() ([hashSize]byte, error)

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

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

type ParseOption

type ParseOption func(*parseOptions)

ParseOption defines a set of functional param options that can be used to modify our we parse orders based on some optional directives.

func WithDefaultChannelType

func WithDefaultChannelType(selector ChanTypeSelector) ParseOption

WithDefaultChannelType allows a caller to select a default channel type based on the version of the lnd node attempting to create the order.

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)

	// DeleteOrder removes the order with the given Nonce.
	//
	// Note: this method deletes the order without checking if it is
	// referenced somewhere else (e.g. pending batch).
	DeleteOrder(Nonce) 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

	// VersionChannelType is the order version that added use of the channel
	// type field. Only orders with this version are allowed to use the
	// channel type field.
	VersionChannelType Version = 5
)

Jump to

Keyboard shortcuts

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