wallet::CWallet

A CWallet maintains a set of transactions and balances, and provides the ability to create new transactions.

Synopsis

Declared in <wallet/wallet.h>

class CWallet final
    : public WalletStorage
    , public interfaces::Chain::Notifications

Base Classes

NameDescription
WalletStorageWallet 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.
interfaces::Chain::Notifications

Types

NameDescription
AddrBookFilter Filter struct for 'ListAddrBookAddresses'
ScanResult Outcome of scanning a range of blocks for wallet transactions.

Type Aliases

NameDescription
HDPubKeyMap Maps a descriptor xpub to the descriptor managers that use it.
ListAddrBookFunc Walk-through the address book entries. Stops when the provided 'ListAddrBookFunc' returns false.
MasterKeyMap Maps a master key id to its encrypted master key.
TxItems Maps a transaction's order position to its wallet transaction.
UpdateWalletTxFn Callback for updating transaction metadata in mapWallet.

Enums

NameDescription
HDKeyFilter Which descriptors GetHDPubKeys() should consider.
SpendType Describes how far along the spend of an output is.

Member Functions

NameDescription
CWallet [constructor]Construct wallet with specified name and database implementation.
~CWallet [destructor] [virtual]Destroy the wallet; asserts no unload slots remain connected.
AbandonTransaction AbandonTransaction overloads
AbortRescan Request that any in-progress rescan abort.
AddActiveScriptPubKeyMan Adds the active ScriptPubKeyMan for the specified type and internal. Writes it to the wallet file
AddToWallet Add the transaction to the wallet, wrapping it up inside a CWalletTx
AddWalletDescriptor Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type
ApplyMigrationData Adds the ScriptPubKeyMans from MigrationData to this wallet, removes the LegacyDataSPKM, and moves transaction and address book entries to watchonly_wallet or solvable_wallet as needed.
BackupWallet Copy the wallet database file to a backup path.
BlockUntilSyncedToCurrentChain Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function is entered Obviously holding cs_main/cs_wallet when going into this call may cause deadlock
CacheNewScriptPubKeys Add scriptPubKeys for this ScriptPubKeyMan into the scriptPubKey cache
CanGetAddresses Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys
CanGrindR Whether the (external) signer performs R-value signature grinding
ChangeWalletPassphrase Change the wallet's encryption passphrase.
Close Close wallet database
CommitTransaction Submit the transaction to the node's mempool and then relay to peers. Should be called after CreateTransaction unless you want to abort broadcasting the transaction.
ComputeTimeSmart Estimate a smart timestamp for a transaction from block and receive times.
ConnectScriptPubKeyManNotifiers Connect the signals from ScriptPubKeyMans to the signals in CWallet
DeactivateScriptPubKeyMan Remove specified ScriptPubKeyMan from set of active SPK managers. Writes the change to the wallet file.
DelAddressBook Remove a destination from the address book.
DelAddressBookWithDB Remove a destination from the address book within a database batch.
DisconnectChainNotifications Disconnect chain notifications and wait for all notifications to be processed
DisplayAddress Display address on an external signer.
DisplayName Return wallet name for display, like LogName() but translates "default wallet" string.
EncryptWallet Encrypt an unencrypted wallet with the given passphrase.
EraseAddressReceiveRequest Erase a stored receive request for a destination.
FillPSBT Fills out a PSBT with information from the wallet. Fills in UTXOs if we have them. Tries to sign if options.sign=true. Sets complete if the PSBT is now complete (i.e. has all required signatures or signature-parts, and is ready to finalize.)
FindAddressBookEntry Look up an address book entry for a destination.
ForEachAddrBookEntry Invoke a callback for each address book entry until it returns false.
GetActiveScriptPubKeyMans Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers
GetAddressReceiveRequests Return the identifiers of all stored receive requests.
GetAllScriptPubKeyMans Returns all unique ScriptPubKeyMans
GetBirthTime Returns the time of the first created key or, in case of an import, it could be the time of the first received transaction
GetBroadcastTransactions Inquire whether this wallet broadcasts transactions.
GetConflicts Get wallet transactions that conflict with given transaction (spend same outputs)
GetDatabase [virtual]Access the wallet's database backend.
GetDebit GetDebit overloads
GetDescriptorScriptPubKeyMan Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet
GetDescriptorsForLegacy Get all of the descriptors from a legacy wallet
GetExtKey Reconstruct the extended private key for an HD xpub. Returns nullopt when no descriptor has the private key, or the wallet is locked.
GetHDPubKeys Retrieve descriptor xpubs matching the requested filter.
GetKey Find the private key for the given key id from the wallet's descriptors, if available Returns nullopt when no descriptor has the key or if the wallet is locked.
GetKeyPoolSize Count the keys currently available in the keypool.
GetLastBlockHash Get the hash of the last block processed by the wallet.
GetLastBlockHeight Get last block processed height
GetLegacyDataSPKM Get the LegacyDataSPKM used for all legacy output types and both internal and external chains.
GetName Get a name for this wallet for logging/debugging purposes.
GetNewChangeDestination Generate a new change destination of the given type.
GetNewDestination Generate a new receiving destination of the given type.
GetOrCreateLegacyDataSPKM Return the legacy data ScriptPubKeyMan, creating it if it does not exist.
GetScriptPubKeyMan GetScriptPubKeyMan overloads
GetScriptPubKeyMans Get all the ScriptPubKeyMans for a script
GetSolvingProvider GetSolvingProvider overloads
GetTXO Look up a single wallet output by outpoint.
GetTXOs Access the cache of transaction outputs owned by this wallet.
GetTxBlocksToMaturity Return the number of blocks until a coinbase transaction matures.
GetTxConflicts Find wallet transactions that conflict with the given transaction.
GetTxDepthInMainChain Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockchain 0 : in memory pool, waiting to be included in a block >=1 : this many blocks deep in the main chain
GetWalletDescriptors Get the wallet descriptors for a script.
GetWalletFlags Retrieve all of the wallet's flags
GetWalletTx Look up a wallet transaction by its txid.
HasEncryptionKeys [virtual]Report whether the wallet holds any encryption keys.
HasWalletSpend Check if a given transaction has any of its outputs spent by another transaction in the wallet
HaveChain Interface to assert chain access
HaveCryptedKeys Report whether the wallet holds any encrypted private keys.
HowSpent Determine how an output has been spent.
IncOrderPosNext Increment the next transaction order id
InitWalletFlags overwrite all flags by the given uint64_t flags must be uninitialised (or 0) only known flags may be present
IsAbortingRescan Report whether a rescan abort has been requested.
IsActiveScriptPubKeyMan Report whether a ScriptPubKeyMan is one of the wallet's active managers.
IsAddressPreviouslySpent Report whether a destination has been marked as previously spent.
IsFromMe should probably be renamed to IsRelevantToMe
IsHDEnabled Returns true if HD is enabled
IsInternalScriptPubKeyMan Returns whether the provided ScriptPubKeyMan is internal
IsLocked [virtual]Report whether the wallet's keys are currently locked (encrypted and unavailable).
IsLockedCoin Report whether an output is locked against spending.
IsMine IsMine overloads
IsScanning Report whether a rescan is running.
IsScanningWithPassphrase Report whether the running rescan holds the wallet passphrase.
IsSpent Report whether an output is spent by any known transaction.
IsSpentKey Whether this or any known scriptPubKey with the same single key has been spent.
IsTxImmatureCoinBase Report whether a transaction is an immature coinbase output.
IsWalletFlagSet [virtual]check if a certain wallet flag is set
KeypoolCountExternalKeys Count the external (receiving) keys available in the keypool.
ListAddrBookAddresses Filter and retrieve destinations stored in the addressbook
ListAddrBookLabels Retrieve all the known labels in the address book
ListLockedCoins List all currently locked outputs.
LoadActiveScriptPubKeyMan Loads an active ScriptPubKeyMan for the specified type and internal. (used by LoadWallet)
LoadAddressPreviouslySpent Marks destination as previously spent.
LoadAddressReceiveRequest Appends payment request to destination.
LoadDescriptorScriptPubKeyMan Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it
LoadLockedCoin Load a locked coin from the database into memory.
LoadToWallet Load a wallet transaction read from the database into memory.
LoadWalletFlags Loads the flags into the wallet. (used by LoadWallet)
Lock Lock the wallet, clearing the decrypted master key from memory.
LockCoin Lock an output so it is not selected for spending.
LogName [virtual]Return wallet name for use in logs, will return "default wallet" if the wallet has no name.
LogStats Write summary statistics about the wallet to the log.
MarkDestinationsDirty Marks all outputs in each one of the destinations dirty, so their cache is reset and does not return outdated information.
MarkDirty Mark cached balances dirty so they are recomputed on next access.
MarkReplaced Mark a transaction as replaced by another transaction.
MaybeUpdateBirthTime Updates wallet birth time if 'time' is below it
MigrateToSQLite Move all records from the BDB database to a new SQLite database for storage. The original BDB file will be deleted and replaced with a new SQLite file. A backup is not created. May crash if something unexpected happens in the filesystem.
PopulateWalletFromDB Load wallet records from the database into memory.
RefreshAllTXOs Cache outputs that belong to the wallet for all transactions in the wallet
RefreshTXOsFromTx Cache outputs that belong to the wallet from a single transaction
RemoveTxs RemoveTxs overloads
ReorderTransactions Reassign order positions to all wallet transactions.
RescanFromTime Rescan the chain for wallet transactions from a given start time.
ResubmitWalletTransactions Resubmit unconfirmed wallet transactions to the mempool and peers.
ScanForWalletTransactions Scan a range of blocks for transactions relevant to this wallet.
ScanningDuration Measure how long the running rescan has been in progress.
ScanningProgress Report the progress of the running rescan.
SetAddressBook Set the address book label and purpose for a destination.
SetAddressPreviouslySpent Record whether a destination has been previously spent.
SetAddressReceiveRequest Store or update a receive request for a destination.
SetBroadcastTransactions Set whether this wallet broadcasts transactions.
SetLastBlockProcessed Set last block processed height, and write to database
SetNextResend Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average.
SetSpentKeyState Record whether the key behind a transaction output has been spent.
SetWalletFlag set a single wallet flag
SetupDescriptorScriptPubKeyMan Create new DescriptorScriptPubKeyMan and add it to the wallet
SetupDescriptorScriptPubKeyMans SetupDescriptorScriptPubKeyMans overloads
SetupLegacyDataSPKM Create a LegacyDataSPKM and set it for all legacy output types and both internal and external chains.
SetupOwnDescriptorScriptPubKeyMans Create new seed and default DescriptorScriptPubKeyMans for this wallet
SetupWalletGeneration Setup new descriptors or seed for new address generation
ShouldResend Return true if all conditions for periodically resending transactions are met.
SignMessage Sign an arbitrary message with the key for a public key hash.
SignTransaction SignTransaction overloads
SubmitTxMemoryPoolAndRelay Pass this transaction to node for optional mempool insertion and relay to peers.
TopUpCallback TopUpCallback overloads
TopUpKeyPool Refill the keypool up to the target size.
TransactionCanBeAbandoned Return whether transaction can be abandoned
TransactionChangeType Choose the change output type for a transaction.
Unlock Unlock the wallet using the given passphrase.
UnlockAllCoins Unlock every locked output.
UnlockCoin Unlock a previously locked output.
UnsetBlankWalletFlag [virtual]Clears the "blank wallet" flag, recording the change in the given batch.
UnsetWalletFlag Unsets a single wallet flag
UpgradeDescriptorCache Upgrade DescriptorCaches
WalletLogPrintf Prepends the wallet name in logging output to ease debugging in multi-wallet use cases
WithEncryptionKey [virtual]Invoke a callback with the decrypted master key while holding the encryption lock.
WriteBestBlock Write the current best block to database
blockConnected Handle a block being connected to the chain tip.
blockDisconnected Handle a block being disconnected from the chain tip.
chain Interface for accessing chain state.
chainStateFlushed [virtual]
postInitProcess Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init tasks
transactionAddedToMempool [virtual]Handle a transaction being added to the node's mempool.
transactionRemovedFromMempool [virtual]Handle a transaction being removed from the node's mempool.
updatedBlockTip [virtual]Handle the chain tip being updated.

