wallet

package
v0.0.14 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2024 License: ISC Imports: 40 Imported by: 0

README

wallet

[Build Status] (https://travis-ci.org/btcsuite/btcwallet)

Feature Overview

TODO: Flesh out this section

Documentation

[GoDoc] (http://godoc.org/github.com/stroomnetwork/btcwallet/wallet)

Full go doc style documentation for the project can be viewed online without installing this package by using the GoDoc site here: http://godoc.org/github.com/stroomnetwork/btcwallet/wallet

You can also view the documentation locally once the package is installed with the godoc tool by running godoc -http=":6060" and pointing your browser to http://localhost:6060/pkg/github.com/stroomnetwork/btcwallet/wallet

Installation

$ go get github.com/stroomnetwork/btcwallet/wallet

Package wallet is licensed under the copyfree ISC License.

Documentation

Overview

Package wallet provides ... TODO: Flesh out this section

Overview

Index

Constants

View Source
const (
	// WalletDBName specified the database filename for the wallet.
	WalletDBName = "wallet.db"

	// DefaultDBTimeout is the default timeout value when opening the wallet
	// database.
	DefaultDBTimeout = 60 * time.Second
)
View Source
const DefaultStorageFileName = "addressMap.gkv"
View Source
const (
	// InsecurePubPassphrase is the default outer encryption passphrase used
	// for public data (everything but private keys).  Using a non-default
	// public passphrase can prevent an attacker without the public
	// passphrase from discovering all past and future wallet addresses if
	// they gain access to the wallet database.
	//
	// NOTE: at time of writing, public encryption only applies to public
	// data in the waddrmgr namespace.  Transactions are not yet encrypted.
	InsecurePubPassphrase = "public"
)

Variables

View Source
var (
	// ErrLoaded describes the error condition of attempting to load or
	// create a wallet when the loader has already done so.
	ErrLoaded = errors.New("wallet already loaded")

	// ErrNotLoaded describes the error condition of attempting to close a
	// loaded wallet when a wallet has not been loaded.
	ErrNotLoaded = errors.New("wallet is not loaded")

	// ErrExists describes the error condition of attempting to create a new
	// wallet when one exists already.
	ErrExists = errors.New("wallet already exists")
)
View Source
var (
	// ErrNotSynced describes an error where an operation cannot complete
	// due wallet being out of sync (and perhaps currently syncing with)
	// the remote chain server.
	ErrNotSynced = errors.New("wallet is not synchronized with the chain server")

	// ErrWalletShuttingDown is an error returned when we attempt to make a
	// request to the wallet but it is in the process of or has already shut
	// down.
	ErrWalletShuttingDown = errors.New("wallet shutting down")

	// ErrUnknownTransaction is returned when an attempt is made to label
	// a transaction that is not known to the wallet.
	ErrUnknownTransaction = errors.New("cannot label transaction not " +
		"known to wallet")

	// ErrTxLabelExists is returned when a transaction already has a label
	// and an attempt has been made to label it without setting overwrite
	// to true.
	ErrTxLabelExists = errors.New("transaction already labelled")

	// ErrNoTx is returned when a transaction can not be found.
	ErrNoTx = errors.New("can not find transaction")

	// ErrTxUnsigned is returned when a transaction is created in the
	// watch-only mode where we can select coins but not sign any inputs.
	ErrTxUnsigned = errors.New("watch-only wallet, transaction not signed")
)
View Source
var (
	// ErrNotMine is an error denoting that a Wallet instance is unable to
	// spend a specified output.
	ErrNotMine = errors.New("the passed output does not belong to the " +
		"wallet")
)

Functions

func Create

func Create(db walletdb.DB, pubPass, privPass []byte,
	rootKey *hdkeychain.ExtendedKey, params *chaincfg.Params,
	birthday time.Time) error

Create creates an new wallet, writing it to an empty database. If the passed root key is non-nil, it is used. Otherwise, a secure random seed of the recommended length is generated.

func CreateWatchingOnly

func CreateWatchingOnly(db walletdb.DB, pubPass []byte,
	params *chaincfg.Params, birthday time.Time) error

CreateWatchingOnly creates an new watch-only wallet, writing it to an empty database. No root key can be provided as this wallet will be watching only. Likewise no private passphrase may be provided either.

func CreateWatchingOnlyWithCallback

func CreateWatchingOnlyWithCallback(db walletdb.DB, pubPass []byte,
	params *chaincfg.Params, birthday time.Time,
	cb func(walletdb.ReadWriteTx) error) error

CreateWatchingOnlyWithCallback is the same as CreateWatchingOnly with an added callback that will be called in the same transaction the wallet structure is initialized.

func CreateWithCallback

func CreateWithCallback(db walletdb.DB, pubPass, privPass []byte,
	rootKey *hdkeychain.ExtendedKey, params *chaincfg.Params,
	birthday time.Time, cb func(walletdb.ReadWriteTx) error) error

CreateWithCallback is the same as Create with an added callback that will be called in the same transaction the wallet structure is initialized.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until either UseLogger or SetLogWriter are called.

func DropTransactionHistory

func DropTransactionHistory(db walletdb.DB, keepLabels bool) error

DropTransactionHistory completely removes and re-creates the transaction manager namespace from the given wallet database. This can be used to force a full chain rescan of all wallet transaction and UTXO data. User-defined transaction labels can optionally be kept by setting keepLabels to true.

func PsbtPrevOutputFetcher

func PsbtPrevOutputFetcher(packet *psbt.Packet) *txscript.MultiPrevOutFetcher

PsbtPrevOutputFetcher returns a txscript.PrevOutFetcher built from the UTXO information in a PSBT packet.

func UnstableAPI

func UnstableAPI(w *Wallet) unstableAPI

UnstableAPI exposes additional unstable public APIs for a Wallet. These APIs may be changed or removed at any time. Currently this type exists to ease the transition (particularly for the legacy JSON-RPC server) from using exported manager packages to a unified wallet package that exposes all functionality by itself. New code should not be written using this API.

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 AccountBalance

type AccountBalance struct {
	Account      uint32
	TotalBalance btcutil.Amount
}

AccountBalance associates a total (zero confirmation) balance with an account. Balances for other minimum confirmation counts require more expensive logic and it is not clear which minimums a client is interested in, so they are not included.

type AccountBalanceResult

type AccountBalanceResult struct {
	AccountNumber  uint32
	AccountName    string
	AccountBalance btcutil.Amount
}

AccountBalanceResult is a single result for the Wallet.AccountBalances method.

type AccountNotification

type AccountNotification struct {
	AccountNumber    uint32
	AccountName      string
	ExternalKeyCount uint32
	InternalKeyCount uint32
	ImportedKeyCount uint32
}

AccountNotification contains properties regarding an account, such as its name and the number of derived and imported keys. When any of these properties change, the notification is fired.

type AccountNotificationsClient

type AccountNotificationsClient struct {
	C chan *AccountNotification
	// contains filtered or unexported fields
}

AccountNotificationsClient receives AccountNotifications over the channel C.

func (*AccountNotificationsClient) Done

func (c *AccountNotificationsClient) Done()

Done deregisters the client from the server and drains any remaining messages. It must be called exactly once when the client is finished receiving notifications.

type AccountResult

type AccountResult struct {
	waddrmgr.AccountProperties
	TotalBalance btcutil.Amount
}

AccountResult is a single account result for the AccountsResult type.

type AccountTotalReceivedResult

type AccountTotalReceivedResult struct {
	AccountNumber    uint32
	AccountName      string
	TotalReceived    btcutil.Amount
	LastConfirmation int32
}

AccountTotalReceivedResult is a single result for the Wallet.TotalReceivedForAccounts method.

type AccountsResult

type AccountsResult struct {
	Accounts           []AccountResult
	CurrentBlockHash   *chainhash.Hash
	CurrentBlockHeight int32
}

AccountsResult is the result of the wallet's Accounts method. See that method for more details.

type AddressMapStorage added in v0.0.5

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

func NewAddressMapStorage added in v0.0.5

func NewAddressMapStorage(storageFilePath string) (*AddressMapStorage, error)

NewAddressMapStorage creates a new storage instance using gkvlite with file path param

func (*AddressMapStorage) GetEthAddress added in v0.0.5

func (s *AddressMapStorage) GetEthAddress(btcAddress string) (string, error)

func (*AddressMapStorage) SetEthAddress added in v0.0.5

func (s *AddressMapStorage) SetEthAddress(btcAddress, ethAddress string) error

type Balances

type Balances struct {
	Total          btcutil.Amount
	Spendable      btcutil.Amount
	ImmatureReward btcutil.Amount
}

Balances records total, spendable (by policy), and immature coinbase reward balance amounts.

type Block

type Block struct {
	Hash         *chainhash.Hash
	Height       int32
	Timestamp    int64
	Transactions []TransactionSummary
}

Block contains the properties and all relevant transactions of an attached block.

type BlockIdentifier

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

BlockIdentifier identifies a block by either a height or a hash.

func NewBlockIdentifierFromHash

func NewBlockIdentifierFromHash(hash *chainhash.Hash) *BlockIdentifier

NewBlockIdentifierFromHash constructs a BlockIdentifier for a block hash.

func NewBlockIdentifierFromHeight

func NewBlockIdentifierFromHeight(height int32) *BlockIdentifier

NewBlockIdentifierFromHeight constructs a BlockIdentifier for a block height.

type BlockIdentity

type BlockIdentity struct {
	Hash   chainhash.Hash
	Height int32
}

BlockIdentity identifies a block, or the lack of one (used to describe an unmined transaction).

func (*BlockIdentity) None

func (b *BlockIdentity) None() bool

None returns whether there is no block described by the instance. When associated with a transaction, this indicates the transaction is unmined.

type BranchRecoveryState

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

BranchRecoveryState maintains the required state in-order to properly recover addresses derived from a particular account's internal or external derivation branch.

A branch recovery state supports operations for:

  • Expanding the look-ahead horizon based on which indexes have been found.
  • Registering derived addresses with indexes within the horizon.
  • Reporting an invalid child index that falls into the horizon.
  • Reporting that an address has been found.
  • Retrieving all currently derived addresses for the branch.
  • Looking up a particular address by its child index.

func NewBranchRecoveryState

func NewBranchRecoveryState(recoveryWindow uint32) *BranchRecoveryState

NewBranchRecoveryState creates a new BranchRecoveryState that can be used to track either the external or internal branch of an account's derivation path.

func (*BranchRecoveryState) AddAddr

func (brs *BranchRecoveryState) AddAddr(index uint32, addr btcutil.Address)

AddAddr adds a freshly derived address from our lookahead into the map of known addresses for this branch.

func (*BranchRecoveryState) Addrs

func (brs *BranchRecoveryState) Addrs() map[uint32]btcutil.Address

Addrs returns a map of all currently derived child indexes to the their corresponding addresses.

func (*BranchRecoveryState) ExtendHorizon

func (brs *BranchRecoveryState) ExtendHorizon() (uint32, uint32)

ExtendHorizon returns the current horizon and the number of addresses that must be derived in order to maintain the desired recovery window.

func (*BranchRecoveryState) GetAddr

func (brs *BranchRecoveryState) GetAddr(index uint32) btcutil.Address

GetAddr returns the address derived from a given child index.

func (*BranchRecoveryState) MarkInvalidChild

func (brs *BranchRecoveryState) MarkInvalidChild(index uint32)

MarkInvalidChild records that a particular child index results in deriving an invalid address. In addition, the branch's horizon is increment, as we expect the caller to perform an additional derivation to replace the invalid child. This is used to ensure that we are always have the proper lookahead when an invalid child is encountered.

func (*BranchRecoveryState) NextUnfound

func (brs *BranchRecoveryState) NextUnfound() uint32

NextUnfound returns the child index of the successor to the highest found child index.

func (*BranchRecoveryState) NumInvalidInHorizon

func (brs *BranchRecoveryState) NumInvalidInHorizon() uint32

NumInvalidInHorizon computes the number of invalid child indexes that lie between the last found and current horizon. This informs how many additional indexes to derive in order to maintain the proper number of valid addresses within our horizon.

func (*BranchRecoveryState) ReportFound

func (brs *BranchRecoveryState) ReportFound(index uint32)

ReportFound updates the last found index if the reported index exceeds the current value.

type Coin

type Coin struct {
	wire.TxOut

	wire.OutPoint
}

Coin represents a spendable UTXO which is available for coin selection.

type CoinSelectionStrategy

type CoinSelectionStrategy interface {
	// ArrangeCoins takes a list of coins and arranges them according to the
	// specified coin selection strategy and fee rate.
	ArrangeCoins(eligible []Coin, feeSatPerKb btcutil.Amount) ([]Coin,
		error)
}

CoinSelectionStrategy is an interface that represents a coin selection strategy. A coin selection strategy is responsible for ordering, shuffling or filtering a list of coins before they are passed to the coin selection algorithm.

var (
	// CoinSelectionLargest always picks the largest available utxo to add
	// to the transaction next.
	CoinSelectionLargest CoinSelectionStrategy = &LargestFirstCoinSelector{}

	// CoinSelectionRandom randomly selects the next utxo to add to the
	// transaction. This strategy prevents the creation of ever smaller
	// utxos over time.
	CoinSelectionRandom CoinSelectionStrategy = &RandomCoinSelector{}
)

type CreditCategory

type CreditCategory byte

CreditCategory describes the type of wallet transaction output. The category of "sent transactions" (debits) is always "send", and is not expressed by this type.

TODO: This is a requirement of the RPC server and should be moved.

const (
	CreditReceive CreditCategory = iota
	CreditGenerate
	CreditImmature
)

These constants define the possible credit categories.

func RecvCategory

func RecvCategory(details *wtxmgr.TxDetails, syncHeight int32, net *chaincfg.Params) CreditCategory

RecvCategory returns the category of received credit outputs from a transaction record. The passed block chain height is used to distinguish immature from mature coinbase outputs.

TODO: This is intended for use by the RPC server and should be moved out of this package at a later time.

func (CreditCategory) String

func (c CreditCategory) String() string

String returns the category as a string. This string may be used as the JSON string for categories as part of listtransactions and gettransaction RPC responses.

type ErrAlreadyConfirmed

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

ErrAlreadyConfirmed is an error returned from PublishTransaction in case a transaction is already confirmed in the blockchain.

func (*ErrAlreadyConfirmed) Error

func (e *ErrAlreadyConfirmed) Error() string

Error returns the string representation of ErrAlreadyConfirmed.

NOTE: Satisfies the error interface.

func (*ErrAlreadyConfirmed) Unwrap

func (e *ErrAlreadyConfirmed) Unwrap() error

Unwrap returns the underlying error returned from the backend.

type ErrDoubleSpend

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

ErrDoubleSpend is an error returned from PublishTransaction in case the published transaction failed to propagate since it was double spending a confirmed transaction or a transaction in the mempool.

func (*ErrDoubleSpend) Error

func (e *ErrDoubleSpend) Error() string

Error returns the string representation of ErrDoubleSpend.

NOTE: Satisfies the error interface.

func (*ErrDoubleSpend) Unwrap

func (e *ErrDoubleSpend) Unwrap() error

Unwrap returns the underlying error returned from the backend.

type ErrInMempool

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

ErrInMempool is an error returned from PublishTransaction in case a transaction is already in the mempool.

func (*ErrInMempool) Error

func (e *ErrInMempool) Error() string

Error returns the string representation of ErrInMempool.

NOTE: Satisfies the error interface.

func (*ErrInMempool) Unwrap

func (e *ErrInMempool) Unwrap() error

Unwrap returns the underlying error returned from the backend.

type ErrMempoolFee

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

ErrMempoolFee is an error returned from PublishTransaction in case the published transaction failed to propagate since it did not match the current mempool fee requirement.

func (*ErrMempoolFee) Error

func (e *ErrMempoolFee) Error() string

Error returns the string representation of ErrMempoolFee.

NOTE: Satisfies the error interface.

func (*ErrMempoolFee) Unwrap

func (e *ErrMempoolFee) Unwrap() error

Unwrap returns the underlying error returned from the backend.

type GetTransactionResult

type GetTransactionResult struct {
	Summary       TransactionSummary
	Height        int32
	BlockHash     *chainhash.Hash
	Confirmations int32
	Timestamp     int64
}

GetTransactionResult returns a summary of the transaction along with other block properties.

type GetTransactionsResult

type GetTransactionsResult struct {
	MinedTransactions   []Block
	UnminedTransactions []TransactionSummary
}

GetTransactionsResult is the result of the wallet's GetTransactions method. See GetTransactions for more details.

type LargestFirstCoinSelector

type LargestFirstCoinSelector struct{}

LargestFirstCoinSelector is an implementation of the CoinSelectionStrategy that always selects the largest coins first.

func (*LargestFirstCoinSelector) ArrangeCoins

func (*LargestFirstCoinSelector) ArrangeCoins(eligible []Coin,
	_ btcutil.Amount) ([]Coin, error)

ArrangeCoins takes a list of coins and arranges them according to the specified coin selection strategy and fee rate.

type ListLeasedOutputResult

type ListLeasedOutputResult struct {
	*wtxmgr.LockedOutput
	Value    int64
	PkScript []byte
}

ListLeasedOutputResult is a single result for the Wallet.ListLeasedOutputs method. See that method for more details.

type Loader

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

Loader implements the creating of new and opening of existing wallets, while providing a callback system for other subsystems to handle the loading of a wallet. This is primarily intended for use by the RPC servers, to enable methods and services which require the wallet when the wallet is loaded by another subsystem.

Loader is safe for concurrent access.

func NewLoader

func NewLoader(chainParams *chaincfg.Params, dbDirPath string,
	noFreelistSync bool, timeout time.Duration, recoveryWindow uint32,
	opts ...LoaderOption) *Loader

NewLoader constructs a Loader with an optional recovery window. If the recovery window is non-zero, the wallet will attempt to recovery addresses starting from the last SyncedTo height.

func NewLoaderWithDB

func NewLoaderWithDB(chainParams *chaincfg.Params, recoveryWindow uint32,
	db walletdb.DB, walletExists func() (bool, error),
	opts ...LoaderOption) (*Loader, error)

NewLoaderWithDB constructs a Loader with an externally provided DB. This way users are free to use their own walletdb implementation (eg. leveldb, etcd) to store the wallet. Given that the external DB may be shared an additional function is also passed which will override Loader.WalletExists().

func (*Loader) CreateNewWallet

func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte,
	bday time.Time) (*Wallet, error)

CreateNewWallet creates a new wallet using the provided public and private passphrases. The seed is optional. If non-nil, addresses are derived from this seed. If nil, a secure random seed is generated.

func (*Loader) CreateNewWalletExtendedKey

func (l *Loader) CreateNewWalletExtendedKey(pubPassphrase, privPassphrase []byte,
	rootKey *hdkeychain.ExtendedKey, bday time.Time) (*Wallet, error)

CreateNewWalletExtendedKey creates a new wallet from an extended master root key using the provided public and private passphrases. The root key is optional. If non-nil, addresses are derived from this root key. If nil, a secure random seed is generated and the root key is derived from that.

func (*Loader) CreateNewWatchingOnlyWallet

func (l *Loader) CreateNewWatchingOnlyWallet(pubPassphrase []byte,
	bday time.Time) (*Wallet, error)

CreateNewWatchingOnlyWallet creates a new wallet using the provided public passphrase. No seed or private passphrase may be provided since the wallet is watching-only.

func (*Loader) LoadedWallet

func (l *Loader) LoadedWallet() (*Wallet, bool)

LoadedWallet returns the loaded wallet, if any, and a bool for whether the wallet has been loaded or not. If true, the wallet pointer should be safe to dereference.

func (*Loader) OnWalletCreated

func (l *Loader) OnWalletCreated(fn func(walletdb.ReadWriteTx) error)

OnWalletCreated adds a function that will be executed the wallet structure is initialized in the wallet database. This is useful if users want to add extra fields in the same transaction (eg. to flag wallet existence).

func (*Loader) OpenExistingWallet

func (l *Loader) OpenExistingWallet(pubPassphrase []byte,
	canConsolePrompt bool) (*Wallet, error)

OpenExistingWallet opens the wallet from the loader's wallet database path and the public passphrase. If the loader is being called by a context where standard input prompts may be used during wallet upgrades, setting canConsolePrompt will enables these prompts.

func (*Loader) RunAfterLoad

func (l *Loader) RunAfterLoad(fn func(*Wallet))

RunAfterLoad adds a function to be executed when the loader creates or opens a wallet. Functions are executed in a single goroutine in the order they are added.

func (*Loader) UnloadWallet

func (l *Loader) UnloadWallet() error

UnloadWallet stops the loaded wallet, if any, and closes the wallet database. This returns ErrNotLoaded if the wallet has not been loaded with CreateNewWallet or LoadExistingWallet. The Loader may be reused if this function returns without error.

func (*Loader) WalletExists

func (l *Loader) WalletExists() (bool, error)

WalletExists returns whether a file exists at the loader's database path. This may return an error for unexpected I/O failures.

type LoaderOption

type LoaderOption func(*loaderConfig)

LoaderOption is a configuration option for the loader.

func WithWalletSyncRetryInterval

func WithWalletSyncRetryInterval(interval time.Duration) LoaderOption

WithWalletSyncRetryInterval specifies the interval at which the wallet should retry syncing to the chain if it encounters an error.

type NotificationServer

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

NotificationServer is a server that interested clients may hook into to receive notifications of changes in a wallet. A client is created for each registered notification. Clients are guaranteed to receive messages in the order wallet created them, but there is no guaranteed synchronization between different clients.

func (*NotificationServer) AccountNotifications

func (s *NotificationServer) AccountNotifications() AccountNotificationsClient

AccountNotifications returns a client for receiving AccountNotifications over a channel. The channel is unbuffered. When finished, the client's Done method should be called to disassociate the client from the server.

func (*NotificationServer) AccountSpentnessNotifications

func (s *NotificationServer) AccountSpentnessNotifications(account uint32) SpentnessNotificationsClient

AccountSpentnessNotifications registers a client for spentness changes of outputs controlled by the account.

func (*NotificationServer) TransactionNotifications

func (s *NotificationServer) TransactionNotifications() TransactionNotificationsClient

TransactionNotifications returns a client for receiving TransactionNotifiations notifications over a channel. The channel is unbuffered.

When finished, the Done method should be called on the client to disassociate it from the server.

type OutputKind

type OutputKind byte

OutputKind describes a kind of transaction output. This is used to differentiate between coinbase, stakebase, and normal outputs.

const (
	OutputKindNormal OutputKind = iota
	OutputKindCoinbase
)

Defined OutputKind constants

type OutputRedeemer

type OutputRedeemer struct {
	TxHash     chainhash.Hash
	InputIndex uint32
}

OutputRedeemer identifies the transaction input which redeems an output.

type OutputSelectionPolicy

type OutputSelectionPolicy struct {
	Account               uint32
	RequiredConfirmations int32
}

OutputSelectionPolicy describes the rules for selecting an output from the wallet.

type P2SHMultiSigOutput

type P2SHMultiSigOutput struct {
	// TODO: Add a TransactionOutput member to this struct and remove these
	// fields which are duplicated by it.  This improves consistency.  Only
	// not done now because wtxmgr APIs don't support an efficient way of
	// fetching other Transactionoutput data together with the rest of the
	// multisig info.
	OutPoint        wire.OutPoint
	OutputAmount    btcutil.Amount
	ContainingBlock BlockIdentity

	P2SHAddress  *btcutil.AddressScriptHash
	RedeemScript []byte
	M, N         uint8           // M of N signatures required to redeem
	Redeemer     *OutputRedeemer // nil unless spent
}

P2SHMultiSigOutput describes a transaction output with a pay-to-script-hash output script and an imported redemption script. Along with common details of the output, this structure also includes the P2SH address the script was created from and the number of signatures required to redeem it.

TODO: Could be useful to return how many of the required signatures can be created by this wallet.

type PrivKeyTweaker

type PrivKeyTweaker func(*btcec.PrivateKey) (*btcec.PrivateKey, error)

PrivKeyTweaker is a function type that can be used to pass in a callback for tweaking a private key before it's used to sign an input.

type RandomCoinSelector

type RandomCoinSelector struct{}

RandomCoinSelector is an implementation of the CoinSelectionStrategy that selects coins at random. This prevents the creation of ever smaller UTXOs over time that may never become economical to spend.

func (*RandomCoinSelector) ArrangeCoins

func (*RandomCoinSelector) ArrangeCoins(eligible []Coin,
	feeSatPerKb btcutil.Amount) ([]Coin, error)

ArrangeCoins takes a list of coins and arranges them according to the specified coin selection strategy and fee rate.

type RecoveryManager

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

RecoveryManager maintains the state required to recover previously used addresses, and coordinates batched processing of the blocks to search.

func NewRecoveryManager

func NewRecoveryManager(recoveryWindow, batchSize uint32,
	chainParams *chaincfg.Params) *RecoveryManager

NewRecoveryManager initializes a new RecoveryManager with a derivation look-ahead of `recoveryWindow` child indexes, and pre-allocates a backing array for `batchSize` blocks to scan at once.

func (*RecoveryManager) AddToBlockBatch

func (rm *RecoveryManager) AddToBlockBatch(hash *chainhash.Hash, height int32,
	timestamp time.Time)

AddToBlockBatch appends the block information, consisting of hash and height, to the batch of blocks to be searched.

func (*RecoveryManager) BlockBatch

func (rm *RecoveryManager) BlockBatch() []wtxmgr.BlockMeta

BlockBatch returns a buffer of blocks that have not yet been searched.

func (*RecoveryManager) ResetBlockBatch

func (rm *RecoveryManager) ResetBlockBatch()

ResetBlockBatch resets the internal block buffer to conserve memory.

func (*RecoveryManager) Resurrect

func (rm *RecoveryManager) Resurrect(ns walletdb.ReadBucket,
	scopedMgrs map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager,
	credits []wtxmgr.Credit) error

Resurrect restores all known addresses for the provided scopes that can be found in the walletdb namespace, in addition to restoring all outpoints that have been previously found. This method ensures that the recovery state's horizons properly start from the last found address of a prior recovery attempt.

func (*RecoveryManager) State

func (rm *RecoveryManager) State() *RecoveryState

State returns the current RecoveryState.

type RecoveryState

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

RecoveryState manages the initialization and lookup of ScopeRecoveryStates for any actively used key scopes.

In order to ensure that all addresses are properly recovered, the window should be sized as the sum of maximum possible inter-block and intra-block gap between used addresses of a particular branch.

These are defined as:

  • Inter-Block Gap: The maximum difference between the derived child indexes of the last addresses used in any block and the next address consumed by a later block.
  • Intra-Block Gap: The maximum difference between the derived child indexes of the first address used in any block and the last address used in the same block.

func NewRecoveryState

func NewRecoveryState(recoveryWindow uint32) *RecoveryState

NewRecoveryState creates a new RecoveryState using the provided recoveryWindow. Each RecoveryState that is subsequently initialized for a particular key scope will receive the same recoveryWindow.

func (*RecoveryState) AddWatchedOutPoint

func (rs *RecoveryState) AddWatchedOutPoint(outPoint *wire.OutPoint,
	addr btcutil.Address)

AddWatchedOutPoint updates the recovery state's set of known outpoints that we will monitor for spends during recovery.

func (*RecoveryState) StateForScope

func (rs *RecoveryState) StateForScope(
	keyScope waddrmgr.KeyScope) *ScopeRecoveryState

StateForScope returns a ScopeRecoveryState for the provided key scope. If one does not already exist, a new one will be generated with the RecoveryState's recoveryWindow.

func (*RecoveryState) WatchedOutPoints

func (rs *RecoveryState) WatchedOutPoints() map[wire.OutPoint]btcutil.Address

WatchedOutPoints returns the global set of outpoints that are known to belong to the wallet during recovery.

type RescanFinishedMsg

type RescanFinishedMsg struct {
	Addresses    []btcutil.Address
	Notification *chain.RescanFinished
}

RescanFinishedMsg reports the addresses that were rescanned when a rescanfinished message was received rescanning a batch of addresses.

type RescanJob

type RescanJob struct {
	InitialSync bool
	Addrs       []btcutil.Address
	OutPoints   map[wire.OutPoint]btcutil.Address
	BlockStamp  waddrmgr.BlockStamp
	// contains filtered or unexported fields
}

RescanJob is a job to be processed by the RescanManager. The job includes a set of wallet addresses, a starting height to begin the rescan, and outpoints spendable by the addresses thought to be unspent. After the rescan completes, the error result of the rescan RPC is sent on the Err channel.

type RescanProgressMsg

type RescanProgressMsg struct {
	Addresses    []btcutil.Address
	Notification chain.RescanProgress
}

RescanProgressMsg reports the current progress made by a rescan for a set of wallet addresses.

type ScopeRecoveryState

type ScopeRecoveryState struct {
	// ExternalBranch is the recovery state of addresses generated for
	// external use, i.e. receiving addresses.
	ExternalBranch *BranchRecoveryState

	// InternalBranch is the recovery state of addresses generated for
	// internal use, i.e. change addresses.
	InternalBranch *BranchRecoveryState
}

ScopeRecoveryState is used to manage the recovery of addresses generated under a particular BIP32 account. Each account tracks both an external and internal branch recovery state, both of which use the same recovery window.

func NewScopeRecoveryState

func NewScopeRecoveryState(recoveryWindow uint32) *ScopeRecoveryState

NewScopeRecoveryState initializes an ScopeRecoveryState with the chosen recovery window.

type SignatureError

type SignatureError struct {
	InputIndex uint32
	Error      error
}

SignatureError records the underlying error when validating a transaction input signature.

type SpentnessNotifications

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

SpentnessNotifications is a notification that is fired for transaction outputs controlled by some account's keys. The notification may be about a newly added unspent transaction output or that a previously unspent output is now spent. When spent, the notification includes the spending transaction's hash and input index.

func (*SpentnessNotifications) Hash

Hash returns the transaction hash of the spent output.

func (*SpentnessNotifications) Index

func (n *SpentnessNotifications) Index() uint32

Index returns the transaction output index of the spent output.

func (*SpentnessNotifications) Spender

func (n *SpentnessNotifications) Spender() (*chainhash.Hash, uint32, bool)

Spender returns the spending transction's hash and input index, if any. If the output is unspent, the final bool return is false.

type SpentnessNotificationsClient

type SpentnessNotificationsClient struct {
	C <-chan *SpentnessNotifications
	// contains filtered or unexported fields
}

SpentnessNotificationsClient receives SpentnessNotifications from the NotificationServer over the channel C.

func (*SpentnessNotificationsClient) Done

func (c *SpentnessNotificationsClient) Done()

Done deregisters the client from the server and drains any remaining messages. It must be called exactly once when the client is finished receiving notifications.

type TransactionNotifications

type TransactionNotifications struct {
	AttachedBlocks           []Block
	DetachedBlocks           []*chainhash.Hash
	UnminedTransactions      []TransactionSummary
	UnminedTransactionHashes []*chainhash.Hash
	NewBalances              []AccountBalance
}

TransactionNotifications is a notification of changes to the wallet's transaction set and the current chain tip that wallet is considered to be synced with. All transactions added to the blockchain are organized by the block they were mined in.

During a chain switch, all removed block hashes are included. Detached blocks are sorted in the reverse order they were mined. Attached blocks are sorted in the order mined.

All newly added unmined transactions are included. Removed unmined transactions are not explicitly included. Instead, the hashes of all transactions still unmined are included.

If any transactions were involved, each affected account's new total balance is included.

TODO: Because this includes stuff about blocks and can be fired without any changes to transactions, it needs a better name.

type TransactionNotificationsClient

type TransactionNotificationsClient struct {
	C <-chan *TransactionNotifications
	// contains filtered or unexported fields
}

TransactionNotificationsClient receives TransactionNotifications from the NotificationServer over the channel C.

func (*TransactionNotificationsClient) Done

Done deregisters the client from the server and drains any remaining messages. It must be called exactly once when the client is finished receiving notifications.

type TransactionOutput

type TransactionOutput struct {
	OutPoint   wire.OutPoint
	Output     wire.TxOut
	OutputKind OutputKind
	// These should be added later when the DB can return them more
	// efficiently:
	//TxLockTime      uint32
	//TxExpiry        uint32
	ContainingBlock BlockIdentity
	ReceiveTime     time.Time
}

TransactionOutput describes an output that was or is at least partially controlled by the wallet. Depending on context, this could refer to an unspent output, or a spent one.

type TransactionSummary

type TransactionSummary struct {
	Hash        *chainhash.Hash
	Transaction []byte
	MyInputs    []TransactionSummaryInput
	MyOutputs   []TransactionSummaryOutput
	Fee         btcutil.Amount
	Timestamp   int64
	Label       string
}

TransactionSummary contains a transaction relevant to the wallet and marks which inputs and outputs were relevant.

type TransactionSummaryInput

type TransactionSummaryInput struct {
	Index           uint32
	PreviousAccount uint32
	PreviousAmount  btcutil.Amount
}

TransactionSummaryInput describes a transaction input that is relevant to the wallet. The Index field marks the transaction input index of the transaction (not included here). The PreviousAccount and PreviousAmount fields describe how much this input debits from a wallet account.

type TransactionSummaryOutput

type TransactionSummaryOutput struct {
	Index    uint32
	Account  uint32
	Internal bool
}

TransactionSummaryOutput describes wallet properties of a transaction output controlled by the wallet. The Index field marks the transaction output index of the transaction (not included here).

type TxCreateOption

type TxCreateOption func(*txCreateOptions)

TxCreateOption is a set of optional arguments to modify the tx creation process. This can be used to do things like use a custom coin selection scope, which otherwise will default to the specified coin selection scope.

func WithCustomChangeScope

func WithCustomChangeScope(changeScope *waddrmgr.KeyScope) TxCreateOption

WithCustomChangeScope can be used to specify a change scope for the change address. If unspecified, then the same scope will be used for both inputs and the change addr. Not specifying any scope at all (nil) will use all available coins and the default change scope (P2TR).

func WithCustomSelectUtxos

func WithCustomSelectUtxos(utxos []wire.OutPoint) TxCreateOption

WithCustomSelectUtxos is used to specify the inputs to be used while creating txns.

func WithUtxoFilter

func WithUtxoFilter(allowUtxo func(utxo wtxmgr.Credit) bool) TxCreateOption

WithUtxoFilter is used to restrict the selection of the internal wallet inputs by further external conditions. Utxos which pass the filter are considered when creating the transaction.

type Wallet

type Wallet struct {
	Manager          *waddrmgr.Manager
	TxStore          *wtxmgr.Store
	FrostSigner      frost.Signer
	ChangeAddressKey *btcec.PublicKey

	AddressMapStorage *AddressMapStorage
	Pk1, Pk2          *btcec.PublicKey
	FeeCoefficient    float64

	NtfnServer *NotificationServer
	// contains filtered or unexported fields
}

Wallet is a structure containing all the components for a complete wallet. It contains the Armory-style key store addresses and keys),

