Coverage Report

Created: 2026-08-14 20:23

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
401
{
69
    // Add useful DB information here. This will be printed during startup.
70
401
    LogInfo("Using SQLite Version %s", SQLiteDatabaseVersion());
71
401
}
72
73
//
74
// WalletBatch
75
//
76
77
bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName)
78
28.1k
{
79
28.1k
    return WriteIC(std::make_pair(DBKeys::NAME, strAddress), strName);
80
28.1k
}
81
82
bool WalletBatch::EraseName(const std::string& strAddress)
83
28
{
84
    // This should only be used for sending addresses, never for receiving addresses,
85
    // receiving addresses must always have an address book entry if they're not change return.
86
28
    return EraseIC(std::make_pair(DBKeys::NAME, strAddress));
87
28
}
88
89
bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
90
28.1k
{
91
28.1k
    return WriteIC(std::make_pair(DBKeys::PURPOSE, strAddress), strPurpose);
92
28.1k
}
93
94
bool WalletBatch::ErasePurpose(const std::string& strAddress)
95
28
{
96
28
    return EraseIC(std::make_pair(DBKeys::PURPOSE, strAddress));
97
28
}
98
99
bool WalletBatch::WriteTx(const CWalletTx& wtx)
100
23.5k
{
101
23.5k
    const Txid txid = wtx.GetHash();
102
    // Persist all witness variants. Including the canonical one
103
23.5k
    for (const auto& [wtxid, tx] : wtx.GetTxs()) {
104
23.5k
        if (!WriteWtxVariant(txid, tx)) return false;
105
23.5k
    }
106
23.5k
    return WriteIC(std::make_pair(DBKeys::TX, txid), wtx);
107
23.5k
}
108
109
bool WalletBatch::EraseTx(Txid hash)
110
15
{
111
15
    if (!EraseIC(std::make_pair(DBKeys::TX, hash.ToUint256()))) return false;
112
    // Drop all witness variant records too, so none are left dangling
113
15
    return m_batch->ErasePrefix(DataStream() << DBKeys::WTX_VARIANT << hash);
114
15
}
115
116
bool WalletBatch::WriteWtxVariant(const Txid& txid, const CTransactionRef& tx)
117
23.5k
{
118
23.5k
    return WriteIC(std::make_pair(DBKeys::WTX_VARIANT, std::make_pair(txid, tx->GetWitnessHash())), TX_WITH_WITNESS(tx));
119
23.5k
}
120
121
bool WalletBatch::WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite)
122
60
{
123
60
    return WriteIC(std::make_pair(DBKeys::KEYMETA, pubkey), meta, overwrite);
124
60
}
125
126
bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
127
0
{
128
0
    if (!WriteKeyMetadata(keyMeta, vchPubKey, false)) {
129
0
        return false;
130
0
    }
131
132
    // hash pubkey/privkey to accelerate wallet load
133
0
    const auto keypair_hash = Hash(vchPubKey, vchPrivKey);
134
135
0
    return WriteIC(std::make_pair(DBKeys::KEY, vchPubKey), std::make_pair(vchPrivKey, keypair_hash), false);
136
0
}
137
138
bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey,
139
                                const std::vector<unsigned char>& vchCryptedSecret,
140
                                const CKeyMetadata &keyMeta)
141
60
{
142
60
    if (!WriteKeyMetadata(keyMeta, vchPubKey, true)) {
143
0
        return false;
144
0
    }
145
146
    // Compute a checksum of the encrypted key
147
60
    uint256 checksum = Hash(vchCryptedSecret);
148
149
60
    const auto key = std::make_pair(DBKeys::CRYPTED_KEY, vchPubKey);
150
60
    if (!WriteIC(key, std::make_pair(vchCryptedSecret, checksum), false)) {
151
        // It may already exist, so try writing just the checksum
152
0
        std::vector<unsigned char> val;
153
0
        if (!m_batch->Read(key, val)) {
154
0
            return false;
155
0
        }
156
0
        if (!WriteIC(key, std::make_pair(val, checksum), true)) {
157
0
            return false;
158
0
        }
159
0
    }
160
60
    EraseIC(std::make_pair(DBKeys::KEY, vchPubKey));
161
60
    return true;
162
60
}
163
164
bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
165
27
{
166
27
    return WriteIC(std::make_pair(DBKeys::MASTER_KEY, nID), kMasterKey, true);
167
27
}
168
169
bool WalletBatch::EraseMasterKey(unsigned int id)
170
1
{
171
1
    return EraseIC(std::make_pair(DBKeys::MASTER_KEY, id));
172
1
}
173
174
bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
175
0
{
176
0
    if (!WriteIC(std::make_pair(DBKeys::WATCHMETA, dest), keyMeta)) {
177
0
        return false;
178
0
    }
179
0
    return WriteIC(std::make_pair(DBKeys::WATCHS, dest), uint8_t{'1'});
180
0
}
181
182
bool WalletBatch::WriteBestBlock(const CBlockLocator& locator)
183
12.6k
{
184
12.6k
    WriteIC(DBKeys::BESTBLOCK, CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
185
12.6k
    return WriteIC(DBKeys::BESTBLOCK_NOMERKLE, locator);
186
12.6k
}
187
188
bool WalletBatch::ReadBestBlock(CBlockLocator& locator)
189
1.91k
{
190
1.91k
    if (m_batch->Read(DBKeys::BESTBLOCK, locator) && !locator.vHave.empty()) return true;
191
1.91k
    return m_batch->Read(DBKeys::BESTBLOCK_NOMERKLE, locator);
192
1.91k
}
193
194
bool WalletBatch::IsEncrypted()
195
0
{
196
0
    DataStream prefix;
197
0
    prefix << DBKeys::MASTER_KEY;
198
0
    if (auto cursor = m_batch->GetNewPrefixCursor(prefix)) {
199
0
        DataStream k, v;
200
0
        if (cursor->Next(k, v) == DatabaseCursor::Status::MORE) return true;
201
0
    }
202
0
    return false;
203
0
}
204
205
bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
206
17.4k
{
207
17.4k
    return WriteIC(DBKeys::ORDERPOSNEXT, nOrderPosNext);
208
17.4k
}
209
210
bool WalletBatch::WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal)
211
4.30k
{
212
4.30k
    std::string key = internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK;
213
4.30k
    return WriteIC(make_pair(key, type), id);
214
4.30k
}
215
216
bool WalletBatch::EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
217
1
{
218
1
    const std::string key{internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK};
219
1
    return EraseIC(make_pair(key, type));
220
1
}
221
222
bool WalletBatch::WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey)
223
4.47k
{
224
    // hash pubkey/privkey to accelerate wallet load
225
4.47k
    const auto keypair_hash = Hash(pubkey, privkey);
226
227
4.47k
    return WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)), std::make_pair(privkey, keypair_hash), false);
