btc

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2021 License: BlueOak-1.0.0 Imports: 28 Imported by: 9

Documentation

Index

Constants

View Source
const (

	// BipID is the BIP-0044 asset ID.
	BipID = 0
)

Variables

View Source
var (

	// WalletInfo defines some general information about a Bitcoin wallet.
	WalletInfo = &asset.WalletInfo{
		Name:              "Bitcoin",
		Units:             "Satoshis",
		Version:           version,
		DefaultConfigPath: dexbtc.SystemConfigPath("bitcoin"),
		ConfigOpts:        configOpts,
	}
)

Functions

func NewWallet

func NewWallet(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) (asset.Wallet, error)

NewWallet is the exported constructor by which the DEX will import the exchange wallet. The wallet will shut down when the provided context is canceled. The configPath can be an empty string, in which case the standard system location of the bitcoind config file is assumed.

Types

type BTCCloneCFG

type BTCCloneCFG struct {
	WalletCFG           *asset.WalletConfig
	MinNetworkVersion   uint64
	WalletInfo          *asset.WalletInfo
	Symbol              string
	Logger              dex.Logger
	Network             dex.Network
	ChainParams         *chaincfg.Params
	Ports               dexbtc.NetPorts
	DefaultFallbackFee  uint64 // sats/byte
	DefaultFeeRateLimit uint64 // sats/byte
	// LegacyBalance is for clones that don't yet support the 'getbalances' RPC
	// call.
	LegacyBalance bool
	// If segwit is false, legacy addresses and contracts will be used. This
	// setting must match the configuration of the server's asset backend.
	Segwit bool
	// LegacyRawFeeLimit can be true if the RPC only supports the boolean
	// allowHighFees argument to the sendrawtransaction RPC.
	LegacyRawFeeLimit bool
	// AddressDecoder is an optional argument that can decode an address string
	// into btcutil.Address. If AddressDecoder is not supplied,
	// btcutil.DecodeAddress will be used.
	AddressDecoder dexbtc.AddressDecoder
	// ArglessChangeAddrRPC can be true if the getrawchangeaddress takes no
	// address-type argument.
	ArglessChangeAddrRPC bool
	// NonSegwitSigner can be true if the transaction signature hash data is not
	// the standard for non-segwit Bitcoin. If nil, txscript.
	NonSegwitSigner TxInSigner
	// FeeEstimator provides a way to get fees given an RawRequest-enabled
	// client and a confirmation target.
	FeeEstimator func(context.Context, RawRequester, uint64) (uint64, error)
}

BTCCloneCFG holds clone specific parameters.

type Driver

type Driver struct{}

Driver implements asset.Driver.

func (*Driver) DecodeCoinID

func (d *Driver) DecodeCoinID(coinID []byte) (string, error)

DecodeCoinID creates a human-readable representation of a coin ID for Bitcoin.

func (*Driver) Info

func (d *Driver) Info() *asset.WalletInfo

Info returns basic information about the wallet and asset.

func (*Driver) Setup

func (d *Driver) Setup(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) (asset.Wallet, error)

Setup creates the BTC exchange wallet. Start the wallet with its Run method.

type ExchangeWallet

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

ExchangeWallet is a wallet backend for Bitcoin. The backend is how the DEX client app communicates with the BTC blockchain and wallet. ExchangeWallet satisfies the dex.Wallet interface.

func BTCCloneWallet

func BTCCloneWallet(cfg *BTCCloneCFG) (*ExchangeWallet, error)

BTCCloneWallet creates a wallet 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 ExchangeWallet for other assets with minimal coding.

func (*ExchangeWallet) Address

func (btc *ExchangeWallet) Address() (string, error)

Address returns a new external address from the wallet.

func (*ExchangeWallet) AuditContract

func (btc *ExchangeWallet) AuditContract(coinID, contract, txData dex.Bytes) (*asset.AuditInfo, error)

AuditContract retrieves information about a swap contract on the blockchain. AuditContract would be used to audit the counter-party's contract during a swap.

func (*ExchangeWallet) Balance

func (btc *ExchangeWallet) Balance() (*asset.Balance, error)

