Coverage Report

Created: 2026-08-05 14:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/wallet/walletdb.cpp
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
#include <bitcoin-build-config.h> // IWYU pragma: keep
7
8
#include <wallet/walletdb.h>
9
10
#include <common/system.h>
11
#include <key_io.h>
12
#include <primitives/transaction_identifier.h>
13
#include <protocol.h>
14
#include <script/script.h>
15
#include <serialize.h>
16
#include <sync.h>
17
#include <util/bip32.h>
18
#include <util/check.h>
19
#include <util/fs.h>
20
#include <util/time.h>
21
#include <util/translation.h>
22
#include <wallet/migrate.h>
23
#include <wallet/sqlite.h>
24
#include <wallet/wallet.h>
25
26
#include <atomic>
27
#include <optional>
28
#include <string>
29
30
namespace wallet {
31
namespace DBKeys {
32
const std::string ACENTRY{"acentry"};
33
const std::string ACTIVEEXTERNALSPK{"activeexternalspk"};
34
const std::string ACTIVEINTERNALSPK{"activeinternalspk"};
35
const std::string BESTBLOCK_NOMERKLE{"bestblock_nomerkle"};
36
const std::string BESTBLOCK{"bestblock"};
37
const std::string CRYPTED_KEY{"ckey"};
38
const std::string CSCRIPT{"cscript"};
39
const std::string DEFAULTKEY{"defaultkey"};
40
const std::string DESTDATA{"destdata"};
41
const std::string FLAGS{"flags"};
42
const std::string HDCHAIN{"hdchain"};
43
const std::string KEYMETA{"keymeta"};
44
const std::string KEY{"key"};
45
const std::string LOCKED_UTXO{"lockedutxo"};
46
const std::string MASTER_KEY{"mkey"};
47
const std::string MINVERSION{"minversion"};
48
const std::string NAME{"name"};
49
const std::string OLD_KEY{"wkey"};
50
const std::string ORDERPOSNEXT{"orderposnext"};
51
const std::string POOL{"pool"};
52
const std::string PURPOSE{"purpose"};
53
const std::string SETTINGS{"settings"};
54
const std::string TX{"tx"};
55
const std::string WTX_VARIANT{"wtxvariant"};
56
const std::string VERSION{"version"};
57
const std::string WALLETDESCRIPTOR{"walletdescriptor"};
58
const std::string WALLETDESCRIPTORCACHE{"walletdescriptorcache"};
59
const std::string WALLETDESCRIPTORLHCACHE{"walletdescriptorlhcache"};
60
const std::string WALLETDESCRIPTORCKEY{"walletdescriptorckey"};
61
const std::string WALLETDESCRIPTORKEY{"walletdescriptorkey"};
62
const std::string WATCHMETA{"watchmeta"};
63
const std::string WATCHS{"watchs"};
64
const std::unordered_set<std::string> LEGACY_TYPES{CRYPTED_KEY, CSCRIPT, DEFAULTKEY, HDCHAIN, KEYMETA, KEY, OLD_KEY, POOL, WATCHMETA, WATCHS};
65
} // namespace DBKeys
66
67
void LogDBInfo()
68
397
{
69
    // Add useful DB information here. This will be printed during startup.
70
397
    LogInfo("Using SQLite Version %s", SQLiteDatabaseVersion());
71
397
}
72
73
//
74
// WalletBatch
75
//
76
77
bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName)
78
28.1k
{
79
28.1k
    return WriteIC(std::make_pair(DBKeys::NAME, strAddress), strName);
80
28.1k
}
81
82
bool WalletBatch::EraseName(const std::string& strAddress)
83
28
{
84
    // This should only be used for sending addresses, never for receiving addresses,
85
    // receiving addresses must always have an address book entry if they're not change return.
86
28
    return EraseIC(std::make_pair(DBKeys::NAME, strAddress));
87
28
}
88
89
bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
90
28.1k
{
91
28.1k
    return WriteIC(std::make_pair(DBKeys::PURPOSE, strAddress), strPurpose);
92
28.1k
}
93
94
bool WalletBatch::ErasePurpose(const std::string& strAddress)
95
28
{
96
28
    return EraseIC(std::make_pair(DBKeys::PURPOSE, strAddress));
97
28
}
98
99
bool WalletBatch::WriteTx(const CWalletTx& wtx)
100
23.0k
{
101
23.0k
    const Txid txid = wtx.GetHash();
102
    // Persist all witness variants. Including the canonical one
103
23.0k
    for (const auto& [wtxid, tx] : wtx.GetTxs()) {
104
23.0k
        if (!WriteWtxVariant(txid, tx)) return false;
105
23.0k
    }
106
23.0k
    return WriteIC(std::make_pair(DBKeys::TX, txid), wtx);
107
23.0k
}
108
109
bool WalletBatch::EraseTx(Txid hash)
110
15
{
111
15
    if (!EraseIC(std::make_pair(DBKeys::TX, hash.ToUint256()))) return false;
112
    // Drop all witness variant records too, so none are left dangling
113
15
    return m_batch->ErasePrefix(DataStream() << DBKeys::WTX_VARIANT << hash);
114
15
}
115
116
bool WalletBatch::WriteWtxVariant(const Txid& txid, const CTransactionRef& tx)
117
23.0k
{
118
23.0k
    return WriteIC(std::make_pair(DBKeys::WTX_VARIANT, std::make_pair(txid, tx->GetWitnessHash())), TX_WITH_WITNESS(tx));
119
23.0k
}
120
121
bool WalletBatch::WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite)
122
0
{
123
0
    return WriteIC(std::make_pair(DBKeys::KEYMETA, pubkey), meta, overwrite);
124
0
}
125
126
bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
127
0
{
128
0
    if (!WriteKeyMetadata(keyMeta, vchPubKey, false)) {
129
0
        return false;
130
0
    }
131
132
    // hash pubkey/privkey to accelerate wallet load
133
0
    const auto keypair_hash = Hash(vchPubKey, vchPrivKey);
134
135
0
    return WriteIC(std::make_pair(DBKeys::KEY, vchPubKey), std::make_pair(vchPrivKey, keypair_hash), false);
136
0
}
137
138
bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey,
139
                                const std::vector<unsigned char>& vchCryptedSecret,
140
                                const CKeyMetadata &keyMeta)