Static Member Functions

NameDescription
CreateNew Initializes, creates and returns a new CWallet; returns a null pointer in case of an error
LoadExisting Initializes, loads, and returns a CWallet from an existing wallet; returns a null pointer in case of an error
LoadWalletArgs Apply command-line and configuration arguments to a wallet.

Data Members

NameDescription
NotifyAddressBookChanged Address book entry changed.
NotifyCanGetAddressesChanged Keypool has new keys
NotifyStatusChanged Wallet status (encrypted, locked) changed. Note: Called without locks held.
NotifyTransactionChanged Wallet transaction added, removed or updated.
NotifyUnload Wallet is about to be unloaded
ShowProgress Show progress e.g. for rescan
cs_wallet Main wallet lock. This lock protects all the fields added by CWallet.
m_address_book Address book entries indexed by destination.
m_allow_fallback_fee will be false if -fallbackfee=0
m_chain_notifications_handler Registered interfaces::Chain::Notifications handler.
m_confirm_target Default confirmation target (in blocks) for fee estimation.
m_consolidate_feerate When the actual feerate is less than the consolidate feerate, we will tend to make transactions which consolidate inputs. When the actual feerate is greater than the consolidate feerate, we will tend to make transactions which have the lowest fees.
m_default_address_type Default output type for newly generated receiving addresses.
m_default_change_type Default output type for change outputs. When unset, automatically choose type based on address type setting and the types other of non-change outputs (see -changetype option documentation and implementation in CWallet::TransactionChangeType for details).
m_default_max_tx_fee Absolute maximum transaction fee (in satoshis) used by default for the wallet
m_discard_rate If the cost to spend a change output at this feerate is greater than the value of the output itself, just drop it to fees.
m_fallback_fee If fee estimation does not have enough data to provide estimates, use this fee instead. Has no effect if not using fee estimation Override with -fallbackfee
m_keypool_size Number of pre-generated keys/scripts by each spkm (part of the look-ahead process, used to detect payments)
m_locked_coins Set of Coins owned by this wallet that we won't try to spend from. A Coin may be locked if it has already been used to fund a transaction that hasn't confirmed yet. We wouldn't consider the Coin spent already, but also shouldn't try to use it again. bool to track whether this locked coin is persisted to disk.
m_max_aps_fee note: this is absolute fee, not fee rate
m_min_fee Minimum fee rate to use when creating transactions.
m_notify_tx_changed_script Notify external script when a wallet transaction comes in or is updated (handled by -walletnotify)
m_relock_mutex Used to prevent deleting the passphrase from memory when it is still in use.
m_signal_rbf Whether new transactions signal opt-in Replace-By-Fee.
m_spend_zero_conf_change Allow Coin Selection to pick unconfirmed UTXOs that were sent from our own wallet if it cannot fund the transaction otherwise.
m_unlock_mutex Used to prevent concurrent calls to walletpassphrase RPC.
mapMasterKeys Encrypted master keys held by this wallet, indexed by id.
mapWallet Map from txid to CWalletTx for all transactions this wallet is interested in, including received and sent transactions.
nMasterKeyMaxID Highest master key id assigned so far.
nOrderPosNext Order position to assign to the next transaction added to the wallet.
nRelockTime Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
wtxOrdered Wallet transactions ordered by their insertion order position.