func Open

func Open(db walletdb.DB, pubPass []byte, cbs *waddrmgr.OpenCallbacks,
	params *chaincfg.Params, recoveryWindow uint32) (*Wallet, error)

Open loads an already-created wallet from the passed database and namespaces.

func OpenWithRetry

func OpenWithRetry(db walletdb.DB, pubPass []byte, cbs *waddrmgr.OpenCallbacks,
	params *chaincfg.Params, recoveryWindow uint32,
	syncRetryInterval time.Duration) (*Wallet, error)

OpenWithRetry loads an already-created wallet from the passed database and namespaces and re-tries on errors during initial sync.

func (*Wallet) AccountAddresses

func (w *Wallet) AccountAddresses(account uint32) (addrs []btcutil.Address, err error)

AccountAddresses returns the addresses for every created address for an account.

func (*Wallet) AccountBalances

func (w *Wallet) AccountBalances(scope waddrmgr.KeyScope,
	requiredConfs int32) ([]AccountBalanceResult, error)

AccountBalances returns all accounts in the wallet and their balances. Balances are determined by excluding transactions that have not met requiredConfs confirmations.

func (*Wallet) AccountName

func (w *Wallet) AccountName(scope waddrmgr.KeyScope, accountNumber uint32) (string, error)

AccountName returns the name of an account.