228
4.47k
}
229
230
bool WalletBatch::WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret)
231
322
{
232
322
    if (!WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORCKEY, std::make_pair(desc_id, pubkey)), secret, false)) {
233
0
        return false;
234
0
    }
235
322
    EraseIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)));
236
322
    return true;
237
322
}
238
239
bool WalletBatch::WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor)
240
98.8k
{
241
98.8k
    return WriteIC(make_pair(DBKeys::WALLETDESCRIPTOR, desc_id), descriptor);
242
98.8k
}
243
244
bool WalletBatch::WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index)
245
24.0k
{
246
24.0k
    std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
247
24.0k
    xpub.Encode(ser_xpub.data());
248
24.0k
    return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), std::make_pair(key_exp_index, der_index)), ser_xpub);
249
24.0k
}
250
251
bool WalletBatch::WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
252
5.34k
{
253
5.34k
    std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
254
5.34k
    xpub.Encode(ser_xpub.data());
255
5.34k
    return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), key_exp_index), ser_xpub);
256
5.34k
}
257
258
bool WalletBatch::WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
259
4.04k
{
260
4.04k
    std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
261
4.04k
    xpub.Encode(ser_xpub.data());
262
4.04k
    return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORLHCACHE, desc_id), key_exp_index), ser_xpub);
263
4.04k
}
264
265
bool WalletBatch::WriteDescriptorCacheItems(const uint256& desc_id, const DescriptorCache& cache)
266
430k
{
267
430k
    for (const auto& parent_xpub_pair : cache.GetCachedParentExtPubKeys()) {
268
5.34k
        if (!WriteDescriptorParentCache(parent_xpub_pair.second, desc_id, parent_xpub_pair.first)) {
269
0
            return false;
270
0
        }
271
5.34k
    }
272
430k
    for (const auto& derived_xpub_map_pair : cache.GetCachedDerivedExtPubKeys()) {
273
24.0k
        for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
274
24.0k
            if (!WriteDescriptorDerivedCache(derived_xpub_pair.second, desc_id, derived_xpub_map_pair.first, derived_xpub_pair.first)) {
275
0
                return false;
276
0
            }
277
24.0k
        }
278
24.0k
    }
279
430k
    for (const auto& lh_xpub_pair : cache.GetCachedLastHardenedExtPubKeys()) {
280
4.04k
        if (!WriteDescriptorLastHardenedCache(lh_xpub_pair.second, desc_id, lh_xpub_pair.first)) {
281
0
            return false;
282
0
        }
283
4.04k
    }
284
430k
    return true;
285
430k
}
286
287
bool WalletBatch::WriteLockedUTXO(const COutPoint& output)
288
3
{
289
3
    return WriteIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)), uint8_t{'1'});
290
3
}
291
292
bool WalletBatch::EraseLockedUTXO(const COutPoint& output)
293
1
{
294
1
    return EraseIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)));
295
1
}
296
297
bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
298
243
{
299
243
    LOCK(pwallet->cs_wallet);
300
243
    try {
301
243
        CPubKey vchPubKey;
302
243
        ssKey >> vchPubKey;
303
243
        if (!vchPubKey.IsValid())
304
0
        {
305
0
            strErr = "Error reading wallet database: CPubKey corrupt";
306
0
            return false;
307
0
        }
308
243
        CKey key;
309
243
        CPrivKey pkey;
310
243
        uint256 hash;
311
312
243
        ssValue >> pkey;
313
314
        // Old wallets store keys as DBKeys::KEY [pubkey] => [privkey]
315
        // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
316
        // using EC operations as a checksum.
317
        // Newer wallets store keys as DBKeys::KEY [pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
318
        // remaining backwards-compatible.
319
243
        try
320
243
        {
321
243
            ssValue >> hash;
322
243
        }
323
243
        catch (const std::ios_base::failure&) {}
324
325
243
        bool fSkipCheck = false;
326
327
243
        if (!hash.IsNull())
328
243
        {
329
            // hash pubkey/privkey to accelerate wallet load
330
243
            const auto keypair_hash = Hash(vchPubKey, pkey);
331
332
243
            if (keypair_hash != hash)
333
0
            {
334
0
                strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
335
0
                return false;
336
0
            }
337
338
243
            fSkipCheck = true;
339
243
        }
340
341
243
        if (!key.Load(pkey, vchPubKey, fSkipCheck))
342
0
        {
343
0
            strErr = "Error reading wallet database: CPrivKey corrupt";
344
0
            return false;
345
0
        }
346
243
        if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadKey(key, vchPubKey))
347
0
        {
348
0
            strErr = "Error reading wallet database: LegacyDataSPKM::LoadKey failed";
349
0
            return false;
350
0
        }
351
243
    } catch (const std::exception& e) {
352
0
        if (strErr.empty()) {
353
0
            strErr = e.what();
354
0
        }
355
0
        return false;
356
0
    }
357
243
    return true;
