Coverage Report

Created: 2026-10-03 10:33

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