fuzz coverage

Coverage Report

Created: 2025-08-28 15:26

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