358
243
}
359
360
bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
361
84
{
362
84
    LOCK(pwallet->cs_wallet);
363
84
    try {
364
84
        CPubKey vchPubKey;
365
84
        ssKey >> vchPubKey;
366
84
        if (!vchPubKey.IsValid())
367
0
        {
368
0
            strErr = "Error reading wallet database: CPubKey corrupt";
369
0
            return false;
370
0
        }
371
84
        std::vector<unsigned char> vchPrivKey;
372
84
        ssValue >> vchPrivKey;
373
374
        // Get the checksum and check it
375
84
        bool checksum_valid = false;
376
84
        if (!ssValue.empty()) {
377
24
            uint256 checksum;
378
24
            ssValue >> checksum;
379
24
            if (!(checksum_valid = Hash(vchPrivKey) == checksum)) {
380
0
                strErr = "Error reading wallet database: Encrypted key corrupt";
381
0
                return false;
382
0
            }
383
24
        }
384
385
84
        if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCryptedKey(vchPubKey, vchPrivKey, checksum_valid))
386
0
        {
387
0
            strErr = "Error reading wallet database: LegacyDataSPKM::LoadCryptedKey failed";
388
0
            return false;
389
0
        }
390
84
    } catch (const std::exception& e) {
391
0
        if (strErr.empty()) {
392
0
            strErr = e.what();
393
0
        }
394
0
        return false;
395
0
    }
396
84
    return true;
397
84
}
398
399
bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
400
22
{
401
22
    LOCK(pwallet->cs_wallet);
402
22
    try {
403
        // Master encryption key is loaded into only the wallet and not any of the ScriptPubKeyMans.
404
22
        unsigned int nID;
405
22
        ssKey >> nID;
406
22
        CMasterKey kMasterKey;
407
22
        ssValue >> kMasterKey;
408
22
        if(pwallet->mapMasterKeys.contains(nID))
409
0
        {
410
0
            strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
411
0
            return false;
412
0
        }
413
22
        pwallet->mapMasterKeys[nID] = kMasterKey;
414
22
        if (pwallet->nMasterKeyMaxID < nID)
415
22
            pwallet->nMasterKeyMaxID = nID;
416
417
22
    } catch (const std::exception& e) {
418
0
        if (strErr.empty()) {
419
0
            strErr = e.what();
420
0
        }
421
0
        return false;
422
0
    }
423
22
    return true;
424
22
}
425
426
bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr)
427
38
{
428
38
    LOCK(pwallet->cs_wallet);
429
38
    try {
430
38
        CHDChain chain;
431
38
        ssValue >> chain;
432
38
        pwallet->GetOrCreateLegacyDataSPKM()->LoadHDChain(chain);
433
38
    } catch (const std::exception& e) {
434
0
        if (strErr.empty()) {
435
0
            strErr = e.what();
436
0
        }
437
0
        return false;
438
0
    }
439
38
    return true;
440
38
}
441
442
static DBErrors LoadWalletFlags(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
443
386
{
444
386
    AssertLockHeld(pwallet->cs_wallet);
445
386
    uint64_t flags;
446
386
    if (batch.Read(DBKeys::FLAGS, flags)) {
447
376
        if (!pwallet->LoadWalletFlags(flags)) {
448
0
            pwallet->WalletLogPrintf("Error reading wallet database: Unknown non-tolerable wallet flags found\n");
449
0
            return DBErrors::TOO_NEW;
450
0
        }
451
        // All wallets must be descriptor wallets unless opened with a bdb_ro db
452
        // bdb_ro is only used for legacy to descriptor migration.
453
376
        if (pwallet->GetDatabase().Format() != "bdb_ro" && !pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
454
0
            return DBErrors::LEGACY_WALLET;
455
0
        }
456
376
    }
457
386
    return DBErrors::LOAD_OK;
458
386
}
459
460
struct LoadResult
461
{
462
    DBErrors m_result{DBErrors::LOAD_OK};
463
    int m_records{0};
464
};
465
466
using LoadFunc = std::function<DBErrors(CWallet* pwallet, DataStream& key, DataStream& value, std::string& err)>;
467
static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, DataStream& prefix, LoadFunc load_func)
468
15.3k
{
469
15.3k
    LoadResult result;
470
15.3k
    DataStream ssKey;
471
15.3k
    DataStream ssValue{};
472
473
15.3k
    Assume(!prefix.empty());
474
15.3k
    std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
475
15.3k
    if (!cursor) {
476
0
        pwallet->WalletLogPrintf("Error getting database cursor for '%s' records\n", key);
477
0
        result.m_result = DBErrors::CORRUPT;
478
0
        return result;
479
0
    }
480
481
42.4k
    while (true) {
482
42.4k
        DatabaseCursor::Status status = cursor->Next(ssKey, ssValue);
483
42.4k
        if (status == DatabaseCursor::Status::DONE) {
484
15.3k
            break;
485
27.1k
        } else if (status == DatabaseCursor::Status::FAIL) {
486
0
            pwallet->WalletLogPrintf("Error reading next '%s' record for wallet database\n", key);
487
0
            result.m_result = DBErrors::CORRUPT;
488
0
            return result;
489
0
        }
490
27.1k
        std::string type;
491
27.1k
        ssKey >> type;
492
27.1k
        assert(type == key);
493
27.1k
        std::string error;
494
27.1k
        DBErrors record_res = load_func(pwallet, ssKey, ssValue, error);
495
27.1k
        if (record_res != DBErrors::LOAD_OK) {
496
4
            pwallet->WalletLogPrintf("%s\n", error);
497
4
        }
498
27.1k
        result.m_result = std::max(result.m_result, record_res);
499
27.1k
        ++result.m_records;
500
27.1k
    }
501
15.3k
    return result;
502
15.3k
}
503
504
static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, LoadFunc load_func)
505
4.36k
{
506
4.36k
    DataStream prefix;
507
4.36k
    prefix << key;
508
4.36k
    return LoadRecords(pwallet, batch, key, prefix, load_func);
509
4.36k
}
510
511
bool HasLegacyRecords(CWallet& wallet)
512
49
{
513
49
    const auto& batch = wallet.GetDatabase().MakeBatch();
514
49
    return HasLegacyRecords(wallet, *batch);
515
49
}
516
517
bool HasLegacyRecords(CWallet& wallet, DatabaseBatch& batch)
518
377
{
519
3.41k
    for (const auto& type : DBKeys::LEGACY_TYPES) {
520
3.41k
        DataStream key;
521
3.41k
        DataStream value{};
522
3.41k
        DataStream prefix;
523
524
3.41k
        prefix << type;
525
3.41k
        std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
526
3.41k
        if (!cursor) {
527
            // Could only happen on a closed db, which means there is an error in the code flow.
528
0
            throw std::runtime_error(strprintf("Error getting database cursor for '%s' records", type));
529
0
        }
530
531
3.41k
        DatabaseCursor::Status status = cursor->Next(key, value);
532
3.41k
        if (status != DatabaseCursor::Status::DONE) {
533
47
            return true;
534
47
        }
535
3.41k
    }
536
330
    return false;
537
377
}
538
539
static DBErrors LoadLegacyWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
540
386
{
541
386
    AssertLockHeld(pwallet->cs_wallet);
542
386
    DBErrors result = DBErrors::LOAD_OK;
543
544
    // Make sure descriptor wallets don't have any legacy records
545
386
    if (pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
546
328
        if (HasLegacyRecords(*pwallet, batch)) {
547
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());
548
1
            return DBErrors::UNEXPECTED_LEGACY_ENTRY;
549
1
        }
550
551
327
        return DBErrors::LOAD_OK;
552
328
    }
