CWallet

The CWallet object is the fundamental wallet representation inside Bitcoin Core. CWallet stores transactions and balances and has the ability to create new transactions. CWallet also contains references to the chain interface for the wallet along with storing wallet metadata such as nWalletVersion, wallet flags, wallet name and address book.

CWallet creation

The CWallet constructor takes a pointer to the chain interface for the wallet, a wallet name and a pointer to the underlying WalletDatabase:

The constructor is not called directly, but instead from the public function CWallet::Create(), which is itself called from CreateWallet(), LoadWallets() (or TestLoadWallet()). In addition to the arguments required by the constructor, CWallet::Create() also has a wallet_flags argument. Wallet flags are represented as a single unit64_t bit field which encode certain wallet properties:

src/wallet/walletutil.h
enum WalletFlags : uint64_t {
    WALLET_FLAG_AVOID_REUSE = (1ULL << 0),
    WALLET_FLAG_KEY_ORIGIN_METADATA = (1ULL << 1),
    WALLET_FLAG_DISABLE_PRIVATE_KEYS = (1ULL << 32),
    WALLET_FLAG_BLANK_WALLET = (1ULL << 33),
    WALLET_FLAG_DESCRIPTORS = (1ULL << 34),
    WALLET_FLAG_EXTERNAL_SIGNER = (1ULL << 35),
};

See src/wallet/walletutil.h for additional information on the meanings of the wallet flags.

CWallet::Create() will first attempt to create the CWallet object and load it, returning if any errors are encountered.

If CWallet::Create is creating a new wallet — on its 'first run' — the wallet version and wallet flags will be set, before either LegacyScriptPubKeyMan or DescriptorScriptPubKeyMan's are setup, depending on whether the WALLET_FLAG_DESCRIPTORS flag was set on the wallet.

Following successful creation, various program arguments are checked and applied to the wallet. These include options such as -addresstype, -changetype, -mintxfee and -maxtxfee amongst others. It is at this stage that warnings for unusual or unsafe values of these arguments are generated to be returned to the user.

After the wallet is fully initialized and setup, its keypool will be topped up before the wallet is locked and registered with the Validation interface, which will handle callback notifications generated during the (optional) upcoming chain rescan. The rescan is smart in detecting the wallet "birthday" using metadata stored in the SPKM and won’t scan blocks produced before this date.

Finally, the walletinterface is setup for the wallet before the WalletInstance is returned to the caller.