wallet

Wallet subsystem.

Namespaces

NameDescription
DBKeys Record type prefixes used as keys in the wallet database.
WalletTool Command-line wallet tool commands.
feebumper Helpers for replacing a wallet transaction with a higher-fee version.
wallet_crypto_tests Test-only helpers for exercising the wallet crypto internals.

Types

NameDescription
Balance Breakdown of a wallet's balance by category.
BerkeleyROBatch RAII class that provides access to a BerkeleyRODatabase
BerkeleyROCursor Cursor that iterates over the records of a BerkeleyRODatabase.
BerkeleyRODatabase A class representing a BerkeleyDB file from which we can only read records. This is used only for migration of legacy to descriptor wallets
BytePrefix Compares equal to any byte span that begins with the same prefix.
CAddressBookData Address book data.
CCoinControl Coin Control Features.
CCrypter Encryption/decryption context with key information
CHDChain Simple HD chain data model.
CKeyMetadata Metadata about a wallet key, such as its creation time and HD derivation info.
CMasterKey Master key for wallet encryption
CMerkleTx Legacy class used for deserializing vtxPrev for backwards compatibility. vtxPrev was removed in commit 93a18a3650292afbb441a47d1fa1b94aeb0164e3, but old wallet.dat files may still contain vtxPrev vectors of CMerkleTxs. These need to get deserialized for field alignment when deserializing a CWalletTx, but the deserialized values are discarded.*
COutput A UTXO under consideration for use in funding a new transaction.
COutputEntry A single received or sent output belonging to the wallet.
CRecipient A transaction output target: a destination, an amount, and fee handling.
CWallet A CWallet maintains a set of transactions and balances, and provides the ability to create new transactions.
CWalletTx A transaction with a bunch of additional info that only the owner cares about. It includes any unrecorded transactions needed to link it back to the block chain.
CachableAmount Cachable amount subdivided into avoid reuse and all balances
CoinEligibilityFilter Parameters for filtering which OutputGroups we may use in coin selection. We start by being very selective and requiring multiple confirmations and then get more permissive if we cannot fund the transaction.
CoinFilterParams Parameters that filter which coins are considered available for spending.
CoinSelectionParams Parameters for one iteration of Coin Selection.
CoinsResult COutputs available for spending, stored by OutputType. This struct is really just a wrapper around OutputType vectors with a convenient method for concatenating and returning all COutputs as one vector.
CreatedTransactionResult Outcome of building a new transaction, bundling the transaction with its fee details.
DatabaseBatch RAII class that provides access to a WalletDatabase
DatabaseCursor Iterates over records stored in a wallet database.
DatabaseOptions Options controlling how a wallet database is opened or created.
DbTxnListener Callbacks invoked when a wallet database transaction commits or aborts.
DescriptorScriptPubKeyMan A ScriptPubKeyMan backed by a single output descriptor.
Groups A pair of output group collections split by whether they hold only positive-value UTXOs.
InMemoryWalletDatabase An in-memory SQLiteDatabase. Used as a temporary build artifact where no on-disk persistence is needed.
LegacyDataSPKM Manages the minimum data needed to load and migrate a legacy wallet.
LegacySigningProvider SigningProvider wrapper for LegacyDataSPKM that does not provide private keys.
MigrationData struct containing information needed for migrating legacy wallets to descriptor wallets
MigrationResult Result of migrating a legacy wallet to descriptor wallets.
MinimumFeeRateResult Result of resolving the minimum fee rate to use for a transaction.
OutputGroup A group of UTXOs paid to the same output script.
OutputGroupTypeMap Stores several 'Groups' whose were mapped by output type.
OutputPtrComparator Comparator ordering shared pointers to COutput by the pointed-to output.
PreselectedInput Holds the user-supplied details for a single manually selected transaction input.
ReserveDestination A wrapper to reserve an address from a wallet
SQLiteBatch RAII class that provides access to a WalletDatabase
SQLiteCursor RAII class that provides a database cursor
SQLiteDatabase An instance of this class represents one SQLite3 database.
SQliteExecHandler Class responsible for executing SQL statements in SQLite databases. Methods are virtual so they can be overridden by unit tests testing unusual database conditions.
ScriptPubKeyMan A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet. It contains the scripts and keys related to the scriptPubKeys it manages. A ScriptPubKeyMan will be able to give out scriptPubKeys to be used, as well as marking when a scriptPubKey has been used. It also handles when and how to store a scriptPubKey and its related scripts and keys, including encryption.
SelectionFilter Pairs a coin eligibility filter with whether mixing output types is allowed.
SelectionResult The set of inputs chosen by a coin selection algorithm, along with its metrics.
TxSize Holds the virtual size and weight of a transaction.
TxStateBlockConflicted State of rejected transaction that conflicts with a confirmed block.
TxStateConfirmed State of transaction confirmed in a block.
TxStateInMempool State of transaction added to mempool.
TxStateInactive State of transaction not confirmed or conflicting with a known block and not in the mempool. May conflict with the mempool, or with an unknown block, or be abandoned, never broadcast, or rejected from the mempool for another reason.
TxStateUnrecognized State of transaction loaded in an unrecognized state with unexpected hash or index values. Treated as inactive (with serialized hash and index values preserved) by default, but may enter another state if transaction is added to the mempool, or confirmed, or abandoned, or found conflicting.
WalletBatch Access to the wallet database. Opens the database and provides read and write access to it. Each read and write is its own transaction. Multiple operation transactions can be started using TxnBegin() and committed using TxnCommit() Otherwise the transaction will be committed when the object goes out of scope. Optionally (on by default) it will flush to disk on close. Every 1000 writes will automatically trigger a flush to disk.
WalletContext WalletContext struct containing references to state shared between CWallet instances, like the reference to the chain interface, and the list of opened wallets.
WalletDatabase An instance of this class represents one database.
WalletDescInfo Exportable form of a WalletDescriptor with the descriptor as a string and without its ID or cache.
WalletDescriptor Descriptor with some wallet metadata
WalletDestination A destination together with whether it belongs to the internal (change) chain.
WalletError Wallet-layer error with both programmatic and user-facing information.
WalletRescanReserver RAII object to check and reserve a wallet rescan
WalletStorage Wallet storage things that ScriptPubKeyMans need in order to be able to store things to the wallet database. It provides access to things that are part of the entire wallet and not specific to a ScriptPubKeyMan such as wallet flags, wallet version, encryption keys, encryption status, and the database itself. This allows a ScriptPubKeyMan to have callbacks into CWallet without causing a circular dependency. WalletStorage should be the same for all ScriptPubKeyMans of a wallet.
WalletTXO A single wallet transaction output, pairing a wallet transaction with one of its outputs.
WalletTxOrderComparator Orders wallet transactions by their position in the ordered transaction list.

