Coverage Report

Created: 2026-10-07 13:27

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