Bitcoin Core 29.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#include <wallet/migrate.h>
22#include <wallet/sqlite.h>
23#include <wallet/wallet.h>
24
25#include <atomic>
26#include <optional>
27#include <string>
28
29namespace wallet {
30namespace DBKeys {
31const std::string ACENTRY{"acentry"};
32const std::string ACTIVEEXTERNALSPK{"activeexternalspk"};
33const std::string ACTIVEINTERNALSPK{"activeinternalspk"};
34const std::string BESTBLOCK_NOMERKLE{"bestblock_nomerkle"};
35const std::string BESTBLOCK{"bestblock"};
36const std::string CRYPTED_KEY{"ckey"};
37const std::string CSCRIPT{"cscript"};
38const std::string DEFAULTKEY{"defaultkey"};
39const std::string DESTDATA{"destdata"};
40const std::string FLAGS{"flags"};
41const std::string HDCHAIN{"hdchain"};
42const std::string KEYMETA{"keymeta"};
43const std::string KEY{"key"};
44const std::string LOCKED_UTXO{"lockedutxo"};
45const std::string MASTER_KEY{"mkey"};
46const std::string MINVERSION{"minversion"};
47const std::string NAME{"name"};
48const std::string OLD_KEY{"wkey"};
49const std::string ORDERPOSNEXT{"orderposnext"};
50const std::string POOL{"pool"};
51const std::string PURPOSE{"purpose"};
52const std::string SETTINGS{"settings"};
53const std::string TX{"tx"};
54const std::string VERSION{"version"};
55const std::string WALLETDESCRIPTOR{"walletdescriptor"};
56const std::string WALLETDESCRIPTORCACHE{"walletdescriptorcache"};
57const std::string WALLETDESCRIPTORLHCACHE{"walletdescriptorlhcache"};
58const std::string WALLETDESCRIPTORCKEY{"walletdescriptorckey"};
59const std::string WALLETDESCRIPTORKEY{"walletdescriptorkey"};
60const std::string WATCHMETA{"watchmeta"};
61const std::string WATCHS{"watchs"};
62const std::unordered_set<std::string> LEGACY_TYPES{CRYPTED_KEY, CSCRIPT, DEFAULTKEY, HDCHAIN, KEYMETA, KEY, OLD_KEY, POOL, WATCHMETA, WATCHS};
63} // namespace DBKeys
64
65//
66// WalletBatch
67//
68
69bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName)
70{
71 return WriteIC(std::make_pair(DBKeys::NAME, strAddress), strName);
72}
73
74bool WalletBatch::EraseName(const std::string& strAddress)
75{
76 // This should only be used for sending addresses, never for receiving addresses,
77 // receiving addresses must always have an address book entry if they're not change return.
78 return EraseIC(std::make_pair(DBKeys::NAME, strAddress));
79}
80
81bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
82{
83 return WriteIC(std::make_pair(DBKeys::PURPOSE, strAddress), strPurpose);
84}
85
86bool WalletBatch::ErasePurpose(const std::string& strAddress)
87{
88 return EraseIC(std::make_pair(DBKeys::PURPOSE, strAddress));
89}
90
92{
93 return WriteIC(std::make_pair(DBKeys::TX, wtx.GetHash()), wtx);
94}
95
97{
98 return EraseIC(std::make_pair(DBKeys::TX, hash));
99}
100
101bool WalletBatch::WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite)
102{
103 return WriteIC(std::make_pair(DBKeys::KEYMETA, pubkey), meta, overwrite);
104}
105
106bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
107{
108 if (!WriteKeyMetadata(keyMeta, vchPubKey, false)) {
109 return false;
110 }
111
112 // hash pubkey/privkey to accelerate wallet load
113 std::vector<unsigned char> vchKey;
114 vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
115 vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
116 vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
117
118 return WriteIC(std::make_pair(DBKeys::KEY, vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey)), false);
119}
120
122 const std::vector<unsigned char>& vchCryptedSecret,
123 const CKeyMetadata &keyMeta)
124{
125 if (!WriteKeyMetadata(keyMeta, vchPubKey, true)) {
126 return false;
127 }
128
129 // Compute a checksum of the encrypted key
130 uint256 checksum = Hash(vchCryptedSecret);
131
132 const auto key = std::make_pair(DBKeys::CRYPTED_KEY, vchPubKey);
133 if (!WriteIC(key, std::make_pair(vchCryptedSecret, checksum), false)) {
134 // It may already exist, so try writing just the checksum
135 std::vector<unsigned char> val;
136 if (!m_batch->Read(key, val)) {
137 return false;
138 }
139 if (!WriteIC(key, std::make_pair(val, checksum), true)) {
140 return false;
141 }
142 }
143 EraseIC(std::make_pair(DBKeys::KEY, vchPubKey));
144 return true;
145}
146
147bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
148{
149 return WriteIC(std::make_pair(DBKeys::MASTER_KEY, nID), kMasterKey, true);
150}
151
152bool WalletBatch::EraseMasterKey(unsigned int id)
153{
154 return EraseIC(std::make_pair(DBKeys::MASTER_KEY, id));
155}
156
157bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
158{
159 if (!WriteIC(std::make_pair(DBKeys::WATCHMETA, dest), keyMeta)) {
160 return false;
161 }
162 return WriteIC(std::make_pair(DBKeys::WATCHS, dest), uint8_t{'1'});
163}
164
166{
167 if (!EraseIC(std::make_pair(DBKeys::WATCHMETA, dest))) {
168 return false;
169 }
170 return EraseIC(std::make_pair(DBKeys::WATCHS, dest));
171}
172
174{
175 WriteIC(DBKeys::BESTBLOCK, CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
176 return WriteIC(DBKeys::BESTBLOCK_NOMERKLE, locator);
177}
178
180{
181 if (m_batch->Read(DBKeys::BESTBLOCK, locator) && !locator.vHave.empty()) return true;
182 return m_batch->Read(DBKeys::BESTBLOCK_NOMERKLE, locator);
183}
184
186{
189 if (auto cursor = m_batch->GetNewPrefixCursor(prefix)) {
190 DataStream k, v;
191 if (cursor->Next(k, v) == DatabaseCursor::Status::MORE) return true;
192 }
193 return false;
194}
195
196bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
197{
198 return WriteIC(DBKeys::ORDERPOSNEXT, nOrderPosNext);
199}
200
202{
203 return WriteIC(DBKeys::MINVERSION, nVersion);
204}
205
206bool WalletBatch::WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal)
207{
208 std::string key = internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK;
209 return WriteIC(make_pair(key, type), id);
210}
211
212bool WalletBatch::EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
213{
214 const std::string key{internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK};
215 return EraseIC(make_pair(key, type));
216}
217
218bool WalletBatch::WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey)
219{
220 // hash pubkey/privkey to accelerate wallet load
221 std::vector<unsigned char> key;
222 key.reserve(pubkey.size() + privkey.size());
223 key.insert(key.end(), pubkey.begin(), pubkey.end());
224 key.insert(key.end(), privkey.begin(), privkey.end());
225
226 return WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)), std::make_pair(privkey, Hash(key)), false);
227}
228
229bool WalletBatch::WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret)
230{
231 if (!WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORCKEY, std::make_pair(desc_id, pubkey)), secret, false)) {
232 return false;
233 }
234 EraseIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)));
235 return true;
236}
237
238bool WalletBatch::WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor)
239{
240 return WriteIC(make_pair(DBKeys::WALLETDESCRIPTOR, desc_id), descriptor);
241}
242
243bool WalletBatch::WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index)
244{
245 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
246 xpub.Encode(ser_xpub.data());
247 return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), std::make_pair(key_exp_index, der_index)), ser_xpub);
248}
249
250bool WalletBatch::WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
251{
252 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
253 xpub.Encode(ser_xpub.data());
254 return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), key_exp_index), ser_xpub);
255}
256
257bool WalletBatch::WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
258{
259 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
260 xpub.Encode(ser_xpub.data());
261 return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORLHCACHE, desc_id), key_exp_index), ser_xpub);
262}
263
265{
266 for (const auto& parent_xpub_pair : cache.GetCachedParentExtPubKeys()) {
267 if (!WriteDescriptorParentCache(parent_xpub_pair.second, desc_id, parent_xpub_pair.first)) {
268 return false;
269 }
270 }
271 for (const auto& derived_xpub_map_pair : cache.GetCachedDerivedExtPubKeys()) {
272 for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
273 if (!WriteDescriptorDerivedCache(derived_xpub_pair.second, desc_id, derived_xpub_map_pair.first, derived_xpub_pair.first)) {
274 return false;
275 }
276 }
277 }
278 for (const auto& lh_xpub_pair : cache.GetCachedLastHardenedExtPubKeys()) {
279 if (!WriteDescriptorLastHardenedCache(lh_xpub_pair.second, desc_id, lh_xpub_pair.first)) {
280 return false;
281 }
282 }
283 return true;
284}
285
287{
288 return WriteIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)), uint8_t{'1'});
289}
290
292{
293 return EraseIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)));
294}
295
296bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
297{
298 LOCK(pwallet->cs_wallet);
299 try {
300 CPubKey vchPubKey;
301 ssKey >> vchPubKey;
302 if (!vchPubKey.IsValid())
303 {
304 strErr = "Error reading wallet database: CPubKey corrupt";
305 return false;
306 }
307 CKey key;
308 CPrivKey pkey;
309 uint256 hash;
310
311 ssValue >> pkey;
312
313 // Old wallets store keys as DBKeys::KEY [pubkey] => [privkey]
314 // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
315 // using EC operations as a checksum.
316 // Newer wallets store keys as DBKeys::KEY [pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
317 // remaining backwards-compatible.
318 try
319 {
320 ssValue >> hash;
321 }
322 catch (const std::ios_base::failure&) {}
323
324 bool fSkipCheck = false;
325
326 if (!hash.IsNull())
327 {
328 // hash pubkey/privkey to accelerate wallet load
329 std::vector<unsigned char> vchKey;
330 vchKey.reserve(vchPubKey.size() + pkey.size());
331 vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
332 vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
333
334 if (Hash(vchKey) != hash)
335 {
336 strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
337 return false;
338 }
339
340 fSkipCheck = true;
341 }
342
343 if (!key.Load(pkey, vchPubKey, fSkipCheck))
344 {
345 strErr = "Error reading wallet database: CPrivKey corrupt";
346 return false;
347 }
348 if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadKey(key, vchPubKey))
349 {
350 strErr = "Error reading wallet database: LegacyDataSPKM::LoadKey failed";
351 return false;
352 }
353 } catch (const std::exception& e) {
354 if (strErr.empty()) {
355 strErr = e.what();
356 }
357 return false;
358 }
359 return true;
360}
361
362bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
363{
364 LOCK(pwallet->cs_wallet);
365 try {
366 CPubKey vchPubKey;
367 ssKey >> vchPubKey;
368 if (!vchPubKey.IsValid())
369 {
370 strErr = "Error reading wallet database: CPubKey corrupt";
371 return false;
372 }
373 std::vector<unsigned char> vchPrivKey;
374 ssValue >> vchPrivKey;
375
376 // Get the checksum and check it
377 bool checksum_valid = false;
378 if (!ssValue.eof()) {
379 uint256 checksum;
380 ssValue >> checksum;
381 if (!(checksum_valid = Hash(vchPrivKey) == checksum)) {
382 strErr = "Error reading wallet database: Encrypted key corrupt";
383 return false;
384 }
385 }
386
387 if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCryptedKey(vchPubKey, vchPrivKey, checksum_valid))
388 {
389 strErr = "Error reading wallet database: LegacyDataSPKM::LoadCryptedKey failed";
390 return false;
391 }
392 } catch (const std::exception& e) {
393 if (strErr.empty()) {
394 strErr = e.what();
395 }
396 return false;
397 }
398 return true;
399}
400
401bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
402{
403 LOCK(pwallet->cs_wallet);
404 try {
405 // Master encryption key is loaded into only the wallet and not any of the ScriptPubKeyMans.
406 unsigned int nID;
407 ssKey >> nID;
408 CMasterKey kMasterKey;
409 ssValue >> kMasterKey;
410 if(pwallet->mapMasterKeys.count(nID) != 0)
411 {
412 strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
413 return false;
414 }
415 pwallet->mapMasterKeys[nID] = kMasterKey;
416 if (pwallet->nMasterKeyMaxID < nID)
417 pwallet->nMasterKeyMaxID = nID;
418
419 } catch (const std::exception& e) {
420 if (strErr.empty()) {
421 strErr = e.what();
422 }
423 return false;
424 }
425 return true;
426}
427
428bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr)
429{
430 LOCK(pwallet->cs_wallet);
431 try {
432 CHDChain chain;
433 ssValue >> chain;
434 pwallet->GetOrCreateLegacyDataSPKM()->LoadHDChain(chain);
435 } catch (const std::exception& e) {
436 if (strErr.empty()) {
437 strErr = e.what();
438 }
439 return false;
440 }
441 return true;
442}
443
444static DBErrors LoadMinVersion(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
445{
446 AssertLockHeld(pwallet->cs_wallet);
447 int nMinVersion = 0;
448 if (batch.Read(DBKeys::MINVERSION, nMinVersion)) {
449 if (nMinVersion > FEATURE_LATEST)
450 return DBErrors::TOO_NEW;
451 pwallet->LoadMinVersion(nMinVersion);
452 }
453 return DBErrors::LOAD_OK;
454}
455
456static DBErrors LoadWalletFlags(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
457{
458 AssertLockHeld(pwallet->cs_wallet);
459 uint64_t flags;
460 if (batch.Read(DBKeys::FLAGS, flags)) {
461 if (!pwallet->LoadWalletFlags(flags)) {
462 pwallet->WalletLogPrintf("Error reading wallet database: Unknown non-tolerable wallet flags found\n");
463 return DBErrors::TOO_NEW;
464 }
465 // All wallets must be descriptor wallets unless opened with a bdb_ro db
466 // bdb_ro is only used for legacy to descriptor migration.
467 if (pwallet->GetDatabase().Format() != "bdb_ro" && !pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
469 }
470 }
471 return DBErrors::LOAD_OK;
472}
473
475{
477 int m_records{0};
478};
479
480using LoadFunc = std::function<DBErrors(CWallet* pwallet, DataStream& key, DataStream& value, std::string& err)>;
481static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, DataStream& prefix, LoadFunc load_func)
482{
483 LoadResult result;
484 DataStream ssKey;
485 DataStream ssValue{};
486
487 Assume(!prefix.empty());
488 std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
489 if (!cursor) {
490 pwallet->WalletLogPrintf("Error getting database cursor for '%s' records\n", key);
492 return result;
493 }
494
495 while (true) {
496 DatabaseCursor::Status status = cursor->Next(ssKey, ssValue);
497 if (status == DatabaseCursor::Status::DONE) {
498 break;
499 } else if (status == DatabaseCursor::Status::FAIL) {
500 pwallet->WalletLogPrintf("Error reading next '%s' record for wallet database\n", key);
502 return result;
503 }
504 std::string type;
505 ssKey >> type;
506 assert(type == key);
507 std::string error;
508 DBErrors record_res = load_func(pwallet, ssKey, ssValue, error);
509 if (record_res != DBErrors::LOAD_OK) {
510 pwallet->WalletLogPrintf("%s\n", error);
511 }
512 result.m_result = std::max(result.m_result, record_res);
513 ++result.m_records;
514 }
515 return result;
516}
517
518static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, LoadFunc load_func)
519{
521 prefix << key;
522 return LoadRecords(pwallet, batch, key, prefix, load_func);
523}
524
526{
527 const auto& batch = wallet.GetDatabase().MakeBatch();
528 return HasLegacyRecords(wallet, *batch);
529}
530
532{
533 for (const auto& type : DBKeys::LEGACY_TYPES) {
534 DataStream key;
535 DataStream value{};
537
538 prefix << type;
539 std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
540 if (!cursor) {
541 // Could only happen on a closed db, which means there is an error in the code flow.
542 wallet.WalletLogPrintf("Error getting database cursor for '%s' records", type);
543 throw std::runtime_error(strprintf("Error getting database cursor for '%s' records", type));
544 }
545
546 DatabaseCursor::Status status = cursor->Next(key, value);
547 if (status != DatabaseCursor::Status::DONE) {
548 return true;
549 }
550 }
551 return false;
552}
553
554static DBErrors LoadLegacyWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
555{
556 AssertLockHeld(pwallet->cs_wallet);
558
559 // Make sure descriptor wallets don't have any legacy records
560 if (pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
561 if (HasLegacyRecords(*pwallet, batch)) {
562 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());
564 }
565
566 return DBErrors::LOAD_OK;
567 }
568
569 // Load HD Chain
570 // Note: There should only be one HDCHAIN record with no data following the type
571 LoadResult hd_chain_res = LoadRecords(pwallet, batch, DBKeys::HDCHAIN,
572 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
573 return LoadHDChain(pwallet, value, err) ? DBErrors:: LOAD_OK : DBErrors::CORRUPT;
574 });
575 result = std::max(result, hd_chain_res.m_result);
576
577 // Load unencrypted keys
578 LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::KEY,
579 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
580 return LoadKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
581 });
582 result = std::max(result, key_res.m_result);
583
584 // Load encrypted keys
585 LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::CRYPTED_KEY,
586 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
587 return LoadCryptedKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
588 });
589 result = std::max(result, ckey_res.m_result);
590
591 // Load scripts
592 LoadResult script_res = LoadRecords(pwallet, batch, DBKeys::CSCRIPT,
593 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
594 uint160 hash;
595 key >> hash;
597 value >> script;
599 {
600 strErr = "Error reading wallet database: LegacyDataSPKM::LoadCScript failed";
601 return DBErrors::NONCRITICAL_ERROR;
602 }
603 return DBErrors::LOAD_OK;
604 });
605 result = std::max(result, script_res.m_result);
606
607 // Check whether rewrite is needed
608 if (ckey_res.m_records > 0) {
609 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
610 if (last_client == 40000 || last_client == 50000) result = std::max(result, DBErrors::NEED_REWRITE);
611 }
612
613 // Load keymeta
614 std::map<uint160, CHDChain> hd_chains;
615 LoadResult keymeta_res = LoadRecords(pwallet, batch, DBKeys::KEYMETA,
616 [&hd_chains] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
617 CPubKey vchPubKey;
618 key >> vchPubKey;
619 CKeyMetadata keyMeta;
620 value >> keyMeta;
621 pwallet->GetOrCreateLegacyDataSPKM()->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
622
623 // Extract some CHDChain info from this metadata if it has any
624 if (keyMeta.nVersion >= CKeyMetadata::VERSION_WITH_HDDATA && !keyMeta.hd_seed_id.IsNull() && keyMeta.hdKeypath.size() > 0) {
625 // Get the path from the key origin or from the path string
626 // Not applicable when path is "s" or "m" as those indicate a seed
627 // See https://github.com/bitcoin/bitcoin/pull/12924
628 bool internal = false;
629 uint32_t index = 0;
630 if (keyMeta.hdKeypath != "s" && keyMeta.hdKeypath != "m") {
631 std::vector<uint32_t> path;
632 if (keyMeta.has_key_origin) {
633 // We have a key origin, so pull it from its path vector
634 path = keyMeta.key_origin.path;
635 } else {
636 // No key origin, have to parse the string
637 if (!ParseHDKeypath(keyMeta.hdKeypath, path)) {
638 strErr = "Error reading wallet database: keymeta with invalid HD keypath";
639 return DBErrors::NONCRITICAL_ERROR;
640 }
641 }
642
643 // Extract the index and internal from the path
644 // Path string is m/0'/k'/i'
645 // Path vector is [0', k', i'] (but as ints OR'd with the hardened bit
646 // k == 0 for external, 1 for internal. i is the index
647 if (path.size() != 3) {
648 strErr = "Error reading wallet database: keymeta found with unexpected path";
649 return DBErrors::NONCRITICAL_ERROR;
650 }
651 if (path[0] != 0x80000000) {
652 strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
653 return DBErrors::NONCRITICAL_ERROR;
654 }
655 if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
656 strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
657 return DBErrors::NONCRITICAL_ERROR;
658 }
659 if ((path[2] & 0x80000000) == 0) {
660 strErr = strprintf("Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
661 return DBErrors::NONCRITICAL_ERROR;
662 }
663 internal = path[1] == (1 | 0x80000000);
664 index = path[2] & ~0x80000000;
665 }
666
667 // Insert a new CHDChain, or get the one that already exists
668 auto [ins, inserted] = hd_chains.emplace(keyMeta.hd_seed_id, CHDChain());
669 CHDChain& chain = ins->second;
670 if (inserted) {
671 // For new chains, we want to default to VERSION_HD_BASE until we see an internal
673 chain.seed_id = keyMeta.hd_seed_id;
674 }
675 if (internal) {
677 chain.nInternalChainCounter = std::max(chain.nInternalChainCounter, index + 1);
678 } else {
679 chain.nExternalChainCounter = std::max(chain.nExternalChainCounter, index + 1);
680 }
681 }
682 return DBErrors::LOAD_OK;
683 });
684 result = std::max(result, keymeta_res.m_result);
685
686 // Set inactive chains
687 if (!hd_chains.empty()) {
688 LegacyDataSPKM* legacy_spkm = pwallet->GetLegacyDataSPKM();
689 if (legacy_spkm) {
690 for (const auto& [hd_seed_id, chain] : hd_chains) {
691 if (hd_seed_id != legacy_spkm->GetHDChain().seed_id) {
692 legacy_spkm->AddInactiveHDChain(chain);
693 }
694 }
695 } else {
696 pwallet->WalletLogPrintf("Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
697 result = DBErrors::CORRUPT;
698 }
699 }
700
701 // Load watchonly scripts
702 LoadResult watch_script_res = LoadRecords(pwallet, batch, DBKeys::WATCHS,
703 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
705 key >> script;
706 uint8_t fYes;
707 value >> fYes;
708 if (fYes == '1') {
709 pwallet->GetOrCreateLegacyDataSPKM()->LoadWatchOnly(script);
710 }
711 return DBErrors::LOAD_OK;
712 });
713 result = std::max(result, watch_script_res.m_result);
714
715 // Load watchonly meta
716 LoadResult watch_meta_res = LoadRecords(pwallet, batch, DBKeys::WATCHMETA,
717 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
719 key >> script;
720 CKeyMetadata keyMeta;
721 value >> keyMeta;
722 pwallet->GetOrCreateLegacyDataSPKM()->LoadScriptMetadata(CScriptID(script), keyMeta);
723 return DBErrors::LOAD_OK;
724 });
725 result = std::max(result, watch_meta_res.m_result);
726
727 // Deal with old "wkey" and "defaultkey" records.
728 // These are not actually loaded, but we need to check for them
729
730 // We don't want or need the default key, but if there is one set,
731 // we want to make sure that it is valid so that we can detect corruption
732 // Note: There should only be one DEFAULTKEY with nothing trailing the type
733 LoadResult default_key_res = LoadRecords(pwallet, batch, DBKeys::DEFAULTKEY,
734 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
735 CPubKey default_pubkey;
736 try {
737 value >> default_pubkey;
738 } catch (const std::exception& e) {
739 err = e.what();
740 return DBErrors::CORRUPT;
741 }
742 if (!default_pubkey.IsValid()) {
743 err = "Error reading wallet database: Default Key corrupt";
744 return DBErrors::CORRUPT;
745 }
746 return DBErrors::LOAD_OK;
747 });
748 result = std::max(result, default_key_res.m_result);
749
750 // "wkey" records are unsupported, if we see any, throw an error
751 LoadResult wkey_res = LoadRecords(pwallet, batch, DBKeys::OLD_KEY,
752 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
753 err = "Found unsupported 'wkey' record, try loading with version 0.18";
754 return DBErrors::LOAD_FAIL;
755 });
756 result = std::max(result, wkey_res.m_result);
757
758 if (result <= DBErrors::NONCRITICAL_ERROR) {
759 // Only do logging and time first key update if there were no critical errors
760 pwallet->WalletLogPrintf("Legacy Wallet Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total.\n",
761 key_res.m_records, ckey_res.m_records, keymeta_res.m_records, key_res.m_records + ckey_res.m_records);
762 }
763
764 return result;
765}
766
767template<typename... Args>
768static DataStream PrefixStream(const Args&... args)
769{
772 return prefix;
773}
774
775static DBErrors LoadDescriptorWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
776{
777 AssertLockHeld(pwallet->cs_wallet);
778
779 // Load descriptor record
780 int num_keys = 0;
781 int num_ckeys= 0;
782 LoadResult desc_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTOR,
783 [&batch, &num_keys, &num_ckeys, &last_client] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
784 DBErrors result = DBErrors::LOAD_OK;
785
786 uint256 id;
787 key >> id;
788 WalletDescriptor desc;
789 try {
790 value >> desc;
791 } catch (const std::ios_base::failure& e) {
792 strErr = strprintf("Error: Unrecognized descriptor found in wallet %s. ", pwallet->GetName());
793 strErr += (last_client > CLIENT_VERSION) ? "The wallet might had been created on a newer version. " :
794 "The database might be corrupted or the software version is not compatible with one of your wallet descriptors. ";
795 strErr += "Please try running the latest software version";
796 // Also include error details
797 strErr = strprintf("%s\nDetails: %s", strErr, e.what());
798 return DBErrors::UNKNOWN_DESCRIPTOR;
799 }
801
802 // Prior to doing anything with this spkm, verify ID compatibility
803 if (id != spkm.GetID()) {
804 strErr = "The descriptor ID calculated by the wallet differs from the one in DB";
805 return DBErrors::CORRUPT;
806 }
807
808 DescriptorCache cache;
809
810 // Get key cache for this descriptor
812 LoadResult key_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCACHE, prefix,
813 [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
814 bool parent = true;
815 uint256 desc_id;
816 uint32_t key_exp_index;
817 uint32_t der_index;
818 key >> desc_id;
819 assert(desc_id == id);
820 key >> key_exp_index;
821
822 // if the der_index exists, it's a derived xpub
823 try
824 {
825 key >> der_index;
826 parent = false;
827 }
828 catch (...) {}
829
830 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
831 value >> ser_xpub;
832 CExtPubKey xpub;
833 xpub.Decode(ser_xpub.data());
834 if (parent) {
835 cache.CacheParentExtPubKey(key_exp_index, xpub);
836 } else {
837 cache.CacheDerivedExtPubKey(key_exp_index, der_index, xpub);
838 }
839 return DBErrors::LOAD_OK;
840 });
841 result = std::max(result, key_cache_res.m_result);
842
843 // Get last hardened cache for this descriptor
845 LoadResult lh_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORLHCACHE, prefix,
846 [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
847 uint256 desc_id;
848 uint32_t key_exp_index;
849 key >> desc_id;
850 assert(desc_id == id);
851 key >> key_exp_index;
852
853 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
854 value >> ser_xpub;
855 CExtPubKey xpub;
856 xpub.Decode(ser_xpub.data());
857 cache.CacheLastHardenedExtPubKey(key_exp_index, xpub);
858 return DBErrors::LOAD_OK;
859 });
860 result = std::max(result, lh_cache_res.m_result);
861
862 // Set the cache for this descriptor
863 auto spk_man = (DescriptorScriptPubKeyMan*)pwallet->GetScriptPubKeyMan(id);
864 assert(spk_man);
865 spk_man->SetCache(cache);
866
867 // Get unencrypted keys
869 LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORKEY, prefix,
870 [&id, &spk_man] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
871 uint256 desc_id;
872 CPubKey pubkey;
873 key >> desc_id;
874 assert(desc_id == id);
875 key >> pubkey;
876 if (!pubkey.IsValid())
877 {
878 strErr = "Error reading wallet database: descriptor unencrypted key CPubKey corrupt";
879 return DBErrors::CORRUPT;
880 }
881 CKey privkey;
882 CPrivKey pkey;
883 uint256 hash;
884
885 value >> pkey;
886 value >> hash;
887
888 // hash pubkey/privkey to accelerate wallet load
889 std::vector<unsigned char> to_hash;
890 to_hash.reserve(pubkey.size() + pkey.size());
891 to_hash.insert(to_hash.end(), pubkey.begin(), pubkey.end());
892 to_hash.insert(to_hash.end(), pkey.begin(), pkey.end());
893
894 if (Hash(to_hash) != hash)
895 {
896 strErr = "Error reading wallet database: descriptor unencrypted key CPubKey/CPrivKey corrupt";
897 return DBErrors::CORRUPT;
898 }
899
900 if (!privkey.Load(pkey, pubkey, true))
901 {
902 strErr = "Error reading wallet database: descriptor unencrypted key CPrivKey corrupt";
903 return DBErrors::CORRUPT;
904 }
905 spk_man->AddKey(pubkey.GetID(), privkey);
906 return DBErrors::LOAD_OK;
907 });
908 result = std::max(result, key_res.m_result);
909 num_keys = key_res.m_records;
910
911 // Get encrypted keys
913 LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCKEY, prefix,
914 [&id, &spk_man] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
915 uint256 desc_id;
916 CPubKey pubkey;
917 key >> desc_id;
918 assert(desc_id == id);
919 key >> pubkey;
920 if (!pubkey.IsValid())
921 {
922 err = "Error reading wallet database: descriptor encrypted key CPubKey corrupt";
923 return DBErrors::CORRUPT;
924 }
925 std::vector<unsigned char> privkey;
926 value >> privkey;
927
928 spk_man->AddCryptedKey(pubkey.GetID(), pubkey, privkey);
929 return DBErrors::LOAD_OK;
930 });
931 result = std::max(result, ckey_res.m_result);
932 num_ckeys = ckey_res.m_records;
933
934 return result;
935 });
936
937 if (desc_res.m_result <= DBErrors::NONCRITICAL_ERROR) {
938 // Only log if there are no critical errors
939 pwallet->WalletLogPrintf("Descriptors: %u, Descriptor Keys: %u plaintext, %u encrypted, %u total.\n",
940 desc_res.m_records, num_keys, num_ckeys, num_keys + num_ckeys);
941 }
942
943 return desc_res.m_result;
944}
945
947{
948 AssertLockHeld(pwallet->cs_wallet);
949 DBErrors result = DBErrors::LOAD_OK;
950
951 // Load name record
952 LoadResult name_res = LoadRecords(pwallet, batch, DBKeys::NAME,
953 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
954 std::string strAddress;
955 key >> strAddress;
956 std::string label;
957 value >> label;
958 pwallet->m_address_book[DecodeDestination(strAddress)].SetLabel(label);
959 return DBErrors::LOAD_OK;
960 });
961 result = std::max(result, name_res.m_result);
962
963 // Load purpose record
964 LoadResult purpose_res = LoadRecords(pwallet, batch, DBKeys::PURPOSE,
965 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
966 std::string strAddress;
967 key >> strAddress;
968 std::string purpose_str;
969 value >> purpose_str;
970 std::optional<AddressPurpose> purpose{PurposeFromString(purpose_str)};
971 if (!purpose) {
972 pwallet->WalletLogPrintf("Warning: nonstandard purpose string '%s' for address '%s'\n", purpose_str, strAddress);
973 }
974 pwallet->m_address_book[DecodeDestination(strAddress)].purpose = purpose;
975 return DBErrors::LOAD_OK;
976 });
977 result = std::max(result, purpose_res.m_result);
978
979 // Load destination data record
980 LoadResult dest_res = LoadRecords(pwallet, batch, DBKeys::DESTDATA,
981 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
982 std::string strAddress, strKey, strValue;
983 key >> strAddress;
984 key >> strKey;
985 value >> strValue;
986 const CTxDestination& dest{DecodeDestination(strAddress)};
987 if (strKey.compare("used") == 0) {
988 // Load "used" key indicating if an IsMine address has
989 // previously been spent from with avoid_reuse option enabled.
990 // The strValue is not used for anything currently, but could
991 // hold more information in the future. Current values are just
992 // "1" or "p" for present (which was written prior to
993 // f5ba424cd44619d9b9be88b8593d69a7ba96db26).
994 pwallet->LoadAddressPreviouslySpent(dest);
995 } else if (strKey.starts_with("rr")) {
996 // Load "rr##" keys where ## is a decimal number, and strValue
997 // is a serialized RecentRequestEntry object.
998 pwallet->LoadAddressReceiveRequest(dest, strKey.substr(2), strValue);
999 }
1000 return DBErrors::LOAD_OK;
1001 });
1002 result = std::max(result, dest_res.m_result);
1003
1004 return result;
1005}
1006
1007static DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch, std::vector<uint256>& upgraded_txs, bool& any_unordered) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1008{
1009 AssertLockHeld(pwallet->cs_wallet);
1010 DBErrors result = DBErrors::LOAD_OK;
1011
1012 // Load tx record
1013 any_unordered = false;
1014 LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,
1015 [&any_unordered, &upgraded_txs] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1016 DBErrors result = DBErrors::LOAD_OK;
1017 uint256 hash;
1018 key >> hash;
1019 // LoadToWallet call below creates a new CWalletTx that fill_wtx
1020 // callback fills with transaction metadata.
1021 auto fill_wtx = [&](CWalletTx& wtx, bool new_tx) {
1022 if(!new_tx) {
1023 // There's some corruption here since the tx we just tried to load was already in the wallet.
1024 err = "Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.";
1025 result = DBErrors::CORRUPT;
1026 return false;
1027 }
1028 value >> wtx;
1029 if (wtx.GetHash() != hash)
1030 return false;
1031
1032 // Undo serialize changes in 31600
1033 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
1034 {
1035 if (!value.empty())
1036 {
1037 uint8_t fTmp;
1038 uint8_t fUnused;
1039 std::string unused_string;
1040 value >> fTmp >> fUnused >> unused_string;
1041 pwallet->WalletLogPrintf("LoadWallet() upgrading tx ver=%d %d %s\n",
1042 wtx.fTimeReceivedIsTxTime, fTmp, hash.ToString());
1043 wtx.fTimeReceivedIsTxTime = fTmp;
1044 }
1045 else
1046 {
1047 pwallet->WalletLogPrintf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString());
1048 wtx.fTimeReceivedIsTxTime = 0;
1049 }
1050 upgraded_txs.push_back(hash);
1051 }
1052
1053 if (wtx.nOrderPos == -1)
1054 any_unordered = true;
1055
1056 return true;
1057 };
1058 if (!pwallet->LoadToWallet(hash, fill_wtx)) {
1059 // Use std::max as fill_wtx may have already set result to CORRUPT
1060 result = std::max(result, DBErrors::NEED_RESCAN);
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->LockCoin(COutPoint(hash, n));
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 std::vector<uint256> upgraded_txs;
1152
1153 LOCK(pwallet->cs_wallet);
1154
1155 // Last client version to open this wallet
1156 int last_client = CLIENT_VERSION;
1157 bool has_last_client = m_batch->Read(DBKeys::VERSION, last_client);
1158 pwallet->WalletLogPrintf("Wallet file version = %d, last client version = %d\n", pwallet->GetVersion(), last_client);
1159
1160 try {
1161 if ((result = LoadMinVersion(pwallet, *m_batch)) != DBErrors::LOAD_OK) return result;
1162
1163 // Load wallet flags, so they are known when processing other records.
1164 // The FLAGS key is absent during wallet creation.
1165 if ((result = LoadWalletFlags(pwallet, *m_batch)) != DBErrors::LOAD_OK) return result;
1166
1167#ifndef ENABLE_EXTERNAL_SIGNER
1169 pwallet->WalletLogPrintf("Error: External signer wallet being loaded without external signer support compiled\n");
1170 return DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED;
1171 }
1172#endif
1173
1174 // Load legacy wallet keys
1175 result = std::max(LoadLegacyWalletRecords(pwallet, *m_batch, last_client), result);
1176
1177 // Load descriptors
1178 result = std::max(LoadDescriptorWalletRecords(pwallet, *m_batch, last_client), result);
1179 // Early return if there are unknown descriptors. Later loading of ACTIVEINTERNALSPK and ACTIVEEXTERNALEXPK
1180 // may reference the unknown descriptor's ID which can result in a misleading corruption error
1181 // when in reality the wallet is simply too new.
1182 if (result == DBErrors::UNKNOWN_DESCRIPTOR) return result;
1183
1184 // Load address book
1185 result = std::max(LoadAddressBookRecords(pwallet, *m_batch), result);
1186
1187 // Load tx records
1188 result = std::max(LoadTxRecords(pwallet, *m_batch, upgraded_txs, any_unordered), result);
1189
1190 // Load SPKMs
1191 result = std::max(LoadActiveSPKMs(pwallet, *m_batch), result);
1192
1193 // Load decryption keys
1194 result = std::max(LoadDecryptionKeys(pwallet, *m_batch), result);
1195 } catch (...) {
1196 // Exceptions that can be ignored or treated as non-critical are handled by the individual loading functions.
1197 // Any uncaught exceptions will be caught here and treated as critical.
1198 result = DBErrors::CORRUPT;
1199 }
1200
1201 // Any wallet corruption at all: skip any rewriting or
1202 // upgrading, we don't want to make it worse.
1203 if (result != DBErrors::LOAD_OK)
1204 return result;
1205
1206 for (const uint256& hash : upgraded_txs)
1207 WriteTx(pwallet->mapWallet.at(hash));
1208
1209 if (!has_last_client || last_client != CLIENT_VERSION) // Update
1210 m_batch->Write(DBKeys::VERSION, 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(const DbTxnListener& l)
1337{
1338 assert(m_batch->HasActiveTxn());
1339 m_txn_listeners.emplace_back(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).", fs::PathToString(path)));
1387 status = DatabaseStatus::FAILED_BAD_FORMAT;
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:536
ArgsManager & args
Definition: bitcoind.cpp:277
#define STR_INTERNAL_BUG(msg)
Definition: check.h:89
#define Assume(val)
Assume is the identity function.
Definition: check.h:118
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
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
uint32_t nInternalChainCounter
Definition: walletdb.h:94
static const int VERSION_HD_BASE
Definition: walletdb.h:99
uint32_t nExternalChainCounter
Definition: walletdb.h:93
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:100
CKeyID seed_id
seed hash160
Definition: walletdb.h:95
std::string hdKeypath
Definition: walletdb.h:137
static const int VERSION_WITH_HDDATA
Definition: walletdb.h:132
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:3649
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:3527
bool HaveCryptedKeys() const
Definition: wallet.cpp:3510
LegacyDataSPKM * GetOrCreateLegacyDataSPKM()
Definition: wallet.cpp:3476
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:925
bool HasEncryptionKeys() const override
Definition: wallet.cpp:3505
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.h:813
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:3392
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(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:189
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:238
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:250
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:74
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:173
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:179
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
Definition: walletdb.cpp:264
bool EraseTx(uint256 hash)
Definition: walletdb.cpp:96
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:147
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:201
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:157
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:69
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:81
std::unique_ptr< DatabaseBatch > m_batch
Definition: walletdb.h:282
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:101
bool WriteDescriptorLastHardenedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:257
bool WriteIC(const K &key, const T &value, bool fOverwrite=true)
Definition: walletdb.h:192
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:196
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:91
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:106
bool EraseIC(const K &key)
Definition: walletdb.h:201
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:121
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:86
bool EraseLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:291
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
Definition: walletdb.cpp:243
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition: walletdb.cpp:229
bool WriteLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:286
bool EraseMasterKey(unsigned int id)
Definition: walletdb.cpp:152
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:206
bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
Definition: walletdb.cpp:212
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:218
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:165
An instance of this class represents one database.
Definition: db.h:130
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
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1154
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
Definition: wallet.cpp:1696
DBErrors ReorderTransactions()
Definition: wallet.cpp:884
void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade DescriptorCaches.
Definition: wallet.cpp:547
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
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:47
const std::string BESTBLOCK
Definition: walletdb.cpp:35
const std::string WALLETDESCRIPTORCKEY
Definition: walletdb.cpp:58
const std::string WATCHS
Definition: walletdb.cpp:61
const std::string WALLETDESCRIPTORLHCACHE
Definition: walletdb.cpp:57
const std::string POOL
Definition: walletdb.cpp:50
const std::string MINVERSION
Definition: walletdb.cpp:46
const std::string WATCHMETA
Definition: walletdb.cpp:60
const std::string DEFAULTKEY
Definition: walletdb.cpp:38
const std::string OLD_KEY
Definition: walletdb.cpp:48
const std::string WALLETDESCRIPTORKEY
Definition: walletdb.cpp:59
const std::string ACENTRY
Definition: walletdb.cpp:31
const std::string ACTIVEEXTERNALSPK
Definition: walletdb.cpp:32
const std::string TX
Definition: walletdb.cpp:53
const std::string KEY
Definition: walletdb.cpp:43
const std::string CRYPTED_KEY
Definition: walletdb.cpp:36
const std::string DESTDATA
Definition: walletdb.cpp:39
const std::string CSCRIPT
Definition: walletdb.cpp:37
const std::unordered_set< std::string > LEGACY_TYPES
Definition: walletdb.cpp:62
const std::string SETTINGS
Definition: walletdb.cpp:52
const std::string BESTBLOCK_NOMERKLE
Definition: walletdb.cpp:34
const std::string LOCKED_UTXO
Definition: walletdb.cpp:44
const std::string ACTIVEINTERNALSPK
Definition: walletdb.cpp:33
const std::string HDCHAIN
Definition: walletdb.cpp:41
const std::string ORDERPOSNEXT
Definition: walletdb.cpp:49
const std::string FLAGS
Definition: walletdb.cpp:40
const std::string VERSION
Definition: walletdb.cpp:54
const std::string WALLETDESCRIPTORCACHE
Definition: walletdb.cpp:56
const std::string MASTER_KEY
Definition: walletdb.cpp:45
const std::string KEYMETA
Definition: walletdb.cpp:42
const std::string PURPOSE
Definition: walletdb.cpp:51
const std::string WALLETDESCRIPTOR
Definition: walletdb.cpp:55
static LoadResult LoadRecords(CWallet *pwallet, DatabaseBatch &batch, const std::string &key, LoadFunc load_func)
Definition: walletdb.cpp:518
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:366
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:296
static DataStream PrefixStream(const Args &... args)
Definition: walletdb.cpp:768
static DBErrors LoadLegacyWalletRecords(CWallet *pwallet, DatabaseBatch &batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:554
bool LoadCryptedKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:362
std::function< DBErrors(CWallet *pwallet, DataStream &key, DataStream &value, std::string &err)> LoadFunc
Definition: walletdb.cpp:480
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
Overview of wallet database classes:
Definition: walletdb.h:40
static DBErrors LoadWalletFlags(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:456
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:401
bool HasLegacyRecords(CWallet &wallet)
Returns true if there are any DBKeys::LEGACY_TYPES record in the wallet db.
Definition: walletdb.cpp:525
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:428
@ 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:1007
static DBErrors LoadAddressBookRecords(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:946
static LoadResult LoadRecords(CWallet *pwallet, DatabaseBatch &batch, const std::string &key, DataStream &prefix, LoadFunc load_func)
Definition: walletdb.cpp:481
static DBErrors LoadDescriptorWalletRecords(CWallet *pwallet, DatabaseBatch &batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:775
DatabaseStatus
Definition: db.h:183
static DBErrors LoadMinVersion(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:444
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:170
std::optional< DatabaseFormat > require_format
Definition: db.h:172
#define LOCK(cs)
Definition: sync.h:257
#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())