Bitcoin Core 32.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
122{
123 return WriteIC(std::make_pair(DBKeys::TX, wtx.GetHash()), wtx);
124}
125
126bool WalletBatch::WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite)
127{
128 return WriteIC(std::make_pair(DBKeys::KEYMETA, pubkey), meta, overwrite);
129}
130
131bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
132{
133 if (!WriteKeyMetadata(keyMeta, vchPubKey, false)) {
134 return false;
135 }
136
137 // hash pubkey/privkey to accelerate wallet load
138 const auto keypair_hash = Hash(vchPubKey, vchPrivKey);
139
140 return WriteIC(std::make_pair(DBKeys::KEY, vchPubKey), std::make_pair(vchPrivKey, keypair_hash), false);
141}
142
144 const std::vector<unsigned char>& vchCryptedSecret,
145 const CKeyMetadata &keyMeta)
146{
147 if (!WriteKeyMetadata(keyMeta, vchPubKey, true)) {
148 return false;
149 }
150
151 // Compute a checksum of the encrypted key
152 uint256 checksum = Hash(vchCryptedSecret);
153
154 const auto key = std::make_pair(DBKeys::CRYPTED_KEY, vchPubKey);
155 if (!WriteIC(key, std::make_pair(vchCryptedSecret, checksum), false)) {
156 // It may already exist, so try writing just the checksum
157 std::vector<unsigned char> val;
158 if (!m_batch->Read(key, val)) {
159 return false;
160 }
161 if (!WriteIC(key, std::make_pair(val, checksum), true)) {
162 return false;
163 }
164 }
165 EraseIC(std::make_pair(DBKeys::KEY, vchPubKey));
166 return true;
167}
168
169bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
170{
171 return WriteIC(std::make_pair(DBKeys::MASTER_KEY, nID), kMasterKey, true);
172}
173
174bool WalletBatch::EraseMasterKey(unsigned int id)
175{
176 return EraseIC(std::make_pair(DBKeys::MASTER_KEY, id));
177}
178
179bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
180{
181 if (!WriteIC(std::make_pair(DBKeys::WATCHMETA, dest), keyMeta)) {
182 return false;
183 }
184 return WriteIC(std::make_pair(DBKeys::WATCHS, dest), uint8_t{'1'});
185}
186
188{
189 WriteIC(DBKeys::BESTBLOCK, CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
190 return WriteIC(DBKeys::BESTBLOCK_NOMERKLE, locator);
191}
192
194{
195 if (m_batch->Read(DBKeys::BESTBLOCK, locator) && !locator.vHave.empty()) return true;
196 return m_batch->Read(DBKeys::BESTBLOCK_NOMERKLE, locator);
197}
198
200{
203 if (auto cursor = m_batch->GetNewPrefixCursor(prefix)) {
204 DataStream k, v;
205 if (cursor->Next(k, v) == DatabaseCursor::Status::MORE) return true;
206 }
207 return false;
208}
209
210bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
211{
212 return WriteIC(DBKeys::ORDERPOSNEXT, nOrderPosNext);
213}
214
215bool WalletBatch::WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal)
216{
217 std::string key = internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK;
218 return WriteIC(make_pair(key, type), id);
219}
220
221bool WalletBatch::EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
222{
223 const std::string key{internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK};
224 return EraseIC(make_pair(key, type));
225}
226
227bool WalletBatch::WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey)
228{
229 // hash pubkey/privkey to accelerate wallet load
230 const auto keypair_hash = Hash(pubkey, privkey);
231
232 return WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)), std::make_pair(privkey, keypair_hash), false);
233}
234
235bool WalletBatch::WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret)
236{
237 if (!WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORCKEY, std::make_pair(desc_id, pubkey)), secret, false)) {
238 return false;
239 }
240 EraseIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)));
241 return true;
242}
243
244bool WalletBatch::WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor)
245{
246 return WriteIC(make_pair(DBKeys::WALLETDESCRIPTOR, desc_id), descriptor);
247}
248
249bool WalletBatch::WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index)
250{
251 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
252 xpub.Encode(ser_xpub.data());
253 return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), std::make_pair(key_exp_index, der_index)), ser_xpub);
254}
255
256bool WalletBatch::WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
257{
258 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
259 xpub.Encode(ser_xpub.data());
260 return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), key_exp_index), ser_xpub);
261}
262
263bool WalletBatch::WriteDescriptorLastHardenedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
264{
265 std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
266 xpub.Encode(ser_xpub.data());
267 return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORLHCACHE, desc_id), key_exp_index), ser_xpub);
268}
269
271{
272 for (const auto& parent_xpub_pair : cache.GetCachedParentExtPubKeys()) {
273 if (!WriteDescriptorParentCache(parent_xpub_pair.second, desc_id, parent_xpub_pair.first)) {
274 return false;
275 }
276 }
277 for (const auto& derived_xpub_map_pair : cache.GetCachedDerivedExtPubKeys()) {
278 for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
279 if (!WriteDescriptorDerivedCache(derived_xpub_pair.second, desc_id, derived_xpub_map_pair.first, derived_xpub_pair.first)) {
280 return false;
281 }
282 }
283 }
284 for (const auto& lh_xpub_pair : cache.GetCachedLastHardenedExtPubKeys()) {
285 if (!WriteDescriptorLastHardenedCache(lh_xpub_pair.second, desc_id, lh_xpub_pair.first)) {
286 return false;
287 }
288 }
289 return true;
290}
291
293{
294 return WriteIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)), uint8_t{'1'});
295}
296
298{
299 return EraseIC(std::make_pair(DBKeys::LOCKED_UTXO, std::make_pair(output.hash, output.n)));
300}
301
302bool LoadKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
303{
304 LOCK(pwallet->cs_wallet);
305 try {
306 CPubKey vchPubKey;
307 ssKey >> vchPubKey;
308 if (!vchPubKey.IsValid())
309 {
310 strErr = "Error reading wallet database: CPubKey corrupt";
311 return false;
312 }
313 CKey key;
314 CPrivKey pkey;
315 uint256 hash;
316
317 ssValue >> pkey;
318
319 // Old wallets store keys as DBKeys::KEY [pubkey] => [privkey]
320 // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
321 // using EC operations as a checksum.
322 // Newer wallets store keys as DBKeys::KEY [pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
323 // remaining backwards-compatible.
324 try
325 {
326 ssValue >> hash;
327 }
328 catch (const std::ios_base::failure&) {}
329
330 bool fSkipCheck = false;
331
332 if (!hash.IsNull())
333 {
334 // hash pubkey/privkey to accelerate wallet load
335 const auto keypair_hash = Hash(vchPubKey, pkey);
336
337 if (keypair_hash != hash)
338 {
339 strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
340 return false;
341 }
342
343 fSkipCheck = true;
344 }
345
346 if (!key.Load(pkey, vchPubKey, fSkipCheck))
347 {
348 strErr = "Error reading wallet database: CPrivKey corrupt";
349 return false;
350 }
351 if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadKey(key, vchPubKey))
352 {
353 strErr = "Error reading wallet database: LegacyDataSPKM::LoadKey failed";
354 return false;
355 }
356 } catch (const std::exception& e) {
357 if (strErr.empty()) {
358 strErr = e.what();
359 }
360 return false;
361 }
362 return true;
363}
364
365bool LoadCryptedKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
366{
367 LOCK(pwallet->cs_wallet);
368 try {
369 CPubKey vchPubKey;
370 ssKey >> vchPubKey;
371 if (!vchPubKey.IsValid())
372 {
373 strErr = "Error reading wallet database: CPubKey corrupt";
374 return false;
375 }
376 std::vector<unsigned char> vchPrivKey;
377 ssValue >> vchPrivKey;
378
379 // Get the checksum and check it
380 bool checksum_valid = false;
381 if (!ssValue.empty()) {
382 uint256 checksum;
383 ssValue >> checksum;
384 if (!(checksum_valid = Hash(vchPrivKey) == checksum)) {
385 strErr = "Error reading wallet database: Encrypted key corrupt";
386 return false;
387 }
388 }
389
390 if (!pwallet->GetOrCreateLegacyDataSPKM()->LoadCryptedKey(vchPubKey, vchPrivKey, checksum_valid))
391 {
392 strErr = "Error reading wallet database: LegacyDataSPKM::LoadCryptedKey failed";
393 return false;
394 }
395 } catch (const std::exception& e) {
396 if (strErr.empty()) {
397 strErr = e.what();
398 }
399 return false;
400 }
401 return true;
402}
403
404bool LoadEncryptionKey(CWallet* pwallet, DataStream& ssKey, DataStream& ssValue, std::string& strErr)
405{
406 LOCK(pwallet->cs_wallet);
407 try {
408 // Master encryption key is loaded into only the wallet and not any of the ScriptPubKeyMans.
409 unsigned int nID;
410 ssKey >> nID;
411 CMasterKey kMasterKey;
412 ssValue >> kMasterKey;
413 if(pwallet->mapMasterKeys.contains(nID))
414 {
415 strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
416 return false;
417 }
418 pwallet->mapMasterKeys[nID] = kMasterKey;
419 if (pwallet->nMasterKeyMaxID < nID)
420 pwallet->nMasterKeyMaxID = nID;
421
422 } catch (const std::exception& e) {
423 if (strErr.empty()) {
424 strErr = e.what();
425 }
426 return false;
427 }
428 return true;
429}
430
431bool LoadHDChain(CWallet* pwallet, DataStream& ssValue, std::string& strErr)
432{
433 LOCK(pwallet->cs_wallet);
434 try {
435 CHDChain chain;
436 ssValue >> chain;
437 pwallet->GetOrCreateLegacyDataSPKM()->LoadHDChain(chain);
438 } catch (const std::exception& e) {
439 if (strErr.empty()) {
440 strErr = e.what();
441 }
442 return false;
443 }
444 return true;
445}
446
447static DBErrors LoadWalletFlags(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
448{
449 AssertLockHeld(pwallet->cs_wallet);
450 uint64_t flags;
451 if (batch.Read(DBKeys::FLAGS, flags)) {
452 if (!pwallet->LoadWalletFlags(flags)) {
453 pwallet->WalletLogPrintf("Error reading wallet database: Unknown non-tolerable wallet flags found\n");
454 return DBErrors::TOO_NEW;
455 }
456 // All wallets must be descriptor wallets unless opened with a bdb_ro db
457 // bdb_ro is only used for legacy to descriptor migration.
458 if (pwallet->GetDatabase().Format() != "bdb_ro" && !pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
460 }
461 }
462 return DBErrors::LOAD_OK;
463}
464
466{
468 int m_records{0};
469};
470
471using LoadFunc = std::function<DBErrors(CWallet* pwallet, DataStream& key, DataStream& value, std::string& err)>;
472static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, DataStream& prefix, LoadFunc load_func)
473{
474 LoadResult result;
475 DataStream ssKey;
476 DataStream ssValue{};
477
478 Assume(!prefix.empty());
479 std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
480 if (!cursor) {
481 pwallet->WalletLogPrintf("Error getting database cursor for '%s' records\n", key);
483 return result;
484 }
485
486 while (true) {
487 DatabaseCursor::Status status = cursor->Next(ssKey, ssValue);
488 if (status == DatabaseCursor::Status::DONE) {
489 break;
490 } else if (status == DatabaseCursor::Status::FAIL) {
491 pwallet->WalletLogPrintf("Error reading next '%s' record for wallet database\n", key);
493 return result;
494 }
495 std::string type;
496 ssKey >> type;
497 assert(type == key);
498 std::string error;
499 DBErrors record_res = load_func(pwallet, ssKey, ssValue, error);
500 if (record_res != DBErrors::LOAD_OK) {
501 pwallet->WalletLogPrintf("%s\n", error);
502 }
503 result.m_result = std::max(result.m_result, record_res);
504 ++result.m_records;
505 }
506 return result;
507}
508
509static LoadResult LoadRecords(CWallet* pwallet, DatabaseBatch& batch, const std::string& key, LoadFunc load_func)
510{
512 prefix << key;
513 return LoadRecords(pwallet, batch, key, prefix, load_func);
514}
515
517{
518 const auto& batch = wallet.GetDatabase().MakeBatch();
519 return HasLegacyRecords(wallet, *batch);
520}
521
523{
524 for (const auto& type : DBKeys::LEGACY_TYPES) {
525 DataStream key;
526 DataStream value{};
528
529 prefix << type;
530 std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix);
531 if (!cursor) {
532 // Could only happen on a closed db, which means there is an error in the code flow.
533 throw std::runtime_error(strprintf("Error getting database cursor for '%s' records", type));
534 }
535
536 DatabaseCursor::Status status = cursor->Next(key, value);
537 if (status != DatabaseCursor::Status::DONE) {
538 return true;
539 }
540 }
541 return false;
542}
543
544static DBErrors LoadLegacyWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
545{
546 AssertLockHeld(pwallet->cs_wallet);
548
549 // Make sure descriptor wallets don't have any legacy records
550 if (pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
551 if (HasLegacyRecords(*pwallet, batch)) {
552 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());
554 }
555
556 return DBErrors::LOAD_OK;
557 }
558
559 // Load HD Chain
560 // Note: There should only be one HDCHAIN record with no data following the type
561 LoadResult hd_chain_res = LoadRecords(pwallet, batch, DBKeys::HDCHAIN,
562 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
563 return LoadHDChain(pwallet, value, err) ? DBErrors:: LOAD_OK : DBErrors::CORRUPT;
564 });
565 result = std::max(result, hd_chain_res.m_result);
566
567 // Load unencrypted keys
568 LoadResult key_res = LoadRecords(pwallet, batch, DBKeys::KEY,
569 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
570 return LoadKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
571 });
572 result = std::max(result, key_res.m_result);
573
574 // Load encrypted keys
575 LoadResult ckey_res = LoadRecords(pwallet, batch, DBKeys::CRYPTED_KEY,
576 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
577 return LoadCryptedKey(pwallet, key, value, err) ? DBErrors::LOAD_OK : DBErrors::CORRUPT;
578 });
579 result = std::max(result, ckey_res.m_result);
580
581 // Load scripts
582 LoadResult script_res = LoadRecords(pwallet, batch, DBKeys::CSCRIPT,
583 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
584 uint160 hash;
585 key >> hash;
587 value >> script;
589 {
590 strErr = "Error reading wallet database: LegacyDataSPKM::LoadCScript failed";
591 return DBErrors::NONCRITICAL_ERROR;
592 }
593 return DBErrors::LOAD_OK;
594 });
595 result = std::max(result, script_res.m_result);
596
597 // Load keymeta
598 std::map<uint160, CHDChain> hd_chains;
599 LoadResult keymeta_res = LoadRecords(pwallet, batch, DBKeys::KEYMETA,
600 [&hd_chains] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
601 CPubKey vchPubKey;
602 key >> vchPubKey;
603 CKeyMetadata keyMeta;
604 value >> keyMeta;
605 pwallet->GetOrCreateLegacyDataSPKM()->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
606
607 // Extract some CHDChain info from this metadata if it has any
608 if (keyMeta.nVersion >= CKeyMetadata::VERSION_WITH_HDDATA && !keyMeta.hd_seed_id.IsNull() && keyMeta.hdKeypath.size() > 0) {
609 // Get the path from the key origin or from the path string
610 // Not applicable when path is "s" or "m" as those indicate a seed
611 // See https://github.com/bitcoin/bitcoin/pull/12924
612 bool internal = false;
613 uint32_t index = 0;
614 if (keyMeta.hdKeypath != "s" && keyMeta.hdKeypath != "m") {
615 std::vector<uint32_t> path;
616 if (keyMeta.has_key_origin) {
617 // We have a key origin, so pull it from its path vector
618 path = keyMeta.key_origin.path;
619 } else {
620 // No key origin, have to parse the string
621 if (!ParseHDKeypath(keyMeta.hdKeypath, path)) {
622 strErr = "Error reading wallet database: keymeta with invalid HD keypath";
623 return DBErrors::NONCRITICAL_ERROR;
624 }
625 }
626
627 // Extract the index and internal from the path
628 // Path string is m/0'/k'/i'
629 // Path vector is [0', k', i'] (but as ints OR'd with the hardened bit
630 // k == 0 for external, 1 for internal. i is the index
631 if (path.size() != 3) {
632 strErr = "Error reading wallet database: keymeta found with unexpected path";
633 return DBErrors::NONCRITICAL_ERROR;
634 }
635 if (path[0] != BIP32_HARDENED_FLAG) {
636 strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
637 return DBErrors::NONCRITICAL_ERROR;
638 }
639 if (path[1] != BIP32_HARDENED_FLAG && path[1] != (1 | BIP32_HARDENED_FLAG)) {
640 strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
641 return DBErrors::NONCRITICAL_ERROR;
642 }
643 if ((path[2] & BIP32_HARDENED_FLAG) == 0) {
644 strErr = strprintf("Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
645 return DBErrors::NONCRITICAL_ERROR;
646 }
647 internal = path[1] == (1 | BIP32_HARDENED_FLAG);
648 index = path[2] & ~BIP32_HARDENED_FLAG;
649 }
650
651 // Insert a new CHDChain, or get the one that already exists
652 auto [ins, inserted] = hd_chains.emplace(keyMeta.hd_seed_id, CHDChain());
653 CHDChain& chain = ins->second;
654 if (inserted) {
655 // For new chains, we want to default to VERSION_HD_BASE until we see an internal
657 chain.seed_id = keyMeta.hd_seed_id;
658 }
659 if (internal) {
661 chain.nInternalChainCounter = std::max(chain.nInternalChainCounter, index + 1);
662 } else {
663 chain.nExternalChainCounter = std::max(chain.nExternalChainCounter, index + 1);
664 }
665 }
666 return DBErrors::LOAD_OK;
667 });
668 result = std::max(result, keymeta_res.m_result);
669
670 // Set inactive chains
671 if (!hd_chains.empty()) {
672 LegacyDataSPKM* legacy_spkm = pwallet->GetLegacyDataSPKM();
673 if (legacy_spkm) {
674 for (const auto& [hd_seed_id, chain] : hd_chains) {
675 if (hd_seed_id != legacy_spkm->GetHDChain().seed_id) {
676 legacy_spkm->AddInactiveHDChain(chain);
677 }
678 }
679 } else {
680 pwallet->WalletLogPrintf("Inactive HD chains found but no LegacyDataSPKM\n");
681 result = DBErrors::CORRUPT;
682 }
683 }
684
685 // Load watchonly scripts
686 LoadResult watch_script_res = LoadRecords(pwallet, batch, DBKeys::WATCHS,
687 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
689 key >> script;
690 uint8_t fYes;
691 value >> fYes;
692 if (fYes == '1') {
693 pwallet->GetOrCreateLegacyDataSPKM()->LoadWatchOnly(script);
694 }
695 return DBErrors::LOAD_OK;
696 });
697 result = std::max(result, watch_script_res.m_result);
698
699 // Load watchonly meta
700 LoadResult watch_meta_res = LoadRecords(pwallet, batch, DBKeys::WATCHMETA,
701 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
703 key >> script;
704 CKeyMetadata keyMeta;
705 value >> keyMeta;
706 pwallet->GetOrCreateLegacyDataSPKM()->LoadScriptMetadata(CScriptID(script), keyMeta);
707 return DBErrors::LOAD_OK;
708 });
709 result = std::max(result, watch_meta_res.m_result);
710
711 // Deal with old "wkey" and "defaultkey" records.
712 // These are not actually loaded, but we need to check for them
713
714 // We don't want or need the default key, but if there is one set,
715 // we want to make sure that it is valid so that we can detect corruption
716 // Note: There should only be one DEFAULTKEY with nothing trailing the type
717 LoadResult default_key_res = LoadRecords(pwallet, batch, DBKeys::DEFAULTKEY,
718 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
719 CPubKey default_pubkey;
720 try {
721 value >> default_pubkey;
722 } catch (const std::exception& e) {
723 err = e.what();
724 return DBErrors::CORRUPT;
725 }
726 if (!default_pubkey.IsValid()) {
727 err = "Error reading wallet database: Default Key corrupt";
728 return DBErrors::CORRUPT;
729 }
730 return DBErrors::LOAD_OK;
731 });
732 result = std::max(result, default_key_res.m_result);
733
734 // "wkey" records are unsupported, if we see any, throw an error
735 LoadResult wkey_res = LoadRecords(pwallet, batch, DBKeys::OLD_KEY,
736 [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {
737 err = "Found unsupported 'wkey' record, try loading with version 0.18";
738 return DBErrors::LOAD_FAIL;
739 });
740 result = std::max(result, wkey_res.m_result);
741
742 if (result <= DBErrors::NONCRITICAL_ERROR) {
743 // Only do logging and time first key update if there were no critical errors
744 pwallet->WalletLogPrintf("Legacy Wallet Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total.\n",
745 key_res.m_records, ckey_res.m_records, keymeta_res.m_records, key_res.m_records + ckey_res.m_records);
746 }
747
748 return result;
749}
750
751template<typename... Args>
752static DataStream PrefixStream(const Args&... args)
753{
756 return prefix;
757}
758
759static DBErrors LoadDescriptorWalletRecords(CWallet* pwallet, DatabaseBatch& batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
760{
761 AssertLockHeld(pwallet->cs_wallet);
762
763 // Load descriptor record
764 int num_keys = 0;
765 int num_ckeys= 0;
766 LoadResult desc_res = LoadRecords(pwallet, batch, DBKeys::WALLETDESCRIPTOR,
767 [&batch, &num_keys, &num_ckeys, &last_client] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {
768 DBErrors result = DBErrors::LOAD_OK;
769
770 uint256 id;
771 key >> id;
772 WalletDescriptor desc;
773 try {
774 value >> desc;
775 } catch (const std::ios_base::failure& e) {
776 strErr = strprintf("Error: Unrecognized descriptor found in wallet %s. ", pwallet->GetName());
777 strErr += (last_client > CLIENT_VERSION) ? "The wallet might have been created on a newer version. " :
778 "The database might be corrupted or the software version is not compatible with one of your wallet descriptors. ";
779 strErr += "Please try running the latest software version";
780 // Also include error details
781 strErr = strprintf("%s\nDetails: %s", strErr, e.what());
782 return DBErrors::UNKNOWN_DESCRIPTOR;
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:104
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:103
std::string hdKeypath
Definition: walletdb.h:145
static constexpr int VERSION_WITH_HDDATA
Definition: walletdb.h:140
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:3733
unsigned int nMasterKeyMaxID
Definition: wallet.h:473
bool HaveCryptedKeys() const
Definition: wallet.cpp:3586
LegacyDataSPKM * GetOrCreateLegacyDataSPKM()
Definition: wallet.cpp:3552
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:3606
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:3581
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:194
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:389
const std::map< Wtxid, CTransactionRef > & GetTxs() const
Definition: transaction.h:393
RAII class that provides access to a WalletDatabase.
Definition: db.h:50
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:197
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:244
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:256
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:82
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:187
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:193
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
Definition: walletdb.cpp:270
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:169
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:179
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:301
bool WriteDescriptorLastHardenedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:263
bool WriteIC(const K &key, const T &value, bool fOverwrite=true)
Definition: walletdb.h:200
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:210
bool WriteFullTx(const CWalletTx &wtx)
Definition: walletdb.cpp:99
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:131
bool EraseIC(const K &key)
Definition: walletdb.h:209
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:143
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:94
bool EraseLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:297
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
Definition: walletdb.cpp:249
bool WriteTxMetadata(const CWalletTx &wtx)
Definition: walletdb.cpp:121
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition: walletdb.cpp:235
bool WriteLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:292
bool EraseMasterKey(unsigned int id)
Definition: walletdb.cpp:174
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:215
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:221
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, bool overwrite)
Definition: walletdb.cpp:126
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:227
An instance of this class represents one database.
Definition: db.h:129
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:160
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
Definition: wallet.cpp:1784
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:509
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:302
static DataStream PrefixStream(const Args &... args)
Definition: walletdb.cpp:752
static DBErrors LoadLegacyWalletRecords(CWallet *pwallet, DatabaseBatch &batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:544
bool LoadCryptedKey(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, std::string &strErr)
Definition: walletdb.cpp:365
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:471
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:447
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:404
bool HasLegacyRecords(CWallet &wallet)
Returns true if there are any DBKeys::LEGACY_TYPES record in the wallet db.
Definition: walletdb.cpp:516
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:431
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:472
static DBErrors LoadDescriptorWalletRecords(CWallet *pwallet, DatabaseBatch &batch, int last_client) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:759
DatabaseStatus
Definition: db.h:180
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:1195
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:169
std::optional< DatabaseFormat > require_format
Definition: db.h:171
#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())