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