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