Balance returns the total available funds in the wallet. Part of the asset.Wallet interface.

func (*ExchangeWallet) Confirmations

func (btc *ExchangeWallet) Confirmations(_ context.Context, id dex.Bytes) (confs uint32, spent bool, err error)

Confirmations gets the number of confirmations for the specified coin ID by first checking for a unspent output, and if not found, searching indexed wallet transactions.

func (*ExchangeWallet) Connect

func (btc *ExchangeWallet) Connect(ctx context.Context) (*sync.WaitGroup, error)

Connect connects the wallet to the RPC server. Satisfies the dex.Connector interface.

func (*ExchangeWallet) FindRedemption

func (btc *ExchangeWallet) FindRedemption(ctx context.Context, coinID dex.Bytes) (redemptionCoin, secret dex.Bytes, err error)

FindRedemption watches for the input that spends the specified contract coin, and returns the spending input and the contract's secret key when it finds a spender.

This method blocks until the redemption is found, an error occurs or the provided context is canceled.

func (*ExchangeWallet) FundOrder

func (btc *ExchangeWallet) FundOrder(ord *asset.Order) (asset.Coins, []dex.Bytes, error)

FundOrder selects coins for use in an order. The coins will be locked, and will not be returned in subsequent calls to FundOrder or calculated in calls to Available, unless they are unlocked with ReturnCoins. The returned []dex.Bytes contains the redeem scripts for the selected coins. Equal number of coins and redeemed scripts must be returned. A nil or empty dex.Bytes should be appended to the redeem scripts collection for coins with no redeem script.

func (*ExchangeWallet) FundingCoins

func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error)

FundingCoins gets funding coins for the coin IDs. The coins are locked. This method might be called to reinitialize an order from data stored externally. This method will only return funding coins, e.g. unspent transaction outputs.

func (*ExchangeWallet) Info

func (btc *ExchangeWallet) Info() *asset.WalletInfo

Info returns basic information about the wallet and asset.

func (*ExchangeWallet) Lock

func (btc *ExchangeWallet) Lock() error

Lock locks the ExchangeWallet and the underlying bitcoind wallet.

func (*ExchangeWallet) Locked

func (btc *ExchangeWallet) Locked() bool

Locked will be true if the wallet is currently locked.

func (*ExchangeWallet) LocktimeExpired

func (btc *ExchangeWallet) LocktimeExpired(contract dex.Bytes) (bool, time.Time, error)

LocktimeExpired returns true if the specified contract's locktime has expired, making it possible to issue a Refund.

func (*ExchangeWallet) MaxOrder added in v0.2.0

func (btc *ExchangeWallet) MaxOrder(lotSize, feeSuggestion uint64, nfo *dex.Asset) (*asset.SwapEstimate, error)

MaxOrder generates information about the maximum order size and associated fees that the wallet can support for the given DEX configuration. The fees are an estimate based on current network conditions, and will be <= the fees associated with nfo.MaxFeeRate. For quote assets, the caller will have to calculate lotSize based on a rate conversion from the base asset's lot size. lotSize must not be zero and will cause a panic if so.

func (*ExchangeWallet) Net added in v0.2.0

func (btc *ExchangeWallet) Net() *chaincfg.Params

Net returns the ExchangeWallet's *chaincfg.Params. This is not part of the asset.Wallet interface, but is provided as a convenience for embedding types.

func (*ExchangeWallet) OwnsAddress

func (btc *ExchangeWallet) OwnsAddress(address string) (bool, error)

OwnsAddress indicates if an address belongs to the wallet.

func (*ExchangeWallet) PayFee

func (btc *ExchangeWallet) PayFee(address string, regFee uint64) (asset.Coin, error)

PayFee sends the dex registration fee. Transaction fees are in addition to the registration fee, and the fee rate is taken from the DEX configuration.

func (*ExchangeWallet) PreRedeem added in v0.2.0

func (btc *ExchangeWallet) PreRedeem(req *asset.PreRedeemForm) (*asset.PreRedeem, error)

PreRedeem generates an estimate of the range of redemption fees that could be assessed.

func (*ExchangeWallet) PreSwap added in v0.2.0