Type Aliases

NameDescription
BerkeleyROData Ordered map of raw key/value records read from a BerkeleyDB file.
CKeyingMaterial Secure byte buffer used to hold sensitive key material in memory.
CryptedKeyMap Map from key id to its public key and encrypted private key material.
FilteredOutputGroups Output groups keyed by the eligibility filter that selected them.
KeyMap Map from key id to its private key.
LoadWalletFn Callback invoked when a wallet is loaded, receiving the wallet interface.
OutputSet A set of COutput pointers ordered by the pointed-to output.
SyncTxState Subset of states transaction sync logic is implemented to handle.
TxState All possible CWalletTx states

Enums

NameDescription
AddressPurpose Address purpose field that has been been stored with wallet sending and receiving addresses since BIP70 payment protocol support was added in https://github.com/bitcoin/bitcoin/pull/2539. This field is not currently used for any logic inside the wallet, but it is still shown in RPC and GUI interfaces and saved for new addresses. It is basically redundant with an address's IsMine() result.
DBErrors Error statuses for the wallet database. Values are in order of severity. When multiple errors occur, the most severe (highest value) will be returned.
DatabaseFormat On-disk format of a wallet database.
DatabaseStatus Result of opening or creating a wallet database.
SelectionAlgorithm Identifies which coin selection algorithm produced a result.
WalletErrorCode Machine-readable wallet error codes.
WalletFlags Feature and state flags stored on a wallet.

