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