Documentation ¶
Index ¶
- Constants
- func LiveFeeRates(btc *Backend, t *testing.T, standards map[string]uint64)
- func LiveP2SHStats(btc *Backend, t *testing.T, numToDo int)
- func LiveUTXOStats(btc *Backend, t *testing.T)
- func NewBackend(cfg *asset.BackendConfig) (asset.Backend, error)
- func ParseBondTx(ver uint16, msgTx *wire.MsgTx, chainParams *chaincfg.Params, segwit bool) (amt int64, bondAddr string, bondPubKeyHash []byte, lockTime int64, ...)
- func TestMedianFees(btc *Backend, t *testing.T)
- func TestMedianFeesTheHardWay(btc *Backend, t *testing.T)
- type BTCFeeTx
- type Backend
- func (btc *Backend) BlockChannel(size int) <-chan *asset.BlockUpdate
- func (btc *Backend) BondCoin(ctx context.Context, ver uint16, coinID []byte) (amt, lockTime, confs int64, acct account.AccountID, err error)
- func (dcr *Backend) BondVer() uint16
- func (btc *Backend) CheckSwapAddress(addr string) bool
- func (btc *Backend) Connect(ctx context.Context) (*sync.WaitGroup, error)
- func (btc *Backend) Contract(coinID []byte, redeemScript []byte) (*asset.Contract, error)
- func (btc *Backend) FeeRate(ctx context.Context) (uint64, error)
- func (btc *Backend) FundingCoin(_ context.Context, coinID []byte, redeemScript []byte) (asset.FundingCoin, error)
- func (*Backend) Info() *asset.BackendInfo
- func (btc *Backend) Net() *chaincfg.Params
- func (btc *Backend) ParseBondTx(ver uint16, rawTx []byte) (bondCoinID []byte, amt int64, bondAddr string, bondPubKeyHash []byte, ...)
- func (btc *Backend) Redemption(redemptionID, contractID, _ []byte) (asset.Coin, error)
- func (btc *Backend) Synced() (bool, error)
- func (btc *Backend) TxData(coinID []byte) ([]byte, error)
- func (btc *Backend) ValidateCoinID(coinID []byte) (string, error)
- func (btc *Backend) ValidateContract(contract []byte) error
- func (btc *Backend) ValidateFeeRate(c asset.Coin, reqFeeRate uint64) bool
- func (btc *Backend) ValidateOrderFunding(swapVal, valSum, _, inputsSize, maxSwaps uint64, nfo *dex.Asset) bool
- func (btc *Backend) ValidateSecret(secret, contract []byte) bool
- func (btc *Backend) VerifyUnspentCoin(_ context.Context, coinID []byte) error
- type BackendCloneConfig
- type BlockFeeTransactions
- type Driver
- func (d *Driver) DecodeCoinID(coinID []byte) (string, error)
- func (d *Driver) MinBondSize(maxFeeRate uint64) uint64
- func (d *Driver) MinLotSize(maxFeeRate uint64) uint64
- func (d *Driver) Name() string
- func (d *Driver) Setup(cfg *asset.BackendConfig) (asset.Backend, error)
- func (d *Driver) UnitInfo() dex.UnitInfo
- func (d *Driver) Version() uint32
- type FeeTx
- type GetBlockVerboseResult
- type GetBlockchainInfoResult
- type Input
- type JoinSplit
- type Output
- func (output *Output) Addresses() []string
- func (output *Output) Auth(pubkeys, sigs [][]byte, msg []byte) error
- func (output *Output) Confirmations(context.Context) (int64, error)
- func (output *Output) ID() []byte
- func (output *Output) SpendSize() uint32
- func (output *Output) String() string
- func (output *Output) Value() uint64
- type RPCClient
- func (rc *RPCClient) Call(method string, args []any, thing any) error
- func (rc *RPCClient) EstimateFee(confTarget int64) (uint64, error)
- func (rc *RPCClient) EstimateSmartFee(confTarget int64, mode *btcjson.EstimateSmartFeeMode) (uint64, error)
- func (rc *RPCClient) GetBestBlockHash() (*chainhash.Hash, error)
- func (rc *RPCClient) GetBlockChainInfo() (*GetBlockchainInfoResult, error)
- func (rc *RPCClient) GetBlockVerbose(blockHash *chainhash.Hash) (*GetBlockVerboseResult, error)
- func (rc *RPCClient) GetMsgBlock(blockHash *chainhash.Hash) (*wire.MsgBlock, error)
- func (rc *RPCClient) GetRawBlock(blockHash *chainhash.Hash) ([]byte, error)
- func (rc *RPCClient) GetRawTransaction(txHash *chainhash.Hash) ([]byte, error)
- func (rc *RPCClient) GetRawTransactionVerbose(txHash *chainhash.Hash) (*VerboseTxExtended, error)
- func (rc *RPCClient) GetTxOut(txHash *chainhash.Hash, index uint32, mempool bool) (*btcjson.GetTxOutResult, error)
- func (rc *RPCClient) RawRequest(method string, params []json.RawMessage) (json.RawMessage, error)
- type RawRequester
- type TXIO
- type Tx
- type UTXO
- type VerboseHeader
- type VerboseTxExtended
Constants ¶
const ( BipID = 0 BondVersion = 0 )
const ErrReorgDetected = dex.ErrorKind("reorg detected")
Variables ¶
This section is empty.
Functions ¶
func LiveFeeRates ¶
LiveFeeRates scans a mapping of txid -> fee rate checking that the backend returns the expected fee rate.
func LiveP2SHStats ¶
LiveP2SHStats will scan the provided Backend's node for inputs that spend pay-to-script-hash outputs. The pubkey scripts and redeem scripts are examined to ensure the backend understands what they are and can extract addresses. Ideally, the stats will show no scripts which were unparseable by the backend, but the presence of unknowns is not an error.
func LiveUTXOStats ¶
LiveUTXOStats will scan the provided Backend's node for transaction outputs. The outputs are requested with GetRawTransactionVerbose, and statistics collected regarding spendability and pubkey script types. This test does not request via the Backend.UTXO method and is not meant to cover that code. Instead, these tests check the backend's real-world blockchain literacy. Ideally, the stats will show no scripts which were unparseable by the backend, but the presence of unknowns is not an error.
func NewBackend ¶
func NewBackend(cfg *asset.BackendConfig) (asset.Backend, error)
NewBackend is the exported constructor by which the DEX will import the backend. The configPath can be an empty string, in which case the standard system location of the bitcoind config file is assumed.
func ParseBondTx ¶ added in v0.6.0
func ParseBondTx(ver uint16, msgTx *wire.MsgTx, chainParams *chaincfg.Params, segwit bool) (amt int64, bondAddr string, bondPubKeyHash []byte, lockTime int64, acct account.AccountID, err error)
ParseBondTx performs basic validation of a serialized time-locked fidelity bond transaction given the bond's P2SH or P2WSH redeem script.
The transaction must have at least two outputs: out 0 pays to a P2SH address (the bond), and out 1 is a nulldata output that commits to an account ID. There may also be a change output.
Returned: The bond's coin ID (i.e. encoded UTXO) of the bond output. The bond output's amount and P2SH/P2WSH address. The lockTime and pubkey hash data pushes from the script. The account ID from the second output is also returned.
Properly formed transactions:
- The bond output (vout 0) must be a P2SH/P2WSH output.
- The bond's redeem script must be of the form: <lockTime[4]> OP_CHECKLOCKTIMEVERIFY OP_DROP OP_DUP OP_HASH160 <pubkeyhash[20]> OP_EQUALVERIFY OP_CHECKSIG
- The null data output (vout 1) must have a 58-byte data push (ver | account ID | lockTime | pubkeyHash).
- The transaction must have a zero locktime and expiry.
- All inputs must have the max sequence num set (finalized).
- The transaction must pass the checks in the blockchain.CheckTransactionSanity function.
func TestMedianFees ¶ added in v0.5.0
func TestMedianFeesTheHardWay ¶ added in v0.5.0
Types ¶
type BTCFeeTx ¶ added in v1.0.0
BTCFeeTx is the FeeTx for a standard Bitcoin MsgTx.
type Backend ¶
type Backend struct {
// contains filtered or unexported fields
}
Backend is a dex backend for Bitcoin or a Bitcoin clone. It has methods for fetching UTXO information and subscribing to block updates. It maintains a cache of block data for quick lookups. Backend implements asset.Backend, so provides exported methods for DEX-related blockchain info.
func NewBTCClone ¶
func NewBTCClone(cloneCfg *BackendCloneConfig) (*Backend, error)
NewBTCClone creates a BTC backend for a set of network parameters and default network ports. A BTC clone can use this method, possibly in conjunction with ReadCloneParams, to create a Backend for other assets with minimal coding. See ReadCloneParams and CompatibilityCheck for more info.
func (*Backend) BlockChannel ¶
func (btc *Backend) BlockChannel(size int) <-chan *asset.BlockUpdate
BlockChannel creates and returns a new channel on which to receive block updates. If the returned channel is ever blocking, there will be no error logged from the btc package. Part of the asset.Backend interface.
func (*Backend) BondCoin ¶ added in v0.6.0
func (btc *Backend) BondCoin(ctx context.Context, ver uint16, coinID []byte) (amt, lockTime, confs int64, acct account.AccountID, err error)
BondCoin locates a bond transaction output, validates the entire transaction, and returns the amount, encoded lockTime and account ID, and the confirmations of the transaction. It is a CoinNotFoundError if the transaction output is spent.
func (*Backend) CheckSwapAddress ¶ added in v0.6.0
CheckSwapAddress checks that the given address is parseable, and suitable as a redeem address in a swap contract script.
func (*Backend) Contract ¶
Contract is part of the asset.Backend interface. An asset.Contract is an output that has been validated as a swap contract for the passed redeem script. A spendable output is one that can be spent in the next block. Every output from a non-coinbase transaction is spendable immediately. Coinbase outputs are only spendable after CoinbaseMaturity confirmations. Pubkey scripts can be P2PKH or P2SH. Multi-sig P2SH redeem scripts are supported.
func (*Backend) FundingCoin ¶
func (btc *Backend) FundingCoin(_ context.Context, coinID []byte, redeemScript []byte) (asset.FundingCoin, error)
FundingCoin is an unspent output.
func (*Backend) Info ¶ added in v0.5.0
func (*Backend) Info() *asset.BackendInfo
Info provides some general information about the backend.
func (*Backend) Net ¶ added in v0.2.0
Net returns the *chaincfg.Params. This is not part of the asset.Backend interface, and is exported as a convenience for embedding types.
func (*Backend) ParseBondTx ¶ added in v0.6.0
func (btc *Backend) ParseBondTx(ver uint16, rawTx []byte) (bondCoinID []byte, amt int64, bondAddr string, bondPubKeyHash []byte, lockTime int64, acct account.AccountID, err error)
ParseBondTx makes the package-level ParseBondTx pure function accessible via a Backend instance. This performs basic validation of a serialized time-locked fidelity bond transaction given the bond's P2SH redeem script.
func (*Backend) Redemption ¶
Redemption is an input that redeems a swap contract.
func (*Backend) TxData ¶ added in v0.2.0
TxData is the raw transaction bytes. SPV clients rebroadcast the transaction bytes to get around not having a mempool to check.
func (*Backend) ValidateCoinID ¶
ValidateCoinID attempts to decode the coinID.
func (*Backend) ValidateContract ¶
ValidateContract ensures that the swap contract is constructed properly, and contains valid sender and receiver addresses.
func (*Backend) ValidateFeeRate ¶ added in v0.5.0
ValidateFeeRate checks that the transaction fees used to initiate the contract are sufficient.
func (*Backend) ValidateOrderFunding ¶ added in v1.0.0
func (*Backend) ValidateSecret ¶
ValidateSecret checks that the secret satisfies the contract.
func (*Backend) VerifyUnspentCoin ¶
VerifyUnspentCoin attempts to verify a coin ID by decoding the coin ID and retrieving the corresponding UTXO. If the coin is not found or no longer unspent, an asset.CoinNotFoundError is returned.
type BackendCloneConfig ¶ added in v0.2.0
type BackendCloneConfig struct { Name string Segwit bool ConfigPath string AddressDecoder dexbtc.AddressDecoder Logger dex.Logger Net dex.Network ChainParams *chaincfg.Params Ports dexbtc.NetPorts // ManualFeeScan specifies that median block fees should be calculated by // scanning transactions since the getblockstats rpc is not available. // Median block fees are used to estimate fee rates when the cache is not // primed. ManualMedianFee bool // NoCompetitionFeeRate specifies a fee rate to use if estimatesmartfee // or estimatefee aren't ready and the median fee is finding relatively // empty blocks. NoCompetitionFeeRate uint64 // DumbFeeEstimates is for asset's whose RPC is estimatefee instead of // estimatesmartfee. DumbFeeEstimates bool // Argsless fee estimates are for assets who don't take an argument for // number of blocks to estimatefee. ArglessFeeEstimates bool // FeeConfs specifies the target number of confirmations to use for // estimate(smart)fee. If not set, default value is 1, FeeConfs int64 // MaxFeeBlocks is the maximum number of blocks that can be evaluated for // median fee calculations. If > 100 txs are not seen in the last // MaxFeeBlocks, then the NoCompetitionRate will be returned as the median // fee. MaxFeeBlocks int // BooleanGetBlockRPC will pass true instead of 2 as the getblock argument. BooleanGetBlockRPC bool // BlockDeserializer can be used in place of (*wire.MsgBlock).Deserialize. BlockDeserializer func(blk []byte) (*wire.MsgBlock, error) // TxDeserializer is an optional function used to deserialize a transaction. // TxDeserializer is only used if ManualMedianFee is true. TxDeserializer func([]byte) (*wire.MsgTx, error) // TxHasher is a function that generates a tx hash from a MsgTx. TxHasher func(*wire.MsgTx) *chainhash.Hash // BlockFeeTransactions is a function to fetch a set of FeeTx and a previous // block hash for a specific block. BlockFeeTransactions BlockFeeTransactions // NumericGetRawRPC uses a numeric boolean indicator for the // getrawtransaction RPC. NumericGetRawRPC bool // ShieldedIO is a function to read a transaction and calculate the shielded // input and output amounts. This is a temporary measure until zcashd // encodes valueBalanceOrchard in their getrawtransaction RPC results. ShieldedIO func(tx *VerboseTxExtended) (in, out uint64, err error) // RelayAddr is an address for a NodeRelay. RelayAddr string FeeFetcher *txfee.FeeFetcher }
BackendCloneConfig captures the arguments necessary to configure a BTC clone backend.
type BlockFeeTransactions ¶ added in v0.5.0
type BlockFeeTransactions func(rc *RPCClient, blockHash *chainhash.Hash) (feeTxs []FeeTx, prevBlock chainhash.Hash, err error)
BlockFeeTransactions is a function that fetches a set of FeeTx, used to calculate median-fees manually.
type Driver ¶
type Driver struct{}
Driver implements asset.Driver.
func (*Driver) DecodeCoinID ¶
DecodeCoinID creates a human-readable representation of a coin ID for Bitcoin.
func (*Driver) MinBondSize ¶ added in v1.0.0
MinBondSize calculates the minimum bond size for a given fee rate that avoids dust outputs on the bond and refund txs, assuming the maxFeeRate doesn't change.
func (*Driver) MinLotSize ¶ added in v1.0.0
MinLotSize calculates the minimum bond size for a given fee rate that avoids dust outputs on the swap and refund txs, assuming the maxFeeRate doesn't change.
type FeeTx ¶ added in v0.5.0
type FeeTx interface { PrevOuts() []wire.OutPoint FeeRate(map[chainhash.Hash]map[int]int64) (uint64, error) }
FeeTx is a representation of a transaction that 1) has zero or more previous outpoints to fetch, and 2) given the requested outpoints, can report its tx fee rate, in Sats/byte.
type GetBlockVerboseResult ¶ added in v0.5.0
type GetBlockVerboseResult struct { Hash string `json:"hash"` Confirmations int64 `json:"confirmations"` Height int64 `json:"height"` Tx []string `json:"tx,omitempty"` PreviousHash string `json:"previousblockhash"` }
GetBlockVerboseResult is a subset of *btcjson.GetBlockVerboseResult.
type GetBlockchainInfoResult ¶ added in v0.4.0
type GetBlockchainInfoResult struct { Blocks int64 `json:"blocks"` Headers int64 `json:"headers"` BestBlockHash string `json:"bestblockhash"` InitialBlockDownload bool `json:"initialblockdownload"` }
GetBlockchainInfoResult models the data returned from the getblockchaininfo command.
type Input ¶
type Input struct { TXIO // contains filtered or unexported fields }
Input is a transaction input.
func (*Input) Confirmations ¶
Confirmations returns the number of confirmations on this input's transaction.
type JoinSplit ¶ added in v0.5.0
type JoinSplit struct { // Old = input Old uint64 `json:"vpub_oldZat"` // New = output New uint64 `json:"vpub_newZat"` }
JoinSplit represents a Zcash JoinSplit. https://zips.z.cash/protocol/canopy.pdf section 4.11
type Output ¶
type Output struct { TXIO // contains filtered or unexported fields }
Output represents a transaction output.
func (*Output) Auth ¶
Auth verifies that the output pays to the supplied public key(s). This is an asset.Backend method.
func (*Output) Confirmations ¶
Confirmations returns the number of confirmations on this output's transaction.
func (*Output) SpendSize ¶
SpendSize returns the maximum size of the serialized TxIn that spends this output, in bytes. This is a method of the asset.Output interface.
type RPCClient ¶ added in v0.4.0
type RPCClient struct {
// contains filtered or unexported fields
}
RPCClient is a bitcoind wallet RPC client that uses rpcclient.Client's RawRequest for wallet-related calls.
func (*RPCClient) Call ¶ added in v0.4.3
Call is used to marshal parameters and send requests to the RPC server via (*rpcclient.Client).RawRequest. If `thing` is non-nil, the result will be marshaled into `thing`.
func (*RPCClient) EstimateFee ¶ added in v0.5.0
EstimateFee requests the server to estimate a fee level.
func (*RPCClient) EstimateSmartFee ¶ added in v0.4.0
func (rc *RPCClient) EstimateSmartFee(confTarget int64, mode *btcjson.EstimateSmartFeeMode) (uint64, error)
EstimateSmartFee requests the server to estimate a fee level.
func (*RPCClient) GetBestBlockHash ¶ added in v0.4.0
GetBestBlockHash returns the hash of the best block in the longest block chain.
func (*RPCClient) GetBlockChainInfo ¶ added in v0.4.0
func (rc *RPCClient) GetBlockChainInfo() (*GetBlockchainInfoResult, error)
GetBlockChainInfo returns information related to the processing state of various chain-specific details.
func (*RPCClient) GetBlockVerbose ¶ added in v0.4.0
func (rc *RPCClient) GetBlockVerbose(blockHash *chainhash.Hash) (*GetBlockVerboseResult, error)
GetBlockVerbose fetches verbose block data for the block with the given hash.
func (*RPCClient) GetMsgBlock ¶ added in v0.5.0
func (*RPCClient) GetRawBlock ¶ added in v0.5.0
func (*RPCClient) GetRawTransaction ¶ added in v0.4.0
GetRawTransaction retrieves tx's information.
func (*RPCClient) GetRawTransactionVerbose ¶ added in v0.4.0
func (rc *RPCClient) GetRawTransactionVerbose(txHash *chainhash.Hash) (*VerboseTxExtended, error)
GetRawTransactionVerbose retrieves the verbose tx information.
func (*RPCClient) GetTxOut ¶ added in v0.4.0
func (rc *RPCClient) GetTxOut(txHash *chainhash.Hash, index uint32, mempool bool) (*btcjson.GetTxOutResult, error)
GetTxOut returns the transaction output info if it's unspent and nil, otherwise.
func (*RPCClient) RawRequest ¶ added in v0.4.0
func (rc *RPCClient) RawRequest(method string, params []json.RawMessage) (json.RawMessage, error)
RawRequest is a wrapper func for callers that are not context-enabled.
type RawRequester ¶ added in v0.4.0
type RawRequester interface { RawRequest(context.Context, string, []json.RawMessage) (json.RawMessage, error) Shutdown() WaitForShutdown() }
RawRequester is for sending context-aware RPC requests, and has methods for shutting down the underlying connection. The returned error should be of type dcrjson.RPCError if non-nil.
type TXIO ¶
type TXIO struct {
// contains filtered or unexported fields
}
TXIO is common information stored with an Input or Output.
func (*TXIO) InputsValue ¶ added in v1.0.0
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx is information about a transaction. It must satisfy the asset.DEXTx interface to be DEX-compatible.
type UTXO ¶
type UTXO struct {
*Output
}
A UTXO is information regarding an unspent transaction output.
func (*UTXO) Confirmations ¶
Confirmations returns the number of confirmations on this output's transaction. See also (*Output).Confirmations. This function differs from the Output method in that it is necessary to relocate the utxo after a reorg, it may error if the output is spent.
type VerboseHeader ¶ added in v1.0.0
type VerboseHeader struct { Hash string `json:"hash"` Confirmations int64 `json:"confirmations"` Height int32 `json:"height"` Version int32 `json:"version"` VersionHex string `json:"versionHex"` MerkleRoot string `json:"merkleroot"` Time int64 `json:"time"` // Nonce uint64 `json:"nonce"` Bits string `json:"bits"` Difficulty float64 `json:"difficulty"` PreviousHash string `json:"previousblockhash,omitempty"` NextHash string `json:"nextblockhash,omitempty"` }
type VerboseTxExtended ¶ added in v0.5.0
type VerboseTxExtended struct { Raw dex.Bytes `json:"hex"` Hex string Txid string `json:"txid"` Size int32 `json:"size,omitempty"` Vsize int32 `json:"vsize,omitempty"` Vin []*btcjson.Vin `json:"vin"` Vout []*btcjson.Vout `json:"vout"` BlockHash string `json:"blockhash,omitempty"` Confirmations uint64 `json:"confirmations,omitempty"` VJoinSplit []*JoinSplit `json:"vjoinsplit"` ValueBalanceSapling int64 `json:"valueBalanceZat"` // Sapling pool // ValueBalanceOrchard is disabled until zcashd encodes valueBalanceOrchard. ValueBalanceOrchard int64 `json:"valueBalanceOrchardZat"` // Orchard pool }
VerboseTxExtended is a subset of *btcjson.TxRawResult, with the addition of some asset-specific fields.