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