553
554
    // Load HD Chain
555
    // Note: There should only be one HDCHAIN record with no data following the type
556
58
    LoadResult hd_chain_res = LoadRecords(pwallet, batch, DBKeys::HDCHAIN,
557
58
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
558
38
        return LoadHDChain(pwallet, value, err) ? DBErrors:: LOAD_OK : DBErrors::CORRUPT;
559
38
    });
560
58
    result = std::max(result, hd_chain_res.m_result);
561
562
    // Load unencrypted keys
563
58
    LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::KEY,
564
243
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
565
243
        return LoadKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
566
243
    });
567
58
    result = std::max(result, key_res.m_result);
568
569
    // Load encrypted keys
570
58
    LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::CRYPTED_KEY,
571
84
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
572
84
        return LoadCryptedKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
573
84
    });
574
58
    result = std::max(result, ckey_res.m_result);
575
576
    // Load scripts
577
58
    LoadResult script_res = LoadRecords(pwallet, batch, DBKeys::CSCRIPT,
578
90
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
579
90
        uint160 hash;
580
90
        key >> hash;
581
90
        CScript script;
582
90
        value >> script;
583
90
        if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCScript(script))
584
0
        {
585
0
            strErr = "Error reading wallet database: LegacyDataSPKM::LoadCScript failed";
586
0
            return DBErrors::NONCRITICAL_ERROR;
587
0
        }
588
90
        return DBErrors::LOAD_OK;
589
90
    });
590
58
    result = std::max(result, script_res.m_result);
591
592
    // Load keymeta
593
58
    std::map<uint160, CHDChain> hd_chains;
594
58
    LoadResult keymeta_res = LoadRecords(pwallet, batch, DBKeys::KEYMETA,
595
331
        [&hd_chains] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
596
331
        CPubKey vchPubKey;
597
331
        key >> vchPubKey;
598
331
        CKeyMetadata keyMeta;
599
331
        value >> keyMeta;
600
331
        pwallet->GetOrCreateLegacyDataSPKM()->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
601
602
        // Extract some CHDChain info from this metadata if it has any
603
331
        if (keyMeta.nVersion >= CKeyMetadata::VERSION_WITH_HDDATA && !keyMeta.hd_seed_id.IsNull() && keyMeta.hdKeypath.size() > 0) {
604
            // Get the path from the key origin or from the path string
605
            // Not applicable when path is "s" or "m" as those indicate a seed
606
            // See https://github.com/bitcoin/bitcoin/pull/12924
607
274
            bool internal = false;
608
274
            uint32_t index = 0;
609
274
            if (keyMeta.hdKeypath != "s" && keyMeta.hdKeypath != "m") {
610
229
                std::vector<uint32_t> path;
611
229
                if (keyMeta.has_key_origin) {
612
                    // We have a key origin, so pull it from its path vector
613
181
                    path = keyMeta.key_origin.path;
614
181
                } else {
615
                    // No key origin, have to parse the string
616
48
                    if (!ParseHDKeypath(keyMeta.hdKeypath, path)) {
617
0
                        strErr = "Error reading wallet database: keymeta with invalid HD keypath";
618
0
                        return DBErrors::NONCRITICAL_ERROR;
619
0
                    }
620
48
                }
621
622
                // Extract the index and internal from the path
623
                // Path string is m/0'/k'/i'
624
                // Path vector is [0', k', i'] (but as ints OR'd with the hardened bit
625
                // k == 0 for external, 1 for internal. i is the index
626
229
                if (path.size() != 3) {
627
1
                    strErr = "Error reading wallet database: keymeta found with unexpected path";
628
1
                    return DBErrors::NONCRITICAL_ERROR;
629
1
                }
630
228
                if (path[0] != 0x80000000) {
631
0
                    strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
632
0
                    return DBErrors::NONCRITICAL_ERROR;
633
0
                }
634
228
                if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
635
0
                    strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
636
0
                    return DBErrors::NONCRITICAL_ERROR;
637
0
                }
638
228
                if ((path[2] & 0x80000000) == 0) {
639
0
                    strErr = strprintf("Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
640
0
                    return DBErrors::NONCRITICAL_ERROR;
641
0
                }
642
228
                internal = path[1] == (1 | 0x80000000);
643
228
                index = path[2] & ~0x80000000;
644
228
            }
645
646
            // Insert a new CHDChain, or get the one that already exists
647
273
            auto [ins, inserted] = hd_chains.emplace(keyMeta.hd_seed_id, CHDChain());
648
273
            CHDChain& chain = ins->second;
649
273
            if (inserted) {
650
                // For new chains, we want to default to VERSION_HD_BASE until we see an internal
651
45
                chain.nVersion = CHDChain::VERSION_HD_BASE;
652
45
                chain.seed_id = keyMeta.hd_seed_id;
653
45
            }
654
273
            if (internal) {
655
75
                chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
656
75
                chain.nInternalChainCounter = std::max(chain.nInternalChainCounter, index + 1);
657
198
            } else {
658
198
                chain.nExternalChainCounter = std::max(chain.nExternalChainCounter, index + 1);
659
198
            }
660
273
        }
661
330
        return DBErrors::LOAD_OK;
662
331
    });