141
0
{
142
0
    if (!WriteKeyMetadata(keyMeta, vchPubKey, true)) {
143
0
        return false;
144
0
    }
145
146
    // Compute a checksum of the encrypted key
147
0
    uint256 checksum = Hash(vchCryptedSecret);
148
149
0
    const auto key = std::make_pair(DBKeys::CRYPTED_KEY, vchPubKey);
150
0
    if (!WriteIC(key, std::make_pair(vchCryptedSecret, checksum), false)) {
151
        // It may already exist, so try writing just the checksum
152
0
        std::vector<unsigned char> val;
153
0
        if (!m_batch->Read(key, val)) {
154
0
            return false;
155
0
        }
156
0
        if (!WriteIC(key, std::make_pair(val, checksum), true)) {
157
0
            return false;
158
0
        }
159
0
    }
160
0
    EraseIC(std::make_pair(DBKeys::KEY, vchPubKey));
161
0
    return true;
162
0
}
163
164
bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
165
27
{
166
27
    return WriteIC(std::make_pair(DBKeys::MASTER_KEY, nID), kMasterKey, true);
167
27
}
168
169
bool WalletBatch::EraseMasterKey(unsigned int id)
170
1
{
171
1
    return EraseIC(std::make_pair(DBKeys::MASTER_KEY, id));
172
1
}
173
174
bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
175
0
{
176
0
    if (!WriteIC(std::make_pair(DBKeys::WATCHMETA, dest), keyMeta)) {
177
0
        return false;
178
0
    }
179
0
    return WriteIC(std::make_pair(DBKeys::WATCHS, dest), uint8_t{'1'});
180
0
}
181
182
bool WalletBatch::EraseWatchOnly(const CScript &dest)
183
0
{
184
0
    if (!EraseIC(std::make_pair(DBKeys::WATCHMETA, dest))) {
185
0
        return false;
186
0
    }
187
0
    return EraseIC(std::make_pair(DBKeys::WATCHS, dest));
188
0
}
189
190
bool WalletBatch::WriteBestBlock(const CBlockLocator& locator)
191
12.5k
{
192
12.5k
    WriteIC(DBKeys::BESTBLOCK, CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
193
12.5k
    return WriteIC(DBKeys::BESTBLOCK_NOMERKLE, locator);
194
12.5k
}
195
196
bool WalletBatch::ReadBestBlock(CBlockLocator& locator)
197
1.89k
{
198
1.89k
    if (m_batch->Read(DBKeys::BESTBLOCK, locator) && !locator.vHave.empty()) return true;
199
1.89k
    return m_batch->Read(DBKeys::BESTBLOCK_NOMERKLE, locator);
200
1.89k
}
201
202
bool WalletBatch::IsEncrypted()
203
0
{
204
0
    DataStream prefix;
205
0
    prefix << DBKeys::MASTER_KEY;
206
0
    if (auto cursor = m_batch->GetNewPrefixCursor(prefix)) {
207
0
        DataStream k, v;
208
0
        if (cursor->Next(k, v) == DatabaseCursor::Status::MORE) return true;
209
0
    }
210
0
    return false;
211
0
}
212
213
bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
214
17.4k
{
215
17.4k
    return WriteIC(DBKeys::ORDERPOSNEXT, nOrderPosNext);
216
17.4k
}
217
218
bool WalletBatch::WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal)
219
4.26k
{
220
4.26k
    std::string key = internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK;
221
4.26k
    return WriteIC(make_pair(key, type), id);
222
4.26k
}
223
224
bool WalletBatch::EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
225
1
{
226
1
    const std::string key{internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK};
227
1
    return EraseIC(make_pair(key, type));
228
1
}
229
230
bool WalletBatch::WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey)
231
4.42k
{
232
    // hash pubkey/privkey to accelerate wallet load
233
4.42k
    const auto keypair_hash = Hash(pubkey, privkey);
234
235
4.42k
    return WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)), std::make_pair(privkey, keypair_hash), false);
236
4.42k
}
237
238
bool WalletBatch::WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret)
239
273
{
240
273
    if (!WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORCKEY, std::make_pair(desc_id, pubkey)), secret, false)) {
241
0
        return false;
242
0
    }
243
273
    EraseIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)));
244
273
    return true;
245
273
}
246
247
bool WalletBatch::WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor)
248
101k
{
249
101k
    return WriteIC(make_pair(DBKeys::WALLETDESCRIPTOR, desc_id), descriptor);
250
101k
}
251
252
bool WalletBatch::WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index)
253
24.0k
{
254
24.0k
    std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
255
24.0k
    xpub.Encode(ser_xpub.data());
256
24.0k
    return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), std::make_pair(key_exp_index, der_index)), ser_xpub);
257
24.0k
}
258
259
bool WalletBatch::WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
260
5.29k
{
261
5.29k
    std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
262
5.29k
    xpub.Encode(ser_xpub.data());
263
5.29k
    return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), key_exp_index), ser_xpub);
264
5.29k
}
265
266
bool WalletBatch::WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
267
4.00k
{
268
4.00k
    std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
269
4.00k
    xpub.Encode(ser_xpub.data());
270
4.00k
    return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORLHCACHE, desc_id), key_exp_index), ser_xpub);
271
4.00k
}
272
273
bool WalletBatch::WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache)
274
430k
{
275
430k
    for (const auto& parent_xpub_pair : cache.GetCachedParentExtPubKeys()) {
276
5.29k
        if (!WriteDescriptorParentCache(parent_xpub_pair.second, desc_id, parent_xpub_pair.first)) {
277
0
            return false;
278
0
        }
279
5.29k
    }
280
430k
    for (const auto& derived_xpub_map_pair : cache.GetCachedDerivedExtPubKeys()) {
281
24.0k
        for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
282
24.0k
            if (!WriteDescriptorDerivedCache(derived_xpub_pair.second, desc_id, derived_xpub_map_pair.first, derived_xpub_pair.first)) {
283
0
                return false;
284
0
            }
285
24.0k
        }
286
24.0k
    }
287
430k
    for (const auto& lh_xpub_pair : cache.GetCachedLastHardenedExtPubKeys()) {
288
4.00k
        if (!WriteDescriptorLastHardenedCache(lh_xpub_pair.second, desc_id, lh_xpub_pair.first)) {
289
0
            return false;
290
0
        }
291
4.00k
    }
292
430k
    return true;
293
430k
}
294
295
bool WalletBatch::WriteLockedUTXO(const COutPoint& output)
296
3
{
297
3
    return WriteIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)), uint8_t{'1'});
298
3
}
299
300
bool WalletBatch::EraseLockedUTXO(const COutPoint& output)
301
1
{
302
1
    return EraseIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)));
303
1
}
304
305
bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
306
200
{
307
200
    LOCK(pwallet->cs_wallet);
308
200
    try {
309
200
        CPubKey vchPubKey;
310
200
        ssKey >> vchPubKey;
311
200
        if (!vchPubKey.IsValid())
312
0
        {
313
0
            strErr = "Error reading wallet database: CPubKey corrupt";
314
0
            return false;
315
0
        }
316
200
        CKey key;
317
200
        CPrivKey pkey;
318
200
        uint256 hash;
319
320
200
        ssValue >> pkey;
321
322
        // Old wallets store keys as DBKeys::KEY [pubkey] => [privkey]
323
        // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
324
        // using EC operations as a checksum.
325
        // Newer wallets store keys as DBKeys::KEY [pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
326
        // remaining backwards-compatible.
327
200
        try
328
200
        {
329
200
            ssValue >> hash;
330
200
        }
331
200
        catch (const std::ios_base::failure&) {}
332
333
200
        bool fSkipCheck = false;
334
335
200
        if (!hash.IsNull())
336
200
        {
337
            // hash pubkey/privkey to accelerate wallet load
338
200
            const auto keypair_hash = Hash(vchPubKey, pkey);
339
340
200
            if (keypair_hash != hash)
341
0
            {
342
0
                strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
343
0
                return false;
344
0
            }
345
346
200
            fSkipCheck = true;
347
200
        }
348
349
200
        if (!key.Load(pkey, vchPubKey, fSkipCheck))
350
0
        {
351
0
            strErr = "Error reading wallet database: CPrivKey corrupt";
352
0
            return false;
353
0
        }
354
200
        if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadKey(key, vchPubKey))
355
0
        {
356
0
            strErr = "Error reading wallet database: LegacyDataSPKM::LoadKey failed";
357
0
            return false;
358
0
        }
359
200
    } catch (const std::exception& e) {
360
0
        if (strErr.empty()) {
361
0
            strErr = e.what();
362
0
        }
363
0
        return false;
364
0
    }
365
200
    return true;