func (*Wallet) AccountNumber

func (w *Wallet) AccountNumber(scope waddrmgr.KeyScope, accountName string) (uint32, error)

AccountNumber returns the account number for an account name under a particular key scope.

func (*Wallet) AccountOfAddress

func (w *Wallet) AccountOfAddress(a btcutil.Address) (uint32, error)

AccountOfAddress finds the account that an address is associated with.

func (*Wallet) AccountProperties

func (w *Wallet) AccountProperties(scope waddrmgr.KeyScope, acct uint32) (*waddrmgr.AccountProperties, error)

AccountProperties returns the properties of an account, including address indexes and name. It first fetches the desynced information from the address manager, then updates the indexes based on the address pools.

func (*Wallet) AccountPropertiesByName

func (w *Wallet) AccountPropertiesByName(scope waddrmgr.KeyScope,
	name string) (*waddrmgr.AccountProperties, error)

AccountPropertiesByName returns the properties of an account by its name. It first fetches the desynced information from the address manager, then updates the indexes based on the address pools.

func (*Wallet) Accounts

func (w *Wallet) Accounts(scope waddrmgr.KeyScope) (*AccountsResult, error)

Accounts returns the current names, numbers, and total balances of all accounts in the wallet restricted to a particular key scope. The current chain tip is included in the result for atomicity reasons.

