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