Coverage Report

Created: 2026-09-15 16:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/wallet/walletdb.h
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#ifndef BITCOIN_WALLET_WALLETDB_H
7
#define BITCOIN_WALLET_WALLETDB_H
8
9
#include <key.h>
10
#include <primitives/transaction.h>
11
#include <primitives/transaction_identifier.h>
12
#include <script/sign.h>
13
#include <wallet/db.h>
14
#include <wallet/walletutil.h>
15
16
#include <cstdint>
17
#include <string>
18
#include <unordered_set>
19
#include <vector>
20
21
class CScript;
22
class uint160;
23
class uint256;
24
struct CBlockLocator;
25
26
namespace wallet {
27
class CMasterKey;
28
class CWallet;
29
class CWalletTx;
30
struct WalletContext;
31
32
// Logs information about the database, including available engines, features, and other capabilities
33
void LogDBInfo();
34
35
/**
36
 * Overview of wallet database classes:
37
 *
38
 * - WalletBatch is an abstract modifier object for the wallet database, and encapsulates a database
39
 *   batch update as well as methods to act on the database. It should be agnostic to the database implementation.
40
 */
41
42
/** Error statuses for the wallet database.
43
 * Values are in order of severity. When multiple errors occur, the most severe (highest value) will be returned.
44
 */
45
enum class DBErrors : int
46
{
47
    LOAD_OK = 0,
48
    NEED_RESCAN = 1,
49
    EXTERNAL_SIGNER_SUPPORT_REQUIRED = 3,
50
    NONCRITICAL_ERROR = 4,
51
    TOO_NEW = 5,
52
    UNKNOWN_DESCRIPTOR = 6,
53
    LOAD_FAIL = 7,
54
    UNEXPECTED_LEGACY_ENTRY = 8,
55
    LEGACY_WALLET = 9,
56
    CORRUPT = 10,
57
};
58
59
namespace DBKeys {
60
extern const std::string ACENTRY;
61
extern const std::string ACTIVEEXTERNALSPK;
62
extern const std::string ACTIVEINTERNALSPK;
63
extern const std::string BESTBLOCK;
64
extern const std::string BESTBLOCK_NOMERKLE;
65
extern const std::string CRYPTED_KEY;
66
extern const std::string CSCRIPT;
67
extern const std::string DEFAULTKEY;
68
extern const std::string DESTDATA;
69
extern const std::string FLAGS;
70
extern const std::string HDCHAIN;
71
extern const std::string KEY;
72
extern const std::string KEYMETA;
73
extern const std::string LOCKED_UTXO;
74
extern const std::string MASTER_KEY;
75
extern const std::string MINVERSION;
76
extern const std::string NAME;
77
extern const std::string OLD_KEY;
78
extern const std::string ORDERPOSNEXT;
79
extern const std::string POOL;
80
extern const std::string PURPOSE;
81
extern const std::string SETTINGS;
82
extern const std::string TX;
83
extern const std::string WTX_VARIANT;
84
extern const std::string VERSION;
85
extern const std::string WALLETDESCRIPTOR;
86
extern const std::string WALLETDESCRIPTORCKEY;
87
extern const std::string WALLETDESCRIPTORKEY;
88
extern const std::string WATCHMETA;
89
extern const std::string WATCHS;
90
91
// Keys in this set pertain only to legacy wallets and are removed during migration to descriptors.
92
extern const std::unordered_set<std::string> LEGACY_TYPES;
93
} // namespace DBKeys
94
95
/* simple HD chain data model */
96
class CHDChain
97
{
98
public:
99
    uint32_t nExternalChainCounter;
100
    uint32_t nInternalChainCounter;
101
    CKeyID seed_id; //!< seed hash160
102
103
    static constexpr int VERSION_HD_BASE{1};
104
    static constexpr int VERSION_HD_CHAIN_SPLIT{2};
105
    static constexpr int CURRENT_VERSION{VERSION_HD_CHAIN_SPLIT};
106
    int nVersion;
107
108
0
    CHDChain() { SetNull(); }
109
110
    SERIALIZE_METHODS(CHDChain, obj)
111
0
    {
112
0
        READWRITE(obj.nVersion, obj.nExternalChainCounter, obj.seed_id);
113
0
        if (obj.nVersion >= VERSION_HD_CHAIN_SPLIT) {
  Branch (113:13): [True: 0, False: 0]
114
0
            READWRITE(obj.nInternalChainCounter);
115
0
        }
116
0
    }
117
118
    void SetNull()
119
0
    {
120
0
        nVersion = CHDChain::CURRENT_VERSION;
121
0
        nExternalChainCounter = 0;
122
0
        nInternalChainCounter = 0;
123
0
        seed_id.SetNull();
124
0
    }
125
126
    bool operator==(const CHDChain& chain) const
127
0
    {
128
0
        return seed_id == chain.seed_id;
129
0
    }
130
    bool operator<(const CHDChain& chain) const
131
0
    {
132
0
        return seed_id < chain.seed_id;
133
0
    }
134
};
135
136
class CKeyMetadata
137
{
138
public:
139
    static constexpr int VERSION_BASIC{1};
140
    static constexpr int VERSION_WITH_HDDATA{10};
141
    static constexpr int VERSION_WITH_KEY_ORIGIN{12};
142
    static constexpr int CURRENT_VERSION{VERSION_WITH_KEY_ORIGIN};
143
    int nVersion;
144
    int64_t nCreateTime; // 0 means unknown
145
    std::string hdKeypath; //optional HD/bip32 keypath. Still used to determine whether a key is a seed. Also kept for backwards compatibility
146
    CKeyID hd_seed_id; //id of the HD seed used to derive this key
147
    KeyOriginInfo key_origin; // Key origin info with path and fingerprint
148
    bool has_key_origin = false; //!< Whether the key_origin is useful
149
150
    CKeyMetadata()
151
0
    {
152
0
        SetNull();
153
0
    }
154
    explicit CKeyMetadata(int64_t nCreateTime_)
155
0
    {
156
0
        SetNull();
157
0
        nCreateTime = nCreateTime_;
158
0
    }
159
160
    SERIALIZE_METHODS(CKeyMetadata, obj)
161
0
    {
162
0
        READWRITE(obj.nVersion, obj.nCreateTime);
163
0
        if (obj.nVersion >= VERSION_WITH_HDDATA) {
  Branch (163:13): [True: 0, False: 0]
  Branch (163:13): [True: 0, False: 0]
164
0
            READWRITE(obj.hdKeypath, obj.hd_seed_id);
165
0
        }
166
0
        if (obj.nVersion >= VERSION_WITH_KEY_ORIGIN)
  Branch (166:13): [True: 0, False: 0]
  Branch (166:13): [True: 0, False: 0]
167
0
        {
168
0
            READWRITE(obj.key_origin);
169
0
            READWRITE(obj.has_key_origin);
170
0
        }
171
0
    }
Unexecuted instantiation: _ZN6wallet12CKeyMetadata16SerializationOpsI10DataStreamS0_17ActionUnserializeEEvRT0_RT_T1_
Unexecuted instantiation: _ZN6wallet12CKeyMetadata16SerializationOpsI10DataStreamKS0_15ActionSerializeEEvRT0_RT_T1_
172
173
    void SetNull()
174
0
    {
175
0
        nVersion = CKeyMetadata::CURRENT_VERSION;
176
0
        nCreateTime = 0;
177
0
        hdKeypath.clear();
178
0
        hd_seed_id.SetNull();
179
0
        key_origin.clear();
180
0
        has_key_origin = false;
181
0
    }
182
};
183
184
struct DbTxnListener
185
{
186
    std::function<void()> on_commit, on_abort;
187
};
188
189
/** Access to the wallet database.
190
 * Opens the database and provides read and write access to it. Each read and write is its own transaction.
191
 * Multiple operation transactions can be started using TxnBegin() and committed using TxnCommit()
192
 * Otherwise the transaction will be committed when the object goes out of scope.
193
 * Optionally (on by default) it will flush to disk on close.
194
 * Every 1000 writes will automatically trigger a flush to disk.
195
 */
196
class WalletBatch
197
{
198
private:
199
    template <typename K, typename T>
200
    bool WriteIC(const K& key, const T& value, bool fOverwrite = true)
201
0
    {
202
0
        if (!m_batch->Write(key, value, fOverwrite)) {
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
  Branch (202:13): [True: 0, False: 0]
203
0
            return false;
204
0
        }
205
0
        return true;
206
0
    }
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_ES8_EEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE22transaction_identifierILb0EEENS_9CWalletTxEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_I22transaction_identifierILb0EES9_ILb1EEEE13ParamsWrapperI20TransactionSerParamsKSt10shared_ptrIK12CTransactionEEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7CPubKeyENS_12CKeyMetadataEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7CPubKeyES2_ISt6vectorIh16secure_allocatorIhEE7uint256EEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7CPubKeyES2_ISt6vectorIhSaIhEE7uint256EEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEjENS_10CMasterKeyEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7CScriptENS_12CKeyMetadataEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7CScriptEhEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE13CBlockLocatorEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEElEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEhE7uint256EEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_I7uint2567CPubKeyEES2_ISt6vectorIh16secure_allocatorIhEES9_EEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_I7uint2567CPubKeyEESt6vectorIhSaIhEEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7uint256ENS_16WalletDescriptorEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairIS2_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7uint256ES2_IjjEESt6vectorIhSaIhEEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairIS2_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7uint256EjESt6vectorIhSaIhEEEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_I22transaction_identifierILb0EEjEEhEEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_IS8_S8_EES8_EEbRKT_RKT0_b
Unexecuted instantiation: _ZN6wallet11WalletBatch7WriteICINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEmEEbRKT_RKT0_b
207
208
    template <typename K>
209
    bool EraseIC(const K& key)
210
0
    {
211
0
        if (!m_batch->Erase(key)) {
  Branch (211:13): [True: 0, False: 0]
  Branch (211:13): [True: 0, False: 0]
  Branch (211:13): [True: 0, False: 0]
  Branch (211:13): [True: 0, False: 0]
  Branch (211:13): [True: 0, False: 0]
  Branch (211:13): [True: 0, False: 0]
  Branch (211:13): [True: 0, False: 0]
  Branch (211:13): [True: 0, False: 0]
212
0
            return false;
213
0
        }
214
0
        return true;
215
0
    }
Unexecuted instantiation: _ZN6wallet11WalletBatch7EraseICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_EEEbRKT_
Unexecuted instantiation: _ZN6wallet11WalletBatch7EraseICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7uint256EEEbRKT_
Unexecuted instantiation: _ZN6wallet11WalletBatch7EraseICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE7CPubKeyEEEbRKT_
Unexecuted instantiation: _ZN6wallet11WalletBatch7EraseICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEjEEEbRKT_
Unexecuted instantiation: _ZN6wallet11WalletBatch7EraseICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEhEEEbRKT_
Unexecuted instantiation: _ZN6wallet11WalletBatch7EraseICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_I7uint2567CPubKeyEEEEbRKT_
Unexecuted instantiation: _ZN6wallet11WalletBatch7EraseICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_I22transaction_identifierILb0EEjEEEEbRKT_
Unexecuted instantiation: _ZN6wallet11WalletBatch7EraseICISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_IS8_S8_EEEEbRKT_
216
217
public:
218
    explicit WalletBatch(WalletDatabase &database) :
219
0
        m_batch(database.MakeBatch())
220
0
    {
221
0
    }
222
    WalletBatch(const WalletBatch&) = delete;
223
    WalletBatch& operator=(const WalletBatch&) = delete;
224
225
    bool WriteName(const std::string& strAddress, const std::string& strName);
226
    bool EraseName(const std::string& strAddress);
227
228
    bool WritePurpose(const std::string& strAddress, const std::string& purpose);
229
    bool ErasePurpose(const std::string& strAddress);
230
231
    // Write a CWalletTx and all variant witness txs (single tx record and multiple wtxvariant records)
232
    bool WriteFullTx(const CWalletTx& wtx);
233
    bool EraseTx(Txid hash);
234
    // Write a single witness variant of CWalletTx (single wtxvariant record)
235
    bool WriteWtxVariant(const Txid& txid, const CTransactionRef& tx);
236
    // Write only the canonical witness tx and all of the tx metadata (single tx record)
237
    bool WriteTxMetadata(const CWalletTx& wtx);
238
239
    bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, bool overwrite);
240
    bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata &keyMeta);
