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