btc

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2023 License: BlueOak-1.0.0 Imports: 54 Imported by: 8

Documentation

Index

Constants

View Source
const (
	WalletTransactionNotFound = dex.ErrorKind("wallet transaction not found")
	SpentStatusUnknown        = dex.ErrorKind("spend status not known")
)
View Source
const (

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

Variables

View Source
var (
	// ContractSearchLimit is how far back in time AuditContract in SPV mode
	// will search for a contract if no txData is provided. This should be a
	// positive duration.
	ContractSearchLimit = 48 * time.Hour

	ElectrumConfigOpts = []*asset.ConfigOption{
		{
			Key:         "rpcuser",
			DisplayName: "JSON-RPC Username",
			Description: "Electrum's 'rpcuser' setting",
		},
		{
			Key:         "rpcpassword",
			DisplayName: "JSON-RPC Password",
			Description: "Electrum's 'rpcpassword' setting",
			NoEcho:      true,
		},
		{
			Key:         "rpcport",
			DisplayName: "JSON-RPC Port",
			Description: "Electrum's 'rpcport' (if not set with rpcbind)",
		},
		{
			Key:          "rpcbind",
			DisplayName:  "JSON-RPC Address",
			Description:  "Electrum's 'rpchost' <addr> or <addr>:<port>",
			DefaultValue: "127.0.0.1",
		},
		{
			Key:          "walletname",
			DisplayName:  "Wallet File",
			Description:  "Full path to the wallet file (empty is default_wallet)",
			DefaultValue: "",
		},
	}

	// WalletInfo defines some general information about a Bitcoin wallet.
	WalletInfo = &asset.WalletInfo{
		Name:              "Bitcoin",
		Version:           version,
		SupportedVersions: []uint32{version},
		UnitInfo:          dexbtc.UnitInfo,
		AvailableWallets: []*asset.WalletDefinition{
			spvWalletDefinition,
			rpcWalletDefinition,
			electrumWalletDefinition,
		},
		LegacyWalletIndex: 1,
	}
)

Functions

func CommonConfigOpts added in v0.6.0

func CommonConfigOpts(symbol string, withApiFallback bool) []*asset.ConfigOption

CommonConfigOpts are the common options that the Wallets recognize.

func NewWallet

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

NewWallet is the exported constructor by which the DEX will import the exchange wallet.

func RPCConfigOpts added in v0.6.0

func RPCConfigOpts(name, rpcPort string) []*asset.ConfigOption

RPCConfigOpts are the settings that are used to connect to and external RPC wallet.

func SPVConfigOpts added in v0.6.0

func SPVConfigOpts(symbol string) []*asset.ConfigOption

SPVConfigOpts are the options common to built-in SPV wallets.

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 is the default wallet RPC tcp ports used when undefined in
	// WalletConfig.
	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
	// ZECStyleBalance is for clones that don't support getbalances or
	// walletinfo, and don't take an account name argument.
	ZECStyleBalance 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
	// InitTxSize is the size of a swap initiation transaction with a single
	// input i.e. chained swaps.
	InitTxSize uint32
	// InitTxSizeBase is the size of a swap initiation transaction with no
	// inputs. This is used to accurately determine the size of the first swap
	// in a chain when considered with the actual inputs.
	InitTxSizeBase uint32
	// AddrFunc is an optional function to produce new addresses. If AddrFunc
	// is provided, the regular getnewaddress and getrawchangeaddress methods
	// will not be used, and AddrFunc will be used instead.
	AddrFunc func() (btcutil.Address, error)
	// 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 // string => btcutil.Address
	// AddressStringer is an optional argument that can encode a btcutil.Address
	// into an address string. If AddressStringer is not supplied, the
	// (btcutil.Address).String method will be used.
	AddressStringer dexbtc.AddressStringer // btcutil.Address => string, may be an override or just the String method
	// BlockDeserializer can be used in place of (*wire.MsgBlock).Deserialize.
	BlockDeserializer func([]byte) (*wire.MsgBlock, error)
	// 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
	// ConnectFunc, if provided, is called by the RPC client at the end of the
	// (*rpcClient).connect method. Errors returned by ConnectFunc will preclude
	// the starting of goroutines associated with block and peer monitoring.
	ConnectFunc func() error
	// FeeEstimator provides a way to get fees given an RawRequest-enabled
	// client and a confirmation target.
	FeeEstimator func(context.Context, RawRequester, uint64) (uint64, error)
	// ExternalFeeEstimator should be supplied if the clone provides the
	// apifeefallback ConfigOpt. TODO: confTarget uint64
	ExternalFeeEstimator func(context.Context, dex.Network) (uint64, error)
	// OmitAddressType causes the address type (bech32, legacy) to be omitted
	// from calls to getnewaddress.
	OmitAddressType bool
	// LegacySignTxRPC causes the RPC client to use the signrawtransaction
	// endpoint instead of the signrawtransactionwithwallet endpoint.
	LegacySignTxRPC bool
	// BooleanGetBlockRPC causes the RPC client to use a boolean second argument
	// for the getblock endpoint, instead of Bitcoin's numeric.
	BooleanGetBlockRPC bool
	// NumericGetRawRPC uses a numeric boolean indicator for the
	// getrawtransaction RPC.
	NumericGetRawRPC bool
	// LegacyValidateAddressRPC uses the validateaddress endpoint instead of
	// getaddressinfo in order to discover ownership of an address.
	LegacyValidateAddressRPC bool
	// SingularWallet signals that the node software supports only one wallet,
	// so the RPC endpoint does not have a /wallet/{walletname} path.
	SingularWallet bool
	// UnlockSpends manually unlocks outputs as they are spent. Most assets will
	// unlock wallet outputs automatically as they are spent.
	UnlockSpends bool
	// ConstantDustLimit is used if an asset enforces a dust limit (minimum
	// output value) that doesn't depend on the serialized size of the output.
	// If ConstantDustLimit is zero, dexbtc.IsDust is used.
	ConstantDustLimit uint64
	// TxDeserializer is an optional function used to deserialize a transaction.
	TxDeserializer func([]byte) (*wire.MsgTx, error)
	// TxSerializer is an optional function used to serialize a transaction.
	TxSerializer func(*wire.MsgTx) ([]byte, error)
	// TxHasher is a function that generates a tx hash from a MsgTx.
	TxHasher func(*wire.MsgTx) *chainhash.Hash
	// TxSizeCalculator is an optional function that will be used to calculate
	// the size of a transaction.
	TxSizeCalculator func(*wire.MsgTx) uint64
	// TxVersion is an optional function that returns a version to use for
	// new transactions.
	TxVersion func() int32
	// ManualMedianTime causes the median time to be calculated manually.
	ManualMedianTime bool
	// OmitRPCOptionsArg is for clones that don't take an options argument.
	OmitRPCOptionsArg bool
	// AssetID is the asset ID of the clone.
	AssetID uint32
}

