Coverage Report

Created: 2026-05-30 09:47

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