663
58
    result = std::max(result, keymeta_res.m_result);
664
665
    // Set inactive chains
666
58
    if (!hd_chains.empty()) {
667
38
        LegacyDataSPKM* legacy_spkm = pwallet->GetLegacyDataSPKM();
668
38
        if (legacy_spkm) {
669
45
            for (const auto& [hd_seed_id, chain] : hd_chains) {
670
45
                if (hd_seed_id != legacy_spkm->GetHDChain().seed_id) {
671
7
                    legacy_spkm->AddInactiveHDChain(chain);
672
7
                }
673
45
            }
674
38
        } else {
675
0
            pwallet->WalletLogPrintf("Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
676
0
            result = DBErrors::CORRUPT;
677
0
        }
678
38
    }
679
680
    // Load watchonly scripts
681
58
    LoadResult watch_script_res = LoadRecords(pwallet, batch, DBKeys::WATCHS,
682
58
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
683
49
        CScript script;
684
49
        key >> script;
685
49
        uint8_t fYes;
686
49
        value >> fYes;
687
49
        if (fYes == '1') {
688
49
            pwallet->GetOrCreateLegacyDataSPKM()->LoadWatchOnly(script);
689
49
        }
690
49
        return DBErrors::LOAD_OK;
691
49
    });
692
58
    result = std::max(result, watch_script_res.m_result);
693
694
    // Load watchonly meta
695
58
    LoadResult watch_meta_res = LoadRecords(pwallet, batch, DBKeys::WATCHMETA,
696
58
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
697
49
        CScript script;
698
49
        key >> script;
699
49
        CKeyMetadata keyMeta;
700
49
        value >> keyMeta;
701
49
        pwallet->GetOrCreateLegacyDataSPKM()->LoadScriptMetadata(CScriptID(script), keyMeta);
702
49
        return DBErrors::LOAD_OK;
703
49
    });
704
58
    result = std::max(result, watch_meta_res.m_result);
705
706
    // Deal with old "wkey" and "defaultkey" records.
707
    // These are not actually loaded, but we need to check for them
708
709
    // We don't want or need the default key, but if there is one set,
710
    // we want to make sure that it is valid so that we can detect corruption
711
    // Note: There should only be one DEFAULTKEY with nothing trailing the type
712
58
    LoadResult default_key_res = LoadRecords(pwallet, batch, DBKeys::DEFAULTKEY,
713
58
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
714
4
        CPubKey default_pubkey;
715
4
        try {
716
4
            value >> default_pubkey;
717
4
        } catch (const std::exception& e) {
718
0
            err = e.what();
719
0
            return DBErrors::CORRUPT;
720
0
        }
721
4
        if (!default_pubkey.IsValid()) {
722
0
            err = "Error reading wallet database: Default Key corrupt";
723
0
            return DBErrors::CORRUPT;
724
0
        }
725
4
        return DBErrors::LOAD_OK;
726
4
    });
727
58
    result = std::max(result, default_key_res.m_result);
728
729
    // "wkey" records are unsupported, if we see any, throw an error
730
58
    LoadResult wkey_res = LoadRecords(pwallet, batch, DBKeys::OLD_KEY,
731
58
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
732
0
        err = "Found unsupported 'wkey' record, try loading with version 0.18";
733
0
        return DBErrors::LOAD_FAIL;
734
0
    });
735
58
    result = std::max(result, wkey_res.m_result);
736
737
58
    if (result <= DBErrors::NONCRITICAL_ERROR) {
738
        // Only do logging and time first key update if there were no critical errors
739
58
        pwallet->WalletLogPrintf("Legacy Wallet Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total.\n",
740
58
               key_res.m_records, ckey_res.m_records, keymeta_res.m_records, key_res.m_records + ckey_res.m_records);
741
58
    }
742
743
58
    return result;