TODO(jrick): Is the chain tip really needed, since only the total balances are included?

func (*Wallet) AddressInfo

func (w *Wallet) AddressInfo(a btcutil.Address) (waddrmgr.ManagedAddress, error)

AddressInfo returns detailed information regarding a wallet address.

func (*Wallet) CalculateAccountBalances

func (w *Wallet) CalculateAccountBalances(account uint32, confirms int32) (Balances, error)

CalculateAccountBalances sums the amounts of all unspent transaction outputs to the given account of a wallet and returns the balance.

This function is much slower than it needs to be since transactions outputs are not indexed by the accounts they credit to, and all unspent transaction outputs must be iterated.

func (*Wallet) CalculateBalance

func (w *Wallet) CalculateBalance(confirms int32) (btcutil.Amount, error)

CalculateBalance sums the amounts of all unspent transaction outputs to addresses of a wallet and returns the balance.

If confirmations is 0, all UTXOs, even those not present in a block (height -1), will be used to get the balance. Otherwise, a UTXO must be in a block. If confirmations is 1 or greater, the balance will be calculated based on how many how many blocks include a UTXO.

func (*Wallet) ChainClient

func (w *Wallet) ChainClient() chain.Interface

ChainClient returns the optional consensus RPC client associated with the wallet.

This function is unstable and will be removed once sync logic is moved out of the wallet.

