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 pwallet->WalletLogPrintf("Wallet file version = %d\n", nMinVersion);
451 if (nMinVersion > FEATURE_LATEST)
452 return DBErrors::TOO_NEW;
453 pwallet->LoadMinVersion(nMinVersion);
454 }
455 return DBErrors::LOAD_OK;
456}
457
458static DBErrors LoadWalletFlags(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
459{
460 AssertLockHeld(pwallet->cs_wallet);
461 uint64_t flags;
462 if (batch.Read(DBKeys::FLAGS, flags)) {
463 if (!pwallet->LoadWalletFlags(flags)) {
464 pwallet->WalletLogPrintf("Error reading wallet database: Unknown non-tolerable wallet flags found\n");
465 return DBErrors::TOO_NEW;
466 }
467 // All wallets must be descriptor wallets unless opened with a bdb_ro db
468 // bdb_ro is only used for legacy to descriptor migration.
469 if (pwallet->GetDatabase().Format() != "bdb_ro" && !pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
471 }
472 }
473 return DBErrors::LOAD_OK;
474}
475
477{
479 int m_records{0};
480};
481
482using LoadFunc = std::function<DBErrors(CWallet* pwallet, DataStream& key, DataStream& value, std::string& err)>;
483static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, DataStream& prefix, LoadFunc load_func)
484{
485 LoadResult result;
486 DataStream ssKey;
487 DataStream ssValue{};
488
489 Assume(!prefix.empty());
490 std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
491 if (!cursor) {
492 pwallet->WalletLogPrintf("Error getting database cursor for '%s' records\n", key);
494 return result;
495 }
496
497 while (true) {
498 DatabaseCursor::Status status = cursor->Next(ssKey, ssValue);
499 if (status == DatabaseCursor::Status::DONE) {
500 break;
501 } else if (status == DatabaseCursor::Status::FAIL) {
502 pwallet->WalletLogPrintf("Error reading next '%s' record for wallet database\n", key);
504 return result;
505 }
506 std::string type;
507 ssKey >> type;
508 assert(type == key);
509 std::string error;
510 DBErrors record_res = load_func(pwallet, ssKey, ssValue, error);
511 if (record_res != DBErrors::LOAD_OK) {
512 pwallet->WalletLogPrintf("%s\n", error);
513 }
514 result.m_result = std::max(result.m_result, record_res);
515 ++result.m_records;
516 }
517 return result;
518}
519
520static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, LoadFunc load_func)
521{
523 prefix << key;
524 return LoadRecords(pwallet, batch, key, prefix, load_func);
525}
526
528{
529 const auto& batch = wallet.GetDatabase().MakeBatch();
530 return HasLegacyRecords(wallet, *batch);
531}
532
534{
535 for (const auto& type : DBKeys::LEGACY_TYPES) {
536 DataStream key;
537 DataStream value{};
539
540 prefix << type;
541 std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
542 if (!cursor) {
543 // Could only happen on a closed db, which means there is an error in the code flow.
544 wallet.WalletLogPrintf("Error getting database cursor for '%s' records", type);
545 throw std::runtime_error(strprintf("Error getting database cursor for '%s' records", type));
546 }
547
548 DatabaseCursor::Status status = cursor->Next(key, value);
549 if (status != DatabaseCursor::Status::DONE) {
550 return true;
551 }
552 }
553 return false;
554}
555
556static DBErrors LoadLegacyWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
557{
558 AssertLockHeld(pwallet->cs_wallet);
560
561 // Make sure descriptor wallets don't have any legacy records
562 if (pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
563 if (HasLegacyRecords(*pwallet, batch)) {
564 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());
566 }
567
568 return DBErrors::LOAD_OK;
569 }
570
571 // Load HD Chain
572 // Note: There should only be one HDCHAIN record with no data following the type
573 LoadResult hd_chain_res = LoadRecords(pwallet, batch, DBKeys::HDCHAIN,
574 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
575 return LoadHDChain(pwallet, value, err) ? DBErrors:: LOAD_OK : DBErrors::CORRUPT;
576 });
577 result = std::max(result, hd_chain_res.m_result);
578
579 // Load unencrypted keys
580 LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::KEY,
581 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
582 return LoadKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
583 });
584 result = std::max(result, key_res.m_result);
585
586 // Load encrypted keys
587 LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::CRYPTED_KEY,
588 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
589 return LoadCryptedKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
590 });
591 result = std::max(result, ckey_res.m_result);
592
593 // Load scripts
594 LoadResult script_res = LoadRecords(pwallet, batch, DBKeys::CSCRIPT,
595 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
596 uint160 hash;
597 key >> hash;
599 value >> script;
601 {
602 strErr = "Error reading wallet database: LegacyDataSPKM::LoadCScript failed";
603 return DBErrors::NONCRITICAL_ERROR;
604 }
605 return DBErrors::LOAD_OK;
606 });
607 result = std::max(result, script_res.m_result);
608
609 // Check whether rewrite is needed
610 if (ckey_res.m_records > 0) {
611 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
612 if (last_client == 40000 || last_client == 50000) result = std::max(result, DBErrors::NEED_REWRITE);
613 }
614
615 // Load keymeta
616 std::map<uint160, CHDChain> hd_chains;
617 LoadResult keymeta_res = LoadRecords(pwallet, batch, DBKeys::KEYMETA,
618 [&hd_chains] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
619 CPubKey vchPubKey;
620 key >> vchPubKey;
621 CKeyMetadata keyMeta;
622 value >> keyMeta;
623 pwallet->GetOrCreateLegacyDataSPKM()->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
624
625 // Extract some CHDChain info from this metadata if it has any
626 if (keyMeta.nVersion >= CKeyMetadata::VERSION_WITH_HDDATA && !keyMeta.hd_seed_id.IsNull() && keyMeta.hdKeypath.size() > 0) {
627 // Get the path from the key origin or from the path string
628 // Not applicable when path is "s" or "m" as those indicate a seed
629 // See https://github.com/bitcoin/bitcoin/pull/12924
630 bool internal = false;
631 uint32_t index = 0;
632 if (keyMeta.hdKeypath != "s" && keyMeta.hdKeypath != "m") {
633 std::vector<uint32_t> path;
634 if (keyMeta.has_key_origin) {
635 // We have a key origin, so pull it from its path vector
636 path = keyMeta.key_origin.path;
637 } else {
638 // No key origin, have to parse the string
639 if (!ParseHDKeypath(keyMeta.hdKeypath, path)) {
640 strErr = "Error reading wallet database: keymeta with invalid HD keypath";
641 return DBErrors::NONCRITICAL_ERROR;
642 }
643 }
644
645 // Extract the index and internal from the path
646 // Path string is m/0'/k'/i'
647 // Path vector is [0', k', i'] (but as ints OR'd with the hardened bit
648 // k == 0 for external, 1 for internal. i is the index
649 if (path.size() != 3) {
650 strErr = "Error reading wallet database: keymeta found with unexpected path";
651 return DBErrors::NONCRITICAL_ERROR;
652 }
653 if (path[0] != 0x80000000) {
654 strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
655 return DBErrors::NONCRITICAL_ERROR;
656 }
657 if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
658 strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
659 return DBErrors::NONCRITICAL_ERROR;
660 }
661 if ((path[2] & 0x80000000) == 0) {
662 strErr = strprintf("Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
663 return DBErrors::NONCRITICAL_ERROR;
664 }
665 internal = path[1] == (1 | 0x80000000);
666 index = path[2] & ~0x80000000;
667 }
668
669 // Insert a new CHDChain, or get the one that already exists
670 auto [ins, inserted] = hd_chains.emplace(keyMeta.hd_seed_id, CHDChain());
671 CHDChain& chain = ins->second;
672 if (inserted) {
673 // For new chains, we want to default to VERSION_HD_BASE until we see an internal
675 chain.seed_id = keyMeta.hd_seed_id;
676 }
677 if (internal) {
679 chain.nInternalChainCounter = std::max(chain.nInternalChainCounter, index + 1);
680 } else {
681 chain.nExternalChainCounter = std::max(chain.nExternalChainCounter, index + 1);
682 }
683 }
684 return DBErrors::LOAD_OK;
685 });
686 result = std::max(result, keymeta_res.m_result);
687
688 // Set inactive chains
689 if (!hd_chains.empty()) {
690 LegacyDataSPKM* legacy_spkm = pwallet->GetLegacyDataSPKM();
691 if (legacy_spkm) {
692 for (const auto& [hd_seed_id, chain] : hd_chains) {
693 if (hd_seed_id != legacy_spkm->GetHDChain().seed_id) {
694 legacy_spkm->AddInactiveHDChain(chain);
695 }
696 }
697 } else {
698 pwallet->WalletLogPrintf("Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
699 result = DBErrors::CORRUPT;
700 }
701 }
702
703 // Load watchonly scripts
704 LoadResult watch_script_res = LoadRecords(pwallet, batch, DBKeys::WATCHS,
705 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
707 key >> script;
708 uint8_t fYes;
709 value >> fYes;
710 if (fYes == '1') {
711 pwallet->GetOrCreateLegacyDataSPKM()->LoadWatchOnly(script);
712 }
713 return DBErrors::LOAD_OK;
714 });
715 result = std::max(result, watch_script_res.m_result);
716
717 // Load watchonly meta
718 LoadResult watch_meta_res = LoadRecords(pwallet, batch, DBKeys::WATCHMETA,
719 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
721 key >> script;
722 CKeyMetadata keyMeta;
723 value >> keyMeta;
724 pwallet->GetOrCreateLegacyDataSPKM()->LoadScriptMetadata(CScriptID(script), keyMeta);
725 return DBErrors::LOAD_OK;
726 });
727 result = std::max(result, watch_meta_res.m_result);
728
729 // Deal with old "wkey" and "defaultkey" records.
730 // These are not actually loaded, but we need to check for them
731
732 // We don't want or need the default key, but if there is one set,
733 // we want to make sure that it is valid so that we can detect corruption
734 // Note: There should only be one DEFAULTKEY with nothing trailing the type
735 LoadResult default_key_res = LoadRecords(pwallet, batch, DBKeys::DEFAULTKEY,
736 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
737 CPubKey default_pubkey;
738 try {
739 value >> default_pubkey;
740 } catch (const std::exception& e) {
741 err = e.what();
742 return DBErrors::CORRUPT;
743 }
744 if (!default_pubkey.IsValid()) {
745 err = "Error reading wallet database: Default Key corrupt";
746 return DBErrors::CORRUPT;
747 }
748 return DBErrors::LOAD_OK;
749 });
750 result = std::max(result, default_key_res.m_result);
751
752 // "wkey" records are unsupported, if we see any, throw an error
753 LoadResult wkey_res = LoadRecords(pwallet, batch, DBKeys::OLD_KEY,
754 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
755 err = "Found unsupported 'wkey' record, try loading with version 0.18";
756 return DBErrors::LOAD_FAIL;
757 });
758 result = std::max(result, wkey_res.m_result);
759
760 if (result <= DBErrors::NONCRITICAL_ERROR) {
761 // Only do logging and time first key update if there were no critical errors
762 pwallet->WalletLogPrintf("Legacy Wallet Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total.\n",
763 key_res.m_records, ckey_res.m_records, keymeta_res.m_records, key_res.m_records + ckey_res.m_records);
764 }
765
766 return result;
767}
768
769template<typename... Args>
770static DataStream PrefixStream(const Args&... args)
771{
774 return prefix;
775}
776
777static DBErrors LoadDescriptorWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
778{
779 AssertLockHeld(pwallet->cs_wallet);
780
781 // Load descriptor record
782 int num_keys = 0;
783 int num_ckeys= 0;
784 LoadResult desc_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTOR,
785 [&batch, &num_keys, &num_ckeys, &last_client] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
786 DBErrors result = DBErrors::LOAD_OK;
787
788 uint256 id;
789 key >> id;
790 WalletDescriptor desc;
791 try {
792 value >> desc;
793 } catch (const std::ios_base::failure& e) {
794 strErr = strprintf("Error: Unrecognized descriptor found in wallet %s. ", pwallet->GetName());
795 strErr += (last_client > CLIENT_VERSION) ? "The wallet might had been created on a newer version. " :
796 "The database might be corrupted or the software version is not compatible with one of your wallet descriptors. ";
797 strErr += "Please try running the latest software version";
798 // Also include error details
799 strErr = strprintf("%s\nDetails: %s", strErr, e.what());
800 return DBErrors::UNKNOWN_DESCRIPTOR;
801 }
803
804 // Prior to doing anything with this spkm, verify ID compatibility
805 if (id != spkm.GetID()) {
806 strErr = "The descriptor ID calculated by the wallet differs from the one in DB";
807 return DBErrors::CORRUPT;
808 }
809
810 DescriptorCache cache;
811
812 // Get key cache for this descriptor
814 LoadResult key_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCACHE, prefix,
815 [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
816 bool parent = true;
817 uint256 desc_id;
818 uint32_t key_exp_index;
819 uint32_t der_index;
820 key >> desc_id;
821 assert(desc_id == id);
822 key >> key_exp_index;
823
824 // if the der_index exists, it's a derived xpub
825 try
826 {
827 key >> der_index;
828 parent = false;
829 }
830 catch (...) {}
831
832 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
833 value >> ser_xpub;
834 CExtPubKey xpub;
835 xpub.Decode(ser_xpub.data());
836 if (parent) {
837 cache.CacheParentExtPubKey(key_exp_index, xpub);
838 } else {
839 cache.CacheDerivedExtPubKey(key_exp_index, der_index, xpub);
840 }
841 return DBErrors::LOAD_OK;
842 });
843 result = std::max(result, key_cache_res.m_result);
844
845 // Get last hardened cache for this descriptor
847 LoadResult lh_cache_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORLHCACHE, prefix,
848 [&id, &cache] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
849 uint256 desc_id;
850 uint32_t key_exp_index;
851 key >> desc_id;
852 assert(desc_id == id);
853 key >> key_exp_index;
854
855 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
856 value >> ser_xpub;
857 CExtPubKey xpub;
858 xpub.Decode(ser_xpub.data());
859 cache.CacheLastHardenedExtPubKey(key_exp_index, xpub);
860 return DBErrors::LOAD_OK;
861 });
862 result = std::max(result, lh_cache_res.m_result);
863
864 // Set the cache for this descriptor
865 auto spk_man = (DescriptorScriptPubKeyMan*)pwallet->GetScriptPubKeyMan(id);
866 assert(spk_man);
867 spk_man->SetCache(cache);
868
869 // Get unencrypted keys
871 LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORKEY, prefix,
872 [&id, &spk_man] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
873 uint256 desc_id;
874 CPubKey pubkey;
875 key >> desc_id;
876 assert(desc_id == id);
877 key >> pubkey;
878 if (!pubkey.IsValid())
879 {
880 strErr = "Error reading wallet database: descriptor unencrypted key CPubKey corrupt";
881 return DBErrors::CORRUPT;
882 }
883 CKey privkey;
884 CPrivKey pkey;
885 uint256 hash;
886
887 value >> pkey;
888 value >> hash;
889
890 // hash pubkey/privkey to accelerate wallet load
891 std::vector<unsigned char> to_hash;
892 to_hash.reserve(pubkey.size() + pkey.size());
893 to_hash.insert(to_hash.end(), pubkey.begin(), pubkey.end());
894 to_hash.insert(to_hash.end(), pkey.begin(), pkey.end());
895
896 if (Hash(to_hash) != hash)
897 {
898 strErr = "Error reading wallet database: descriptor unencrypted key CPubKey/CPrivKey corrupt";
899 return DBErrors::CORRUPT;
900 }
901
902 if (!privkey.Load(pkey, pubkey, true))
903 {
904 strErr = "Error reading wallet database: descriptor unencrypted key CPrivKey corrupt";
905 return DBErrors::CORRUPT;
906 }
907 spk_man->AddKey(pubkey.GetID(), privkey);
908 return DBErrors::LOAD_OK;
909 });
910 result = std::max(result, key_res.m_result);
911 num_keys = key_res.m_records;
912
913 // Get encrypted keys
915 LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTORCKEY, prefix,
916 [&id, &spk_man] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
917 uint256 desc_id;
918 CPubKey pubkey;
919 key >> desc_id;
920 assert(desc_id == id);
921 key >> pubkey;
922 if (!pubkey.IsValid())
923 {
924 err = "Error reading wallet database: descriptor encrypted key CPubKey corrupt";
925 return DBErrors::CORRUPT;
926 }
927 std::vector<unsigned char> privkey;
928 value >> privkey;
929
930 spk_man->AddCryptedKey(pubkey.GetID(), pubkey, privkey);
931 return DBErrors::LOAD_OK;
932 });
933 result = std::max(result, ckey_res.m_result);
934 num_ckeys = ckey_res.m_records;
935
936 return result;
937 });
938
939 if (desc_res.m_result <= DBErrors::NONCRITICAL_ERROR) {
940 // Only log if there are no critical errors
941 pwallet->WalletLogPrintf("Descriptors: %u, Descriptor Keys: %u plaintext, %u encrypted, %u total.\n",
942 desc_res.m_records, num_keys, num_ckeys, num_keys + num_ckeys);
943 }
944
945 return desc_res.m_result;
946}
947
949{
950 AssertLockHeld(pwallet->cs_wallet);
951 DBErrors result = DBErrors::LOAD_OK;
952
953 // Load name record
954 LoadResult name_res = LoadRecords(pwallet, batch, DBKeys::NAME,
955 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
956 std::string strAddress;
957 key >> strAddress;
958 std::string label;
959 value >> label;
960 pwallet->m_address_book[DecodeDestination(strAddress)].SetLabel(label);
961 return DBErrors::LOAD_OK;
962 });
963 result = std::max(result, name_res.m_result);
964
965 // Load purpose record
966 LoadResult purpose_res = LoadRecords(pwallet, batch, DBKeys::PURPOSE,
967 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
968 std::string strAddress;
969 key >> strAddress;
970 std::string purpose_str;
971 value >> purpose_str;
972 std::optional<AddressPurpose> purpose{PurposeFromString(purpose_str)};
973 if (!purpose) {
974 pwallet->WalletLogPrintf("Warning: nonstandard purpose string '%s' for address '%s'\n", purpose_str, strAddress);
975 }
976 pwallet->m_address_book[DecodeDestination(strAddress)].purpose = purpose;
977 return DBErrors::LOAD_OK;
978 });
979 result = std::max(result, purpose_res.m_result);
980
981 // Load destination data record
982 LoadResult dest_res = LoadRecords(pwallet, batch, DBKeys::DESTDATA,
983 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
984 std::string strAddress, strKey, strValue;
985 key >> strAddress;
986 key >> strKey;
987 value >> strValue;
988 const CTxDestination& dest{DecodeDestination(strAddress)};
989 if (strKey.compare("used") == 0) {
990 // Load "used" key indicating if an IsMine address has
991 // previously been spent from with avoid_reuse option enabled.
992 // The strValue is not used for anything currently, but could
993 // hold more information in the future. Current values are just
994 // "1" or "p" for present (which was written prior to
995 // f5ba424cd44619d9b9be88b8593d69a7ba96db26).
996 pwallet->LoadAddressPreviouslySpent(dest);
997 } else if (strKey.starts_with("rr")) {
998 // Load "rr##" keys where ## is a decimal number, and strValue
999 // is a serialized RecentRequestEntry object.
1000 pwallet->LoadAddressReceiveRequest(dest, strKey.substr(2), strValue);
1001 }
1002 return DBErrors::LOAD_OK;
1003 });
1004 result = std::max(result, dest_res.m_result);
1005
1006 return result;
1007}
1008
1009static DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch, std::vector<Txid>& upgraded_txs, bool& any_unordered) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1010{
1011 AssertLockHeld(pwallet->cs_wallet);
1012 DBErrors result = DBErrors::LOAD_OK;
1013
1014 // Load tx record
1015 any_unordered = false;
1016 LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,
1017 [&any_unordered, &upgraded_txs] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1018 DBErrors result = DBErrors::LOAD_OK;
1019 Txid hash;
1020 key >> hash;
1021 // LoadToWallet call below creates a new CWalletTx that fill_wtx
1022 // callback fills with transaction metadata.
1023 auto fill_wtx = [&](CWalletTx& wtx, bool new_tx) {
1024 if(!new_tx) {
1025 // There's some corruption here since the tx we just tried to load was already in the wallet.
1026 err = "Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.";
1027 result = DBErrors::CORRUPT;
1028 return false;
1029 }
1030 value >> wtx;
1031 if (wtx.GetHash() != hash)
1032 return false;
1033
1034 // Undo serialize changes in 31600
1035 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
1036 {
1037 if (!value.empty())
1038 {
1039 uint8_t fTmp;
1040 uint8_t fUnused;
1041 std::string unused_string;
1042 value >> fTmp >> fUnused >> unused_string;
1043 pwallet->WalletLogPrintf("LoadWallet() upgrading tx ver=%d %d %s\n",
1044 wtx.fTimeReceivedIsTxTime, fTmp, hash.ToString());
1045 wtx.fTimeReceivedIsTxTime = fTmp;
1046 }
1047 else
1048 {
1049 pwallet->WalletLogPrintf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString());
1050 wtx.fTimeReceivedIsTxTime = 0;
1051 }
1052 upgraded_txs.push_back(hash);
1053 }
1054
1055 if (wtx.nOrderPos == -1)
1056 any_unordered = true;
1057
1058 return true;
1059 };
1060 if (!pwallet->LoadToWallet(hash, fill_wtx)) {
1061 // Use std::max as fill_wtx may have already set result to CORRUPT
1062 result = std::max(result, DBErrors::NEED_RESCAN);
1063 }
1064 return result;
1065 });
1066 result = std::max(result, tx_res.m_result);
1067
1068 // Load locked utxo record
1069 LoadResult locked_utxo_res = LoadRecords(pwallet, batch, DBKeys::LOCKED_UTXO,
1070 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1071 Txid hash;
1072 uint32_t n;
1073 key >> hash;
1074 key >> n;
1075 pwallet->LockCoin(COutPoint(hash, n));
1076 return DBErrors::LOAD_OK;
1077 });
1078 result = std::max(result, locked_utxo_res.m_result);
1079
1080 // Load orderposnext record
1081 // Note: There should only be one ORDERPOSNEXT record with nothing trailing the type
1082 LoadResult order_pos_res = LoadRecords(pwallet, batch, DBKeys::ORDERPOSNEXT,
1083 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1084 try {
1085 value >> pwallet->nOrderPosNext;
1086 } catch (const std::exception& e) {
1087 err = e.what();
1088 return DBErrors::NONCRITICAL_ERROR;
1089 }
1090 return DBErrors::LOAD_OK;
1091 });
1092 result = std::max(result, order_pos_res.m_result);
1093
1094 // After loading all tx records, abandon any coinbase that is no longer in the active chain.
1095 // This could happen during an external wallet load, or if the user replaced the chain data.
1096 for (auto& [id, wtx] : pwallet->mapWallet) {
1097 if (wtx.IsCoinBase() && wtx.isInactive()) {
1098 pwallet->AbandonTransaction(wtx);
1099 }
1100 }
1101
1102 return result;
1103}
1104
1105static DBErrors LoadActiveSPKMs(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
1106{
1107 AssertLockHeld(pwallet->cs_wallet);
1108 DBErrors result = DBErrors::LOAD_OK;
1109
1110 // Load spk records
1111 std::set<std::pair<OutputType, bool>> seen_spks;
1112 for (const auto& spk_key : {DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK}) {
1113 LoadResult spkm_res = LoadRecords(pwallet, batch, spk_key,
1114 [&seen_spks, &spk_key] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
1115 uint8_t output_type;
1116 key >> output_type;
1117 uint256 id;
1118 value >> id;
1119
1120 bool internal = spk_key == DBKeys::ACTIVEINTERNALSPK;
1121 auto [it, insert] = seen_spks.emplace(static_cast<OutputType>(output_type), internal);
1122 if (!insert) {
1123 strErr = "Multiple ScriptpubKeyMans specified for a single type";
1124 return DBErrors::CORRUPT;
1125 }
1126 pwallet->LoadActiveScriptPubKeyMan(id, static_cast<OutputType>(output_type), /*internal=*/internal);
1127 return DBErrors::LOAD_OK;
1128 });
1129 result = std::max(result, spkm_res.m_result);
1130 }
1131 return result;
1132}
1133
1135{
1136 AssertLockHeld(pwallet->cs_wallet);
1137
1138 // Load decryption key (mkey) records
1139 LoadResult mkey_res = LoadRecords(pwallet, batch, DBKeys::MASTER_KEY,
1140 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
1141 if (!LoadEncryptionKey(pwallet, key, value, err)) {
1142 return DBErrors::CORRUPT;
1143 }
1144 return DBErrors::LOAD_OK;
1145 });
1146 return mkey_res.m_result;
1147}
1148
1150{
1151 DBErrors result = DBErrors::LOAD_OK;
1152 bool any_unordered = false;
1153 std::vector<Txid> upgraded_txs;
1154
1155 LOCK(pwallet->cs_wallet);
1156
1157 // Last client version to open this wallet
1158 int last_client = CLIENT_VERSION;
1159 bool has_last_client = m_batch->Read(DBKeys::VERSION, last_client);
1160 if (has_last_client) pwallet->WalletLogPrintf("Last client version = %d\n", last_client);
1161
1162 try {
1163 if ((result = LoadMinVersion(pwallet, *m_batch)) != DBErrors::LOAD_OK) return result;
1164
1165 // Load wallet flags, so they are known when processing other records.
1166 // The FLAGS key is absent during wallet creation.
1167 if ((result = LoadWalletFlags(pwallet, *m_batch)) != DBErrors::LOAD_OK) return result;
1168
1169#ifndef ENABLE_EXTERNAL_SIGNER
1171 pwallet->WalletLogPrintf("Error: External signer wallet being loaded without external signer support compiled\n");
1172 return DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED;
1173 }
1174#endif
1175
1176 // Load legacy wallet keys
1177 result = std::max(LoadLegacyWalletRecords(pwallet, *m_batch, last_client), result);
1178
1179 // Load descriptors
1180 result = std::max(LoadDescriptorWalletRecords(pwallet, *m_batch, last_client), result);
1181 // Early return if there are unknown descriptors. Later loading of ACTIVEINTERNALSPK and ACTIVEEXTERNALEXPK
1182 // may reference the unknown descriptor's ID which can result in a misleading corruption error
1183 // when in reality the wallet is simply too new.
1184 if (result == DBErrors::UNKNOWN_DESCRIPTOR) return result;
1185
1186 // Load address book
1187 result = std::max(LoadAddressBookRecords(pwallet, *m_batch), result);
1188
1189 // Load tx records
1190 result = std::max(LoadTxRecords(pwallet, *m_batch, upgraded_txs, any_unordered), result);
1191
1192 // Load SPKMs
1193 result = std::max(LoadActiveSPKMs(pwallet, *m_batch), result);
1194
1195 // Load decryption keys
1196 result = std::max(LoadDecryptionKeys(pwallet, *m_batch), result);
1197 } catch (...) {
1198 // Exceptions that can be ignored or treated as non-critical are handled by the individual loading functions.
1199 // Any uncaught exceptions will be caught here and treated as critical.
1200 result = DBErrors::CORRUPT;
1201 }
1202
1203 // Any wallet corruption at all: skip any rewriting or
1204 // upgrading, we don't want to make it worse.
1205 if (result != DBErrors::LOAD_OK)
1206 return result;
1207
1208 for (const Txid& hash : upgraded_txs)
1209 WriteTx(pwallet->mapWallet.at(hash));
1210
1211 if (!has_last_client || last_client != CLIENT_VERSION) // Update
1212 m_batch->Write(DBKeys::VERSION, CLIENT_VERSION);
1213
1214 if (any_unordered)
1215 result = pwallet->ReorderTransactions();
1216
1217 // Upgrade all of the descriptor caches to cache the last hardened xpub
1218 // This operation is not atomic, but if it fails, only new entries are added so it is backwards compatible
1219 try {
1220 pwallet->UpgradeDescriptorCache();
1221 } catch (...) {
1222 result = DBErrors::CORRUPT;
1223 }
1224
1225 // Since it was accidentally possible to "encrypt" a wallet with private keys disabled, we should check if this is
1226 // such a wallet and remove the encryption key records to avoid any future issues.
1227 // Although wallets without private keys should not have *ckey records, we should double check that.
1228 // Removing the mkey records is only safe if there are no *ckey records.
1229 if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && pwallet->HasEncryptionKeys() && !pwallet->HaveCryptedKeys()) {
1230 pwallet->WalletLogPrintf("Detected extraneous encryption keys in this wallet without private keys. Removing extraneous encryption keys.\n");
1231 for (const auto& [id, _] : pwallet->mapMasterKeys) {
1232 if (!EraseMasterKey(id)) {
1233 pwallet->WalletLogPrintf("Error: Unable to remove extraneous encryption key '%u'. Wallet corrupt.\n", id);
1234 return DBErrors::CORRUPT;
1235 }
1236 }
1237 pwallet->mapMasterKeys.clear();
1238 }
1239
1240 return result;
1241}
1242
1243static bool RunWithinTxn(WalletBatch& batch, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1244{
1245 if (!batch.TxnBegin()) {
1246 LogDebug(BCLog::WALLETDB, "Error: cannot create db txn for %s\n", process_desc);
1247 return false;
1248 }
1249
1250 // Run procedure
1251 if (!func(batch)) {
1252 LogDebug(BCLog::WALLETDB, "Error: %s failed\n", process_desc);
1253 batch.TxnAbort();
1254 return false;
1255 }
1256
1257 if (!batch.TxnCommit()) {
1258 LogDebug(BCLog::WALLETDB, "Error: cannot commit db txn for %s\n", process_desc);
1259 return false;
1260 }
1261
1262 // All good
1263 return true;
1264}
1265
1266bool RunWithinTxn(WalletDatabase& database, std::string_view process_desc, const std::function<bool(WalletBatch&)>& func)
1267{
1268 WalletBatch batch(database);
1269 return RunWithinTxn(batch, process_desc, func);
1270}
1271
1272bool WalletBatch::WriteAddressPreviouslySpent(const CTxDestination& dest, bool previously_spent)
1273{
1274 auto key{std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), std::string("used")))};
1275 return previously_spent ? WriteIC(key, std::string("1")) : EraseIC(key);
1276}
1277
1278bool WalletBatch::WriteAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& receive_request)
1279{
1280 return WriteIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), "rr" + id)), receive_request);
1281}
1282
1283bool WalletBatch::EraseAddressReceiveRequest(const CTxDestination& dest, const std::string& id)
1284{
1285 return EraseIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(EncodeDestination(dest), "rr" + id)));
1286}
1287
1288bool WalletBatch::EraseAddressData(const CTxDestination& dest)
1289{
1292 return m_batch->ErasePrefix(prefix);
1293}
1294
1295bool WalletBatch::WriteWalletFlags(const uint64_t flags)
1296{
1297 return WriteIC(DBKeys::FLAGS, flags);
1298}
1299
1300bool WalletBatch::EraseRecords(const std::unordered_set<std::string>& types)
1301{
1302 return std::all_of(types.begin(), types.end(), [&](const std::string& type) {
1303 return m_batch->ErasePrefix(DataStream() << type);
1304 });
1305}
1306
1307bool WalletBatch::TxnBegin()
1308{
1309 return m_batch->TxnBegin();
1310}
1311
1312bool WalletBatch::TxnCommit()
1313{
1314 bool res = m_batch->TxnCommit();
1315 if (res) {
1316 for (const auto& listener : m_txn_listeners) {
1317 listener.on_commit();
1318 }
1319 // txn finished, clear listeners
1320 m_txn_listeners.clear();
1321 }
1322 return res;
1323}
1324
1325bool WalletBatch::TxnAbort()
1326{
1327 bool res = m_batch->TxnAbort();
1328 if (res) {
1329 for (const auto& listener : m_txn_listeners) {
1330 listener.on_abort();
1331 }
1332 // txn finished, clear listeners
1333 m_txn_listeners.clear();
1334 }
1335 return res;
1336}
1337
1338void WalletBatch::RegisterTxnListener(const DbTxnListener& l)
1339{
1340 assert(m_batch->HasActiveTxn());
1341 m_txn_listeners.emplace_back(l);
1342}
1343
1344std::unique_ptr<WalletDatabase> MakeDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error)
1345{
1346 bool exists;
1347 try {
1348 exists = fs::symlink_status(path).type() != fs::file_type::not_found;
1349 } catch (const fs::filesystem_error& e) {
1350 error = Untranslated(strprintf("Failed to access database path '%s': %s", fs::PathToString(path), e.code().message()));
1351 status = DatabaseStatus::FAILED_BAD_PATH;
1352 return nullptr;
1353 }
1354
1355 std::optional<DatabaseFormat> format;
1356 if (exists) {
1357 if (IsBDBFile(BDBDataFile(path))) {
1358 format = DatabaseFormat::BERKELEY_RO;
1359 }
1360 if (IsSQLiteFile(SQLiteDataFile(path))) {
1361 if (format) {
1362 error = Untranslated(strprintf("Failed to load database path '%s'. Data is in ambiguous format.", fs::PathToString(path)));
1363 status = DatabaseStatus::FAILED_BAD_FORMAT;
1364 return nullptr;
1365 }
1366 format = DatabaseFormat::SQLITE;
1367 }
1368 } else if (options.require_existing) {
1369 error = Untranslated(strprintf("Failed to load database path '%s'. Path does not exist.", fs::PathToString(path)));
1370 status = DatabaseStatus::FAILED_NOT_FOUND;
1371 return nullptr;
1372 }
1373
1374 if (!format && options.require_existing) {
1375 error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in recognized format.", fs::PathToString(path)));
1376 status = DatabaseStatus::FAILED_BAD_FORMAT;
1377 return nullptr;
1378 }
1379
1380 if (format && options.require_create) {
1381 error = Untranslated(strprintf("Failed to create database path '%s'. Database already exists.", fs::PathToString(path)));
1382 status = DatabaseStatus::FAILED_ALREADY_EXISTS;
1383 return nullptr;
1384 }
1385
1386 // BERKELEY_RO can only be opened if require_format was set, which only occurs in migration.
1387 if (format && format == DatabaseFormat::BERKELEY_RO && (!options.require_format || options.require_format != DatabaseFormat::BERKELEY_RO)) {
1388 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)));
1389 status = DatabaseStatus::FAILED_BAD_FORMAT;
1390 return nullptr;
1391 }
1392
1393 // A db already exists so format is set, but options also specifies the format, so make sure they agree
1394 if (format && options.require_format && format != options.require_format) {
1395 error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in required format.", fs::PathToString(path)));
1396 status = DatabaseStatus::FAILED_BAD_FORMAT;
1397 return nullptr;
1398 }
1399
1400 // Format is not set when a db doesn't already exist, so use the format specified by the options if it is set.
1401 if (!format && options.require_format) format = options.require_format;
1402
1403 if (!format) {
1404 format = DatabaseFormat::SQLITE;
1405 }
1406
1407 if (format == DatabaseFormat::SQLITE) {
1408 return MakeSQLiteDatabase(path, options, status, error);
1409 }
1410
1411 if (format == DatabaseFormat::BERKELEY_RO) {
1412 return MakeBerkeleyRODatabase(path, options, status, error);
1413 }
1414
1415 error = Untranslated(STR_INTERNAL_BUG("Could not determine wallet format"));
1416 status = DatabaseStatus::FAILED_BAD_FORMAT;
1417 return nullptr;
1418}
1419} // 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:529
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:604
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:3643
unsigned int nMasterKeyMaxID
Definition: wallet.h:462
DescriptorScriptPubKeyMan & LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:3521
bool HaveCryptedKeys() const
Definition: wallet.cpp:3505
LegacyDataSPKM * GetOrCreateLegacyDataSPKM()
Definition: wallet.cpp:3471
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:458
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:917
bool HasEncryptionKeys() const override
Definition: wallet.cpp:3500
MasterKeyMap mapMasterKeys
Definition: wallet.h:461
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:3387
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:448
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:1325
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:1307
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1312
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:1709
bool LoadToWallet(const Txid &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1159
DBErrors ReorderTransactions()
Definition: wallet.cpp:889
void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade DescriptorCaches.
Definition: wallet.cpp:548
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:520
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:367
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: walletdb.cpp:1344
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:1266
bool LoadKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:297
static DataStream PrefixStream(const Args &... args)
Definition: walletdb.cpp:770
static DBErrors LoadLegacyWalletRecords(CWallet *pwallet, DatabaseBatch &batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:556
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:1009
std::function< DBErrors(CWallet *pwallet, DataStream &key, DataStream &value, std::string &err)> LoadFunc
Definition: walletdb.cpp:482
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:458
static DBErrors LoadActiveSPKMs(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:1105
static DBErrors LoadDecryptionKeys(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:1134
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:527
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:776
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:948
static LoadResult LoadRecords(CWallet *pwallet, DatabaseBatch &batch, const std::string &key, DataStream &prefix, LoadFunc load_func)
Definition: walletdb.cpp:483
static DBErrors LoadDescriptorWalletRecords(CWallet *pwallet, DatabaseBatch &batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:777
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())