744
386
}
745
746
template<typename... Args>
747
static DataStream PrefixStream(const Args&... args)
748
10.9k
{
749
10.9k
    DataStream prefix;
750
10.9k
    SerializeMany(prefix, args...);
751
10.9k
    return prefix;
752
10.9k
}
753
754
static DBErrors LoadDescriptorWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
755
386
{
756
386
    AssertLockHeld(pwallet->cs_wallet);
757
758
    // Load descriptor record
759
386
    int num_keys = 0;
760
386
    int num_ckeys= 0;
761
386
    LoadResult desc_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTOR,
762
2.75k
        [&batch, &num_keys, &num_ckeys, &last_client] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
763
2.75k
        DBErrors result = DBErrors::LOAD_OK;
764
765
2.75k
        uint256 id;
766
2.75k
        key >> id;
767
2.75k
        WalletDescriptor desc;
768
2.75k
        try {
769
2.75k
            value >> desc;
770
2.75k
        } catch (const std::ios_base::failure& e) {
771
1
            strErr = strprintf("Error: Unrecognized descriptor found in wallet %s. ", pwallet->GetName());
772
1
            strErr += (last_client > CLIENT_VERSION) ? "The wallet might have been created on a newer version. " :
773
1
                    "The database might be corrupted or the software version is not compatible with one of your wallet descriptors. ";
774
1
            strErr += "Please try running the latest software version";
775
            // Also include error details
776
1
            strErr = strprintf("%s\nDetails: %s", strErr, e.what());
777
1
            return DBErrors::UNKNOWN_DESCRIPTOR;
778
1
        }
779
780
2.74k
        if (id != desc.id) {
781
1
            strErr = "The descriptor ID calculated by the wallet differs from the one in DB";
782
1
            return DBErrors::CORRUPT;
783
1
        }
784
785
2.74k
        DescriptorCache cache;
786
787
        // Get key cache for this descriptor
788
2.74k
        DataStream prefix = PrefixStream(DBKeys::WALLETDESCRIPTORCACHE, id);
789
2.74k
        LoadResult key_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCACHE, prefix,
790
2.74k
            [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
791
2.62k
            bool parent = true;
792
2.62k
            uint256 desc_id;
793
2.62k
            uint32_t key_exp_index;
794
2.62k
            uint32_t der_index;
795
2.62k
            key >> desc_id;
796
2.62k
            assert(desc_id == id);
797
2.62k
            key >> key_exp_index;
798
799
            // if the der_index exists, it's a derived xpub
800
2.62k
            try
801
2.62k
            {
802
2.62k
                key >> der_index;
803
2.62k
                parent = false;
804
2.62k
            }
805
2.62k
            catch (...) {}
806
807
2.62k
            std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
808
2.62k
            value >> ser_xpub;
809
2.62k
            CExtPubKey xpub;
810
2.62k
            xpub.Decode(ser_xpub.data());
811
2.62k
            if (parent) {
812
2.38k
                cache.CacheParentExtPubKey(key_exp_index, xpub);
813
2.38k
            } else {
814
247
                cache.CacheDerivedExtPubKey(key_exp_index, der_index, xpub);
815
247
            }
816
2.62k
            return DBErrors::LOAD_OK;
817
2.62k
        });
818
2.74k
        result = std::max(result, key_cache_res.m_result);
819
820
        // Get last hardened cache for this descriptor
821
2.74k
        prefix = PrefixStream(DBKeys::WALLETDESCRIPTORLHCACHE, id);
822
2.74k
        LoadResult lh_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORLHCACHE, prefix,
823
2.74k
            [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
824
2.28k
            uint256 desc_id;
825
2.28k
            uint32_t key_exp_index;
826
2.28k
            key >> desc_id;
827
2.28k
            assert(desc_id == id);
828
2.28k
            key >> key_exp_index;
829
830
2.28k
            std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
831
2.28k
            value >> ser_xpub;
832
2.28k
            CExtPubKey xpub;
833
2.28k
            xpub.Decode(ser_xpub.data());
834
2.28k
            cache.CacheLastHardenedExtPubKey(key_exp_index, xpub);
835
2.28k
            return DBErrors::LOAD_OK;
836
2.28k
        });
837
2.74k
        result = std::max(result, lh_cache_res.m_result);
838
839
        // Set the cache to the WalletDescriptor
840
2.74k
        desc.cache = cache;
841
842
        // Get unencrypted keys
843
2.74k
        KeyMap keys;
844
2.74k
        prefix = PrefixStream(DBKeys::WALLETDESCRIPTORKEY, id);
845
2.74k
        LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORKEY, prefix,
846
2.74k
            [&id, &keys] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
847
2.32k
            uint256 desc_id;
848
2.32k
            CPubKey pubkey;
849
2.32k
            key >> desc_id;
850
2.32k
            assert(desc_id == id);
851
2.32k
            key >> pubkey;
852
2.32k
            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.32k
            CKey privkey;
858
2.32k
            CPrivKey pkey;
859
2.32k
            uint256 hash;
860
861
2.32k
            value >> pkey;
862
2.32k
            value >> hash;
863
864
            // hash pubkey/privkey to accelerate wallet load
865
2.32k
            const auto keypair_hash = Hash(pubkey, pkey);
866
867
2.32k
            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.32k
            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.32k
            keys[pubkey.GetID()] = privkey;
879
2.32k
            return DBErrors::LOAD_OK;
880
2.32k
        });
881
2.74k
        result = std::max(result, key_res.m_result);
882
2.74k
        num_keys = key_res.m_records;
883
884
        // Get encrypted keys
885
2.74k
        CryptedKeyMap ckeys;
886
2.74k
        prefix = PrefixStream(DBKeys::WALLETDESCRIPTORCKEY, id);
887
2.74k
        LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCKEY, prefix,
888
2.74k
            [&id, &ckeys] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
889
267
            uint256 desc_id;
890
267
            CPubKey pubkey;
891
267
            key >> desc_id;
892
267
            assert(desc_id == id);
893
267
            key >> pubkey;
894
267
            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
267
            std::vector<unsigned char> privkey;
900
267
            value >> privkey;
901
902
267
            ckeys[pubkey.GetID()] = std::make_pair(pubkey, privkey);
903
267
            return DBErrors::LOAD_OK;
904
267
        });
905
2.74k
        result = std::max(result, ckey_res.m_result);
906
2.74k
        num_ckeys = ckey_res.m_records;
907
908
2.74k
        try {
909
2.74k
            pwallet->LoadDescriptorScriptPubKeyMan(id, desc, keys, ckeys);
910
2.74k
        } catch (std::runtime_error& e) {
911
1
            strErr = e.what();
912
1
            return DBErrors::CORRUPT;
913
1
        }
914
915
2.74k
        return result;
916
2.74k
    });
917
918
386
    if (desc_res.m_result <= DBErrors::NONCRITICAL_ERROR) {
919
        // Only log if there are no critical errors
920
383
        pwallet->WalletLogPrintf("Descriptors: %u, Descriptor Keys: %u plaintext, %u encrypted, %u total.\n",
921
383
               desc_res.m_records, num_keys, num_ckeys, num_keys + num_ckeys);
922
383
    }
923
924
386
    return desc_res.m_result;