Friends

NameDescription
wallet::WalletRescanReserverRAII object to check and reserve a wallet rescan

Non-Member Functions

NameDescription
AllInputsMineReturns whether all of the inputs belong to the wallet
AutomaticCoinSelectionSelect a set of coins such that nTargetValue is met; never select unconfirmed coins if they are not ours
AvailableCoinsPopulate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
CachedTxGetAmountsSplits a wallet transaction into received and sent entries plus its fee.
CachedTxGetChangeReturns the cached change amount of a wallet transaction.
CachedTxGetCreditReturns the cached total credit of a wallet transaction.
CachedTxGetDebitReturns the cached total debit of a wallet transaction.
CachedTxIsFromMeReturns whether a wallet transaction debits from the wallet.
CachedTxIsTrustedReturns whether a wallet transaction is trusted.
CachedTxIsTrustedReturns whether a wallet transaction is trusted, tracking visited parents.
CreateTransactionCreate a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also create the change output, when needed
CreateWalletCreate a new wallet and load it into the context.
EnsureWalletIsUnlockedThrows an RPC error if the wallet is locked.
ExportDescriptorsExport the descriptors from a wallet so that they can be imported elsewhere
ExportWatchOnlyWalletMake 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'
FetchSelectedInputsFetch and validate coin control selected inputs. Coins could be internal (from the wallet) or external.
FindNonChangeParentOutputFind non-change parent output.
FundTransactionInsert additional inputs into the transaction by calling CreateTransaction();
GetAddressBalancesReturns the confirmed balance held at each of the wallet's addresses.
GetAddressGroupingsGroups addresses that are believed to share a common owner.
GetAvoidReuseFlagResolves the effective avoid-reuse flag from a request parameter.
GetBalanceComputes the wallet's balance broken down by category.
GetDefaultWalletReturn the default wallet and report how many wallets are loaded.
GetDiscardRateReturn the maximum feerate for discarding change.
GetMinimumFeeRateEstimate the minimum fee rate considering user set parameters and the required fee
GetRequiredFeeReturn the minimum required absolute fee for this size based on the required fee rate
GetRequiredFeeRateReturn the minimum required feerate taking into account the minimum relay feerate and user set minimum transaction feerate
GetWalletLook up a loaded wallet by name.
GetWalletForJSONRPCRequestFigures out what wallet, if any, to use for a JSONRPCRequest.
GroupOutputsGroup coins by the provided filters.
HasLegacyRecordsReturns true if there are any DBKeys::LEGACY_TYPES record in the wallet db.
HasLegacyRecordsReturns true if there are any DBKeys::LEGACY_TYPES record in the wallet db
InputIsMineReturns whether the output spent by an input belongs to the wallet.
ListCoinsReturn list of available coins and locked coins grouped by non-change output address.
LoadCryptedKeyLoads an encrypted key from a database record into the wallet.
LoadEncryptionKeyLoads a master encryption key from a database record into the wallet.
LoadHDChainLoads HD chain data from a database record into the wallet.
LoadKeyLoads an unencrypted key from a database record into the wallet.
LoadWalletLoad an existing wallet from disk into the context.
OutputGetChangeReturns the change amount an output contributes.
OutputGetCreditReturns the credit an output contributes if it belongs to the wallet.
OutputIsChangeReturns whether an output is a change output of the wallet.
PushParentDescriptorsFetch parent descriptors of this scriptPubKey.
RestoreWalletRestore a wallet from a backup file.
ScriptIsChangeReturns whether a script is a change output of the wallet.
SelectCoinsSelect 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.
TxGetChangeReturns the total change amount of a transaction.
TxGetCreditReturns the total credit of a transaction's outputs owned by the wallet.
feebumper::CommitTransactionCommit the bumpfee transaction.
feebumper::CreateRateBumpTransactionCreate bumpfee transaction based on feerate estimates.
feebumper::SignTransactionSign the new transaction,
feebumper::TransactionCanBeBumpedReturn whether transaction can be bumped.