BTCCloneCFG holds clone specific parameters.

type BTCWallet added in v0.6.0

type BTCWallet interface {
	PublishTransaction(tx *wire.MsgTx, label string) error
	CalculateAccountBalances(account uint32, confirms int32) (wallet.Balances, error)
	ListUnspent(minconf, maxconf int32, acctName string) ([]*btcjson.ListUnspentResult, error)
	FetchInputInfo(prevOut *wire.OutPoint) (*wire.MsgTx, *wire.TxOut, *psbt.Bip32Derivation, int64, error)
	ResetLockedOutpoints()
	LockOutpoint(op wire.OutPoint)
	UnlockOutpoint(op wire.OutPoint)
	LockedOutpoints() []btcjson.TransactionInput
	NewChangeAddress(account uint32, scope waddrmgr.KeyScope) (btcutil.Address, error)
	NewAddress(account uint32, scope waddrmgr.KeyScope) (btcutil.Address, error)
	PrivKeyForAddress(a btcutil.Address) (*btcec.PrivateKey, error)
	Unlock(passphrase []byte, lock <-chan time.Time) error
	Lock()
	Locked() bool
	SendOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope, account uint32, minconf int32,
		satPerKb btcutil.Amount, coinSelectionStrategy wallet.CoinSelectionStrategy, label string) (*wire.MsgTx, error)
	HaveAddress(a btcutil.Address) (bool, error)
	WaitForShutdown()
	ChainSynced() bool // currently unused
	AccountProperties(scope waddrmgr.KeyScope, acct uint32) (*waddrmgr.AccountProperties, error)
	// The below methods are not implemented by *wallet.Wallet, so must be
	// implemented by the BTCWallet implementation.
	WalletTransaction(txHash *chainhash.Hash) (*wtxmgr.TxDetails, error)
	SyncedTo() waddrmgr.BlockStamp
	SignTx(*wire.MsgTx) error
	BlockNotifications(context.Context) <-chan *BlockNotification
	RescanAsync() error
	ForceRescan()
	Start() (SPVService, error)
	Stop()
	Reconfigure(*asset.WalletConfig, string) (bool, error)
	Birthday() time.Time
	Peers() ([]*asset.WalletPeer, error)
	AddPeer(string) error
	RemovePeer(string) error
}

BTCWallet is roughly the (btcwallet/wallet.*Wallet) interface, with some additional required methods added.

type BTCWalletConstructor added in v0.6.0

type BTCWalletConstructor func(dir string, cfg *WalletConfig, chainParams *chaincfg.Params, log dex.Logger) BTCWallet

BTCWalletConstructor is a function to construct a BTCWallet.

type Balances added in v0.4.0

type Balances struct {
	Trusted   float64  `json:"trusted"`
	Untrusted float64  `json:"untrusted_pending"`
	Immature  float64  `json:"immature"`
	Used      *float64 `json:"used,omitempty"`
}

Balances is a categorical balance breakdown.

type BlockNotification added in v0.6.0

type BlockNotification struct {
	Hash   chainhash.Hash
	Height int32
}

BlockNotification is block hash and height delivered by a BTCWallet when it is finished processing a block.

type Driver

type Driver struct{}

Driver implements asset.Driver.

func (*Driver) Create added in v0.4.0

func (d *Driver) Create(params *asset.CreateWalletParams) error

Create creates a new SPV wallet.

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) Exists added in v0.4.0

func (d *Driver) Exists(walletType, dataDir string, settings map[string]string, net dex.Network) (bool, error)

Exists checks the existence of the wallet. Part of the Creator interface, so only used for wallets with WalletDefinition.Seeded = true.

func (*Driver) Info

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

Info returns basic information about the wallet and asset.

func (*Driver) Open added in v0.4.0

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

Open opens or connects to the BTC exchange wallet. Start the wallet with its Run method.

type ExchangeWalletAccelerator added in v0.5.0

type ExchangeWalletAccelerator struct {
	*ExchangeWalletFullNode
}

ExchangeWalletAccelerator implements the Accelerator interface on an ExchangeWalletFullNode.

func (*ExchangeWalletAccelerator) AccelerateOrder added in v0.5.0

func (btc *ExchangeWalletAccelerator) AccelerateOrder(swapCoins, accelerationCoins []dex.Bytes, changeCoin dex.Bytes, requiredForRemainingSwaps, newFeeRate uint64) (asset.Coin, string, error)