241
    bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata &keyMeta);
242
    bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey);
243
    bool EraseMasterKey(unsigned int id);
244
245
    bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta);
246
247
    bool WriteBestBlock(const CBlockLocator& locator);
248
    bool ReadBestBlock(CBlockLocator& locator);
249
250
    // Returns true if wallet stores encryption keys
251
    bool IsEncrypted();
252
253
    bool WriteOrderPosNext(int64_t nOrderPosNext);
254
255
    bool WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey);
256
    bool WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret);
257
    bool WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor);
258
    bool WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index);
259
    bool WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
260
    bool WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index);
261
    bool WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache);
262
263
    bool WriteLockedUTXO(const COutPoint& output);
264
    bool EraseLockedUTXO(const COutPoint& output);
265
266
    bool WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent);
267
    bool WriteAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& receive_request);
268
    bool EraseAddressReceiveRequest(const CTxDestination& dest, const std::string& id);
269
    bool EraseAddressData(const CTxDestination& dest);
270
271
    bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal);
272
    bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal);
273
274
    DBErrors LoadWallet(CWallet* pwallet);
275
276
    /**
277
     * Write the given `client_version` to m_batch, indicating the last version
278
     * of client software to load this wallet.
279
     *
280
     * @param[in]   client_version  `CLIENT_VERSION` outside of test code.
281
     * @return      A bool indicating whether or not the write succeeded.
282
     */