Functions

NameDescription
AddWallet Register a loaded wallet with the wallet context.
AddWalletSetting Add wallet name to persistent configuration so it will be loaded on startup.
AllInputsMine Returns whether all of the inputs belong to the wallet
AppendLastProcessedBlock Appends the wallet's last processed block to an RPC result object.
AttemptSelection Attempt to find a valid input set that preserves privacy by not mixing OutputTypes. ChooseSelectionResult() will be called on each OutputType individually and the best the solution (according to the waste metric) will be chosen. If a valid input cannot be found from any single OutputType, fallback to running ChooseSelectionResult() over all available coins.
AutomaticCoinSelection Select a set of coins such that nTargetValue is met; never select unconfirmed coins if they are not ours
AvailableCoins Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
BDBDataFile Returns the path to the Berkeley DB data file for a wallet path.
CachedTxGetAmounts Splits a wallet transaction into received and sent entries plus its fee.
CachedTxGetChange Returns the cached change amount of a wallet transaction.
CachedTxGetCredit Returns the cached total credit of a wallet transaction.
CachedTxGetDebit Returns the cached total debit of a wallet transaction.
CachedTxIsFromMe Returns whether a wallet transaction debits from the wallet.
CachedTxIsTrusted CachedTxIsTrusted overloads
CalculateMaximumSignedInputSize CalculateMaximumSignedInputSize overloads
CalculateMaximumSignedTxSize CalculateMaximumSignedTxSize overloads
ChooseSelectionResult Attempt to find a valid input set that meets the provided eligibility filter and target. Multiple coin selection algorithms will be run and the input set that produces the least waste (according to the waste metric) will be chosen.
CoinGrinder Select coins using the CoinGrinder deterministic search algorithm.
CreateFromDump Creates a new wallet database from a previously dumped file.
CreateTransaction Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also create the change output, when needed
CreateWallet Create a new wallet and load it into the context.
DecryptKey Decrypts an encrypted private key and validates it against its public key.
DecryptSecret Decrypts a secret with the master key using the given IV.
DiscourageFeeSniping Set a height-based locktime for new transactions (uses the height of the current chain tip unless we are not synced with the current chain
DumpWallet Dumps the records of a wallet database to a human-readable file.
EncryptSecret Encrypts a secret with the master key using the given IV.
EnsureUniqueWalletName Ensures that a wallet name is specified across the endpoint and wallet_name. Throws RPC_INVALID_PARAMETER if none or different wallet names are specified.
EnsureWalletContext Retrieves the WalletContext stored in an RPC context, throwing if absent.
EnsureWalletIsUnlocked Throws an RPC error if the wallet is locked.
ExportDescriptors Export the descriptors from a wallet so that they can be imported elsewhere
ExportWatchOnlyWallet Make a new watchonly wallet file containing the public descriptors from this wallet The exported watchonly wallet file will be named and placed at the path specified in 'destination'
FetchSelectedInputs Fetch and validate coin control selected inputs. Coins could be internal (from the wallet) or external.
FindNonChangeParentOutput Find non-change parent output.
FundTransaction Insert additional inputs into the transaction by calling CreateTransaction();
GenerateChangeTarget Choose a random change target for each transaction to make it harder to fingerprint the Core wallet based on the change output values of transactions it creates. Change target covers at least change fees and adds a random value on top of it. The random value is between 50ksat and min(2 * payment_value, 1milsat) When payment_value <= 25ksat, the value is just 50ksat.
GenerateWalletDescriptor Builds a new wallet descriptor for the given key and output type.
GetAddressBalances Returns the confirmed balance held at each of the wallet's addresses.
GetAddressGroupings Groups addresses that are believed to share a common owner.
GetAlgorithmName Return the human-readable name of a selection algorithm.
GetAvoidReuseFlag Resolves the effective avoid-reuse flag from a request parameter.
GetBalance Computes the wallet's balance broken down by category.
GetDefaultWallet Return the default wallet and report how many wallets are loaded.
GetDiscardRate Return the maximum feerate for discarding change.
GetMinimumFee Return the minimum fee for this size given a fee rate result.
GetMinimumFeeRate Estimate the minimum fee rate considering user set parameters and the required fee
GetRequiredFee Return the minimum required absolute fee for this size based on the required fee rate
GetRequiredFeeRate Return the minimum required feerate taking into account the minimum relay feerate and user set minimum transaction feerate
GetWallet Look up a loaded wallet by name.
GetWalletDir Get the path of the wallet directory.
GetWalletForJSONRPCRequest Figures out what wallet, if any, to use for a JSONRPCRequest.
GetWalletNameFromJSONRPCRequest Extracts the wallet name encoded in a JSON-RPC request endpoint, if any.
GetWalletPath Determine the path that the wallet is stored in
GetWalletRPCCommands Returns the RPC commands provided by the wallet component.
GetWallets Return all wallets currently loaded in the context.
GroupOutputs Group coins by the provided filters.
HandleLoadWallet Register a callback invoked whenever a wallet is loaded.
HandleWalletError Translates a wallet loading result into the appropriate RPC error.
HasLegacyRecords HasLegacyRecords overloads
InputIsMine Returns whether the output spent by an input belongs to the wallet.
IsBDBFile Returns whether the file at the path is a Berkeley DB file.
IsSQLiteFile Returns whether the file at the path is a SQLite file.
KnapsackSolver Select coins using the original Knapsack approximation, used as a fallback.
LabelFromValue Validates and extracts an address label from an RPC value.
ListCoins Return list of available coins and locked coins grouped by non-change output address.
ListDatabases Recursively list database paths in directory.
LoadCryptedKey Loads an encrypted key from a database record into the wallet.
LoadEncryptionKey Loads a master encryption key from a database record into the wallet.
LoadHDChain Loads HD chain data from a database record into the wallet.
LoadKey Loads an unencrypted key from a database record into the wallet.
LoadWallet Load an existing wallet from disk into the context.
LoadWallets Load wallet databases.
LogDBInfo Logs information about the database, including available engines, features, and other capabilities.
MakeBerkeleyRODatabase Return object giving access to Berkeley Read Only database at specified path.
MakeDatabase Creates or opens a wallet database at the given path.
MakeInMemoryWalletDatabase Create a new in-memory wallet database.
MakeSQLiteDatabase Open or create a SQLite wallet database at the given path.
MakeWalletDatabase Open the database backend for a wallet.
MaybeResendWalletTxs Called periodically by the schedule thread. Prompts individual wallets to resend their transactions. Actual rebroadcast schedule is managed by the wallets themselves.
MigrateLegacyToDescriptor MigrateLegacyToDescriptor overloads
NotifyWalletLoaded Fire the load-wallet callbacks for a newly loaded wallet.
OutputGetChange Returns the change amount an output contributes.
OutputGetCredit Returns the credit an output contributes if it belongs to the wallet.
OutputIsChange Returns whether an output is a change output of the wallet.
PurposeFromString Parse an address purpose from its serialized string form.
PurposeToString Convert an address purpose to its serialized string form.
PushParentDescriptors Fetch parent descriptors of this scriptPubKey.
ReadDatabaseArgs Fills database options from command-line arguments.
RemoveWallet Remove a wallet from the wallet context and optionally update its load-on-startup setting.
RemoveWalletSetting Remove wallet name from persistent configuration so it will not be loaded on startup.
RestoreWallet Restore a wallet from a backup file.
RunWithinTxn Executes the provided function 'func' within a database transaction context.
SQLiteDataFile Returns the path to the SQLite data file for a wallet path.
SQLiteDatabaseVersion Return the version of the SQLite library in use.
ScriptIsChange Returns whether a script is a change output of the wallet.
SelectCoins Select all coins from coin_control, and if coin_control 'm_allow_other_inputs=true', call 'AutomaticCoinSelection' to select a set of coins such that nTargetValue - pre_set_inputs.total_amount is met.
SelectCoinsBnB Select coins using the Branch and Bound algorithm to find a changeless solution.
SelectCoinsSRD Select coins by Single Random Draw (SRD). SRD selects eligible OutputGroups from a shuffled ordering until the effective value of the input set suffices to create the recipient outputs and a change output with an amount of at least CHANGE_LOWER. While the maximum selection weight is exceeded during selection, the OutputGroup with the lowest effective value is dropped from the selection before additional OutputGroups are selected. Due to this greedy approach, SRD can fail to discover possible solutions in pathological cases.
StartWallets Complete startup of wallets.
TxGetChange Returns the total change amount of a transaction.
TxGetCredit Returns the total credit of a transaction's outputs owned by the wallet.
TxStateString Return TxState or SyncTxState as a string for logging or debugging.
UnloadWallets Stop and unload all wallets held by the context.
VerifyWallets Responsible for reading and validating the -wallet arguments and verifying the wallet database.
WaitForDeleteWallet Explicitly delete the wallet. Blocks the current thread until the wallet is destructed.
operator< Less-than operators

Variables

NameDescription
CHANGE_LOWER lower bound for randomly-chosen target change amount
CHANGE_UPPER upper bound for randomly-chosen target change amount
DEFAULT_ADDRESS_TYPE Default for -addresstype
DEFAULT_AVOIDPARTIALSPENDS Default for -avoidpartialspends
DEFAULT_CONSOLIDATE_FEERATE -consolidatefeerate default
DEFAULT_DISABLE_WALLET -disablewallet default
DEFAULT_DISCARD_FEE -discardfee default
DEFAULT_FALLBACK_FEE -fallbackfee default
DEFAULT_KEYPOOL_SIZE Default for -keypool
DEFAULT_MAX_AVOIDPARTIALSPEND_FEE maximum fee increase allowed to do partial spend avoidance, even for nodes with this feature disabled by default
DEFAULT_MAX_DEPTH Default maximum chain depth for a coin to be considered available.
DEFAULT_MIN_DEPTH Default minimum chain depth for a coin to be considered available.
DEFAULT_SPEND_ZEROCONF_CHANGE Default for -spendzeroconfchange
DEFAULT_TRANSACTION_MAXFEE -maxtxfee default
DEFAULT_TRANSACTION_MINFEE -mintxfee default
DEFAULT_TX_CONFIRM_TARGET -txconfirmtarget default
DEFAULT_WALLETBROADCAST -walletbroadcast default
DEFAULT_WALLETCROSSCHAIN -walletcrosschain default
DEFAULT_WALLET_RBF -walletrbf default
DEFAULT_WALLET_REJECT_LONG_CHAINS Default for -walletrejectlongchains
DEFAULT_WALLET_TX_VERSION Default transaction version used when building wallet transactions.
DUMMY_NESTED_P2WPKH_INPUT_SIZE Pre-calculated constants for input size estimation in virtual size
HELP_REQUIRING_PASSPHRASE Help text appended to RPC methods that require the wallet passphrase.
HIGH_APS_FEE discourage APS fee higher than this amount
HIGH_MAX_TX_FEE -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
HIGH_TX_FEE_PER_KB Discourage users to set fees higher than this amount (in satoshis) per kB
KNOWN_WALLET_FLAGS Bitmask of all wallet flags recognized by this version.
LEGACY_OUTPUT_TYPES Output types associated with LegacyDataSPKM.
MUTABLE_WALLET_FLAGS Bitmask of wallet flags that may be changed after wallet creation.
RESULT_LAST_PROCESSED_BLOCK RPC result describing the block a piece of wallet information was generated on.
STRING_TO_WALLET_FLAG Maps each wallet flag string name back to its flag value.
UNKNOWN_TIME Constant representing an unknown spkm creation time
WALLET_CRYPTO_IV_SIZE Size in bytes of the AES initialization vector.
WALLET_CRYPTO_KEY_SIZE Size in bytes of the AES-256 encryption key derived for the wallet.
WALLET_CRYPTO_SALT_SIZE Size in bytes of the salt mixed into the passphrase during key derivation.
WALLET_FLAG_TO_STRING Maps each wallet flag to its serialized string name.
WALLET_INCREMENTAL_RELAY_FEE minimum recommended increment for replacement txs