AccelerateOrder uses the Child-Pays-For-Parent technique to accelerate a chain of swap transactions and previous accelerations. It broadcasts a new transaction with a fee high enough so that the average fee of all the unconfirmed transactions in the chain and the new transaction will have an average fee rate of newFeeRate. The changeCoin argument is the latest change in the order. It must be the input in the acceleration transaction in order for the order to be accelerated. requiredForRemainingSwaps is the amount of funds required to complete the rest of the swaps in the order. The change output of the acceleration transaction will have at least this amount.

The returned change coin may be nil, and should be checked before use.

func (*ExchangeWalletAccelerator) AccelerationEstimate added in v0.5.0

func (btc *ExchangeWalletAccelerator) AccelerationEstimate(swapCoins, accelerationCoins []dex.Bytes, changeCoin dex.Bytes, requiredForRemainingSwaps, newFeeRate uint64) (uint64, error)

AccelerationEstimate takes the same parameters as AccelerateOrder, but instead of broadcasting the acceleration transaction, it just returns the amount of funds that will need to be spent in order to increase the average fee rate to the desired amount.

func (ExchangeWalletAccelerator) Connect added in v0.5.0

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

Connect connects the wallet to the btc.Wallet backend and starts monitoring blocks and peers. Satisfies the dex.Connector interface.

func (ExchangeWalletAccelerator) EstimateSendTxFee added in v0.6.0

func (btc ExchangeWalletAccelerator) EstimateSendTxFee(address string, sendAmount, feeRate uint64, subtract bool) (fee uint64, isValidAddress bool, err error)

EstimateSendTxFee returns a tx fee estimate for sending or withdrawing the provided amount using the provided feeRate.

func (ExchangeWalletAccelerator) FeesForRemainingSwaps added in v0.6.0

func (btc ExchangeWalletAccelerator) FeesForRemainingSwaps(n, feeRate uint64) uint64

FeesForRemainingSwaps returns the fees for a certain number of swaps at a given feeRate. This is only accurate if each swap has a single input. Accurate estimates should use PreSwap or FundOrder.

func (ExchangeWalletAccelerator) FindRedemption added in v0.5.0

func (btc ExchangeWalletAccelerator) 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 (*ExchangeWalletAccelerator) PreAccelerate added in v0.5.0

func (btc *ExchangeWalletAccelerator) PreAccelerate(swapCoins, accelerationCoins []dex.Bytes, changeCoin dex.Bytes, requiredForRemainingSwaps, feeSuggestion uint64) (uint64, *asset.XYRange, *asset.EarlyAcceleration, error)

PreAccelerate returns the current average fee rate of the unmined swap initiation and acceleration transactions, and also returns a suggested range that the fee rate should be increased to in order to expedite mining. The feeSuggestion argument is the current prevailing network rate. It is used to help determine the suggestedRange, which is a range meant to give the user a good amount of flexibility in determining the post acceleration effective fee rate, but still not allowing them to pick something outrageously high.

type ExchangeWalletElectrum added in v0.5.0

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

ExchangeWalletElectrum is the asset.Wallet for an external Electrum wallet.

func ElectrumWallet added in v0.5.0

func ElectrumWallet(cfg *BTCCloneCFG) (*ExchangeWalletElectrum, error)

ElectrumWallet creates a new ExchangeWalletElectrum for the provided configuration, which must contain the necessary details for accessing the Electrum wallet's RPC server in the WalletCFG.Settings map.

func (ExchangeWalletElectrum) AuditContract added in v0.5.0

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

AuditContract retrieves information about a swap contract from the provided txData. The extracted information would be used to audit the counter-party's contract during a swap. The txData may be empty to attempt retrieval of the transaction output from the network, but it is only ensured to succeed for a full node or, if the tx is confirmed, an SPV wallet. Normally the server should communicate this txData, and the caller can decide to require it. The ability to work with an empty txData is a convenience for recovery tools and testing, and it may change in the future if a GetTxData method is added for this purpose.

func (ExchangeWalletElectrum) Balance added in v0.5.0

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

Balance should return the total available funds in the wallet.

func (ExchangeWalletElectrum) BondsFeeBuffer added in v0.6.0

func (btc ExchangeWalletElectrum) BondsFeeBuffer(feeRate uint64) uint64

BondsFeeBuffer suggests how much extra may be required for the transaction fees part of required bond reserves when bond rotation is enabled. The provided fee rate may be zero, in which case the wallet will use it's own estimate or fallback value.

func (ExchangeWalletElectrum) CallRPC added in v0.6.1

func (btc ExchangeWalletElectrum) CallRPC(method string, args []interface{}, thing interface{}) error

CallRPC is a method for making RPC calls directly on an underlying RPC client. CallRPC is not part of the wallet interface. Its intended use is for clone wallets to implement custom functionality.

func (*ExchangeWalletElectrum) Connect added in v0.5.0

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

Connect connects to the Electrum wallet's RPC server and an electrum server directly. Goroutines are started to monitor for new blocks and server connection changes. Satisfies the dex.Connector interface.

func (ExchangeWalletElectrum) ContractLockTimeExpired added in v0.6.0

func (btc ExchangeWalletElectrum) ContractLockTimeExpired(ctx context.Context, contract dex.Bytes) (bool, time.Time, error)

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

func (*ExchangeWalletElectrum) DepositAddress added in v0.5.0

func (btc *ExchangeWalletElectrum) DepositAddress() (string, error)

DepositAddress returns an address for depositing funds into the exchange wallet. The address will be unused but not necessarily new. Use NewAddress to request a new address, but it should be used immediately.

