fuzz coverage

Coverage Report

Created: 2025-06-01 19:34

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