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