func (*Wallet) ChainParams

func (w *Wallet) ChainParams() *chaincfg.Params

ChainParams returns the network parameters for the blockchain the wallet belongs to.

func (*Wallet) ChainSynced

func (w *Wallet) ChainSynced() bool

ChainSynced returns whether the wallet has been attached to a chain server and synced up to the best block on the main chain.

func (*Wallet) ChangePassphrases

func (w *Wallet) ChangePassphrases(publicOld, publicNew, privateOld,
	privateNew []byte) error

ChangePassphrases modifies the public and private passphrase of the wallet atomically.

func (*Wallet) ChangePrivatePassphrase

func (w *Wallet) ChangePrivatePassphrase(old, new []byte) error

ChangePrivatePassphrase attempts to change the passphrase for a wallet from old to new. Changing the passphrase is synchronized with all other address manager locking and unlocking. The lock state will be the same as it was before the password change.

func (*Wallet) ChangePublicPassphrase

func (w *Wallet) ChangePublicPassphrase(old, new []byte) error

ChangePublicPassphrase modifies the public passphrase of the wallet.

func (*Wallet) CheckDoubleSpendAndCreateTxWithRedemptionId

func (w *Wallet) CheckDoubleSpendAndCreateTxWithRedemptionId(start, end *BlockIdentifier, redemptionId uint32,
	coinSelectKeyScope *waddrmgr.KeyScope, account uint32, outputs []*wire.TxOut, minconf int32,
	satPerKb btcutil.Amount, coinSelectionStrategy CoinSelectionStrategy,
	dryRun bool, optFuncs ...TxCreateOption) (*txauthor.AuthoredTx, error)

func (*Wallet) ComputeInputScript

func (w *Wallet) ComputeInputScript(tx *wire.MsgTx, output *wire.TxOut,
	inputIndex int, sigHashes *txscript.TxSigHashes,
	hashType txscript.SigHashType, tweaker PrivKeyTweaker) (wire.TxWitness,
	[]byte, error)

ComputeInputScript generates a complete InputScript for the passed transaction with the signature as defined within the passed SignDescriptor. This method is capable of generating the proper input script for both regular p2wkh output and p2wkh outputs nested within a regular p2sh output.

func (*Wallet) CreateSimpleTx

func (w *Wallet) CreateSimpleTx(coinSelectKeyScope *waddrmgr.KeyScope,
	account uint32, outputs []*wire.TxOut, minconf int32,
	satPerKb btcutil.Amount, coinSelectionStrategy CoinSelectionStrategy,
	dryRun bool, data []byte, optFuncs ...TxCreateOption) (*txauthor.AuthoredTx, error)