925
386
}
926
927
static DBErrors LoadAddressBookRecords(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
928
385
{
929
385
    AssertLockHeld(pwallet->cs_wallet);
930
385
    DBErrors result = DBErrors::LOAD_OK;
931
932
    // Load name record
933
385
    LoadResult name_res = LoadRecords(pwallet, batch, DBKeys::NAME,
934
2.28k
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
935
2.28k
        std::string strAddress;
936
2.28k
        key >> strAddress;
937
2.28k
        std::string label;
938
2.28k
        value >> label;
939
2.28k
        pwallet->m_address_book[DecodeDestination(strAddress)].SetLabel(label);
940
2.28k
        return DBErrors::LOAD_OK;
941
2.28k
    });
942
385
    result = std::max(result, name_res.m_result);
943
944
    // Load purpose record
945
385
    LoadResult purpose_res = LoadRecords(pwallet, batch, DBKeys::PURPOSE,
946
2.28k
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
947
2.28k
        std::string strAddress;
948
2.28k
        key >> strAddress;
949
2.28k
        std::string purpose_str;
950
2.28k
        value >> purpose_str;
951
2.28k
        std::optional<AddressPurpose> purpose{PurposeFromString(purpose_str)};
952
2.28k
        if (!purpose) {
953
0
            pwallet->WalletLogPrintf("Warning: nonstandard purpose string '%s' for address '%s'\n", purpose_str, strAddress);
954
0
        }
955
2.28k
        pwallet->m_address_book[DecodeDestination(strAddress)].purpose = purpose;
956
2.28k
        return DBErrors::LOAD_OK;
957
2.28k
    });
958
385
    result = std::max(result, purpose_res.m_result);
959
960
    // Load destination data record
961
385
    LoadResult dest_res = LoadRecords(pwallet, batch, DBKeys::DESTDATA,
962
385
        [] (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
385
    result = std::max(result, dest_res.m_result);
984
985
385
    return result;
986
385
}
987
988
static std::map<Wtxid, CTransactionRef> ReadWtxVariants(DatabaseBatch& batch, const Txid& txid)
989
8.89k
{
990
8.89k
    std::map<Wtxid, CTransactionRef> variants;
991
992
8.89k
    DataStream prefix;
993
8.89k
    prefix << DBKeys::WTX_VARIANT << txid;
994
8.89k
    std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
995
8.89k
    if (!cursor) {
996
0
        throw std::runtime_error(strprintf("Error getting database cursor for '%s' records", DBKeys::WTX_VARIANT));
997
0
    }
998
999
8.89k
    DataStream key;
1000
8.89k
    DataStream value;
1001
17.3k
    while (true) {
1002
17.3k
        DatabaseCursor::Status status = cursor->Next(key, value);
1003
17.3k
        if (status == DatabaseCursor::Status::DONE) break;
1004
8.41k
        if (status == DatabaseCursor::Status::FAIL) {
1005
0
            throw std::runtime_error(strprintf("Error reading '%s' record", DBKeys::WTX_VARIANT));
1006
0
        }
1007
8.41k
        CTransactionRef tx;
1008
8.41k
        value >> TX_WITH_WITNESS(tx);
1009
8.41k
        if (tx->GetHash() != txid) {
1010
0
            throw std::runtime_error(strprintf("Corrupted witness variant, tx hash differs"));
1011
0
        }
1012
8.41k
        if (!variants.emplace(tx->GetWitnessHash(), std::move(tx)).second) {
1013
0
            throw std::runtime_error(strprintf("Duplicate witness variant"));
1014
0
        }
1015
8.41k
    }
1016
8.89k
    return variants;
1017
8.89k
}
1018
1019
static DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch, bool& any_unordered) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1020
384
{
1021
384
    AssertLockHeld(pwallet->cs_wallet);
1022
384
    DBErrors result = DBErrors::LOAD_OK;
1023
1024
    // Load tx record
1025
384
    any_unordered = false;
1026
384
    LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,
1027
8.89k
        [&any_unordered, &batch] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1028
8.89k
        DBErrors result = DBErrors::LOAD_OK;
1029
8.89k
        Txid hash;
1030
8.89k
        key >> hash;
1031
8.89k
        try {
1032
8.89k
            CWalletTx wtx{deserialize, value, ReadWtxVariants(batch, hash)};
1033
8.89k
            if (wtx.GetHash() != hash) {
1034
0
                result = std::max(result, DBErrors::NEED_RESCAN);
1035
0
            }
1036
1037
8.89k
            if (wtx.nOrderPos == -1) {
1038
0
                any_unordered = true;
1039
0
            }
1040
1041
8.89k
            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
8.89k
        } 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
8.89k
        return result;
1050
8.89k
    });
1051
384
    result = std::max(result, tx_res.m_result);
1052
1053
    // Load locked utxo record