366
200
}
367
368
bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
369
24
{
370
24
    LOCK(pwallet->cs_wallet);
371
24
    try {
372
24
        CPubKey vchPubKey;
373
24
        ssKey >> vchPubKey;
374
24
        if (!vchPubKey.IsValid())
375
0
        {
376
0
            strErr = "Error reading wallet database: CPubKey corrupt";
377
0
            return false;
378
0
        }
379
24
        std::vector<unsigned char> vchPrivKey;
380
24
        ssValue >> vchPrivKey;
381
382
        // Get the checksum and check it
383
24
        bool checksum_valid = false;
384
24
        if (!ssValue.empty()) {
385
24
            uint256 checksum;
386
24
            ssValue >> checksum;
387
24
            if (!(checksum_valid = Hash(vchPrivKey) == checksum)) {
388
0
                strErr = "Error reading wallet database: Encrypted key corrupt";
389
0
                return false;
390
0
            }
391
24
        }
392
393
24
        if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCryptedKey(vchPubKey, vchPrivKey, checksum_valid))
394
0
        {
395
0
            strErr = "Error reading wallet database: LegacyDataSPKM::LoadCryptedKey failed";
396
0
            return false;
397
0
        }
398
24
    } catch (const std::exception& e) {
399
0
        if (strErr.empty()) {
400
0
            strErr = e.what();
401
0
        }
402
0
        return false;
403
0
    }
404
24
    return true;
405
24
}
406
407
bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
408
18
{
409
18
    LOCK(pwallet->cs_wallet);
410
18
    try {
411
        // Master encryption key is loaded into only the wallet and not any of the ScriptPubKeyMans.
412
18
        unsigned int nID;
413
18
        ssKey >> nID;
414
18
        CMasterKey kMasterKey;
415
18
        ssValue >> kMasterKey;
416
18
        if(pwallet->mapMasterKeys.contains(nID))
417
0
        {
418
0
            strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
419
0
            return false;
420
0
        }
421
18
        pwallet->mapMasterKeys[nID] = kMasterKey;
422
18
        if (pwallet->nMasterKeyMaxID < nID)
423
18
            pwallet->nMasterKeyMaxID = nID;
424
425
18
    } catch (const std::exception& e) {
426
0
        if (strErr.empty()) {
427
0
            strErr = e.what();
428
0
        }
429
0
        return false;
430
0
    }
431
18
    return true;
432
18
}
433
434
bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr)
435
36
{
436
36
    LOCK(pwallet->cs_wallet);
437
36
    try {
438
36
        CHDChain chain;
439
36
        ssValue >> chain;
440
36
        pwallet->GetOrCreateLegacyDataSPKM()->LoadHDChain(chain);
441
36
    } catch (const std::exception& e) {
442
0
        if (strErr.empty()) {
443
0
            strErr = e.what();
444
0
        }
445
0
        return false;
446
0
    }
447
36
    return true;
448
36
}
449
450
static DBErrors LoadWalletFlags(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
451
378
{
452
378
    AssertLockHeld(pwallet->cs_wallet);
453
378
    uint64_t flags;
454
378
    if (batch.Read(DBKeys::FLAGS, flags)) {
455
372
        if (!pwallet->LoadWalletFlags(flags)) {
456
0
            pwallet->WalletLogPrintf("Error reading wallet database: Unknown non-tolerable wallet flags found\n");
457
0
            return DBErrors::TOO_NEW;
458
0
        }
459
        // All wallets must be descriptor wallets unless opened with a bdb_ro db
460
        // bdb_ro is only used for legacy to descriptor migration.
461
372
        if (pwallet->GetDatabase().Format() != "bdb_ro" && !pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
462
0
            return DBErrors::LEGACY_WALLET;
463
0
        }
464
372
    }
465
378
    return DBErrors::LOAD_OK;
466
378
}
467
468
struct LoadResult
469
{
470
    DBErrors m_result{DBErrors::LOAD_OK};
471
    int m_records{0};
472
};
473
474
using LoadFunc = std::function<DBErrors(CWallet* pwallet, DataStream& key, DataStream& value, std::string& err)>;
475
static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, DataStream& prefix, LoadFunc load_func)
476
14.9k
{
477
14.9k
    LoadResult result;
478
14.9k
    DataStream ssKey;
479
14.9k
    DataStream ssValue{};
480
481
14.9k
    Assume(!prefix.empty());
482
14.9k
    std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
483
14.9k
    if (!cursor) {
484
0
        pwallet->WalletLogPrintf("Error getting database cursor for '%s' records\n", key);
485
0
        result.m_result = DBErrors::CORRUPT;
486
0
        return result;
487
0
    }
488
489
40.5k
    while (true) {
490
40.5k
        DatabaseCursor::Status status = cursor->Next(ssKey, ssValue);
491
40.5k
        if (status == DatabaseCursor::Status::DONE) {
492
14.8k
            break;
493
25.6k
        } else if (status == DatabaseCursor::Status::FAIL) {
494
0
            pwallet->WalletLogPrintf("Error reading next '%s' record for wallet database\n", key);
495
0
            result.m_result = DBErrors::CORRUPT;
496
0
            return result;
497
0
        }
498
25.6k
        std::string type;
499
25.6k
        ssKey >> type;
500
25.6k
        assert(type == key);
501
25.6k
        std::string error;
502
25.6k
        DBErrors record_res = load_func(pwallet, ssKey, ssValue, error);
503
25.6k
        if (record_res != DBErrors::LOAD_OK) {
504
4
            pwallet->WalletLogPrintf("%s\n", error);
505
4
        }
506
25.6k
        result.m_result = std::max(result.m_result, record_res);
507
25.6k
        ++result.m_records;
508
25.6k
    }
509
14.9k
    return result;
510
14.9k
}
511
512
static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, LoadFunc load_func)
513
4.25k
{
514
4.25k
    DataStream prefix;
515
4.25k
    prefix << key;
516
4.25k
    return LoadRecords(pwallet, batch, key, prefix, load_func);
517
4.25k
}
518
519
bool HasLegacyRecords(CWallet& wallet)
520
45
{
521
45
    const auto& batch = wallet.GetDatabase().MakeBatch();
522
45
    return HasLegacyRecords(wallet, *batch);
523
45
}
524
525
bool HasLegacyRecords(CWallet& wallet, DatabaseBatch& batch)
526
369
{
527
3.35k
    for (const auto& type : DBKeys::LEGACY_TYPES) {
528
3.35k
        DataStream key;
529
3.35k
        DataStream value{};
530
3.35k
        DataStream prefix;
531
532
3.35k
        prefix << type;
533
3.35k
        std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
534
3.35k
        if (!cursor) {
535
            // Could only happen on a closed db, which means there is an error in the code flow.
536
0
            throw std::runtime_error(strprintf("Error getting database cursor for '%s' records", type));
537
0
        }
538
539
3.35k
        DatabaseCursor::Status status = cursor->Next(key, value);
540
3.35k
        if (status != DatabaseCursor::Status::DONE) {
541
43
            return true;
542
43
        }
543
3.35k
    }
544
326
    return false;
545
369
}
546
547
static DBErrors LoadLegacyWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
548
378
{
549
378
    AssertLockHeld(pwallet->cs_wallet);
550
378
    DBErrors result = DBErrors::LOAD_OK;
551
552
    // Make sure descriptor wallets don't have any legacy records
553
378
    if (pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
554
324
        if (HasLegacyRecords(*pwallet, batch)) {
555
1
            pwallet->WalletLogPrintf("Error: Unexpected legacy entry found in descriptor wallet %s. The wallet might have been tampered with or created with malicious intent.\n", pwallet->GetName());
556
1
            return DBErrors::UNEXPECTED_LEGACY_ENTRY;
557
1
        }
558
559
323
        return DBErrors::LOAD_OK;
560
324
    }
561
562
    // Load HD Chain
563
    // Note: There should only be one HDCHAIN record with no data following the type
564
54
    LoadResult hd_chain_res = LoadRecords(pwallet, batch, DBKeys::HDCHAIN,
565
54
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
566
36
        return LoadHDChain(pwallet, value, err) ? DBErrors:: LOAD_OK : DBErrors::CORRUPT;
567
36
    });
568
54
    result = std::max(result, hd_chain_res.m_result);
569
570
    // Load unencrypted keys
571
54
    LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::KEY,
572
200
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
573
200
        return LoadKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
574
200
    });
575
54
    result = std::max(result, key_res.m_result);
576
577
    // Load encrypted keys