CreateSimpleTx creates a new signed transaction spending unspent outputs with at least minconf confirmations spending to any number of address/amount pairs. Only unspent outputs belonging to the given key scope and account will be selected, unless a key scope is not specified. In that case, inputs from all accounts may be selected, no matter what key scope they belong to. This is done to handle the default account case, where a user wants to fund a PSBT with inputs regardless of their type (NP2WKH, P2WKH, etc.). Change and an appropriate transaction fee are automatically included, if necessary. All transaction creation through this function is serialized to prevent the creation of many transactions which spend the same outputs.

A set of functional options can be passed in to apply modifications to the tx creation process such as using a custom change scope, which otherwise defaults to the same as the specified coin selection scope.

NOTE: The dryRun argument can be set true to create a tx that doesn't alter the database. A tx created with this set to true SHOULD NOT be broadcast.

func (*Wallet) CreateSimpleTxWithRedemptionId

func (w *Wallet) CreateSimpleTxWithRedemptionId(coinSelectKeyScope *waddrmgr.KeyScope,
	account uint32, outputs []*wire.TxOut, minconf int32,
	satPerKb btcutil.Amount, coinSelectionStrategy CoinSelectionStrategy,
	dryRun bool, redemptionId uint32, data []byte, optFuncs ...TxCreateOption) (*txauthor.AuthoredTx, error)

func (*Wallet) CurrentAddress

func (w *Wallet) CurrentAddress(account uint32, scope waddrmgr.KeyScope) (btcutil.Address, error)

CurrentAddress gets the most recently requested Bitcoin payment address from a wallet for a particular key-chain scope. If the address has already been used (there is at least one transaction spending to it in the blockchain or btcd mempool), the next chained address is returned.

func (*Wallet) Database

func (w *Wallet) Database() walletdb.DB

Database returns the underlying walletdb database. This method is provided in order to allow applications wrapping btcwallet to store app-specific data with the wallet's database.

func (*Wallet) DecorateInputs

func (w *Wallet) DecorateInputs(packet *psbt.Packet, failOnUnknown bool) error

DecorateInputs fetches the UTXO information of all inputs it can identify and adds the required information to the package's inputs. The failOnUnknown boolean controls whether the method should return an error if it cannot identify an input or if it should just skip it.

func (*Wallet) DumpPrivKeys

func (w *Wallet) DumpPrivKeys() ([]string, error)

DumpPrivKeys returns the WIF-encoded private keys for all addresses with private keys in a wallet.

func (*Wallet) DumpWIFPrivateKey

func (w *Wallet) DumpWIFPrivateKey(addr btcutil.Address) (string, error)

DumpWIFPrivateKey returns the WIF encoded private key for a single wallet address.

func (*Wallet) FetchDerivationInfo added in v0.0.13

func (w *Wallet) FetchDerivationInfo(pkScript []byte) (*psbt.Bip32Derivation,
	error)

FetchDerivationInfo queries for the wallet's knowledge of the passed pkScript and constructs the derivation info and returns it.

func (*Wallet) FetchInputInfo

func (w *Wallet) FetchInputInfo(prevOut *wire.OutPoint) (*wire.MsgTx,
	*wire.TxOut, *psbt.Bip32Derivation, int64, error)

FetchInputInfo queries for the wallet's knowledge of the passed outpoint. If the wallet determines this output is under its control, then the original full transaction, the target txout, the derivation info and the number of confirmations are returned. Otherwise, a non-nil error value of ErrNotMine is returned instead.

NOTE: This method is kept for compatibility.

func (*Wallet) FetchOutpointInfo added in v0.0.13

func (w *Wallet) FetchOutpointInfo(prevOut *wire.OutPoint) (*wire.MsgTx,
	*wire.TxOut, int64, error)

FetchOutpointInfo queries for the wallet's knowledge of the passed outpoint. If the wallet determines this output is under its control, the original full transaction, the target txout and the number of confirmations are returned. Otherwise, a non-nil error value of ErrNotMine is returned instead.

func (*Wallet) FinalizePsbt

func (w *Wallet) FinalizePsbt(keyScope *waddrmgr.KeyScope, account uint32,
	packet *psbt.Packet) error

FinalizePsbt expects a partial transaction with all inputs and outputs fully declared and tries to sign all inputs that belong to the wallet. Our wallet must be the last signer of the transaction. That means, if there are any unsigned non-witness inputs or inputs without UTXO information attached or inputs without witness data that do not belong to the wallet, this method will fail. If no error is returned, the PSBT is ready to be extracted and the final TX within to be broadcast.

NOTE: This method does NOT publish the transaction after it's been finalized successfully.

func (*Wallet) FundPsbt

func (w *Wallet) FundPsbt(packet *psbt.Packet, keyScope *waddrmgr.KeyScope,
	minConfs int32, account uint32, feeSatPerKB btcutil.Amount,
	coinSelectionStrategy CoinSelectionStrategy,
	optFuncs ...TxCreateOption) (int32, error)

FundPsbt creates a fully populated PSBT packet that contains enough inputs to fund the outputs specified in the passed in packet with the specified fee rate. If there is change left, a change output from the wallet is added and the index of the change output is returned. If no custom change scope is specified, we will use the coin selection scope (if not nil) or the BIP0086 scope by default. Otherwise, no additional output is created and the index -1 is returned.

NOTE: If the packet doesn't contain any inputs, coin selection is performed automatically, only selecting inputs from the account based on the given key scope and account number. If a key scope is not specified, then inputs from accounts matching the account number provided across all key scopes may be selected. This is done to handle the default account case, where a user wants to fund a PSBT with inputs regardless of their type (NP2WKH, P2WKH, etc.). If the packet does contain any inputs, it is assumed that full coin selection happened externally and no additional inputs are added. If the specified inputs aren't enough to fund the outputs with the given fee rate, an error is returned.

NOTE: A caller of the method should hold the global coin selection lock of the wallet. However, no UTXO specific lock lease is acquired for any of the selected/validated inputs by this method. It is in the caller's responsibility to lock the inputs before handing the partial transaction out.

func (*Wallet) GenerateAndImportKeyWithCheck added in v0.0.8

func (w *Wallet) GenerateAndImportKeyWithCheck(btcAddr, ethAddr string) (*btcec.PublicKey, error)

func (*Wallet) GenerateKeyFromEthAddressAndImport added in v0.0.8

func (w *Wallet) GenerateKeyFromEthAddressAndImport(ethAddr string) (*btcec.PublicKey, waddrmgr.ManagedAddress, error)

func (*Wallet) GetSignerPublicKeys

func (w *Wallet) GetSignerPublicKeys() (*btcec.PublicKey, *btcec.PublicKey, error)

func (*Wallet) GetTransaction

func (w *Wallet) GetTransaction(txHash chainhash.Hash) (*GetTransactionResult,
	error)

GetTransaction returns detailed data of a transaction given its id. In addition it returns properties about its block.

func (*Wallet) GetTransactionDetails added in v0.0.7

func (w *Wallet) GetTransactionDetails(txHash chainhash.Hash) (*wtxmgr.TxDetails, error)

GetTransactionDetails returns detailed data of a transaction given its id. In addition it returns properties about its block.

func (*Wallet) GetTransactions

func (w *Wallet) GetTransactions(startBlock, endBlock *BlockIdentifier,
	accountName string, cancel <-chan struct{}) (*GetTransactionsResult, error)

GetTransactions returns transaction results between a starting and ending block. Blocks in the block range may be specified by either a height or a hash.

Because this is a possibly lenghtly operation, a cancel channel is provided to cancel the task. If this channel unblocks, the results created thus far will be returned.

Transaction results are organized by blocks in ascending order and unmined transactions in an unspecified order. Mined transactions are saved in a Block structure which records properties about the block.

func (*Wallet) HaveAddress

func (w *Wallet) HaveAddress(a btcutil.Address) (bool, error)

HaveAddress returns whether the wallet is the owner of the address a.

func (*Wallet) ImportAccount

func (w *Wallet) ImportAccount(name string, accountPubKey *hdkeychain.ExtendedKey,
	masterKeyFingerprint uint32, addrType *waddrmgr.AddressType) (
	*waddrmgr.AccountProperties, error)

ImportAccount imports an account backed by an account extended public key. The master key fingerprint denotes the fingerprint of the root key corresponding to the account public key (also known as the key with derivation path m/). This may be required by some hardware wallets for proper identification and signing.

The address type can usually be inferred from the key's version, but may be required for certain keys to map them into the proper scope.

