Bitcoin Core  21.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-2020 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 <wallet/walletdb.h>
7 
8 #include <fs.h>
9 #include <key_io.h>
10 #include <protocol.h>
11 #include <serialize.h>
12 #include <sync.h>
13 #include <util/bip32.h>
14 #include <util/system.h>
15 #include <util/time.h>
16 #include <util/translation.h>
17 #ifdef USE_BDB
18 #include <wallet/bdb.h>
19 #endif
20 #ifdef USE_SQLITE
21 #include <wallet/sqlite.h>
22 #endif
23 #include <wallet/wallet.h>
24 
25 #include <atomic>
26 #include <optional>
27 #include <string>
28 
29 namespace DBKeys {
30 const std::string ACENTRY{"acentry"};
31 const std::string ACTIVEEXTERNALSPK{"activeexternalspk"};
32 const std::string ACTIVEINTERNALSPK{"activeinternalspk"};
33 const std::string BESTBLOCK_NOMERKLE{"bestblock_nomerkle"};
34 const std::string BESTBLOCK{"bestblock"};
35 const std::string CRYPTED_KEY{"ckey"};
36 const std::string CSCRIPT{"cscript"};
37 const std::string DEFAULTKEY{"defaultkey"};
38 const std::string DESTDATA{"destdata"};
39 const std::string FLAGS{"flags"};
40 const std::string HDCHAIN{"hdchain"};
41 const std::string KEYMETA{"keymeta"};
42 const std::string KEY{"key"};
43 const std::string MASTER_KEY{"mkey"};
44 const std::string MINVERSION{"minversion"};
45 const std::string NAME{"name"};
46 const std::string OLD_KEY{"wkey"};
47 const std::string ORDERPOSNEXT{"orderposnext"};
48 const std::string POOL{"pool"};
49 const std::string PURPOSE{"purpose"};
50 const std::string SETTINGS{"settings"};
51 const std::string TX{"tx"};
52 const std::string VERSION{"version"};
53 const std::string WALLETDESCRIPTOR{"walletdescriptor"};
54 const std::string WALLETDESCRIPTORCACHE{"walletdescriptorcache"};
55 const std::string WALLETDESCRIPTORCKEY{"walletdescriptorckey"};
56 const std::string WALLETDESCRIPTORKEY{"walletdescriptorkey"};
57 const std::string WATCHMETA{"watchmeta"};
58 const std::string WATCHS{"watchs"};
59 } // namespace DBKeys
60 
61 //
62 // WalletBatch
63 //
64 
65 bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName)
66 {
67  return WriteIC(std::make_pair(DBKeys::NAME, strAddress), strName);
68 }
69 
70 bool WalletBatch::EraseName(const std::string& strAddress)
71 {
72  // This should only be used for sending addresses, never for receiving addresses,
73  // receiving addresses must always have an address book entry if they're not change return.
74  return EraseIC(std::make_pair(DBKeys::NAME, strAddress));
75 }
76 
77 bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
78 {
79  return WriteIC(std::make_pair(DBKeys::PURPOSE, strAddress), strPurpose);
80 }
81 
82 bool WalletBatch::ErasePurpose(const std::string& strAddress)
83 {
84  return EraseIC(std::make_pair(DBKeys::PURPOSE, strAddress));
85 }
86 
88 {
89  return WriteIC(std::make_pair(DBKeys::TX, wtx.GetHash()), wtx);
90 }
91 
93 {
94  return EraseIC(std::make_pair(DBKeys::TX, hash));
95 }
96 
97 bool WalletBatch::WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite)
98 {
99  return WriteIC(std::make_pair(DBKeys::KEYMETA, pubkey), meta, overwrite);
100 }
101 
102 bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
103 {
104  if (!WriteKeyMetadata(keyMeta, vchPubKey, false)) {
105  return false;
106  }
107 
108  // hash pubkey/privkey to accelerate wallet load
109  std::vector<unsigned char> vchKey;
110  vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
111  vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
112  vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
113 
114  return WriteIC(std::make_pair(DBKeys::KEY, vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey)), false);
115 }
116 
117 bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey,
118  const std::vector<unsigned char>& vchCryptedSecret,
119  const CKeyMetadata &keyMeta)
120 {
121  if (!WriteKeyMetadata(keyMeta, vchPubKey, true)) {
122  return false;
123  }
124 
125  // Compute a checksum of the encrypted key
126  uint256 checksum = Hash(vchCryptedSecret);
127 
128  const auto key = std::make_pair(DBKeys::CRYPTED_KEY, vchPubKey);
129  if (!WriteIC(key, std::make_pair(vchCryptedSecret, checksum), false)) {
130  // It may already exist, so try writing just the checksum
131  std::vector<unsigned char> val;
132  if (!m_batch->Read(key, val)) {
133  return false;
134  }
135  if (!WriteIC(key, std::make_pair(val, checksum), true)) {
136  return false;
137  }
138  }
139  EraseIC(std::make_pair(DBKeys::KEY, vchPubKey));
140  return true;
141 }
142 
143 bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
144 {
145  return WriteIC(std::make_pair(DBKeys::MASTER_KEY, nID), kMasterKey, true);
146 }
147 
148 bool WalletBatch::WriteCScript(const uint160& hash, const CScript& redeemScript)
149 {
150  return WriteIC(std::make_pair(DBKeys::CSCRIPT, hash), redeemScript, false);
151 }
152 
153 bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
154 {
155  if (!WriteIC(std::make_pair(DBKeys::WATCHMETA, dest), keyMeta)) {
156  return false;
157  }
158  return WriteIC(std::make_pair(DBKeys::WATCHS, dest), '1');
159 }
160 
162 {
163  if (!EraseIC(std::make_pair(DBKeys::WATCHMETA, dest))) {
164  return false;
165  }
166  return EraseIC(std::make_pair(DBKeys::WATCHS, dest));
167 }
168 
170 {
171  WriteIC(DBKeys::BESTBLOCK, CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
172  return WriteIC(DBKeys::BESTBLOCK_NOMERKLE, locator);
173 }
174 
176 {
177  if (m_batch->Read(DBKeys::BESTBLOCK, locator) && !locator.vHave.empty()) return true;
178  return m_batch->Read(DBKeys::BESTBLOCK_NOMERKLE, locator);
179 }
180 
181 bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
182 {
183  return WriteIC(DBKeys::ORDERPOSNEXT, nOrderPosNext);
184 }
185 
186 bool WalletBatch::ReadPool(int64_t nPool, CKeyPool& keypool)
187 {
188  return m_batch->Read(std::make_pair(DBKeys::POOL, nPool), keypool);
189 }
190 
191 bool WalletBatch::WritePool(int64_t nPool, const CKeyPool& keypool)
192 {
193  return WriteIC(std::make_pair(DBKeys::POOL, nPool), keypool);
194 }
195 
196 bool WalletBatch::ErasePool(int64_t nPool)
197 {
198  return EraseIC(std::make_pair(DBKeys::POOL, nPool));
199 }
200 
202 {
203  return WriteIC(DBKeys::MINVERSION, nVersion);
204 }
205 
206 bool WalletBatch::WriteActiveScriptPubKeyMan(uint8_t type, const uint256& id, bool internal)
207 {
208  std::string key = internal ? DBKeys::ACTIVEINTERNALSPK : DBKeys::ACTIVEEXTERNALSPK;
209  return WriteIC(make_pair(key, type), id);
210 }
211 
212 bool WalletBatch::WriteDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const CPrivKey& privkey)
213 {
214  // hash pubkey/privkey to accelerate wallet load
215  std::vector<unsigned char> key;
216  key.reserve(pubkey.size() + privkey.size());
217  key.insert(key.end(), pubkey.begin(), pubkey.end());
218  key.insert(key.end(), privkey.begin(), privkey.end());
219 
220  return WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)), std::make_pair(privkey, Hash(key)), false);
221 }
222 
223 bool WalletBatch::WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret)
224 {
225  if (!WriteIC(std::make_pair(DBKeys::WALLETDESCRIPTORCKEY, std::make_pair(desc_id, pubkey)), secret, false)) {
226  return false;
227  }
228  EraseIC(std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey)));
229  return true;
230 }
231 
232 bool WalletBatch::WriteDescriptor(const uint256& desc_id, const WalletDescriptor& descriptor)
233 {
234  return WriteIC(make_pair(DBKeys::WALLETDESCRIPTOR, desc_id), descriptor);
235 }
236 
237 bool WalletBatch::WriteDescriptorDerivedCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index, uint32_t der_index)
238 {
239  std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
240  xpub.Encode(ser_xpub.data());
241  return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), std::make_pair(key_exp_index, der_index)), ser_xpub);
242 }
243 
244 bool WalletBatch::WriteDescriptorParentCache(const CExtPubKey& xpub, const uint256& desc_id, uint32_t key_exp_index)
245 {
246  std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
247  xpub.Encode(ser_xpub.data());
248  return WriteIC(std::make_pair(std::make_pair(DBKeys::WALLETDESCRIPTORCACHE, desc_id), key_exp_index), ser_xpub);
249 }
250 
252 public:
253  unsigned int nKeys{0};
254  unsigned int nCKeys{0};
255  unsigned int nWatchKeys{0};
256  unsigned int nKeyMeta{0};
257  unsigned int m_unknown_records{0};
258  bool fIsEncrypted{false};
259  bool fAnyUnordered{false};
260  std::vector<uint256> vWalletUpgrade;
261  std::map<OutputType, uint256> m_active_external_spks;
262  std::map<OutputType, uint256> m_active_internal_spks;
263  std::map<uint256, DescriptorCache> m_descriptor_caches;
264  std::map<std::pair<uint256, CKeyID>, CKey> m_descriptor_keys;
265  std::map<std::pair<uint256, CKeyID>, std::pair<CPubKey, std::vector<unsigned char>>> m_descriptor_crypt_keys;
266  std::map<uint160, CHDChain> m_hd_chains;
267 
269  }
270 };
271 
272 static bool
273 ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
274  CWalletScanState &wss, std::string& strType, std::string& strErr, const KeyFilterFn& filter_fn = nullptr) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)
275 {
276  try {
277  // Unserialize
278  // Taking advantage of the fact that pair serialization
279  // is just the two items serialized one after the other
280  ssKey >> strType;
281  // If we have a filter, check if this matches the filter
282  if (filter_fn && !filter_fn(strType)) {
283  return true;
284  }
285  if (strType == DBKeys::NAME) {
286  std::string strAddress;
287  ssKey >> strAddress;
288  std::string label;
289  ssValue >> label;
290  pwallet->m_address_book[DecodeDestination(strAddress)].SetLabel(label);
291  } else if (strType == DBKeys::PURPOSE) {
292  std::string strAddress;
293  ssKey >> strAddress;
294  ssValue >> pwallet->m_address_book[DecodeDestination(strAddress)].purpose;
295  } else if (strType == DBKeys::TX) {
296  uint256 hash;
297  ssKey >> hash;
298  // LoadToWallet call below creates a new CWalletTx that fill_wtx
299  // callback fills with transaction metadata.
300  auto fill_wtx = [&](CWalletTx& wtx, bool new_tx) {
301  assert(new_tx);
302  ssValue >> wtx;
303  if (wtx.GetHash() != hash)
304  return false;
305 
306  // Undo serialize changes in 31600
307  if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
308  {
309  if (!ssValue.empty())
310  {
311  char fTmp;
312  char fUnused;
313  std::string unused_string;
314  ssValue >> fTmp >> fUnused >> unused_string;
315  strErr = strprintf("LoadWallet() upgrading tx ver=%d %d %s",
316  wtx.fTimeReceivedIsTxTime, fTmp, hash.ToString());
317  wtx.fTimeReceivedIsTxTime = fTmp;
318  }
319  else
320  {
321  strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
322  wtx.fTimeReceivedIsTxTime = 0;
323  }
324  wss.vWalletUpgrade.push_back(hash);
325  }
326 
327  if (wtx.nOrderPos == -1)
328  wss.fAnyUnordered = true;
329 
330  return true;
331  };
332  if (!pwallet->LoadToWallet(hash, fill_wtx)) {
333  return false;
334  }
335  } else if (strType == DBKeys::WATCHS) {
336  wss.nWatchKeys++;
337  CScript script;
338  ssKey >> script;
339  char fYes;
340  ssValue >> fYes;
341  if (fYes == '1') {
343  }
344  } else if (strType == DBKeys::KEY) {
345  CPubKey vchPubKey;
346  ssKey >> vchPubKey;
347  if (!vchPubKey.IsValid())
348  {
349  strErr = "Error reading wallet database: CPubKey corrupt";
350  return false;
351  }
352  CKey key;
353  CPrivKey pkey;
354  uint256 hash;
355 
356  wss.nKeys++;
357  ssValue >> pkey;
358 
359  // Old wallets store keys as DBKeys::KEY [pubkey] => [privkey]
360  // ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
361  // using EC operations as a checksum.
362  // Newer wallets store keys as DBKeys::KEY [pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
363  // remaining backwards-compatible.
364  try
365  {
366  ssValue >> hash;
367  }
368  catch (const std::ios_base::failure&) {}
369 
370  bool fSkipCheck = false;
371 
372  if (!hash.IsNull())
373  {
374  // hash pubkey/privkey to accelerate wallet load
375  std::vector<unsigned char> vchKey;
376  vchKey.reserve(vchPubKey.size() + pkey.size());
377  vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
378  vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
379 
380  if (Hash(vchKey) != hash)
381  {
382  strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
383  return false;
384  }
385 
386  fSkipCheck = true;
387  }
388 
389  if (!key.Load(pkey, vchPubKey, fSkipCheck))
390  {
391  strErr = "Error reading wallet database: CPrivKey corrupt";
392  return false;
393  }
394  if (!pwallet->GetOrCreateLegacyScriptPubKeyMan()->LoadKey(key, vchPubKey))
395  {
396  strErr = "Error reading wallet database: LegacyScriptPubKeyMan::LoadKey failed";
397  return false;
398  }
399  } else if (strType == DBKeys::MASTER_KEY) {
400  // Master encryption key is loaded into only the wallet and not any of the ScriptPubKeyMans.
401  unsigned int nID;
402  ssKey >> nID;
403  CMasterKey kMasterKey;
404  ssValue >> kMasterKey;
405  if(pwallet->mapMasterKeys.count(nID) != 0)
406  {
407  strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
408  return false;
409  }
410  pwallet->mapMasterKeys[nID] = kMasterKey;
411  if (pwallet->nMasterKeyMaxID < nID)
412  pwallet->nMasterKeyMaxID = nID;
413  } else if (strType == DBKeys::CRYPTED_KEY) {
414  CPubKey vchPubKey;
415  ssKey >> vchPubKey;
416  if (!vchPubKey.IsValid())
417  {
418  strErr = "Error reading wallet database: CPubKey corrupt";
419  return false;
420  }
421  std::vector<unsigned char> vchPrivKey;
422  ssValue >> vchPrivKey;
423 
424  // Get the checksum and check it
425  bool checksum_valid = false;
426  if (!ssValue.eof()) {
427  uint256 checksum;
428  ssValue >> checksum;
429  if ((checksum_valid = Hash(vchPrivKey) != checksum)) {
430  strErr = "Error reading wallet database: Encrypted key corrupt";
431  return false;
432  }
433  }
434 
435  wss.nCKeys++;
436 
437  if (!pwallet->GetOrCreateLegacyScriptPubKeyMan()->LoadCryptedKey(vchPubKey, vchPrivKey, checksum_valid))
438  {
439  strErr = "Error reading wallet database: LegacyScriptPubKeyMan::LoadCryptedKey failed";
440  return false;
441  }
442  wss.fIsEncrypted = true;
443  } else if (strType == DBKeys::KEYMETA) {
444  CPubKey vchPubKey;
445  ssKey >> vchPubKey;
446  CKeyMetadata keyMeta;
447  ssValue >> keyMeta;
448  wss.nKeyMeta++;
449  pwallet->GetOrCreateLegacyScriptPubKeyMan()->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
450 
451  // Extract some CHDChain info from this metadata if it has any
452  if (keyMeta.nVersion >= CKeyMetadata::VERSION_WITH_HDDATA && !keyMeta.hd_seed_id.IsNull() && keyMeta.hdKeypath.size() > 0) {
453  // Get the path from the key origin or from the path string
454  // Not applicable when path is "s" or "m" as those indicate a seed
455  // See https://github.com/bitcoin/bitcoin/pull/12924
456  bool internal = false;
457  uint32_t index = 0;
458  if (keyMeta.hdKeypath != "s" && keyMeta.hdKeypath != "m") {
459  std::vector<uint32_t> path;
460  if (keyMeta.has_key_origin) {
461  // We have a key origin, so pull it from its path vector
462  path = keyMeta.key_origin.path;
463  } else {
464  // No key origin, have to parse the string
465  if (!ParseHDKeypath(keyMeta.hdKeypath, path)) {
466  strErr = "Error reading wallet database: keymeta with invalid HD keypath";
467  return false;
468  }
469  }
470 
471  // Extract the index and internal from the path
472  // Path string is m/0'/k'/i'
473  // Path vector is [0', k', i'] (but as ints OR'd with the hardened bit
474  // k == 0 for external, 1 for internal. i is the index
475  if (path.size() != 3) {
476  strErr = "Error reading wallet database: keymeta found with unexpected path";
477  return false;
478  }
479  if (path[0] != 0x80000000) {
480  strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
481  return false;
482  }
483  if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
484  strErr = strprintf("Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
485  return false;
486  }
487  if ((path[2] & 0x80000000) == 0) {
488  strErr = strprintf("Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
489  return false;
490  }
491  internal = path[1] == (1 | 0x80000000);
492  index = path[2] & ~0x80000000;
493  }
494 
495  // Insert a new CHDChain, or get the one that already exists
496  auto ins = wss.m_hd_chains.emplace(keyMeta.hd_seed_id, CHDChain());
497  CHDChain& chain = ins.first->second;
498  if (ins.second) {
499  // For new chains, we want to default to VERSION_HD_BASE until we see an internal
501  chain.seed_id = keyMeta.hd_seed_id;
502  }
503  if (internal) {
505  chain.nInternalChainCounter = std::max(chain.nInternalChainCounter, index);
506  } else {
507  chain.nExternalChainCounter = std::max(chain.nExternalChainCounter, index);
508  }
509  }
510  } else if (strType == DBKeys::WATCHMETA) {
511  CScript script;
512  ssKey >> script;
513  CKeyMetadata keyMeta;
514  ssValue >> keyMeta;
515  wss.nKeyMeta++;
516  pwallet->GetOrCreateLegacyScriptPubKeyMan()->LoadScriptMetadata(CScriptID(script), keyMeta);
517  } else if (strType == DBKeys::DEFAULTKEY) {
518  // We don't want or need the default key, but if there is one set,
519  // we want to make sure that it is valid so that we can detect corruption
520  CPubKey vchPubKey;
521  ssValue >> vchPubKey;
522  if (!vchPubKey.IsValid()) {
523  strErr = "Error reading wallet database: Default Key corrupt";
524  return false;
525  }
526  } else if (strType == DBKeys::POOL) {
527  int64_t nIndex;
528  ssKey >> nIndex;
529  CKeyPool keypool;
530  ssValue >> keypool;
531 
532  pwallet->GetOrCreateLegacyScriptPubKeyMan()->LoadKeyPool(nIndex, keypool);
533  } else if (strType == DBKeys::CSCRIPT) {
534  uint160 hash;
535  ssKey >> hash;
536  CScript script;
537  ssValue >> script;
538  if (!pwallet->GetOrCreateLegacyScriptPubKeyMan()->LoadCScript(script))
539  {
540  strErr = "Error reading wallet database: LegacyScriptPubKeyMan::LoadCScript failed";
541  return false;
542  }
543  } else if (strType == DBKeys::ORDERPOSNEXT) {
544  ssValue >> pwallet->nOrderPosNext;
545  } else if (strType == DBKeys::DESTDATA) {
546  std::string strAddress, strKey, strValue;
547  ssKey >> strAddress;
548  ssKey >> strKey;
549  ssValue >> strValue;
550  pwallet->LoadDestData(DecodeDestination(strAddress), strKey, strValue);
551  } else if (strType == DBKeys::HDCHAIN) {
552  CHDChain chain;
553  ssValue >> chain;
555  } else if (strType == DBKeys::OLD_KEY) {
556  strErr = "Found unsupported 'wkey' record, try loading with version 0.18";
557  return false;
558  } else if (strType == DBKeys::ACTIVEEXTERNALSPK || strType == DBKeys::ACTIVEINTERNALSPK) {
559  uint8_t type;
560  ssKey >> type;
561  uint256 id;
562  ssValue >> id;
563 
564  bool internal = strType == DBKeys::ACTIVEINTERNALSPK;
565  auto& spk_mans = internal ? wss.m_active_internal_spks : wss.m_active_external_spks;
566  if (spk_mans.count(static_cast<OutputType>(type)) > 0) {
567  strErr = "Multiple ScriptPubKeyMans specified for a single type";
568  return false;
569  }
570  spk_mans[static_cast<OutputType>(type)] = id;
571  } else if (strType == DBKeys::WALLETDESCRIPTOR) {
572  uint256 id;
573  ssKey >> id;
574  WalletDescriptor desc;
575  ssValue >> desc;
576  if (wss.m_descriptor_caches.count(id) == 0) {
578  }
579  pwallet->LoadDescriptorScriptPubKeyMan(id, desc);
580  } else if (strType == DBKeys::WALLETDESCRIPTORCACHE) {
581  bool parent = true;
582  uint256 desc_id;
583  uint32_t key_exp_index;
584  uint32_t der_index;
585  ssKey >> desc_id;
586  ssKey >> key_exp_index;
587 
588  // if the der_index exists, it's a derived xpub
589  try
590  {
591  ssKey >> der_index;
592  parent = false;
593  }
594  catch (...) {}
595 
596  std::vector<unsigned char> ser_xpub(BIP32_EXTKEY_SIZE);
597  ssValue >> ser_xpub;
598  CExtPubKey xpub;
599  xpub.Decode(ser_xpub.data());
600  if (parent) {
601  wss.m_descriptor_caches[desc_id].CacheParentExtPubKey(key_exp_index, xpub);
602  } else {
603  wss.m_descriptor_caches[desc_id].CacheDerivedExtPubKey(key_exp_index, der_index, xpub);
604  }
605  } else if (strType == DBKeys::WALLETDESCRIPTORKEY) {
606  uint256 desc_id;
607  CPubKey pubkey;
608  ssKey >> desc_id;
609  ssKey >> pubkey;
610  if (!pubkey.IsValid())
611  {
612  strErr = "Error reading wallet database: CPubKey corrupt";
613  return false;
614  }
615  CKey key;
616  CPrivKey pkey;
617  uint256 hash;
618 
619  wss.nKeys++;
620  ssValue >> pkey;
621  ssValue >> hash;
622 
623  // hash pubkey/privkey to accelerate wallet load
624  std::vector<unsigned char> to_hash;
625  to_hash.reserve(pubkey.size() + pkey.size());
626  to_hash.insert(to_hash.end(), pubkey.begin(), pubkey.end());
627  to_hash.insert(to_hash.end(), pkey.begin(), pkey.end());
628 
629  if (Hash(to_hash) != hash)
630  {
631  strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
632  return false;
633  }
634 
635  if (!key.Load(pkey, pubkey, true))
636  {
637  strErr = "Error reading wallet database: CPrivKey corrupt";
638  return false;
639  }
640  wss.m_descriptor_keys.insert(std::make_pair(std::make_pair(desc_id, pubkey.GetID()), key));
641  } else if (strType == DBKeys::WALLETDESCRIPTORCKEY) {
642  uint256 desc_id;
643  CPubKey pubkey;
644  ssKey >> desc_id;
645  ssKey >> pubkey;
646  if (!pubkey.IsValid())
647  {
648  strErr = "Error reading wallet database: CPubKey corrupt";
649  return false;
650  }
651  std::vector<unsigned char> privkey;
652  ssValue >> privkey;
653  wss.nCKeys++;
654 
655  wss.m_descriptor_crypt_keys.insert(std::make_pair(std::make_pair(desc_id, pubkey.GetID()), std::make_pair(pubkey, privkey)));
656  wss.fIsEncrypted = true;
657  } else if (strType != DBKeys::BESTBLOCK && strType != DBKeys::BESTBLOCK_NOMERKLE &&
658  strType != DBKeys::MINVERSION && strType != DBKeys::ACENTRY &&
659  strType != DBKeys::VERSION && strType != DBKeys::SETTINGS &&
660  strType != DBKeys::FLAGS) {
661  wss.m_unknown_records++;
662  }
663  } catch (const std::exception& e) {
664  if (strErr.empty()) {
665  strErr = e.what();
666  }
667  return false;
668  } catch (...) {
669  if (strErr.empty()) {
670  strErr = "Caught unknown exception in ReadKeyValue";
671  }
672  return false;
673  }
674  return true;
675 }
676 
677 bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, std::string& strType, std::string& strErr, const KeyFilterFn& filter_fn)
678 {
679  CWalletScanState dummy_wss;
680  LOCK(pwallet->cs_wallet);
681  return ReadKeyValue(pwallet, ssKey, ssValue, dummy_wss, strType, strErr, filter_fn);
682 }
683 
684 bool WalletBatch::IsKeyType(const std::string& strType)
685 {
686  return (strType == DBKeys::KEY ||
687  strType == DBKeys::MASTER_KEY || strType == DBKeys::CRYPTED_KEY);
688 }
689 
691 {
692  CWalletScanState wss;
693  bool fNoncriticalErrors = false;
694  DBErrors result = DBErrors::LOAD_OK;
695 
696  LOCK(pwallet->cs_wallet);
697  try {
698  int nMinVersion = 0;
699  if (m_batch->Read(DBKeys::MINVERSION, nMinVersion)) {
700  if (nMinVersion > FEATURE_LATEST)
701  return DBErrors::TOO_NEW;
702  pwallet->LoadMinVersion(nMinVersion);
703  }
704 
705  // Load wallet flags, so they are known when processing other records.
706  // The FLAGS key is absent during wallet creation.
707  uint64_t flags;
708  if (m_batch->Read(DBKeys::FLAGS, flags)) {
709  if (!pwallet->LoadWalletFlags(flags)) {
710  pwallet->WalletLogPrintf("Error reading wallet database: Unknown non-tolerable wallet flags found\n");
711  return DBErrors::CORRUPT;
712  }
713  }
714 
715  // Get cursor
716  if (!m_batch->StartCursor())
717  {
718  pwallet->WalletLogPrintf("Error getting wallet database cursor\n");
719  return DBErrors::CORRUPT;
720  }
721 
722  while (true)
723  {
724  // Read next record
727  bool complete;
728  bool ret = m_batch->ReadAtCursor(ssKey, ssValue, complete);
729  if (complete) {
730  break;
731  }
732  else if (!ret)
733  {
734  m_batch->CloseCursor();
735  pwallet->WalletLogPrintf("Error reading next record from wallet database\n");
736  return DBErrors::CORRUPT;
737  }
738 
739  // Try to be tolerant of single corrupt records:
740  std::string strType, strErr;
741  if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
742  {
743  // losing keys is considered a catastrophic error, anything else
744  // we assume the user can live with:
745  if (IsKeyType(strType) || strType == DBKeys::DEFAULTKEY) {
746  result = DBErrors::CORRUPT;
747  } else if (strType == DBKeys::FLAGS) {
748  // reading the wallet flags can only fail if unknown flags are present
749  result = DBErrors::TOO_NEW;
750  } else {
751  // Leave other errors alone, if we try to fix them we might make things worse.
752  fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
753  if (strType == DBKeys::TX)
754  // Rescan if there is a bad transaction record:
755  gArgs.SoftSetBoolArg("-rescan", true);
756  }
757  }
758  if (!strErr.empty())
759  pwallet->WalletLogPrintf("%s\n", strErr);
760  }
761  } catch (...) {
762  result = DBErrors::CORRUPT;
763  }
764  m_batch->CloseCursor();
765 
766  // Set the active ScriptPubKeyMans
767  for (auto spk_man_pair : wss.m_active_external_spks) {
768  pwallet->LoadActiveScriptPubKeyMan(spk_man_pair.second, spk_man_pair.first, /* internal */ false);
769  }
770  for (auto spk_man_pair : wss.m_active_internal_spks) {
771  pwallet->LoadActiveScriptPubKeyMan(spk_man_pair.second, spk_man_pair.first, /* internal */ true);
772  }
773 
774  // Set the descriptor caches
775  for (auto desc_cache_pair : wss.m_descriptor_caches) {
776  auto spk_man = pwallet->GetScriptPubKeyMan(desc_cache_pair.first);
777  assert(spk_man);
778  ((DescriptorScriptPubKeyMan*)spk_man)->SetCache(desc_cache_pair.second);
779  }
780 
781  // Set the descriptor keys
782  for (auto desc_key_pair : wss.m_descriptor_keys) {
783  auto spk_man = pwallet->GetScriptPubKeyMan(desc_key_pair.first.first);
784  ((DescriptorScriptPubKeyMan*)spk_man)->AddKey(desc_key_pair.first.second, desc_key_pair.second);
785  }
786  for (auto desc_key_pair : wss.m_descriptor_crypt_keys) {
787  auto spk_man = pwallet->GetScriptPubKeyMan(desc_key_pair.first.first);
788  ((DescriptorScriptPubKeyMan*)spk_man)->AddCryptedKey(desc_key_pair.first.second, desc_key_pair.second.first, desc_key_pair.second.second);
789  }
790 
791  if (fNoncriticalErrors && result == DBErrors::LOAD_OK)
793 
794  // Any wallet corruption at all: skip any rewriting or
795  // upgrading, we don't want to make it worse.
796  if (result != DBErrors::LOAD_OK)
797  return result;
798 
799  // Last client version to open this wallet, was previously the file version number
800  int last_client = CLIENT_VERSION;
801  m_batch->Read(DBKeys::VERSION, last_client);
802 
803  int wallet_version = pwallet->GetVersion();
804  pwallet->WalletLogPrintf("Wallet File Version = %d\n", wallet_version > 0 ? wallet_version : last_client);
805 
806  pwallet->WalletLogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total. Unknown wallet records: %u\n",
807  wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys, wss.m_unknown_records);
808 
809  // nTimeFirstKey is only reliable if all keys have metadata
810  if (pwallet->IsLegacy() && (wss.nKeys + wss.nCKeys + wss.nWatchKeys) != wss.nKeyMeta) {
811  auto spk_man = pwallet->GetOrCreateLegacyScriptPubKeyMan();
812  if (spk_man) {
813  LOCK(spk_man->cs_KeyStore);
814  spk_man->UpdateTimeFirstKey(1);
815  }
816  }
817 
818  for (const uint256& hash : wss.vWalletUpgrade)
819  WriteTx(pwallet->mapWallet.at(hash));
820 
821  // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
822  if (wss.fIsEncrypted && (last_client == 40000 || last_client == 50000))
823  return DBErrors::NEED_REWRITE;
824 
825  if (last_client < CLIENT_VERSION) // Update
827 
828  if (wss.fAnyUnordered)
829  result = pwallet->ReorderTransactions();
830 
831  // Upgrade all of the wallet keymetadata to have the hd master key id
832  // This operation is not atomic, but if it fails, updated entries are still backwards compatible with older software
833  try {
834  pwallet->UpgradeKeyMetadata();
835  } catch (...) {
836  result = DBErrors::CORRUPT;
837  }
838 
839  // Set the inactive chain
840  if (wss.m_hd_chains.size() > 0) {
841  LegacyScriptPubKeyMan* legacy_spkm = pwallet->GetLegacyScriptPubKeyMan();
842  if (!legacy_spkm) {
843  pwallet->WalletLogPrintf("Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
844  return DBErrors::CORRUPT;
845  }
846  for (const auto& chain_pair : wss.m_hd_chains) {
847  if (chain_pair.first != pwallet->GetLegacyScriptPubKeyMan()->GetHDChain().seed_id) {
848  pwallet->GetLegacyScriptPubKeyMan()->AddInactiveHDChain(chain_pair.second);
849  }
850  }
851  }
852 
853  return result;
854 }
855 
856 DBErrors WalletBatch::FindWalletTx(std::vector<uint256>& vTxHash, std::list<CWalletTx>& vWtx)
857 {
858  DBErrors result = DBErrors::LOAD_OK;
859 
860  try {
861  int nMinVersion = 0;
862  if (m_batch->Read(DBKeys::MINVERSION, nMinVersion)) {
863  if (nMinVersion > FEATURE_LATEST)
864  return DBErrors::TOO_NEW;
865  }
866 
867  // Get cursor
868  if (!m_batch->StartCursor())
869  {
870  LogPrintf("Error getting wallet database cursor\n");
871  return DBErrors::CORRUPT;
872  }
873 
874  while (true)
875  {
876  // Read next record
879  bool complete;
880  bool ret = m_batch->ReadAtCursor(ssKey, ssValue, complete);
881  if (complete) {
882  break;
883  } else if (!ret) {
884  m_batch->CloseCursor();
885  LogPrintf("Error reading next record from wallet database\n");
886  return DBErrors::CORRUPT;
887  }
888 
889  std::string strType;
890  ssKey >> strType;
891  if (strType == DBKeys::TX) {
892  uint256 hash;
893  ssKey >> hash;
894  vTxHash.push_back(hash);
895  vWtx.emplace_back(nullptr /* wallet */, nullptr /* tx */);
896  ssValue >> vWtx.back();
897  }
898  }
899  } catch (...) {
900  result = DBErrors::CORRUPT;
901  }
902  m_batch->CloseCursor();
903 
904  return result;
905 }
906 
907 DBErrors WalletBatch::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uint256>& vTxHashOut)
908 {
909  // build list of wallet TXs and hashes
910  std::vector<uint256> vTxHash;
911  std::list<CWalletTx> vWtx;
912  DBErrors err = FindWalletTx(vTxHash, vWtx);
913  if (err != DBErrors::LOAD_OK) {
914  return err;
915  }
916 
917  std::sort(vTxHash.begin(), vTxHash.end());
918  std::sort(vTxHashIn.begin(), vTxHashIn.end());
919 
920  // erase each matching wallet TX
921  bool delerror = false;
922  std::vector<uint256>::iterator it = vTxHashIn.begin();
923  for (const uint256& hash : vTxHash) {
924  while (it < vTxHashIn.end() && (*it) < hash) {
925  it++;
926  }
927  if (it == vTxHashIn.end()) {
928  break;
929  }
930  else if ((*it) == hash) {
931  if(!EraseTx(hash)) {
932  LogPrint(BCLog::WALLETDB, "Transaction was found for deletion but returned database error: %s\n", hash.GetHex());
933  delerror = true;
934  }
935  vTxHashOut.push_back(hash);
936  }
937  }
938 
939  if (delerror) {
940  return DBErrors::CORRUPT;
941  }
942  return DBErrors::LOAD_OK;
943 }
944 
946 {
947  static std::atomic<bool> fOneThread(false);
948  if (fOneThread.exchange(true)) {
949  return;
950  }
951 
952  for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
953  WalletDatabase& dbh = pwallet->GetDatabase();
954 
955  unsigned int nUpdateCounter = dbh.nUpdateCounter;
956 
957  if (dbh.nLastSeen != nUpdateCounter) {
958  dbh.nLastSeen = nUpdateCounter;
959  dbh.nLastWalletUpdate = GetTime();
960  }
961 
962  if (dbh.nLastFlushed != nUpdateCounter && GetTime() - dbh.nLastWalletUpdate >= 2) {
963  if (dbh.PeriodicFlush()) {
964  dbh.nLastFlushed = nUpdateCounter;
965  }
966  }
967  }
968 
969  fOneThread = false;
970 }
971 
972 bool WalletBatch::WriteDestData(const std::string &address, const std::string &key, const std::string &value)
973 {
974  return WriteIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(address, key)), value);
975 }
976 
977 bool WalletBatch::EraseDestData(const std::string &address, const std::string &key)
978 {
979  return EraseIC(std::make_pair(DBKeys::DESTDATA, std::make_pair(address, key)));
980 }
981 
982 
984 {
985  return WriteIC(DBKeys::HDCHAIN, chain);
986 }
987 
989 {
990  return WriteIC(DBKeys::FLAGS, flags);
991 }
992 
994 {
995  return m_batch->TxnBegin();
996 }
997 
999 {
1000  return m_batch->TxnCommit();
1001 }
1002 
1004 {
1005  return m_batch->TxnAbort();
1006 }
1007 
1008 std::unique_ptr<WalletDatabase> MakeDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error)
1009 {
1010  bool exists;
1011  try {
1012  exists = fs::symlink_status(path).type() != fs::file_not_found;
1013  } catch (const fs::filesystem_error& e) {
1014  error = Untranslated(strprintf("Failed to access database path '%s': %s", path.string(), fsbridge::get_filesystem_error_message(e)));
1016  return nullptr;
1017  }
1018 
1019  std::optional<DatabaseFormat> format;
1020  if (exists) {
1021  if (IsBDBFile(BDBDataFile(path))) {
1023  }
1024  if (IsSQLiteFile(SQLiteDataFile(path))) {
1025  if (format) {
1026  error = Untranslated(strprintf("Failed to load database path '%s'. Data is in ambiguous format.", path.string()));
1028  return nullptr;
1029  }
1031  }
1032  } else if (options.require_existing) {
1033  error = Untranslated(strprintf("Failed to load database path '%s'. Path does not exist.", path.string()));
1035  return nullptr;
1036  }
1037 
1038  if (!format && options.require_existing) {
1039  error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in recognized format.", path.string()));
1041  return nullptr;
1042  }
1043 
1044  if (format && options.require_create) {
1045  error = Untranslated(strprintf("Failed to create database path '%s'. Database already exists.", path.string()));
1047  return nullptr;
1048  }
1049 
1050  // A db already exists so format is set, but options also specifies the format, so make sure they agree
1051  if (format && options.require_format && format != options.require_format) {
1052  error = Untranslated(strprintf("Failed to load database path '%s'. Data is not in required format.", path.string()));
1054  return nullptr;
1055  }
1056 
1057  // Format is not set when a db doesn't already exist, so use the format specified by the options if it is set.
1058  if (!format && options.require_format) format = options.require_format;
1059 
1060  // If the format is not specified or detected, choose the default format based on what is available. We prefer BDB over SQLite for now.
1061  if (!format) {
1062 #ifdef USE_SQLITE
1064 #endif
1065 #ifdef USE_BDB
1067 #endif
1068  }
1069 
1070  if (format == DatabaseFormat::SQLITE) {
1071 #ifdef USE_SQLITE
1072  return MakeSQLiteDatabase(path, options, status, error);
1073 #endif
1074  error = Untranslated(strprintf("Failed to open database path '%s'. Build does not support SQLite database format.", path.string()));
1076  return nullptr;
1077  }
1078 
1079 #ifdef USE_BDB
1080  return MakeBerkeleyDatabase(path, options, status, error);
1081 #endif
1082  error = Untranslated(strprintf("Failed to open database path '%s'. Build does not support Berkeley DB database format.", path.string()));
1084  return nullptr;
1085 }
1086 
1088 std::unique_ptr<WalletDatabase> CreateDummyWalletDatabase()
1089 {
1090  return std::make_unique<DummyDatabase>();
1091 }
1092 
1094 std::unique_ptr<WalletDatabase> CreateMockWalletDatabase()
1095 {
1096 #ifdef USE_BDB
1097  return std::make_unique<BerkeleyDatabase>(std::make_shared<BerkeleyEnvironment>(), "");
1098 #elif USE_SQLITE
1099  return std::make_unique<SQLiteDatabase>("", "", true);
1100 #endif
1101 }
WalletBatch::WritePool
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:191
DatabaseStatus::FAILED_BAD_PATH
@ FAILED_BAD_PATH
DatabaseOptions::require_existing
bool require_existing
Definition: db.h:204
DatabaseOptions
Definition: db.h:203
CWallet::WalletLogPrintf
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:1209
BIP32_EXTKEY_SIZE
const unsigned int BIP32_EXTKEY_SIZE
Definition: pubkey.h:18
WalletBatch::WriteDestData
bool WriteDestData(const std::string &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
Definition: walletdb.cpp:972
WalletBatch::WriteDescriptor
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:232
bip32.h
CWallet::nMasterKeyMaxID
unsigned int nMasterKeyMaxID
Definition: wallet.h:768
WalletBatch::IsKeyType
static bool IsKeyType(const std::string &strType)
Definition: walletdb.cpp:684
CHDChain::nExternalChainCounter
uint32_t nExternalChainCounter
Definition: walletdb.h:88
CWalletScanState::CWalletScanState
CWalletScanState()
Definition: walletdb.cpp:268
DBKeys::OLD_KEY
const std::string OLD_KEY
Definition: walletdb.cpp:46
GetWallets
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: wallet.cpp:136
WalletBatch::WriteCScript
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:148
OutputType
OutputType
Definition: outputtype.h:17
WalletBatch::WriteCryptedDescriptorKey
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition: walletdb.cpp:223
DBKeys::CSCRIPT
const std::string CSCRIPT
Definition: walletdb.cpp:36
WalletBatch::m_batch
std::unique_ptr< DatabaseBatch > m_batch
Definition: walletdb.h:274
WalletBatch::WriteName
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:65
DBKeys::FLAGS
const std::string FLAGS
Definition: walletdb.cpp:39
MaybeCompactWalletDB
void MaybeCompactWalletDB()
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
Definition: walletdb.cpp:945
DatabaseStatus
DatabaseStatus
Definition: db.h:212
tinyformat::format
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:1062
SER_DISK
@ SER_DISK
Definition: serialize.h:167
CreateDummyWalletDatabase
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
Definition: walletdb.cpp:1088
wallet.h
DBKeys::BESTBLOCK
const std::string BESTBLOCK
Definition: walletdb.cpp:34
CKeyPool
A key from a CWallet's keypool.
Definition: scriptpubkeyman.h:101
LegacyScriptPubKeyMan::GetHDChain
const CHDChain & GetHDChain() const
Definition: scriptpubkeyman.h:430
fs.h
DBKeys::MASTER_KEY
const std::string MASTER_KEY
Definition: walletdb.cpp:43
DBErrors::NEED_REWRITE
@ NEED_REWRITE
WalletBatch::EraseTx
bool EraseTx(uint256 hash)
Definition: walletdb.cpp:92
flags
int flags
Definition: bitcoin-tx.cpp:512
key_io.h
DBKeys::ORDERPOSNEXT
const std::string ORDERPOSNEXT
Definition: walletdb.cpp:47
ArgsManager::SoftSetBoolArg
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:529
CWalletScanState::m_descriptor_keys
std::map< std::pair< uint256, CKeyID >, CKey > m_descriptor_keys
Definition: walletdb.cpp:264
sync.h
CHDChain::nVersion
int nVersion
Definition: walletdb.h:95
WalletBatch::LoadWallet
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:690
DBKeys::CRYPTED_KEY
const std::string CRYPTED_KEY
Definition: walletdb.cpp:35
LegacyScriptPubKeyMan::LoadKeyPool
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
Definition: scriptpubkeyman.cpp:1117
CWalletScanState::m_descriptor_crypt_keys
std::map< std::pair< uint256, CKeyID >, std::pair< CPubKey, std::vector< unsigned char > > > m_descriptor_crypt_keys
Definition: walletdb.cpp:265
fsbridge::get_filesystem_error_message
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:137
CWallet::LoadDescriptorScriptPubKeyMan
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:4499
bilingual_str
Bilingual messages:
Definition: translation.h:16
IsSQLiteFile
bool IsSQLiteFile(const fs::path &path)
Definition: db.cpp:100
CWalletScanState::fAnyUnordered
bool fAnyUnordered
Definition: walletdb.cpp:259
CPrivKey
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
secure_allocator is defined in allocators.h CPrivKey is a serialized private key, with all parameters...
Definition: key.h:24
CWalletScanState
Definition: walletdb.cpp:251
LegacyScriptPubKeyMan::LoadKeyMetadata
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
Definition: scriptpubkeyman.cpp:757
DBKeys::WATCHS
const std::string WATCHS
Definition: walletdb.cpp:58
DatabaseOptions::require_create
bool require_create
Definition: db.h:205
WalletBatch::WriteMasterKey
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:143
GetTime
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
DBErrors::NONCRITICAL_ERROR
@ NONCRITICAL_ERROR
ReadKeyValue
static bool ReadKeyValue(CWallet *pwallet, CDataStream &ssKey, CDataStream &ssValue, CWalletScanState &wss, std::string &strType, std::string &strErr, const KeyFilterFn &filter_fn=nullptr) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:273
DBKeys::WALLETDESCRIPTORCACHE
const std::string WALLETDESCRIPTORCACHE
Definition: walletdb.cpp:54
CMasterKey
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
Definition: crypter.h:33
WalletDatabase
An instance of this class represents one database.
Definition: db.h:103
CHDChain::VERSION_HD_CHAIN_SPLIT
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:93
LegacyScriptPubKeyMan
Definition: scriptpubkeyman.h:257
bdb.h
CExtPubKey::Decode
void Decode(const unsigned char code[BIP32_EXTKEY_SIZE])
Definition: pubkey.cpp:285
MakeDatabase
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: walletdb.cpp:1008
LegacyScriptPubKeyMan::LoadKey
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
Definition: scriptpubkeyman.cpp:690
CWalletScanState::fIsEncrypted
bool fIsEncrypted
Definition: walletdb.cpp:258
DBKeys::VERSION
const std::string VERSION
Definition: walletdb.cpp:52
sqlite.h
DBKeys::MINVERSION
const std::string MINVERSION
Definition: walletdb.cpp:44
WalletBatch::WriteActiveScriptPubKeyMan
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:206
DBKeys::ACTIVEINTERNALSPK
const std::string ACTIVEINTERNALSPK
Definition: walletdb.cpp:32
WalletBatch::TxnCommit
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:998
DBKeys::WATCHMETA
const std::string WATCHMETA
Definition: walletdb.cpp:57
CWallet::GetVersion
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.h:1096
WalletBatch::WriteDescriptorParentCache
bool WriteDescriptorParentCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:244
DescriptorScriptPubKeyMan
Definition: scriptpubkeyman.h:517
DBKeys::WALLETDESCRIPTORCKEY
const std::string WALLETDESCRIPTORCKEY
Definition: walletdb.cpp:55
CPubKey::begin
const unsigned char * begin() const
Definition: pubkey.h:112
DBKeys::PURPOSE
const std::string PURPOSE
Definition: walletdb.cpp:49
WalletDatabase::nUpdateCounter
std::atomic< unsigned int > nUpdateCounter
Definition: db.h:148
Hash
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition: hash.h:75
LegacyScriptPubKeyMan::LoadCScript
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
Definition: scriptpubkeyman.cpp:742
CWallet::UpgradeKeyMetadata
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
Definition: wallet.cpp:366
CHDChain::VERSION_HD_BASE
static const int VERSION_HD_BASE
Definition: walletdb.h:92
WalletDatabase::nLastWalletUpdate
int64_t nLastWalletUpdate
Definition: db.h:151
CWalletScanState::nKeyMeta
unsigned int nKeyMeta
Definition: walletdb.cpp:256
BCLog::WALLETDB
@ WALLETDB
Definition: logging.h:44
DBKeys::KEYMETA
const std::string KEYMETA
Definition: walletdb.cpp:41
LegacyScriptPubKeyMan::LoadHDChain
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
Definition: scriptpubkeyman.cpp:921
CWallet::LoadWalletFlags
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
Definition: wallet.cpp:1508
Untranslated
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:40
WalletBatch::EraseIC
bool EraseIC(const K &key)
Definition: walletdb.h:193
WalletBatch::ReadPool
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:186
DatabaseStatus::FAILED_ALREADY_EXISTS
@ FAILED_ALREADY_EXISTS
WalletBatch::WriteOrderPosNext
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:181
WalletBatch::EraseDestData
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:977
DBKeys::POOL
const std::string POOL
Definition: walletdb.cpp:48
CWallet::LoadDestData
void LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a destination data tuple to the store, without saving it to disk.
Definition: wallet.cpp:3786
DBKeys::WALLETDESCRIPTOR
const std::string WALLETDESCRIPTOR
Definition: walletdb.cpp:53
MakeSQLiteDatabase
std::unique_ptr< SQLiteDatabase > MakeSQLiteDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: sqlite.cpp:563
CPubKey::end
const unsigned char * end() const
Definition: pubkey.h:113
DBKeys::BESTBLOCK_NOMERKLE
const std::string BESTBLOCK_NOMERKLE
Definition: walletdb.cpp:33
DBKeys::KEY
const std::string KEY
Definition: walletdb.cpp:42
IsBDBFile
bool IsBDBFile(const fs::path &path)
Definition: db.cpp:75
WalletBatch::WritePurpose
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:77
DBKeys::SETTINGS
const std::string SETTINGS
Definition: walletdb.cpp:50
WalletBatch::EraseWatchOnly
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:161
CWalletScanState::vWalletUpgrade
std::vector< uint256 > vWalletUpgrade
Definition: walletdb.cpp:260
time.h
CHDChain::nInternalChainCounter
uint32_t nInternalChainCounter
Definition: walletdb.h:89
DBKeys::DEFAULTKEY
const std::string DEFAULTKEY
Definition: walletdb.cpp:37
WalletDatabase::nLastFlushed
unsigned int nLastFlushed
Definition: db.h:150
LogPrintf
#define LogPrintf(...)
Definition: logging.h:183
WalletBatch::WriteBestBlock
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:169
WalletBatch::ErasePool
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:196
BDBDataFile
fs::path BDBDataFile(const fs::path &wallet_path)
Definition: db.cpp:56
WalletBatch::WriteDescriptorDerivedCache
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
Definition: walletdb.cpp:237
CWallet::mapMasterKeys
MasterKeyMap mapMasterKeys
Definition: wallet.h:767
CWallet::ReorderTransactions
DBErrors ReorderTransactions()
Definition: wallet.cpp:700
CPubKey::size
unsigned int size() const
Simple read-only vector-like interface to the pubkey data.
Definition: pubkey.h:110
uint256
256-bit opaque blob.
Definition: uint256.h:124
WalletBatch::EraseName
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:70
DecodeDestination
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
Definition: key_io.cpp:246
DBKeys
Definition: walletdb.cpp:29
LogPrint
#define LogPrint(category,...)
Definition: logging.h:187
CExtPubKey::Encode
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
Definition: pubkey.cpp:275
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
CWalletScanState::m_active_internal_spks
std::map< OutputType, uint256 > m_active_internal_spks
Definition: walletdb.cpp:262
CWallet::GetLegacyScriptPubKeyMan
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:4449
WalletBatch::WriteHDChain
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:983
DatabaseFormat::SQLITE
@ SQLITE
DBErrors::LOAD_OK
@ LOAD_OK
DatabaseStatus::FAILED_NOT_FOUND
@ FAILED_NOT_FOUND
DBKeys::ACTIVEEXTERNALSPK
const std::string ACTIVEEXTERNALSPK
Definition: walletdb.cpp:31
DescriptorCache
Cache for single descriptor's derived extended pubkeys.
Definition: descriptor.h:19
DatabaseFormat::BERKELEY
@ BERKELEY
CWalletScanState::m_unknown_records
unsigned int m_unknown_records
Definition: walletdb.cpp:257
LegacyScriptPubKeyMan::LoadCryptedKey
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)
Definition: scriptpubkeyman.cpp:794
CWalletScanState::m_active_external_spks
std::map< OutputType, uint256 > m_active_external_spks
Definition: walletdb.cpp:261
WalletBatch::ReadBestBlock
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:175
WalletBatch::WriteDescriptorKey
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:212
WalletDatabase::nLastSeen
unsigned int nLastSeen
Definition: db.h:149
system.h
CWalletScanState::nWatchKeys
unsigned int nWatchKeys
Definition: walletdb.cpp:255
CWalletScanState::nCKeys
unsigned int nCKeys
Definition: walletdb.cpp:254
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
LegacyScriptPubKeyMan::LoadScriptMetadata
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
Definition: scriptpubkeyman.cpp:764
DBErrors
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:43
uint160
160-bit opaque blob.
Definition: uint256.h:113
CPubKey
An encapsulated public key.
Definition: pubkey.h:31
FEATURE_LATEST
@ FEATURE_LATEST
Definition: walletutil.h:29
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:31
WalletBatch::WriteCryptedKey
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:117
CKey
An encapsulated private key.
Definition: key.h:27
translation.h
CWalletScanState::m_hd_chains
std::map< uint160, CHDChain > m_hd_chains
Definition: walletdb.cpp:266
CHDChain
Definition: walletdb.h:85
EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
CBlockLocator::vHave
std::vector< uint256 > vHave
Definition: block.h:116
LOCK
#define LOCK(cs)
Definition: sync.h:232
SQLiteDataFile
fs::path SQLiteDataFile(const fs::path &path)
Definition: db.cpp:70
gArgs
ArgsManager gArgs
Definition: system.cpp:79
CreateMockWalletDatabase
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
Definition: walletdb.cpp:1094
CWallet
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:638
CHDChain::seed_id
CKeyID seed_id
seed hash160
Definition: walletdb.h:90
CWalletTx::GetHash
const uint256 & GetHash() const
Definition: wallet.h:552
CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:273
WalletBatch::FindWalletTx
DBErrors FindWalletTx(std::vector< uint256 > &vTxHash, std::list< CWalletTx > &vWtx)
Definition: walletdb.cpp:856
CWalletScanState::nKeys
unsigned int nKeys
Definition: walletdb.cpp:253
LegacyScriptPubKeyMan::LoadWatchOnly
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
Definition: scriptpubkeyman.cpp:872
CLIENT_VERSION
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:33
DBErrors::CORRUPT
@ CORRUPT
WalletBatch::WriteKeyMetadata
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:97
CKeyMetadata::VERSION_WITH_HDDATA
static const int VERSION_WITH_HDDATA
Definition: walletdb.h:125
MakeBerkeleyDatabase
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:825
CWallet::IsLegacy
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:4600
WalletBatch::WriteWatchOnly
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:153
CWallet::cs_wallet
RecursiveMutex cs_wallet
Definition: wallet.h:746
serialize.h
WalletDatabase::PeriodicFlush
virtual bool PeriodicFlush()=0
CDataStream
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:204
WalletBatch::WriteIC
bool WriteIC(const K &key, const T &value, bool fOverwrite=true)
Definition: walletdb.h:180
CWallet::GetScriptPubKeyMan
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:4392
WalletBatch::ErasePurpose
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:82
WalletBatch::ZapSelectTx
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: walletdb.cpp:907
WalletBatch::WriteMinVersion
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:201
WalletDescriptor
Descriptor with some wallet metadata.
Definition: walletutil.h:72
KeyFilterFn
std::function< bool(const std::string &)> KeyFilterFn
Callback for filtering key types to deserialize in ReadKeyValue.
Definition: walletdb.h:282
walletdb.h
CDataStream::empty
bool empty() const
Definition: streams.h:256
DBKeys::ACENTRY
const std::string ACENTRY
Definition: walletdb.cpp:30
DBKeys::HDCHAIN
const std::string HDCHAIN
Definition: walletdb.cpp:40
CKey::Load
bool Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck)
Load private key and check that public key matches.
Definition: key.cpp:261
WalletBatch::TxnBegin
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:993
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:50
WalletBatch::WriteTx
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:87
CBlockLocator
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:114
LegacyScriptPubKeyMan::AddInactiveHDChain
void AddInactiveHDChain(const CHDChain &chain)
Definition: scriptpubkeyman.cpp:942
ParseHDKeypath
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0'/2000".
Definition: bip32.cpp:12
CWallet::LoadActiveScriptPubKeyMan
void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Loads an active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:4589
CScriptID
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:86
WalletBatch::WriteKey
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:102
CWalletScanState::m_descriptor_caches
std::map< uint256, DescriptorCache > m_descriptor_caches
Definition: walletdb.cpp:263
DBKeys::TX
const std::string TX
Definition: walletdb.cpp:51
DBKeys::NAME
const std::string NAME
Definition: walletdb.cpp:45
assert
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
CExtPubKey
Definition: pubkey.h:240
DatabaseOptions::require_format
std::optional< DatabaseFormat > require_format
Definition: db.h:206
CWallet::LoadToWallet
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:971
CKeyMetadata
Definition: walletdb.h:121
CDataStream::eof
bool eof() const
Definition: streams.h:356
CWallet::GetOrCreateLegacyScriptPubKeyMan
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:4461
DatabaseStatus::FAILED_BAD_FORMAT
@ FAILED_BAD_FORMAT
CWallet::LoadMinVersion
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:869
it
auto it
Definition: validation.cpp:399
DBErrors::TOO_NEW
@ TOO_NEW
DBKeys::WALLETDESCRIPTORKEY
const std::string WALLETDESCRIPTORKEY
Definition: walletdb.cpp:56
WalletBatch::WriteWalletFlags
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:988
WalletBatch::TxnAbort
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:1003
DBKeys::DESTDATA
const std::string DESTDATA
Definition: walletdb.cpp:38