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