578
54
    LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::CRYPTED_KEY,
579
54
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
580
24
        return LoadCryptedKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
581
24
    });
582
54
    result = std::max(result, ckey_res.m_result);
583
584
    // Load scripts
585
54
    LoadResult script_res = LoadRecords(pwallet, batch, DBKeys::CSCRIPT,
586
86
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
587
86
        uint160 hash;
588
86
        key >> hash;
589
86
        CScript script;
590
86
        value >> script;
591
86
        if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCScript(script))
592
0
        {
593
0
            strErr = "Error reading wallet database: LegacyDataSPKM::LoadCScript failed";
594
0
            return DBErrors::NONCRITICAL_ERROR;
595
0
        }
596
86
        return DBErrors::LOAD_OK;
597
86
    });
598
54
    result = std::max(result, script_res.m_result);
599
600
    // Load keymeta
601
54
    std::map<uint160, CHDChain> hd_chains;
602
54
    LoadResult keymeta_res = LoadRecords(pwallet, batch, DBKeys::KEYMETA,
603
228
        [&hd_chains] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
604
228
        CPubKey vchPubKey;
605
228
        key >> vchPubKey;
606
228
        CKeyMetadata keyMeta;
607
228
        value >> keyMeta;
608
228
        pwallet->GetOrCreateLegacyDataSPKM()->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
609
610
        // Extract some CHDChain info from this metadata if it has any
611
228
        if (keyMeta.nVersion >= CKeyMetadata::VERSION_WITH_HDDATA && !keyMeta.hd_seed_id.IsNull() && keyMeta.hdKeypath.size() > 0) {
612
            // Get the path from the key origin or from the path string
613
            // Not applicable when path is "s" or "m" as those indicate a seed
614
            // See https://github.com/bitcoin/bitcoin/pull/12924
615
219
            bool internal = false;
616
219
            uint32_t index = 0;
617
219
            if (keyMeta.hdKeypath != "s" && keyMeta.hdKeypath != "m") {
618
177
                std::vector<uint32_t> path;
619
177
                if (keyMeta.has_key_origin) {
620
                    // We have a key origin, so pull it from its path vector
621
177
                    path = keyMeta.key_origin.path;
622
177
                } else {
623
                    // No key origin, have to parse the string
624
0
                    if (!ParseHDKeypath(keyMeta.hdKeypath, path)) {
625
0
                        strErr = "Error reading wallet database: keymeta with invalid HD keypath";
626
0
                        return DBErrors::NONCRITICAL_ERROR;
627
0
                    }
628
0
                }
629
630
                // Extract the index and internal from the path
631
                // Path string is m/0'/k'/i'
632
                // Path vector is [0', k', i'] (but as ints OR'd with the hardened bit
633
                // k == 0 for external, 1 for internal. i is the index
634
177
                if (path.size() != 3) {
635
1
                    strErr = "Error reading wallet database: keymeta found with unexpected path";
636
1
                    return DBErrors::NONCRITICAL_ERROR;
637
1
                }
638
176
                if (path[0] != 0x80000000) {
639
0
                    strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
640
0
                    return DBErrors::NONCRITICAL_ERROR;
641
0
                }
642
176
                if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
643
0
                    strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
644
0
                    return DBErrors::NONCRITICAL_ERROR;
645
0
                }
646
176
                if ((path[2] & 0x80000000) == 0) {
647
0
                    strErr = strprintf("Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
648
0
                    return DBErrors::NONCRITICAL_ERROR;
649
0
                }
650
176
                internal = path[1] == (1 | 0x80000000);
651
176
                index = path[2] & ~0x80000000;
652
176
            }
653
654
            // Insert a new CHDChain, or get the one that already exists
655
218
            auto [ins, inserted] = hd_chains.emplace(keyMeta.hd_seed_id, CHDChain());
656
218
            CHDChain& chain = ins->second;
657
218
            if (inserted) {
658
                // For new chains, we want to default to VERSION_HD_BASE until we see an internal
659
42
                chain.nVersion = CHDChain::VERSION_HD_BASE;
660
42
                chain.seed_id = keyMeta.hd_seed_id;
661
42
            }
662
218
            if (internal) {
663
71
                chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
664
71
                chain.nInternalChainCounter = std::max(chain.nInternalChainCounter, index + 1);
665
147
            } else {
666
147
                chain.nExternalChainCounter = std::max(chain.nExternalChainCounter, index + 1);
667
147
            }
668
218
        }
669
227
        return DBErrors::LOAD_OK;
670
228
    });
671
54
    result = std::max(result, keymeta_res.m_result);
672
673
    // Set inactive chains
674
54
    if (!hd_chains.empty()) {
675
36
        LegacyDataSPKM* legacy_spkm = pwallet->GetLegacyDataSPKM();
676
36
        if (legacy_spkm) {
677
42
            for (const auto& [hd_seed_id, chain] : hd_chains) {
678
42
                if (hd_seed_id != legacy_spkm->GetHDChain().seed_id) {
679
6
                    legacy_spkm->AddInactiveHDChain(chain);
680
6
                }
681
42
            }
682
36
        } else {
683
0
            pwallet->WalletLogPrintf("Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
684
0
            result = DBErrors::CORRUPT;
685
0
        }
686
36
    }
687
688
    // Load watchonly scripts
689
54
    LoadResult watch_script_res = LoadRecords(pwallet, batch, DBKeys::WATCHS,
690
54
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
691
49
        CScript script;
692
49
        key >> script;
693
49
        uint8_t fYes;
694
49
        value >> fYes;
695
49
        if (fYes == '1') {
696
49
            pwallet->GetOrCreateLegacyDataSPKM()->LoadWatchOnly(script);
697
49
        }
698
49
        return DBErrors::LOAD_OK;
699
49
    });
700
54
    result = std::max(result, watch_script_res.m_result);
701
702
    // Load watchonly meta
703
54
    LoadResult watch_meta_res = LoadRecords(pwallet, batch, DBKeys::WATCHMETA,
704
54
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
705
49
        CScript script;
706
49
        key >> script;
707
49
        CKeyMetadata keyMeta;
708
49
        value >> keyMeta;
709
49
        pwallet->GetOrCreateLegacyDataSPKM()->LoadScriptMetadata(CScriptID(script), keyMeta);
710
49
        return DBErrors::LOAD_OK;
711
49
    });
712
54
    result = std::max(result, watch_meta_res.m_result);
713
714
    // Deal with old "wkey" and "defaultkey" records.
715
    // These are not actually loaded, but we need to check for them
716
717
    // We don't want or need the default key, but if there is one set,
718
    // we want to make sure that it is valid so that we can detect corruption
719
    // Note: There should only be one DEFAULTKEY with nothing trailing the type
720
54
    LoadResult default_key_res = LoadRecords(pwallet, batch, DBKeys::DEFAULTKEY,
721
54
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
722
0
        CPubKey default_pubkey;
723
0
        try {
724
0
            value >> default_pubkey;
725
0
        } catch (const std::exception& e) {
726
0
            err = e.what();
727
0
            return DBErrors::CORRUPT;
728
0
        }
729
0
        if (!default_pubkey.IsValid()) {
730
0
            err = "Error reading wallet database: Default Key corrupt";
731
0
            return DBErrors::CORRUPT;
732
0
        }
733
0
        return DBErrors::LOAD_OK;
734
0
    });
735
54
    result = std::max(result, default_key_res.m_result);
736
737
    // "wkey" records are unsupported, if we see any, throw an error
738
54
    LoadResult wkey_res = LoadRecords(pwallet, batch, DBKeys::OLD_KEY,
739
54
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
740
0
        err = "Found unsupported 'wkey' record, try loading with version 0.18";
741
0
        return DBErrors::LOAD_FAIL;
742
0
    });
743
54
    result = std::max(result, wkey_res.m_result);