func (ExchangeWalletElectrum) EstimateRegistrationTxFee added in v0.5.0

func (btc ExchangeWalletElectrum) EstimateRegistrationTxFee(feeRate uint64) uint64

EstimateRegistrationTxFee returns an estimate for the tx fee needed to pay the registration fee using the provided feeRate.

func (ExchangeWalletElectrum) FeeRate added in v0.5.0

func (btc ExchangeWalletElectrum) FeeRate() uint64

FeeRate satisfies asset.FeeRater.

func (*ExchangeWalletElectrum) FindRedemption added in v0.5.0

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

FindRedemption locates a swap contract output's redemption transaction input and the secret key used to spend the output.

func (ExchangeWalletElectrum) FundOrder added in v0.5.0

func (btc ExchangeWalletElectrum) 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 (ExchangeWalletElectrum) FundingCoins added in v0.5.0

func (btc ExchangeWalletElectrum) 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 (ExchangeWalletElectrum) GetBestBlockHeight added in v0.5.0

func (btc ExchangeWalletElectrum) GetBestBlockHeight() (int32, error)

GetBestBlockHeight is exported for use by clone wallets. Not part of the asset.Wallet interface.

func (ExchangeWalletElectrum) Info added in v0.5.0

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

Info returns basic information about the wallet and asset.

func (ExchangeWalletElectrum) IsDust added in v0.5.0

func (btc ExchangeWalletElectrum) IsDust(txOut *wire.TxOut, minRelayTxFee uint64) bool

IsDust checks if the tx output's value is dust. If the dustLimit is set, it is compared against that, otherwise the formula in dexbtc.IsDust is used.

func (ExchangeWalletElectrum) Lock added in v0.5.0

func (btc ExchangeWalletElectrum) Lock() error

Lock locks the ExchangeWallet and the underlying bitcoind wallet.

func (ExchangeWalletElectrum) LockTimeExpired added in v0.6.0

func (btc ExchangeWalletElectrum) LockTimeExpired(_ context.Context, lockTime time.Time) (bool, error)

LockTimeExpired returns true if the specified locktime has expired, making it possible to redeem the locked coins.

func (ExchangeWalletElectrum) Locked added in v0.5.0

func (btc ExchangeWalletElectrum) Locked() bool

Locked will be true if the wallet is currently locked.

func (ExchangeWalletElectrum) MakeBondTx added in v0.6.0

func (btc ExchangeWalletElectrum) MakeBondTx(ver uint16, amt, feeRate uint64, lockTime time.Time, bondKey *secp256k1.PrivateKey, acctID []byte) (*asset.Bond, func(), error)

MakeBondTx creates a time-locked fidelity bond transaction. The V0 transaction has two required outputs:

Output 0 is a the time-locked bond output of type P2SH with the provided value. The redeem script looks similar to the refund path of an atomic swap script, but with a pubkey hash:

<locktime> OP_CHECKLOCKTIMEVERIFY OP_DROP OP_DUP OP_HASH160 <pubkeyhash[20]> OP_EQUALVERIFY OP_CHECKSIG

The pubkey referenced by the script is provided by the caller.

Output 1 is a DEX Account commitment. This is an OP_RETURN output that references the provided account ID.

OP_RETURN <2-byte version> <32-byte account ID> <4-byte locktime> <20-byte pubkey hash>

Having the account ID in the raw allows the txn alone to identify the account without the bond output's redeem script.

Output 2 is change, if any.

The bond output's redeem script, which is needed to spend the bond output, is returned as the Data field of the Bond. The bond output pays to a pubkeyhash script for a wallet address. Bond.RedeemTx is a backup transaction that spends the bond output after lockTime passes, paying to an address for the current underlying wallet; the bond private key should normally be used to author a new transaction paying to a new address instead.

func (ExchangeWalletElectrum) MaxOrder added in v0.5.0