283
0
    bool WriteVersion(int client_version) { return m_batch->Write(DBKeys::VERSION, client_version); }
284
285
    //! Delete records of the given types
286
    bool EraseRecords(const std::unordered_set<std::string>& types);
287
288
    bool WriteWalletFlags(uint64_t flags);
289
    //! Begin a new transaction
290
    bool TxnBegin();
291
    //! Commit current transaction
292
    bool TxnCommit();
293
    //! Abort current transaction
294
    bool TxnAbort();
295
0
    bool HasActiveTxn() { return m_batch->HasActiveTxn(); }
296
297
    //! Registers db txn callback functions
298
    void RegisterTxnListener(const DbTxnListener& l);
299
300
private:
301
    std::unique_ptr<DatabaseBatch> m_batch;
302
303
    // External functions listening to the current db txn outcome.
304
    // Listeners are cleared at the end of the transaction.
305
    std::vector<DbTxnListener> m_txn_listeners;
306
};
307
308
/**
309
 * Executes the provided function 'func' within a database transaction context.
310
 *
311
 * This function ensures that all db modifications performed within 'func()' are
312
 * atomically committed to the db at the end of the process. And, in case of a
313
 * failure during execution, all performed changes are rolled back.
314
 *
315
 * @param database The db connection instance to perform the transaction on.
316
 * @param process_desc A description of the process being executed, used for logging purposes in the event of a failure.
317
 * @param func The function to be executed within the db txn context. It returns a boolean indicating whether to commit or roll back the txn.
318
 * @return true if the db txn executed successfully, false otherwise.
319
 */
320
bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func);
321
322
bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
323
bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
324
bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr);
325
bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr);
326
327
//! Returns true if there are any DBKeys::LEGACY_TYPES record in the wallet db
328
bool HasLegacyRecords(CWallet& wallet);
329
bool HasLegacyRecords(CWallet& wallet, DatabaseBatch& batch);
330
} // namespace wallet
331
332
#endif // BITCOIN_WALLET_WALLETDB_H