744
745
54
    if (result <= DBErrors::NONCRITICAL_ERROR) {
746
        // Only do logging and time first key update if there were no critical errors
747
54
        pwallet->WalletLogPrintf("Legacy Wallet Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total.\n",
748
54
               key_res.m_records, ckey_res.m_records, keymeta_res.m_records, key_res.m_records + ckey_res.m_records);
749
54
    }
750
751
54
    return result;
752
378
}
753
754
template<typename... Args>
755
static DataStream PrefixStream(const Args&... args)
756
10.6k
{
757
10.6k
    DataStream prefix;
758
10.6k
    SerializeMany(prefix, args...);
759
10.6k
    return prefix;
760
10.6k
}
761
762
static DBErrors LoadDescriptorWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
763
378
{
764
378
    AssertLockHeld(pwallet->cs_wallet);
765
766
    // Load descriptor record
767
378
    int num_keys = 0;
768
378
    int num_ckeys= 0;
769
378
    LoadResult desc_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTOR,
770
2.66k
        [&batch, &num_keys, &num_ckeys, &last_client] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
771
2.66k
        DBErrors result = DBErrors::LOAD_OK;
772
773
2.66k
        uint256 id;
774
2.66k
        key >> id;
775
2.66k
        WalletDescriptor desc;
776
2.66k
        try {
777
2.66k
            value >> desc;
778
2.66k
        } catch (const std::ios_base::failure& e) {
779
1
            strErr = strprintf("Error: Unrecognized descriptor found in wallet %s. ", pwallet->GetName());
780
1
            strErr += (last_client > CLIENT_VERSION) ? "The wallet might have been created on a newer version. " :
781
1
                    "The database might be corrupted or the software version is not compatible with one of your wallet descriptors. ";
782
1
            strErr += "Please try running the latest software version";
783
            // Also include error details
784
1
            strErr = strprintf("%s\nDetails: %s", strErr, e.what());
785
1
            return DBErrors::UNKNOWN_DESCRIPTOR;
786
1
        }
787
788
2.66k
        if (id != desc.id) {
789
1
            strErr = "The descriptor ID calculated by the wallet differs from the one in DB";
790
1
            return DBErrors::CORRUPT;
791
1
        }
792
793
2.66k
        DescriptorCache cache;
794
795
        // Get key cache for this descriptor
796
2.66k
        DataStream prefix = PrefixStream(DBKeys::WALLETDESCRIPTORCACHE, id);
797
2.66k
        LoadResult key_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCACHE, prefix,
798
2.66k
            [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
799
2.54k
            bool parent = true;
800
2.54k
            uint256 desc_id;
801
2.54k
            uint32_t key_exp_index;
802
2.54k
            uint32_t der_index;
803
2.54k
            key >> desc_id;
804
2.54k
            assert(desc_id == id);
805
2.54k
            key >> key_exp_index;
806
807
            // if the der_index exists, it's a derived xpub
808
2.54k
            try
809
2.54k
            {
810
2.54k
                key >> der_index;
811
2.54k
                parent = false;
812
2.54k
            }
813
2.54k
            catch (...) {}
814
815
2.54k
            std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
816
2.54k
            value >> ser_xpub;
817
2.54k
            CExtPubKey xpub;
818
2.54k
            xpub.Decode(ser_xpub.data());
819
2.54k
            if (parent) {
820
2.34k
                cache.CacheParentExtPubKey(key_exp_index, xpub);
821
2.34k
            } else {
822
195
                cache.CacheDerivedExtPubKey(key_exp_index, der_index, xpub);
823
195
            }
824
2.54k
            return DBErrors::LOAD_OK;
825
2.54k
        });
826
2.66k
        result = std::max(result, key_cache_res.m_result);
827
828
        // Get last hardened cache for this descriptor
829
2.66k
        prefix = PrefixStream(DBKeys::WALLETDESCRIPTORLHCACHE, id);
830
2.66k
        LoadResult lh_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORLHCACHE, prefix,
831
2.66k
            [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
832
2.25k
            uint256 desc_id;
833
2.25k
            uint32_t key_exp_index;
834
2.25k
            key >> desc_id;
835
2.25k
            assert(desc_id == id);
836
2.25k
            key >> key_exp_index;
837
838
2.25k
            std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
839
2.25k
            value >> ser_xpub;
840
2.25k
            CExtPubKey xpub;
841
2.25k
            xpub.Decode(ser_xpub.data());
842
2.25k
            cache.CacheLastHardenedExtPubKey(key_exp_index, xpub);
843
2.25k
            return DBErrors::LOAD_OK;
844
2.25k
        });
845
2.66k
        result = std::max(result, lh_cache_res.m_result);
846
847
        // Set the cache to the WalletDescriptor
848
2.66k
        desc.cache = cache;
849
850
        // Get unencrypted keys
851
2.66k
        KeyMap keys;
852
2.66k
        prefix = PrefixStream(DBKeys::WALLETDESCRIPTORKEY, id);
853
2.66k
        LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORKEY, prefix,
854
2.66k
            [&id, &keys] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
855
2.28k
            uint256 desc_id;
856
2.28k
            CPubKey pubkey;
857
2.28k
            key >> desc_id;
858
2.28k
            assert(desc_id == id);
859
2.28k
            key >> pubkey;
860
2.28k
            if (!pubkey.IsValid())
861
0
            {
862
0
                strErr = "Error reading wallet database: descriptor unencrypted key CPubKey corrupt";
863
0
                return DBErrors::CORRUPT;
864
0
            }
865
2.28k
            CKey privkey;
866
2.28k
            CPrivKey pkey;
867
2.28k
            uint256 hash;
868
869
2.28k
            value >> pkey;
870
2.28k
            value >> hash;
871
872
            // hash pubkey/privkey to accelerate wallet load
873
2.28k
            const auto keypair_hash = Hash(pubkey, pkey);
874
875
2.28k
            if (keypair_hash != hash)
876
0
            {
877
0
                strErr = "Error reading wallet database: descriptor unencrypted key CPubKey/CPrivKey corrupt";
878
0
                return DBErrors::CORRUPT;
879
0
            }
880
881
2.28k
            if (!privkey.Load(pkey, pubkey, true))
882
0
            {
883
0
                strErr = "Error reading wallet database: descriptor unencrypted key CPrivKey corrupt";
884
0
                return DBErrors::CORRUPT;
885
0
            }
886
2.28k
            keys[pubkey.GetID()] = privkey;
887
2.28k
            return DBErrors::LOAD_OK;
888
2.28k
        });
889
2.66k
        result = std::max(result, key_res.m_result);
890
2.66k
        num_keys = key_res.m_records;
891
892
        // Get encrypted keys
893
2.66k
        CryptedKeyMap ckeys;
894
2.66k
        prefix = PrefixStream(DBKeys::WALLETDESCRIPTORCKEY, id);
895
2.66k
        LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCKEY, prefix,
896
2.66k
            [&id, &ckeys] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
897
218
            uint256 desc_id;
898
218
            CPubKey pubkey;
899
218
            key >> desc_id;
900
218
            assert(desc_id == id);
901
218
            key >> pubkey;
902
218
            if (!pubkey.IsValid())
903
0
            {
904
0
                err = "Error reading wallet database: descriptor encrypted key CPubKey corrupt";
905
0
                return DBErrors::CORRUPT;
906
0
            }
907
218
            std::vector<unsigned char> privkey;
908
218
            value >> privkey;
909
910
218
            ckeys[pubkey.GetID()] = std::make_pair(pubkey, privkey);
911
218
            return DBErrors::LOAD_OK;
912
218
        });
913
2.66k
        result = std::max(result, ckey_res.m_result);
914
2.66k
        num_ckeys = ckey_res.m_records;
