Coverage Report

Created: 2026-09-14 20:36

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