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