915
916
2.66k
        try {
917
2.66k
            pwallet->LoadDescriptorScriptPubKeyMan(id, desc, keys, ckeys);
918
2.66k
        } catch (std::runtime_error& e) {
919
1
            strErr = e.what();
920
1
            return DBErrors::CORRUPT;
921
1
        }
922
923
2.66k
        return result;
924
2.66k
    });
925
926
378
    if (desc_res.m_result <= DBErrors::NONCRITICAL_ERROR) {
927
        // Only log if there are no critical errors
928
375
        pwallet->WalletLogPrintf("Descriptors: %u, Descriptor Keys: %u plaintext, %u encrypted, %u total.\n",
929
375
               desc_res.m_records, num_keys, num_ckeys, num_keys + num_ckeys);
930
375
    }
931
932
378
    return desc_res.m_result;
933
378
}
934
935
static DBErrors LoadAddressBookRecords(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
936
377
{
937
377
    AssertLockHeld(pwallet->cs_wallet);
938
377
    DBErrors result = DBErrors::LOAD_OK;
939
940
    // Load name record
941
377
    LoadResult name_res = LoadRecords(pwallet, batch, DBKeys::NAME,
942
2.23k
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
943
2.23k
        std::string strAddress;
944
2.23k
        key >> strAddress;
945
2.23k
        std::string label;
946
2.23k
        value >> label;
947
2.23k
        pwallet->m_address_book[DecodeDestination(strAddress)].SetLabel(label);
948
2.23k
        return DBErrors::LOAD_OK;
949
2.23k
    });
950
377
    result = std::max(result, name_res.m_result);
951
952
    // Load purpose record
953
377
    LoadResult purpose_res = LoadRecords(pwallet, batch, DBKeys::PURPOSE,
954
2.23k
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
955
2.23k
        std::string strAddress;
956
2.23k
        key >> strAddress;
957
2.23k
        std::string purpose_str;
958
2.23k
        value >> purpose_str;
959
2.23k
        std::optional<AddressPurpose> purpose{PurposeFromString(purpose_str)};
960
2.23k
        if (!purpose) {
961
0
            pwallet->WalletLogPrintf("Warning: nonstandard purpose string '%s' for address '%s'\n", purpose_str, strAddress);
962
0
        }
963
2.23k
        pwallet->m_address_book[DecodeDestination(strAddress)].purpose = purpose;
964
2.23k
        return DBErrors::LOAD_OK;
965
2.23k
    });
966
377
    result = std::max(result, purpose_res.m_result);
967
968
    // Load destination data record
969
377
    LoadResult dest_res = LoadRecords(pwallet, batch, DBKeys::DESTDATA,
970
377
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
971
11
        std::string strAddress, strKey, strValue;
972
11
        key >> strAddress;
973
11
        key >> strKey;
974
11
        value >> strValue;
975
11
        const CTxDestination& dest{DecodeDestination(strAddress)};
976
11
        if (strKey.compare("used") == 0) {
977
            // Load "used" key indicating if an IsMine address has
978
            // previously been spent from with avoid_reuse option enabled.
979
            // The strValue is not used for anything currently, but could
980
            // hold more information in the future. Current values are just
981
            // "1" or "p" for present (which was written prior to
982
            // f5ba424cd44619d9b9be88b8593d69a7ba96db26).
983
8
            pwallet->LoadAddressPreviouslySpent(dest);
984
8
        } else if (strKey.starts_with("rr")) {
985
            // Load "rr##" keys where ## is a decimal number, and strValue
986
            // is a serialized RecentRequestEntry object.
987
3
            pwallet->LoadAddressReceiveRequest(dest, strKey.substr(2), strValue);
988
3
        }
989
11
        return DBErrors::LOAD_OK;
990
11
    });
991
377
    result = std::max(result, dest_res.m_result);
992
993
377
    return result;
994
377
}
995
996
static std::map<Wtxid, CTransactionRef> ReadWtxVariants(DatabaseBatch& batch, const Txid& txid)
997
8.09k
{
998
8.09k
    std::map<Wtxid, CTransactionRef> variants;
999
1000
8.09k
    DataStream prefix;
1001
8.09k
    prefix << DBKeys::WTX_VARIANT << txid;
1002
8.09k
    std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
1003
8.09k
    if (!cursor) {
1004
0
        throw std::runtime_error(strprintf("Error getting database cursor for '%s' records", DBKeys::WTX_VARIANT));
1005
0
    }
1006
1007
8.09k
    DataStream key;
1008
8.09k
    DataStream value;
1009
16.1k
    while (true) {
1010
16.1k
        DatabaseCursor::Status status = cursor->Next(key, value);
1011
16.1k
        if (status == DatabaseCursor::Status::DONE) break;
1012
8.03k
        if (status == DatabaseCursor::Status::FAIL) {
1013
0
            throw std::runtime_error(strprintf("Error reading '%s' record", DBKeys::WTX_VARIANT));
1014
0
        }
1015
8.03k
        CTransactionRef tx;
1016
8.03k
        value >> TX_WITH_WITNESS(tx);
1017
8.03k
        if (tx->GetHash() != txid) {
1018
0
            throw std::runtime_error(strprintf("Corrupted witness variant, tx hash differs"));
1019
0
        }
1020
8.03k
        if (!variants.emplace(tx->GetWitnessHash(), std::move(tx)).second) {
1021
0
            throw std::runtime_error(strprintf("Duplicate witness variant"));
1022
0
        }
1023
8.03k
    }
1024
8.09k
    return variants;
1025
8.09k
}
1026
1027
static DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch, bool& any_unordered) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1028
376
{
1029
376
    AssertLockHeld(pwallet->cs_wallet);
1030
376
    DBErrors result = DBErrors::LOAD_OK;
1031
1032
    // Load tx record
1033
376
    any_unordered = false;
1034
376
    LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,
1035
8.09k
        [&any_unordered, &batch] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1036
8.09k
        DBErrors result = DBErrors::LOAD_OK;
1037
8.09k
        Txid hash;
1038
8.09k
        key >> hash;
1039
8.09k
        try {
1040
8.09k
            CWalletTx wtx{deserialize, value, ReadWtxVariants(batch, hash)};
1041
8.09k
            if (wtx.GetHash() != hash) {
1042
0
                result = std::max(result, DBErrors::NEED_RESCAN);
1043
0
            }
1044
1045
8.09k
            if (wtx.nOrderPos == -1) {
1046
0
                any_unordered = true;
1047
0
            }
1048
1049
8.09k
            if (!pwallet->LoadToWallet(std::move(wtx))) {
1050
0
                err = "Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.";
1051
0
                return DBErrors::CORRUPT;
1052
0
            }
1053
8.09k
        } catch (const std::exception& e) {
1054
0
            err = strprintf("Error: Corrupt tx record found: %s" ,e.what());
1055
0
            return DBErrors::CORRUPT;
1056
0
        }
1057
8.09k
        return result;
1058
8.09k
    });
1059
376
    result = std::max(result, tx_res.m_result);
1060
1061
    // Load locked utxo record
1062
376
    LoadResult locked_utxo_res = LoadRecords(pwallet, batch, DBKeys::LOCKED_UTXO,
1063
376
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1064
3
        Txid hash;
1065
3
        uint32_t n;
1066
3
        key >> hash;
1067
3
        key >> n;
1068
3
        pwallet->LoadLockedCoin(COutPoint(hash, n), /*persistent=*/true);
1069
3
        return DBErrors::LOAD_OK;
1070
3
    });
1071
376
    result = std::max(result, locked_utxo_res.m_result);
1072
1073
    // Load orderposnext record
1074
    // Note: There should only be one ORDERPOSNEXT record with nothing trailing the type
1075
376
    LoadResult order_pos_res = LoadRecords(pwallet, batch, DBKeys::ORDERPOSNEXT,
1076
376
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1077
202
        try {
1078
202
            value >> pwallet->nOrderPosNext;
1079
202
        } catch (const std::exception& e) {
1080
0
            err = e.what();
1081
0
            return DBErrors::NONCRITICAL_ERROR;
1082
0
        }
1083
202
        return DBErrors::LOAD_OK;
1084
202
    });