1054
384
    LoadResult locked_utxo_res = LoadRecords(pwallet, batch, DBKeys::LOCKED_UTXO,
1055
384
        [] (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
384
    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
384
    LoadResult order_pos_res = LoadRecords(pwallet, batch, DBKeys::ORDERPOSNEXT,
1068
384
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1069
210
        try {
1070
210
            value >> pwallet->nOrderPosNext;
1071
210
        } catch (const std::exception& e) {
1072
0
            err = e.what();
1073
0
            return DBErrors::NONCRITICAL_ERROR;
1074
0
        }
1075
210
        return DBErrors::LOAD_OK;
1076
210
    });
1077
384
    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
8.89k
    for (auto& [id, wtx] : pwallet->mapWallet) {
1082
8.89k
        if (wtx.IsCoinBase() && wtx.isInactive()) {
1083
432
            pwallet->AbandonTransaction(wtx);
1084
432
        }
1085
8.89k
    }
1086
1087
384
    return result;
1088
384
}
1089
1090
static DBErrors LoadActiveSPKMs(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1091
385
{
1092
385
    AssertLockHeld(pwallet->cs_wallet);
1093
385
    DBErrors result = DBErrors::LOAD_OK;
1094
1095
    // Load spk records
1096
385
    std::set<std::pair<OutputType, bool>> seen_spks;
1097
769
    for (const auto& spk_key : {DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK}) {
1098
769
        LoadResult spkm_res = LoadRecords(pwallet, batch, spk_key,
1099
2.25k
            [&seen_spks, &spk_key] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
1100
2.25k
            uint8_t output_type;
1101
2.25k
            key >> output_type;
1102
2.25k
            uint256 id;
1103
2.25k
            value >> id;
1104
1105
2.25k
            bool internal = spk_key == DBKeys::ACTIVEINTERNALSPK;
1106
2.25k
            auto [it, insert] = seen_spks.emplace(static_cast<OutputType>(output_type), internal);
1107
2.25k
            if (!insert) {
1108
0
                strErr = "Multiple ScriptpubKeyMans specified for a single type";
1109
0
                return DBErrors::CORRUPT;
1110
0
            }
1111
2.25k
            pwallet->LoadActiveScriptPubKeyMan(id, static_cast<OutputType>(output_type), /*internal=*/internal);
1112
2.25k
            return DBErrors::LOAD_OK;
1113
2.25k
        });
1114
769
        result = std::max(result, spkm_res.m_result);
1115
769
    }
1116
385
    return result;
1117
385
}
1118
1119
static DBErrors LoadDecryptionKeys(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1120
384
{
1121
384
    AssertLockHeld(pwallet->cs_wallet);
1122
1123
    // Load decryption key (mkey) records
1124
384
    LoadResult mkey_res = LoadRecords(pwallet, batch, DBKeys::MASTER_KEY,
1125
384
        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
1126
22
        if (!LoadEncryptionKey(pwallet, key, value, err)) {
1127
0
            return DBErrors::CORRUPT;
1128
0
        }
1129
22
        return DBErrors::LOAD_OK;
1130
22
    });
1131
384
    return mkey_res.m_result;
1132
384
}
1133
1134
DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
1135
386
{
1136
386
    DBErrors result = DBErrors::LOAD_OK;
1137
386
    bool any_unordered = false;
1138
1139
386
    LOCK(pwallet->cs_wallet);
1140
1141
    // Last client version to open this wallet
1142
386
    int last_client = CLIENT_VERSION;
1143
386
    bool has_last_client = m_batch->Read(DBKeys::VERSION, last_client);
1144
386
    if (has_last_client) pwallet->WalletLogPrintf("Last client version = %d\n", last_client);
1145
1146
386
    try {
1147
        // Load wallet flags, so they are known when processing other records.
1148
        // The FLAGS key is absent during wallet creation.
1149
386
        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
386
        result = std::max(LoadLegacyWalletRecords(pwallet, *m_batch, last_client), result);
1160
1161
        // Load descriptors
1162
386
        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
386
        if (result == DBErrors::UNKNOWN_DESCRIPTOR) return result;
1167
1168
        // Load address book
1169
385
        result = std::max(LoadAddressBookRecords(pwallet, *m_batch), result);
1170
1171
        // Load SPKMs
1172
385
        result = std::max(LoadActiveSPKMs(pwallet, *m_batch), result);
1173
1174
        // Load decryption keys
1175
385
        result = std::max(LoadDecryptionKeys(pwallet, *m_batch), result);
1176
1177
        // Load tx records
1178
385
        result = std::max(LoadTxRecords(pwallet, *m_batch, any_unordered), result);
1179
385
    } 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
385
    if (result != DBErrors::LOAD_OK)
1194
4
        return result;
1195
1196
381
    if (!has_last_client || last_client != CLIENT_VERSION) // Update
1197
105
        this->WriteVersion(CLIENT_VERSION);
1198
1199
381
    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
381
    try {
1205
381
        pwallet->UpgradeDescriptorCache();
1206
381
    } 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
381
    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
381
    return result;
1226
381
}
1227
1228
static bool RunWithinTxn(WalletBatch& batch, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1229
491
{
1230
491
    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
491
    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
490
    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
490
    return true;
1249
490
}
1250
1251
bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1252
491
{
1253
491
    WalletBatch batch(database);
1254
491
    return RunWithinTxn(batch, process_desc, func);
1255
491
}
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.62k
{
1282
4.62k
    return WriteIC(DBKeys::FLAGS, flags);
1283
4.62k
}
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
70.2k
{
1294
70.2k
    return m_batch->TxnBegin();
1295
70.2k
}
1296
1297
bool WalletBatch::TxnCommit()
1298
70.2k
{
1299
70.2k
    bool res = m_batch->TxnCommit();
1300
70.2k
    if (res) {
1301
70.2k
        for (const auto& listener : m_txn_listeners) {
1302
10
            listener.on_commit();
1303
10
        }
1304
        // txn finished, clear listeners
1305
70.2k
        m_txn_listeners.clear();
1306
70.2k
    }
1307
70.2k
    return res;
1308
70.2k
}
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.48k
{
1331
1.48k
    bool exists;
1332
1.48k
    try {
1333
1.48k
        exists = fs::symlink_status(path).type() != fs::file_type::not_found;
1334
1.48k
    } 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.48k
    std::optional<DatabaseFormat> format;
1341
1.48k
    if (exists) {
1342
848
        if (IsBDBFile(BDBDataFile(path))) {
1343
65
            format = DatabaseFormat::BERKELEY_RO;
1344
65
        }
1345
848
        if (IsSQLiteFile(SQLiteDataFile(path))) {
1346
439
            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
439
            format = DatabaseFormat::SQLITE;
1352
439
        }
1353
848
    } 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.48k
    if (!format && options.require_existing) {
1360
291
        error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in recognized format.", fs::PathToString(path)));
1361
291
        status = DatabaseStatus::FAILED_BAD_FORMAT;
1362
291
        return nullptr;
1363
291
    }
1364
1365
1.19k
    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.18k
    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.17k
    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.17k
    if (!format && options.require_format) format = options.require_format;
1387
1388
1.17k
    if (!format) {
1389
3
        format = DatabaseFormat::SQLITE;
1390
3
    }
1391
1392
1.17k
    if (format == DatabaseFormat::SQLITE) {
1393
1.12k
        return MakeSQLiteDatabase(path, options, status, error);
1394
1.12k
    }
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