func (btc *ExchangeWallet) PreSwap(req *asset.PreSwapForm) (*asset.PreSwap, error)

PreSwap get order estimates based on the available funds and the wallet configuration.

func (*ExchangeWallet) Redeem

func (btc *ExchangeWallet) Redeem(form *asset.RedeemForm) ([]dex.Bytes, asset.Coin, uint64, error)

Redeem sends the redemption transaction, completing the atomic swap.

func (*ExchangeWallet) Refund

func (btc *ExchangeWallet) Refund(coinID, contract dex.Bytes) (dex.Bytes, error)

Refund revokes a contract. This can only be used after the time lock has expired. NOTE: The contract cannot be retrieved from the unspent coin info as the wallet does not store it, even though it was known when the init transaction was created. The client should store this information for persistence across sessions.

func (*ExchangeWallet) ReturnCoins

func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error

ReturnCoins unlocks coins. This would be used in the case of a canceled or partially filled order. Part of the asset.Wallet interface.

func (*ExchangeWallet) SignMessage

func (btc *ExchangeWallet) SignMessage(coin asset.Coin, msg dex.Bytes) (pubkeys, sigs []dex.Bytes, err error)

SignMessage signs the message with the private key associated with the specified unspent coin. A slice of pubkeys required to spend the coin and a signature for each pubkey are returned.

func (*ExchangeWallet) Swap

func (btc *ExchangeWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uint64, error)

Swap sends the swaps in a single transaction and prepares the receipts. The Receipts returned can be used to refund a failed transaction. The Input coins are NOT manually unlocked because they're auto-unlocked when the transaction is broadcasted.

func (*ExchangeWallet) SyncStatus

func (btc *ExchangeWallet) SyncStatus() (bool, float32, error)

SyncStatus is information about the blockchain sync status.

func (*ExchangeWallet) Unlock

func (btc *ExchangeWallet) Unlock(pw string) error

Unlock unlocks the ExchangeWallet. The pw supplied should be the same as the password for the underlying bitcoind wallet which will also be unlocked.

func (*ExchangeWallet) ValidateSecret

func (btc *ExchangeWallet) ValidateSecret(secret, secretHash []byte) bool

ValidateSecret checks that the secret satisfies the contract.

func (*ExchangeWallet) Withdraw

func (btc *ExchangeWallet) Withdraw(address string, value uint64) (asset.Coin, error)

Withdraw withdraws funds to the specified address. Fees are subtracted from the value. feeRate is in units of atoms/byte.

type GetAddressInfoResult

type GetAddressInfoResult struct {
	IsMine bool `json:"ismine"`
}

GetAddressInfoResult models the data from the getaddressinfo command.

type GetBalancesResult

type GetBalancesResult struct {
	Mine struct {
		Trusted   float64  `json:"trusted"`
		Untrusted float64  `json:"untrusted_pending"`
		Immature  float64  `json:"immature"`
		Used      *float64 `json:"used,omitempty"`
	} `json:"mine"`
	WatchOnly struct {
		Trusted   float64 `json:"trusted"`
		Untrusted float64 `json:"untrusted_pending"`
		Immature  float64 `json:"immature"`
	} `json:"watchonly"`
}

GetBalancesResult models a successful response from the getbalances request.

type GetTransactionResult

type GetTransactionResult struct {
	Amount         float64            `json:"amount"`
	Fee            float64            `json:"fee"`
	Confirmations  uint64             `json:"confirmations"`
	BlockHash      string             `json:"blockhash"`
	BlockIndex     int64              `json:"blockindex"`
	BlockTime      uint64             `json:"blocktime"`
	TxID           string             `json:"txid"`
	Time           uint64             `json:"time"`
	TimeReceived   uint64             `json:"timereceived"`
	BipReplaceable string             `json:"bip125-replaceable"`
	Hex            dex.Bytes          `json:"hex"`
	Details        []*WalletTxDetails `json:"details"`
}

GetTransactionResult models the data from the gettransaction command.

type GetWalletInfoResult