1085
376
    result = std::max(result, order_pos_res.m_result);
1086
1087
    // After loading all tx records, abandon any coinbase that is no longer in the active chain.
1088
    // This could happen during an external wallet load, or if the user replaced the chain data.
1089
8.09k
    for (auto& [id, wtx] : pwallet->mapWallet) {
1090
8.09k
        if (wtx.IsCoinBase() && wtx.isInactive()) {
1091
432
            pwallet->AbandonTransaction(wtx);
1092
432
        }
1093
8.09k
    }
1094
1095
376
    return result;
1096
376
}
1097
1098
static DBErrors LoadActiveSPKMs(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1099
377
{
1100
377
    AssertLockHeld(pwallet->cs_wallet);
1101
377
    DBErrors result = DBErrors::LOAD_OK;
1102
1103
    // Load spk records
1104
377
    std::set<std::pair<OutputType, bool>> seen_spks;
1105
753
    for (const auto& spk_key : {DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK}) {
1106
753
        LoadResult spkm_res = LoadRecords(pwallet, batch, spk_key,
1107
2.22k
            [&seen_spks, &spk_key] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
1108
2.22k
            uint8_t output_type;
1109
2.22k
            key >> output_type;
1110
2.22k
            uint256 id;
1111
2.22k
            value >> id;
1112
1113
2.22k
            bool internal = spk_key == DBKeys::ACTIVEINTERNALSPK;
1114
2.22k
            auto [it, insert] = seen_spks.emplace(static_cast<OutputType>(output_type), internal);
1115
2.22k
            if (!insert) {
1116
0
                strErr = "Multiple ScriptpubKeyMans specified for a single type";
1117
0
                return DBErrors::CORRUPT;
1118
0
            }
1119
2.22k
            pwallet->LoadActiveScriptPubKeyMan(id, static_cast<OutputType>(output_type), /*internal=*/internal);
1120
2.22k
            return DBErrors::LOAD_OK;
1121
2.22k
        });
1122
753
        result = std::max(result, spkm_res.m_result);
1123
753
    }
1124
377
    return result;
1125
377
}
1126
1127
static DBErrors LoadDecryptionKeys(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1128
376
{
1129
376
    AssertLockHeld(pwallet->cs_wallet);
1130
1131
    // Load decryption key (mkey) records
1132
376
    LoadResult mkey_res = LoadRecords(pwallet, batch, DBKeys::MASTER_KEY,
1133
376
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
1134
18
        if (!LoadEncryptionKey(pwallet, key, value, err)) {
1135
0
            return DBErrors::CORRUPT;
1136
0
        }
1137
18
        return DBErrors::LOAD_OK;
1138
18
    });
1139
376
    return mkey_res.m_result;
1140
376
}
1141
1142
DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
1143
378
{
1144
378
    DBErrors result = DBErrors::LOAD_OK;
1145
378
    bool any_unordered = false;
1146
1147
378
    LOCK(pwallet->cs_wallet);
1148
1149
    // Last client version to open this wallet
1150
378
    int last_client = CLIENT_VERSION;
1151
378
    bool has_last_client = m_batch->Read(DBKeys::VERSION, last_client);
1152
378
    if (has_last_client) pwallet->WalletLogPrintf("Last client version = %d\n", last_client);
1153
1154
378
    try {
1155
        // Load wallet flags, so they are known when processing other records.
1156
        // The FLAGS key is absent during wallet creation.
1157
378
        if ((result = LoadWalletFlags(pwallet, *m_batch)) != DBErrors::LOAD_OK) return result;
1158
1159
#ifndef ENABLE_EXTERNAL_SIGNER
1160
        if (pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
1161
            pwallet->WalletLogPrintf("Error: External signer wallet being loaded without external signer support compiled\n");
1162
            return DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED;
1163
        }
1164
#endif
1165
1166
        // Load legacy wallet keys
1167
378
        result = std::max(LoadLegacyWalletRecords(pwallet, *m_batch, last_client), result);
1168
1169
        // Load descriptors
1170
378
        result = std::max(LoadDescriptorWalletRecords(pwallet, *m_batch, last_client), result);
1171
        // Early return if there are unknown descriptors. Later loading of ACTIVEINTERNALSPK and ACTIVEEXTERNALEXPK
1172
        // may reference the unknown descriptor's ID which can result in a misleading corruption error
1173
        // when in reality the wallet is simply too new.
1174
378
        if (result == DBErrors::UNKNOWN_DESCRIPTOR) return result;
1175
1176
        // Load address book
1177
377
        result = std::max(LoadAddressBookRecords(pwallet, *m_batch), result);
1178
1179
        // Load SPKMs
1180
377
        result = std::max(LoadActiveSPKMs(pwallet, *m_batch), result);
1181
1182
        // Load decryption keys
1183
377
        result = std::max(LoadDecryptionKeys(pwallet, *m_batch), result);
1184
1185
        // Load tx records
1186
377
        result = std::max(LoadTxRecords(pwallet, *m_batch, any_unordered), result);
1187
377
    } catch (std::runtime_error& e) {
1188
        // Exceptions that can be ignored or treated as non-critical are handled by the individual loading functions.
1189
        // Any uncaught exceptions will be caught here and treated as critical.
1190
        // Catch std::runtime_error specifically as many functions throw these and they at least have some message that
1191
        // we can log
1192
0
        pwallet->WalletLogPrintf("%s\n", e.what());
1193
0
        result = DBErrors::CORRUPT;
1194
1
    } catch (...) {
1195
        // All other exceptions are still problematic, but we can't log them
1196
1
        result = DBErrors::CORRUPT;
1197
1
    }
1198
1199
    // Any wallet corruption at all: skip any rewriting or
1200
    // upgrading, we don't want to make it worse.
1201
377
    if (result != DBErrors::LOAD_OK)
1202
4
        return result;
1203
1204
373
    if (!has_last_client || last_client != CLIENT_VERSION) // Update
1205
97
        this->WriteVersion(CLIENT_VERSION);
1206
1207
373
    if (any_unordered)
1208
0
        result = pwallet->ReorderTransactions();
1209
1210
    // Upgrade all of the descriptor caches to cache the last hardened xpub
1211
    // This operation is not atomic, but if it fails, only new entries are added so it is backwards compatible
1212
373
    try {
1213
373
        pwallet->UpgradeDescriptorCache();
1214
373
    } catch (...) {
1215
0
        result = DBErrors::CORRUPT;
1216
0
    }
1217
1218
    // Since it was accidentally possible to "encrypt" a wallet with private keys disabled, we should check if this is
1219
    // such a wallet and remove the encryption key records to avoid any future issues.
1220
    // Although wallets without private keys should not have *ckey records, we should double check that.
1221
    // Removing the mkey records is only safe if there are no *ckey records.
1222
373
    if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && pwallet->HasEncryptionKeys() && !pwallet->HaveCryptedKeys()) {
1223
1
        pwallet->WalletLogPrintf("Detected extraneous encryption keys in this wallet without private keys. Removing extraneous encryption keys.\n");
1224
1
        for (const auto& [id, _] : pwallet->mapMasterKeys) {
1225
1
            if (!EraseMasterKey(id)) {
1226
0
                pwallet->WalletLogPrintf("Error: Unable to remove extraneous encryption key '%u'. Wallet corrupt.\n", id);
1227
0
                return DBErrors::CORRUPT;
1228
0
            }
1229
1
        }
1230
1
        pwallet->mapMasterKeys.clear();
1231
1
    }
1232
1233
373
    return result;