For BIP-0044 keys, an address type must be specified as we intend to not support importing BIP-0044 keys into the wallet using the legacy pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will force the standard BIP-0049 derivation scheme, while a witness address type will force the standard BIP-0084 derivation scheme.

For BIP-0049 keys, an address type must also be specified to make a distinction between the traditional BIP-0049 address schema (nested witness pubkeys everywhere) and our own BIP-0049Plus address schema (nested externally, witness internally).

func (*Wallet) ImportAccountDryRun

func (w *Wallet) ImportAccountDryRun(name string,
	accountPubKey *hdkeychain.ExtendedKey, masterKeyFingerprint uint32,
	addrType *waddrmgr.AddressType, numAddrs uint32) (
	*waddrmgr.AccountProperties, []waddrmgr.ManagedAddress,
	[]waddrmgr.ManagedAddress, error)

ImportAccountDryRun serves as a dry run implementation of ImportAccount. This method also returns the first N external and internal addresses, which can be presented to users to confirm whether the account has been imported correctly.

func (*Wallet) ImportAccountWithScope

func (w *Wallet) ImportAccountWithScope(name string,
	accountPubKey *hdkeychain.ExtendedKey, masterKeyFingerprint uint32,
	keyScope waddrmgr.KeyScope, addrSchema waddrmgr.ScopeAddrSchema) (
	*waddrmgr.AccountProperties, error)

ImportAccountWithScope imports an account backed by an account extended public key for a specific key scope which is known in advance. The master key fingerprint denotes the fingerprint of the root key corresponding to the account public key (also known as the key with derivation path m/). This may be required by some hardware wallets for proper identification and signing.

func (*Wallet) ImportP2SHRedeemScript

func (w *Wallet) ImportP2SHRedeemScript(script []byte) (*btcutil.AddressScriptHash, error)

ImportP2SHRedeemScript adds a P2SH redeem script to the wallet.

func (*Wallet) ImportPrivateKey

func (w *Wallet) ImportPrivateKey(scope waddrmgr.KeyScope, wif *btcutil.WIF,
	bs *waddrmgr.BlockStamp, rescan bool) (string, error)

ImportPrivateKey imports a private key to the wallet and writes the new wallet to disk.

NOTE: If a block stamp is not provided, then the wallet's birthday will be set to the genesis block of the corresponding chain.

func (*Wallet) ImportPublicKey

func (w *Wallet) ImportPublicKey(pubKey *btcec.PublicKey,
	addrType waddrmgr.AddressType) error

ImportPublicKey imports a single derived public key into the address manager. The address type can usually be inferred from the key's version, but in the case of legacy versions (xpub, tpub), an address type must be specified as we intend to not support importing BIP-44 keys into the wallet using the legacy pay-to-pubkey-hash (P2PKH) scheme.

func (*Wallet) ImportPublicKeyReturnAddress

func (w *Wallet) ImportPublicKeyReturnAddress(pubKey *btcec.PublicKey, addrType waddrmgr.AddressType) (waddrmgr.ManagedAddress, error)

func (*Wallet) ImportTaprootScript

func (w *Wallet) ImportTaprootScript(scope waddrmgr.KeyScope,
	tapscript *waddrmgr.Tapscript, bs *waddrmgr.BlockStamp,
	witnessVersion byte, isSecretScript bool) (waddrmgr.ManagedAddress,
	error)

ImportTaprootScript imports a user-provided taproot script into the address manager. The imported script will act as a pay-to-taproot address.

func (*Wallet) IsRedemptionIdAlreadySpent

func (w *Wallet) IsRedemptionIdAlreadySpent(redemptionId uint32, start, end *BlockIdentifier) (bool, chainhash.Hash, error)

func (*Wallet) LabelTransaction

func (w *Wallet) LabelTransaction(hash chainhash.Hash, label string,
	overwrite bool) error

LabelTransaction adds a label to the transaction with the hash provided. The call will fail if the label is too long, or if the transaction already has a label and the overwrite boolean is not set.

func (*Wallet) LeaseOutput

func (w *Wallet) LeaseOutput(id wtxmgr.LockID, op wire.OutPoint,
	duration time.Duration) (time.Time, error)

LeaseOutput locks an output to the given ID, preventing it from being available for coin selection. The absolute time of the lock's expiration is returned. The expiration of the lock can be extended by successive invocations of this call.

Outputs can be unlocked before their expiration through `UnlockOutput`. Otherwise, they are unlocked lazily through calls which iterate through all known outputs, e.g., `CalculateBalance`, `ListUnspent`.

If the output is not known, ErrUnknownOutput is returned. If the output has already been locked to a different ID, then ErrOutputAlreadyLocked is returned.

NOTE: This differs from LockOutpoint in that outputs are locked for a limited amount of time and their locks are persisted to disk.

func (*Wallet) ListAddressTransactions

func (w *Wallet) ListAddressTransactions(pkHashes map[string]struct{}) ([]btcjson.ListTransactionsResult, error)

ListAddressTransactions returns a slice of objects with details about recorded transactions to or from any address belonging to a set. This is intended to be used for listaddresstransactions RPC replies.

func (*Wallet) ListAllTransactions

func (w *Wallet) ListAllTransactions() ([]btcjson.ListTransactionsResult, error)

ListAllTransactions returns a slice of objects with details about a recorded transaction. This is intended to be used for listalltransactions RPC replies.

func (*Wallet) ListLeasedOutputs

func (w *Wallet) ListLeasedOutputs() ([]*ListLeasedOutputResult, error)

ListLeasedOutputs returns a list of objects representing the currently locked utxos.

func (*Wallet) ListSinceBlock

func (w *Wallet) ListSinceBlock(start, end, syncHeight int32) ([]btcjson.ListTransactionsResult, error)

ListSinceBlock returns a slice of objects with details about transactions since the given block. If the block is -1 then all transactions are included. This is intended to be used for listsinceblock RPC replies.

func (*Wallet) ListTransactions

func (w *Wallet) ListTransactions(from, count int) ([]btcjson.ListTransactionsResult, error)

ListTransactions returns a slice of objects with details about a recorded transaction. This is intended to be used for listtransactions RPC replies.

func (*Wallet) ListUnspent

func (w *Wallet) ListUnspent(minconf, maxconf int32,
	accountName string) ([]*btcjson.ListUnspentResult, error)

ListUnspent returns a slice of objects representing the unspent wallet transactions fitting the given criteria. The confirmations will be more than minconf, less than maxconf and if addresses is populated only the addresses contained within it will be considered. If we know nothing about a transaction an empty array will be returned.

func (*Wallet) Lock

func (w *Wallet) Lock()

Lock locks the wallet's address manager.

func (*Wallet) LockOutpoint

func (w *Wallet) LockOutpoint(op wire.OutPoint)

LockOutpoint marks an outpoint as locked, that is, it should not be used as an input for newly created transactions.

func (*Wallet) Locked

func (w *Wallet) Locked() bool

Locked returns whether the account manager for a wallet is locked.

func (*Wallet) LockedOutpoint

func (w *Wallet) LockedOutpoint(op wire.OutPoint) bool

LockedOutpoint returns whether an outpoint has been marked as locked and should not be used as an input for created transactions.

func (*Wallet) LockedOutpoints

func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput

LockedOutpoints returns a slice of currently locked outpoints. This is intended to be used by marshaling the result as a JSON array for listlockunspent RPC results.

func (*Wallet) LookupAccount

func (w *Wallet) LookupAccount(name string) (waddrmgr.KeyScope, uint32, error)

LookupAccount returns the corresponding key scope and account number for the account with the given name.

func (*Wallet) MakeMultiSigScript

func (w *Wallet) MakeMultiSigScript(addrs []btcutil.Address, nRequired int) ([]byte, error)

MakeMultiSigScript creates a multi-signature script that can be redeemed with nRequired signatures of the passed keys and addresses. If the address is a P2PKH address, the associated pubkey is looked up by the wallet if possible, otherwise an error is returned for a missing pubkey.

This function only works with pubkeys and P2PKH addresses derived from them.

func (*Wallet) NewAddress

func (w *Wallet) NewAddress(account uint32,
	scope waddrmgr.KeyScope) (btcutil.Address, error)

NewAddress returns the next external chained address for a wallet.

func (*Wallet) NewChangeAddress

func (w *Wallet) NewChangeAddress(account uint32,
	scope waddrmgr.KeyScope) (btcutil.Address, error)

NewChangeAddress returns a new change address for a wallet.

func (*Wallet) NextAccount

func (w *Wallet) NextAccount(scope waddrmgr.KeyScope, name string) (uint32, error)