func (btc ExchangeWalletElectrum) MaxOrder(ord *asset.MaxOrderForm) (*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 (ExchangeWalletElectrum) NewAddress added in v0.5.0

func (btc ExchangeWalletElectrum) NewAddress() (string, error)

NewAddress returns a new address from the wallet. This satisfies the NewAddresser interface.

func (ExchangeWalletElectrum) OwnsDepositAddress added in v0.5.0

func (btc ExchangeWalletElectrum) OwnsDepositAddress(address string) (bool, error)

OwnsDepositAddress indicates if the provided address can be used to deposit funds into the wallet.

func (ExchangeWalletElectrum) PreRedeem added in v0.5.0

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

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

func (ExchangeWalletElectrum) PreSwap added in v0.5.0

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

PreSwap get order estimates and order options based on the available funds and user-selected options.

func (ExchangeWalletElectrum) Reconfigure added in v0.5.0

func (btc ExchangeWalletElectrum) Reconfigure(ctx context.Context, cfg *asset.WalletConfig, currentAddress string) (restart bool, err error)

Reconfigure attempts to reconfigure the wallet.

func (ExchangeWalletElectrum) Redeem added in v0.5.0

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

Redeem sends the redemption transaction, completing the atomic swap.

func (*ExchangeWalletElectrum) RedemptionAddress added in v0.5.0

func (btc *ExchangeWalletElectrum) RedemptionAddress() (string, error)

RedemptionAddress gets an address for use in redeeming the counterparty's swap. This would be included in their swap initialization. The address will be unused but not necessarily new because these addresses often go unused.

func (ExchangeWalletElectrum) Refund added in v0.5.0

func (btc ExchangeWalletElectrum) Refund(coinID, contract dex.Bytes, feeRate uint64) (dex.Bytes, error)

Refund revokes a contract. This can only be used after the time lock has expired. This MUST return an asset.CoinNotFoundError error if the coin is spent. 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 (ExchangeWalletElectrum) RefundBond added in v0.6.0

func (btc ExchangeWalletElectrum) RefundBond(ctx context.Context, ver uint16, coinID, script []byte, amt uint64, privKey *secp256k1.PrivateKey) (asset.Coin, error)

RefundBond refunds a bond output to a new wallet address given the redeem script and private key. After broadcasting, the output paying to the wallet is returned.

func (ExchangeWalletElectrum) RegFeeConfirmations added in v0.5.0

func (btc ExchangeWalletElectrum) RegFeeConfirmations(_ context.Context, id dex.Bytes) (confs uint32, err error)

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

func (ExchangeWalletElectrum) RegisterUnspent added in v0.6.0

func (btc ExchangeWalletElectrum) RegisterUnspent(inBonds uint64)

RegisterUnspent should be called once for every configured DEX with existing unspent bond amounts, prior to login, which is when reserves for future bonds are then added given the actual account tier, target tier, and this combined existing bonds amount. This must be used before ReserveBondFunds, which begins reserves enforcement provided a future amount that may be required before the existing bonds are refunded. No reserves enforcement is enabled until ReserveBondFunds is called, even with a future value of 0. A wallet that is not enforcing reserves, but which has unspent bonds should use this method to facilitate switching to the wallet for bonds in future.

func (ExchangeWalletElectrum) ReserveBondFunds added in v0.6.0

func (btc ExchangeWalletElectrum) ReserveBondFunds(future int64, feeBuffer uint64, respectBalance bool) bool

ReserveBondFunds increases the bond reserves to accommodate a certain nominal amount of future bonds, or reduces the amount if a negative value is provided. If indicated, updating the reserves will require sufficient available balance, otherwise reserves will be adjusted regardless and the funds are pre-reserved. This returns false if the available balance was insufficient iff the caller requested it be respected, otherwise it always returns true (success). The fee buffer is used only when enabling the reserves (when starting from zero) to compute the fee buffer. It may also be zero, in which case the wallet will attempt to obtain it's own estimate.

The reserves enabled with this method are enforced when funding transactions (e.g. regular withdraws/sends or funding orders), and deducted from available balance. Amounts may be reserved beyond the available balance, but only the amount that is offset by the available balance is reflected in the locked balance category. Like funds locked in swap contracts, the caller must supplement balance reporting with known bond amounts. However, via RegisterUnspent, the wallet is made aware of pre-existing unspent bond amounts (cumulative) that will eventually be spent with RefundBond.

If this wallet is enforcing reserves (this method has been called, even with a future value of zero), when new bonds are created the nominal bond amount is deducted from the enforced reserves; when bonds are spent with RefundBond, the nominal bond amount is added back into the enforced reserves. That is, when there are no active bonds, the locked balance category will reflect the entire amount requested with ReserveBondFunds (plus a fee buffer, see below), and when bonds are created with MakeBondTx, the locked amount decreases since that portion of the reserves are now held in inaccessible UTXOs, the amounts of which the caller tracks independently. When spent with RefundBond, that same *nominal* bond value is added back to the enforced reserves amount.

The amounts requested for bond reserves should be the nominal amounts of the bonds, but the reserved amount reflected in the locked balance category will include a considerable buffer for transaction fees. Therefore when the full amount of the reserves are presently locked in unspent bonds, the locked balance will include this fee buffer while the wallet is enforcing reserves.

Until this method is called, reserves enforcement is disabled, and any unspent bonds registered with RegisterUnspent do not go into the enforced reserves when spent. In this way, all Bonder wallets remain aware of the total nominal value of unspent bonds even if the wallet is not presently being used to maintain a target bonding amount that necessitates reserves enforcement.

A negative value may be provided to reduce allocated reserves. When the amount is reduced by the same amount it was previously increased by both ReserveBondFunds and RegisterUnspent, reserves enforcement including fee padding is disabled. Consider the following example: on startup, .2 BTC of existing unspent bonds are registered via RegisterUnspent, then on login and auth with the relevant DEX host, .4 BTC of future bond reserves are requested with ReserveBondFunds to maintain a configured target tier given the current tier and amounts of the existing unspent bonds. To disable reserves, the client would call ReserveBondFunds with -.6 BTC, which the wallet's internal accounting recognizes as complete removal of the reserves.

func (ExchangeWalletElectrum) ReturnCoins added in v0.5.0

func (btc ExchangeWalletElectrum) 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 (ExchangeWalletElectrum) Send added in v0.5.0

func (btc ExchangeWalletElectrum) Send(address string, value, feeRate uint64) (asset.Coin, error)

Send sends the exact value to the specified address. This is different from Withdraw, which subtracts the tx fees from the amount sent. feeRate is in units of sats/byte.

func (ExchangeWalletElectrum) SendTransaction added in v0.6.0

func (btc ExchangeWalletElectrum) SendTransaction(rawTx []byte) ([]byte, error)

SendTransaction broadcasts a valid fully-signed transaction.

func (ExchangeWalletElectrum) SignMessage added in v0.5.0

func (btc ExchangeWalletElectrum) 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 (ExchangeWalletElectrum) SingleLotRedeemFees added in v0.6.0

func (btc ExchangeWalletElectrum) SingleLotRedeemFees(req *asset.PreRedeemForm) (uint64, error)

SingleLotRedeemFees is a fallback for PreRedeem that uses estimation when funds aren't available. The returned fees are the RealisticWorstCase. The Lots field of the PreSwapForm is ignored and assumed to be a single lot.

func (ExchangeWalletElectrum) SingleLotSwapFees added in v0.6.0

func (btc ExchangeWalletElectrum) SingleLotSwapFees(form *asset.PreSwapForm) (fees uint64, err error)

SingleLotSwapFees is a fallback for PreSwap that uses estimation when funds aren't available. The returned fees are the RealisticWorstCase. The Lots field of the PreSwapForm is ignored and assumed to be a single lot. Similarly, the MaxFeeRate, Immediate, RedeemVersion, and RedeemAssetID fields are unused.

func (ExchangeWalletElectrum) Swap added in v0.5.0

func (btc ExchangeWalletElectrum) 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 (ExchangeWalletElectrum) SwapConfirmations added in v0.5.0

func (btc ExchangeWalletElectrum) SwapConfirmations(_ context.Context, id dex.Bytes, contract dex.Bytes, startTime time.Time) (uint32, bool, error)

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

func (ExchangeWalletElectrum) SyncStatus added in v0.5.0

func (btc ExchangeWalletElectrum) SyncStatus() (bool, float32, error)

SyncStatus is information about the blockchain sync status.

func (ExchangeWalletElectrum) Unlock added in v0.5.0

func (btc ExchangeWalletElectrum) Unlock(pw []byte) 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 (ExchangeWalletElectrum) ValidateAddress added in v0.6.0

func (btc ExchangeWalletElectrum) ValidateAddress(address string) bool

ValidateAddress checks that the provided address is valid.

func (ExchangeWalletElectrum) ValidateSecret added in v0.5.0

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

ValidateSecret checks that the secret satisfies the contract.

func (ExchangeWalletElectrum) Withdraw added in v0.5.0

func (btc ExchangeWalletElectrum) Withdraw(address string, value, feeRate uint64) (asset.Coin, error)

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

type ExchangeWalletFullNode added in v0.4.3

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

ExchangeWalletFullNode implements Wallet and adds the FeeRate method.

func BTCCloneWallet

func BTCCloneWallet(cfg *BTCCloneCFG) (*ExchangeWalletFullNode, 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 (ExchangeWalletFullNode) Connect added in v0.4.3

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

Connect connects the wallet to the btc.Wallet backend and starts monitoring blocks and peers. Satisfies the dex.Connector interface.

func (ExchangeWalletFullNode) EstimateSendTxFee added in v0.6.0

func (btc ExchangeWalletFullNode) EstimateSendTxFee(address string, sendAmount, feeRate uint64, subtract bool) (fee uint64, isValidAddress bool, err error)

EstimateSendTxFee returns a tx fee estimate for sending or withdrawing the provided amount using the provided feeRate.

func (ExchangeWalletFullNode) FeesForRemainingSwaps added in v0.6.0

func (btc ExchangeWalletFullNode) FeesForRemainingSwaps(n, feeRate uint64) uint64

FeesForRemainingSwaps returns the fees for a certain number of swaps at a given feeRate. This is only accurate if each swap has a single input. Accurate estimates should use PreSwap or FundOrder.

func (ExchangeWalletFullNode) FindRedemption added in v0.4.3

func (btc ExchangeWalletFullNode) 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.

type ExchangeWalletSPV added in v0.4.1

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

ExchangeWalletSPV embeds a ExchangeWallet, but also provides the Rescan method to implement asset.Rescanner.

func OpenSPVWallet added in v0.6.0

func OpenSPVWallet(cfg *BTCCloneCFG, walletConstructor BTCWalletConstructor) (*ExchangeWalletSPV, error)

OpenSPVWallet opens the previously created native SPV wallet.

func (*ExchangeWalletSPV) AccelerateOrder added in v0.5.0

func (btc *ExchangeWalletSPV) AccelerateOrder(swapCoins, accelerationCoins []dex.Bytes, changeCoin dex.Bytes, requiredForRemainingSwaps, newFeeRate uint64) (asset.Coin, string, error)

AccelerateOrder uses the Child-Pays-For-Parent technique to accelerate a chain of swap transactions and previous accelerations. It broadcasts a new transaction with a fee high enough so that the average fee of all the unconfirmed transactions in the chain and the new transaction will have an average fee rate of newFeeRate. The changeCoin argument is the latest change in the order. It must be the input in the acceleration transaction in order for the order to be accelerated. requiredForRemainingSwaps is the amount of funds required to complete the rest of the swaps in the order. The change output of the acceleration transaction will have at least this amount.

The returned change coin may be nil, and should be checked before use.

func (*ExchangeWalletSPV) AccelerationEstimate added in v0.5.0

func (btc *ExchangeWalletSPV) AccelerationEstimate(swapCoins, accelerationCoins []dex.Bytes, changeCoin dex.Bytes, requiredForRemainingSwaps, newFeeRate uint64) (uint64, error)

AccelerationEstimate takes the same parameters as AccelerateOrder, but instead of broadcasting the acceleration transaction, it just returns the amount of funds that will need to be spent in order to increase the average fee rate to the desired amount.

func (*ExchangeWalletSPV) AddPeer added in v0.6.0

func (btc *ExchangeWalletSPV) AddPeer(addr string) error

AddPeer connects the wallet to a new peer. The peer's address will be persisted and connected to each time the wallet is started up.

func (ExchangeWalletSPV) Connect added in v0.4.3

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

Connect connects the wallet to the btc.Wallet backend and starts monitoring blocks and peers. Satisfies the dex.Connector interface.

func (ExchangeWalletSPV) EstimateSendTxFee added in v0.6.0

func (btc ExchangeWalletSPV) EstimateSendTxFee(address string, sendAmount, feeRate uint64, subtract bool) (fee uint64, isValidAddress bool, err error)

EstimateSendTxFee returns a tx fee estimate for sending or withdrawing the provided amount using the provided feeRate.

func (ExchangeWalletSPV) FeesForRemainingSwaps added in v0.6.0

func (btc ExchangeWalletSPV) FeesForRemainingSwaps(n, feeRate uint64) uint64

FeesForRemainingSwaps returns the fees for a certain number of swaps at a given feeRate. This is only accurate if each swap has a single input. Accurate estimates should use PreSwap or FundOrder.

func (ExchangeWalletSPV) FindRedemption added in v0.4.3

func (btc ExchangeWalletSPV) 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 (*ExchangeWalletSPV) GetRecoveryCfg added in v0.5.0

func (btc *ExchangeWalletSPV) GetRecoveryCfg() (map[string]string, error)

GetRecoveryCfg returns information that will help the wallet get back to its previous state after it is recreated. Part of the Recoverer interface.

func (*ExchangeWalletSPV) LogFilePath added in v0.4.1

func (btc *ExchangeWalletSPV) LogFilePath() string

LogFilePath returns the path to the neutrino log file.

func (*ExchangeWalletSPV) Move added in v0.5.0

func (btc *ExchangeWalletSPV) Move(backupDir string) error

Destroy will delete all the wallet files so the wallet can be recreated. Part of the Recoverer interface.

func (*ExchangeWalletSPV) Peers added in v0.6.0

func (btc *ExchangeWalletSPV) Peers() ([]*asset.WalletPeer, error)

Peers returns a list of peers that the wallet is connected to.

func (*ExchangeWalletSPV) PreAccelerate added in v0.5.0

func (btc *ExchangeWalletSPV) PreAccelerate(swapCoins, accelerationCoins []dex.Bytes, changeCoin dex.Bytes, requiredForRemainingSwaps, feeSuggestion uint64) (uint64, *asset.XYRange, *asset.EarlyAcceleration, error)

PreAccelerate returns the current average fee rate of the unmined swap initiation and acceleration transactions, and also returns a suggested range that the fee rate should be increased to in order to expedite mining. The feeSuggestion argument is the current prevailing network rate. It is used to help determine the suggestedRange, which is a range meant to give the user a good amount of flexibility in determining the post acceleration effective fee rate, but still not allowing them to pick something outrageously high.

func (*ExchangeWalletSPV) RemovePeer added in v0.6.0

func (btc *ExchangeWalletSPV) RemovePeer(addr string) error

RemovePeer will remove a peer that was added by AddPeer. This peer may still be connected to by the wallet if it discovers it on it's own.

func (*ExchangeWalletSPV) Rescan added in v0.4.1

func (btc *ExchangeWalletSPV) Rescan(_ context.Context) error

Rescan satisfies the asset.Rescanner interface, and issues a rescan wallet command if the backend is an SPV wallet.

type GetAddressInfoResult

type GetAddressInfoResult struct {
	IsMine     bool   `json:"ismine"`
	Descriptor string `json:"desc"` // e.g. "wpkh([b940190e/84'/1'/0'/0/0]0300034...)#0pfw7rck"

	ParentDesc          string `json:"parent_desc"`         // e.g. "wpkh([b940190e/84'/1'/0']tpubDCo.../0/*)#xn4kr3dw" meaning range of external addresses
	HDKeyPath           string `json:"hdkeypath"`           // e.g. "m/84'/1'/0'/0/0"
	HDMasterFingerprint string `json:"hdmasterfingerprint"` // e.g. "b940190e"
}

GetAddressInfoResult models some of the data from the getaddressinfo command.

type GetBalancesResult

type GetBalancesResult struct {
	Mine      Balances `json:"mine"`
	WatchOnly Balances `json:"watchonly"`
}

GetBalancesResult models a successful response from the getbalances request.

type GetTransactionResult

type GetTransactionResult struct {
	// The meaning of Amount and Fee for "wallet" transactions is iffy (and they
	// are unused), so we are going to ignore them.  We have the raw tx (Hex) if
	// it is necessary to compute amounts from the inputs and outputs.
	// Amount         float64   `json:"amount"`
	// Fee            float64   `json:"fee"`
	Confirmations uint64 `json:"confirmations"`
	BlockHash     string `json:"blockhash"`
	BlockIndex    int64  `json:"blockindex"` // unused, consider commenting
	BlockTime     uint64 `json:"blocktime"`
	// BlockHeight   uint64    `json:"blockheight"` // unused, potentially work to obtain
	TxID         string    `json:"txid"`
	Time         uint64    `json:"time"`
	TimeReceived uint64    `json:"timereceived"`
	Hex          dex.Bytes `json:"hex"` // []byte, although it marshals/unmarshals a hex string

}

GetTransactionResult models the required data from the gettransaction command. Several fields from the bitcoind/btcwallet response that are both unneeded and difficult to satisfy are omitted. e.g. the native btcwallet and the external Electrum backends must jump through hoops to reproduce certain fields that are not strictly necessary.

type GetWalletInfoResult

type GetWalletInfoResult struct {
	WalletName            string  `json:"walletname"`
	WalletVersion         uint32  `json:"walletversion"`
	Format                string  `json:"format"`
	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"`
	// Scanning is either a struct or boolean false, and since we're not using
	// it, commenting avoids having to deal with marshaling for now.
	// Scanning   struct {
	// 	Duration uint32  `json:"duration"`
	// 	Progress float32 `json:"progress"`
	// } `json:"scanning"`
	Descriptors bool `json:"descriptors"` // Descriptor wallets that do not support dumpprivkey
}

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"`
	SafePtr       *bool     `json:"safe"`
}

ListUnspentResult models a successful response from the listunspent request.

func (*ListUnspentResult) Safe

func (l *ListUnspentResult) Safe() bool

type PeerManagerChainService added in v0.6.0

type PeerManagerChainService interface {
	AddPeer(addr string) error
	RemovePeer(addr string) error
	Peers() []SPVPeer
}

PeerManagerChainService are the functions needed for an SPVPeerManager to communicate with a chain service.

type RPCConfig added in v0.5.0

type RPCConfig struct {
	dexbtc.RPCConfig `ini:",extends"`
	WalletName       string `ini:"walletname"`
}

RPCConfig adds a wallet name to the basic configuration.

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 RPCWalletConfig added in v0.4.0

type RPCWalletConfig struct {
	RPCConfig    `ini:",extends"`
	WalletConfig `ini:",extends"`
}

RPCWalletConfig is a combination of RPCConfig and WalletConfig. Used for a wallet based on a bitcoind-like RPC API.

type RawRequester added in v0.2.0

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

RawRequester defines decred's rpcclient RawRequest func where all RPC requests sent through. For testing, it can be satisfied by a stub.

type RecoveryCfg added in v0.5.0

type RecoveryCfg struct {
	NumExternalAddresses uint32 `ini:"numexternaladdr"`
	NumInternalAddresses uint32 `ini:"numinternaladdr"`
}

RecoveryCfg is the information that is transferred from the old wallet to the new one when the wallet is recovered.

type SPVPeer added in v0.6.0

type SPVPeer interface {
	StartingHeight() int32
	LastBlock() int32
	Addr() string
}

SPVPeer is satisfied by *neutrino.ServerPeer, but is generalized to accommodate underlying implementations other than lightninglabs/neutrino.

type SPVPeerManager added in v0.6.0

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

SPVPeerManager implements peer management functionality for all bitcoin clone SPV wallets.

func NewSPVPeerManager added in v0.6.0

func NewSPVPeerManager(cs PeerManagerChainService, defaultPeers []string, dir string, log dex.Logger, defaultPort string) *SPVPeerManager

NewSPVPeerManager creates a new SPVPeerManager.

func (*SPVPeerManager) AddPeer added in v0.6.0

func (s *SPVPeerManager) AddPeer(addr string) error

AddPeer connects to a new peer and stores it in the db.

func (*SPVPeerManager) ConnectToInitialWalletPeers added in v0.6.0

func (s *SPVPeerManager) ConnectToInitialWalletPeers()

ConnectToInitialWalletPeers connects to the default peers and the peers that were added by the user and persisted in the db.

func (*SPVPeerManager) Peers added in v0.6.0

func (s *SPVPeerManager) Peers() ([]*asset.WalletPeer, error)

Peers returns the list of peers that the wallet is connected to. It also returns the peers that the user added that the wallet may not currently be connected to.

func (*SPVPeerManager) RemovePeer added in v0.6.0

func (s *SPVPeerManager) RemovePeer(addr string) error

RemovePeer disconnects from a peer added by the user and removes it from the db.

type SPVService added in v0.6.0

type SPVService interface {
	GetBlockHash(int64) (*chainhash.Hash, error)
	BestBlock() (*headerfs.BlockStamp, error)
	Peers() []SPVPeer
	AddPeer(addr string) error
	GetBlockHeight(hash *chainhash.Hash) (int32, error)
	GetBlockHeader(*chainhash.Hash) (*wire.BlockHeader, error)
	GetCFilter(blockHash chainhash.Hash, filterType wire.FilterType, options ...neutrino.QueryOption) (*gcs.Filter, error)
	GetBlock(blockHash chainhash.Hash, options ...neutrino.QueryOption) (*btcutil.Block, error)
	Stop() error
}

SPVService is satisfied by *neutrino.ChainService, with the exception of the Peers method, which has a generic interface in place of neutrino.ServerPeer.

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, vals []int64, prevScripts [][]byte) ([]byte, error)

