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