fuzz coverage

Coverage Report

Created: 2025-10-29 15:27

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