TxInSigner is a transaction input signer. In addition to the standard Bitcoin arguments, TxInSigner receives all values and pubkey scripts for previous outpoints spent in this transaction.

type Wallet added in v0.4.0

type Wallet interface {
	RawRequester // for localFeeRate/rpcFeeRate calls
	// contains filtered or unexported methods
}

Wallet is the interface that BTC wallet backends must implement. TODO: plumb all requests with a context.Context.

type WalletConfig added in v0.4.0

type WalletConfig struct {
	UseSplitTx       bool    `ini:"txsplit"`
	FallbackFeeRate  float64 `ini:"fallbackfee"`
	FeeRateLimit     float64 `ini:"feeratelimit"`
	RedeemConfTarget uint64  `ini:"redeemconftarget"`
	ActivelyUsed     bool    `ini:"special_activelyUsed"` // injected by core
	Birthday         uint64  `ini:"walletbirthday"`       // SPV
	ApiFeeFallback   bool    `ini:"apifeefallback"`
}

WalletConfig are wallet-level configuration settings.

func (*WalletConfig) AdjustedBirthday added in v0.6.0

func (cfg *WalletConfig) AdjustedBirthday() time.Time

AdjustedBirthday converts WalletConfig.Birthday to a time.Time, and adjusts it so that defaultWalletBirthday <= WalletConfig.Birthday <= now.

Directories

Path Synopsis
Package electrum provides a client for an ElectrumX server.
Package electrum provides a client for an ElectrumX server.

Jump to

Keyboard shortcuts

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