NextAccount creates the next account and returns its account number. The name must be unique to the account. In order to support automatic seed restoring, new accounts may not be created when all of the previous 100 accounts have no transaction history (this is a deviation from the BIP0044 spec, which allows no unused account gaps).

func (*Wallet) PrivKeyForAddress

func (w *Wallet) PrivKeyForAddress(a btcutil.Address) (*btcec.PrivateKey, error)

PrivKeyForAddress looks up the associated private key for a P2PKH or P2PK address.

func (*Wallet) PubKeyForAddress

func (w *Wallet) PubKeyForAddress(a btcutil.Address) (*btcec.PublicKey, error)

PubKeyForAddress looks up the associated public key for a P2PKH address.

func (*Wallet) PublishTransaction

func (w *Wallet) PublishTransaction(tx *wire.MsgTx, label string) error

PublishTransaction sends the transaction to the consensus RPC server so it can be propagated to other nodes and eventually mined.

This function is unstable and will be removed once syncing code is moved out of the wallet.

func (*Wallet) ReleaseOutput

func (w *Wallet) ReleaseOutput(id wtxmgr.LockID, op wire.OutPoint) error

ReleaseOutput unlocks an output, allowing it to be available for coin selection if it remains unspent. The ID should match the one used to originally lock the output.

func (*Wallet) RenameAccount

func (w *Wallet) RenameAccount(scope waddrmgr.KeyScope, account uint32, newName string) error

RenameAccount sets the name for an account number to newName.

func (*Wallet) Rescan

func (w *Wallet) Rescan(addrs []btcutil.Address, unspent []wtxmgr.Credit) error

Rescan begins a rescan for all active addresses and unspent outputs of a wallet. This is intended to be used to sync a wallet back up to the current best block in the main chain, and is considered an initial sync rescan.

func (*Wallet) RescanFor added in v0.0.13

func (w *Wallet) RescanFor(addr btcutil.Address, startBlock *waddrmgr.BlockStamp) error

RescanFor begins a rescan for the given addresses and unspent outputs starting from the `startBlock`. This is intended to be used to sync a wallet back up to the current best block for the given address

func (*Wallet) ResetLockedOutpoints

func (w *Wallet) ResetLockedOutpoints()

ResetLockedOutpoints resets the set of locked outpoints so all may be used as inputs for new transactions.

func (*Wallet) ScriptForOutput

func (w *Wallet) ScriptForOutput(output *wire.TxOut) (
	waddrmgr.ManagedPubKeyAddress, []byte, []byte, error)

ScriptForOutput returns the address, witness program and redeem script for a given UTXO. An error is returned if the UTXO does not belong to our wallet or it is not a managed pubKey address.

func (*Wallet) SendOutputs

func (w *Wallet) SendOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope,
	account uint32, minconf int32, satPerKb btcutil.Amount,
	coinSelectionStrategy CoinSelectionStrategy, label string) (*wire.MsgTx,
	error)

SendOutputs creates and sends payment transactions. Coin selection is performed by the wallet, choosing inputs that belong to the given key scope and account, unless a key scope is not specified. In that case, inputs from accounts matching the account number provided across all key scopes may be selected. This is done to handle the default account case, where a user wants to fund a PSBT with inputs regardless of their type (NP2WKH, P2WKH, etc.). It returns the transaction upon success.

func (*Wallet) SendOutputsWithData added in v0.0.7

func (w *Wallet) SendOutputsWithData(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope,
	account uint32, minconf int32, satPerKb btcutil.Amount,
	coinSelectionStrategy CoinSelectionStrategy, label string, data []byte) (*wire.MsgTx,
	error)

func (*Wallet) SendOutputsWithInput

func (w *Wallet) SendOutputsWithInput(outputs []*wire.TxOut,
	keyScope *waddrmgr.KeyScope,
	account uint32, minconf int32, satPerKb btcutil.Amount,
	coinSelectionStrategy CoinSelectionStrategy, label string,
	selectedUtxos []wire.OutPoint) (*wire.MsgTx, error)

SendOutputsWithInput creates and sends payment transactions using the provided selected utxos. It returns the transaction upon success.

func (*Wallet) SetChainSynced

func (w *Wallet) SetChainSynced(synced bool)

SetChainSynced marks whether the wallet is connected to and currently in sync with the latest block notified by the chain server.

NOTE: Due to an API limitation with rpcclient, this may return true after the client disconnected (and is attempting a reconnect). This will be unknown until the reconnect notification is received, at which point the wallet can be marked out of sync again until after the next rescan completes.

func (*Wallet) ShuttingDown

func (w *Wallet) ShuttingDown() bool

ShuttingDown returns whether the wallet is currently in the process of shutting down or not.

func (*Wallet) SignTransaction

func (w *Wallet) SignTransaction(tx *wire.MsgTx, hashType txscript.SigHashType,
	additionalPrevScripts map[wire.OutPoint][]byte,
	additionalKeysByAddress map[string]*btcutil.WIF,
	p2shRedeemScriptsByAddress map[string][]byte) ([]SignatureError, error)

SignTransaction uses secrets of the wallet, as well as additional secrets passed in by the caller, to create and add input signatures to a transaction.

Transaction input script validation is used to confirm that all signatures are valid. For any invalid input, a SignatureError is added to the returns. The final error return is reserved for unexpected or fatal errors, such as being unable to determine a previous output script to redeem.

The transaction pointed to by tx is modified by this function.

func (*Wallet) SortedActivePaymentAddresses

func (w *Wallet) SortedActivePaymentAddresses() ([]string, error)

SortedActivePaymentAddresses returns a slice of all active payment addresses in a wallet.

func (*Wallet) Start

func (w *Wallet) Start()

Start starts the goroutines necessary to manage a wallet.

func (*Wallet) Stop

func (w *Wallet) Stop()

Stop signals all wallet goroutines to shutdown.

func (*Wallet) SubmitRescan

func (w *Wallet) SubmitRescan(job *RescanJob) <-chan error

SubmitRescan submits a RescanJob to the RescanManager. A channel is returned with the final error of the rescan. The channel is buffered and does not need to be read to prevent a deadlock.

func (*Wallet) SynchronizeRPC

func (w *Wallet) SynchronizeRPC(chainClient chain.Interface)

SynchronizeRPC associates the wallet with the consensus RPC client, synchronizes the wallet with the latest changes to the blockchain, and continuously updates the wallet through RPC notifications.

This method is unstable and will be removed when all syncing logic is moved outside of the wallet package.

func (*Wallet) SynchronizingToNetwork

func (w *Wallet) SynchronizingToNetwork() bool

SynchronizingToNetwork returns whether the wallet is currently synchronizing with the Bitcoin network.

func (*Wallet) TotalReceivedForAccounts

func (w *Wallet) TotalReceivedForAccounts(scope waddrmgr.KeyScope,
	minConf int32) ([]AccountTotalReceivedResult, error)

TotalReceivedForAccounts iterates through a wallet's transaction history, returning the total amount of Bitcoin received for all accounts.

func (*Wallet) TotalReceivedForAddr

func (w *Wallet) TotalReceivedForAddr(addr btcutil.Address, minConf int32) (btcutil.Amount, error)

TotalReceivedForAddr iterates through a wallet's transaction history, returning the total amount of bitcoins received for a single wallet address.

func (*Wallet) Unlock

func (w *Wallet) Unlock(passphrase []byte, lock <-chan time.Time) error

Unlock unlocks the wallet's address manager and relocks it after timeout has expired. If the wallet is already unlocked and the new passphrase is correct, the current timeout is replaced with the new one. The wallet will be locked if the passphrase is incorrect or any other error occurs during the unlock.

func (*Wallet) UnlockOutpoint

func (w *Wallet) UnlockOutpoint(op wire.OutPoint)

UnlockOutpoint marks an outpoint as unlocked, that is, it may be used as an input for newly created transactions.

func (*Wallet) UnspentOutputs

func (w *Wallet) UnspentOutputs(policy OutputSelectionPolicy) ([]*TransactionOutput, error)

UnspentOutputs fetches all unspent outputs from the wallet that match rules described in the passed policy.

func (*Wallet) WaitForShutdown

func (w *Wallet) WaitForShutdown()

WaitForShutdown blocks until all wallet goroutines have finished executing.

Directories

Path Synopsis
Package txauthor provides transaction creation code for wallets.
Package txauthor provides transaction creation code for wallets.

Jump to

Keyboard shortcuts

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