1234
373
}
1235
1236
static bool RunWithinTxn(WalletBatch& batch, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1237
486
{
1238
486
    if (!batch.TxnBegin()) {
1239
0
        LogDebug(BCLog::WALLETDB, "Error: cannot create db txn for %s\n", process_desc);
1240
0
        return false;
1241
0
    }
1242
1243
    // Run procedure
1244
486
    if (!func(batch)) {
1245
1
        LogDebug(BCLog::WALLETDB, "Error: %s failed\n", process_desc);
1246
1
        batch.TxnAbort();
1247
1
        return false;
1248
1
    }
1249
1250
485
    if (!batch.TxnCommit()) {
1251
0
        LogDebug(BCLog::WALLETDB, "Error: cannot commit db txn for %s\n", process_desc);
1252
0
        return false;
1253
0
    }
1254
1255
    // All good
1256
485
    return true;
1257
485
}
1258
1259
bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1260
486
{
1261
486
    WalletBatch batch(database);
1262
486
    return RunWithinTxn(batch, process_desc, func);
1263
486
}
1264
1265
bool WalletBatch::WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent)
1266
26
{
1267
26
    auto key{std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), std::string("used")))};
1268
26
    return previously_spent ? WriteIC(key, std::string("1")) : EraseIC(key);
1269
26
}
1270
1271
bool WalletBatch::WriteAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& receive_request)
1272
4
{
1273
4
    return WriteIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), "rr" + id)), receive_request);
1274
4
}
1275
1276
bool WalletBatch::EraseAddressReceiveRequest(const CTxDestination& dest, const std::string& id)
1277
1
{
1278
1
    return EraseIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), "rr" + id)));
1279
1
}
1280
1281
bool WalletBatch::EraseAddressData(const CTxDestination& dest)
1282
29
{
1283
29
    DataStream prefix;
1284
29
    prefix << DBKeys::DESTDATA << EncodeDestination(dest);
1285
29
    return m_batch->ErasePrefix(prefix);
1286
29
}
1287
1288
bool WalletBatch::WriteWalletFlags(const uint64_t flags)
1289
4.57k
{
1290
4.57k
    return WriteIC(DBKeys::FLAGS, flags);
1291
4.57k
}
1292
1293
bool WalletBatch::EraseRecords(const std::unordered_set<std::string>& types)
1294
38
{
1295
380
    return std::all_of(types.begin(), types.end(), [&](const std::string& type) {
1296
380
        return m_batch->ErasePrefix(DataStream() << type);
1297
380
    });
1298
38
}
1299
1300
bool WalletBatch::TxnBegin()
1301
73.4k
{
1302
73.4k
    return m_batch->TxnBegin();
1303
73.4k
}
1304
1305
bool WalletBatch::TxnCommit()
1306
73.4k
{
1307
73.4k
    bool res = m_batch->TxnCommit();
1308
73.4k
    if (res) {
1309
73.4k
        for (const auto& listener : m_txn_listeners) {
1310
10
            listener.on_commit();
1311
10
        }
1312
        // txn finished, clear listeners
1313
73.4k
        m_txn_listeners.clear();
1314
73.4k
    }
1315
73.4k
    return res;
1316
73.4k
}
1317
1318
bool WalletBatch::TxnAbort()
1319
1
{
1320
1
    bool res = m_batch->TxnAbort();
1321
1
    if (res) {
1322
1
        for (const auto& listener : m_txn_listeners) {
1323
0
            listener.on_abort();
1324
0
        }
1325
        // txn finished, clear listeners
1326
1
        m_txn_listeners.clear();
1327
1
    }
1328
1
    return res;
1329
1
}
1330
1331
void WalletBatch::RegisterTxnListener(const DbTxnListener& l)
1332
10
{
1333
10
    assert(m_batch->HasActiveTxn());
1334
10
    m_txn_listeners.emplace_back(l);
1335
10
}
1336
1337
std::unique_ptr<WalletDatabase> MakeDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error)
1338
1.47k
{
1339
1.47k
    bool exists;
1340
1.47k
    try {
1341
1.47k
        exists = fs::symlink_status(path).type() != fs::file_type::not_found;
1342
1.47k
    } catch (const fs::filesystem_error& e) {
1343
0
        error = Untranslated(strprintf("Failed to access database path '%s': %s", fs::PathToString(path), e.code().message()));
1344
0
        status = DatabaseStatus::FAILED_BAD_PATH;
1345
0
        return nullptr;
1346
0
    }
1347
1348
1.47k
    std::optional<DatabaseFormat> format;
1349
1.47k
    if (exists) {
1350
832
        if (IsBDBFile(BDBDataFile(path))) {
1351
61
            format = DatabaseFormat::BERKELEY_RO;
1352
61
        }
1353
832
        if (IsSQLiteFile(SQLiteDataFile(path))) {
1354
435
            if (format) {
1355
0
                error = Untranslated(strprintf("Failed to load database path '%s'. Data is in ambiguous format.", fs::PathToString(path)));
1356
0
                status = DatabaseStatus::FAILED_BAD_FORMAT;
1357
0
                return nullptr;
1358
0
            }
1359
435
            format = DatabaseFormat::SQLITE;
1360
435
        }
1361
832
    } else if (options.require_existing) {
1362
3
        error = Untranslated(strprintf("Failed to load database path '%s'. Path does not exist.", fs::PathToString(path)));
1363
3
        status = DatabaseStatus::FAILED_NOT_FOUND;
1364
3
        return nullptr;
1365
3
    }
1366
1367
1.46k
    if (!format && options.require_existing) {
1368
287
        error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in recognized format.", fs::PathToString(path)));
1369
287
        status = DatabaseStatus::FAILED_BAD_FORMAT;
1370
287
        return nullptr;
1371
287
    }
1372
1373
1.18k
    if (format && options.require_create) {
1374
7
        error = Untranslated(strprintf("Failed to create database path '%s'. Database already exists.", fs::PathToString(path)));
1375
7
        status = DatabaseStatus::FAILED_ALREADY_EXISTS;
1376
7
        return nullptr;
1377
7
    }
1378
1379
    // BERKELEY_RO can only be opened if require_format was set, which only occurs in migration.
1380
1.17k
    if (format && format == DatabaseFormat::BERKELEY_RO && (!options.require_format || options.require_format != DatabaseFormat::BERKELEY_RO)) {
1381
9
        error = Untranslated(strprintf("Failed to open database path '%s'. The wallet appears to be a Legacy wallet, please use the wallet migration tool (migratewallet RPC or the GUI option).", fs::PathToString(path)));
1382
9
        status = DatabaseStatus::FAILED_LEGACY_DISABLED;
1383
9
        return nullptr;
1384
9
    }
1385
1386
    // A db already exists so format is set, but options also specifies the format, so make sure they agree
1387
1.16k
    if (format && options.require_format && format != options.require_format) {
1388
0
        error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in required format.", fs::PathToString(path)));
1389
0
        status = DatabaseStatus::FAILED_BAD_FORMAT;
1390
0
        return nullptr;
1391
0
    }
1392
1393
    // Format is not set when a db doesn't already exist, so use the format specified by the options if it is set.
1394
1.16k
    if (!format && options.require_format) format = options.require_format;
1395
1396
1.16k
    if (!format) {
1397
3
        format = DatabaseFormat::SQLITE;
1398
3
    }
1399
1400
1.16k
    if (format == DatabaseFormat::SQLITE) {
1401
1.11k
        return MakeSQLiteDatabase(path, options, status, error);
1402
1.11k
    }
1403
1404
48
    if (format == DatabaseFormat::BERKELEY_RO) {
1405
48
        return MakeBerkeleyRODatabase(path, options, status, error);
1406
48
    }
1407
1408
0
    error = Untranslated(STR_INTERNAL_BUG("Could not determine wallet format"));
1409
0
    status = DatabaseStatus::FAILED_BAD_FORMAT;
1410
0
    return nullptr;
1411
48
}
1412
} // namespace wallet