type GetWalletInfoResult struct {
	WalletName            string  `json:"walletname"`
	WalletVersion         uint32  `json:"walletversion"`
	Balance               float64 `json:"balance"`
	UnconfirmedBalance    float64 `json:"unconfirmed_balance"`
	ImmatureBalance       float64 `json:"immature_balance"`
	TxCount               uint32  `json:"txcount"`
	KeyPoolOldest         uint64  `json:"keypoololdest"`
	KeyPoolSize           uint32  `json:"keypoolsize"`
	KeyPoolSizeHDInternal uint32  `json:"keypoolsize_hd_internal"`
	PayTxFee              float64 `json:"paytxfee"`
	HdSeedID              string  `json:"hdseedid"`
	// UnlockedUntil is a pointer because for encrypted locked wallets, it will
	// be zero, but for unencrypted wallets the field won't be present in the
	// response.
	UnlockedUntil *int64 `json:"unlocked_until"`
	// HDMasterKeyID is dropped in Bitcoin Core 0.18
	HdMasterKeyID     string `json:"hdmasterkeyid"`
	PriveyKeysEnabled bool   `json:"private_keys_enabled"`
	// AvoidReuse and Scanning were added in Bitcoin Core 0.19
	AvoidReuse bool `json:"avoid_reuse"`
}

GetWalletInfoResult models the data from the getwalletinfo command.

type ListUnspentResult

type ListUnspentResult struct {
	TxID          string    `json:"txid"`
	Vout          uint32    `json:"vout"`
	Address       string    `json:"address"`
	Label         string    `json:"label"`
	ScriptPubKey  dex.Bytes `json:"scriptPubKey"`
	Amount        float64   `json:"amount"`
	Confirmations uint32    `json:"confirmations"`
	RedeemScript  dex.Bytes `json:"redeemScript"`
	Spendable     bool      `json:"spendable"`
	Solvable      bool      `json:"solvable"`
	Safe          bool      `json:"safe"`
}

ListUnspentResult models a successful response from the listunspent request.

type RPCOutpoint

type RPCOutpoint struct {
	TxID string `json:"txid"`
	Vout uint32 `json:"vout"`
}

RPCOutpoint is used to specify outputs to lock in calls to lockunspent.

type RawRequester added in v0.2.0

type RawRequester interface {
	RawRequest(context.Context, string, []json.RawMessage) (json.RawMessage, error)
}

RawRequester is for sending context-aware RPC requests, and has methods for shutting down the underlying connection. For testing, it can be satisfied by a stub. The returned error should be of type dcrjson.RPCError if non-nil.

type SignTxError

type SignTxError struct {
	TxID      string    `json:"txid"`
	Vout      uint32    `json:"vout"`
	ScriptSig dex.Bytes `json:"scriptSig"`
	Sequence  uint64    `json:"sequence"`
	Error     string    `json:"error"`
}

SignTxError models the data that contains script verification errors from the signrawtransaction request

type SignTxResult

type SignTxResult struct {
	Hex      dex.Bytes      `json:"hex"`
	Complete bool           `json:"complete"`
	Errors   []*SignTxError `json:"errors"`
}

SignTxResult models the data from the signrawtransaction command.

type TxInSigner added in v0.2.0

type TxInSigner func(tx *wire.MsgTx, idx int, subScript []byte, hashType txscript.SigHashType, key *btcec.PrivateKey, val uint64) ([]byte, error)

TxInSigner is a transaction input signer.

type WalletTxCategory

type WalletTxCategory string

WalletTxCategory is the tx output category set in WalletTxDetails.

const (
	TxCatSend     WalletTxCategory = "send"
	TxCatReceive  WalletTxCategory = "receive"
	TxCatGenerate WalletTxCategory = "generate"
	TxCatImmature WalletTxCategory = "immature"
	TxCatOrphan   WalletTxCategory = "orphan"
)

type WalletTxDetails

type WalletTxDetails struct {
	Address   string           `json:"address"`
	Category  WalletTxCategory `json:"category"`
	Amount    float64          `json:"amount"`
	Label     string           `json:"label"`
	Vout      uint32           `json:"vout"`
	Fee       float64          `json:"fee"`
	Abandoned bool             `json:"abandoned"`
}

WalletTxDetails models the details data from the gettransaction command.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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