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