Bitcoin Core  21.99.0
P2P Digital Currency
wallet.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/wallet.h>
7 
8 #include <chain.h>
9 #include <consensus/consensus.h>
10 #include <consensus/validation.h>
11 #include <fs.h>
12 #include <interfaces/chain.h>
13 #include <interfaces/wallet.h>
14 #include <key.h>
15 #include <key_io.h>
16 #include <outputtype.h>
17 #include <policy/fees.h>
18 #include <policy/policy.h>
19 #include <primitives/block.h>
20 #include <primitives/transaction.h>
21 #include <psbt.h>
22 #include <script/descriptor.h>
23 #include <script/script.h>
24 #include <script/signingprovider.h>
25 #include <txmempool.h>
26 #include <util/bip32.h>
27 #include <util/check.h>
28 #include <util/error.h>
29 #include <util/fees.h>
30 #include <util/moneystr.h>
31 #include <util/rbf.h>
32 #include <util/string.h>
33 #include <util/translation.h>
34 #include <wallet/coincontrol.h>
35 #include <wallet/fees.h>
37 
38 #include <univalue.h>
39 
40 #include <algorithm>
41 #include <assert.h>
42 #include <optional>
43 
44 #include <boost/algorithm/string/replace.hpp>
45 
47 
48 const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS{
50  "You need to rescan the blockchain in order to correctly mark used "
51  "destinations in the past. Until this is done, some destinations may "
52  "be considered unused, even if the opposite is the case."
53  },
54 };
55 
57 static std::vector<std::shared_ptr<CWallet>> vpwallets GUARDED_BY(cs_wallets);
58 static std::list<LoadWalletFn> g_load_wallet_fns GUARDED_BY(cs_wallets);
59 
60 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
61 {
62  util::SettingsValue setting_value = chain.getRwSetting("wallet");
63  if (!setting_value.isArray()) setting_value.setArray();
64  for (const util::SettingsValue& value : setting_value.getValues()) {
65  if (value.isStr() && value.get_str() == wallet_name) return true;
66  }
67  setting_value.push_back(wallet_name);
68  return chain.updateRwSetting("wallet", setting_value);
69 }
70 
71 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
72 {
73  util::SettingsValue setting_value = chain.getRwSetting("wallet");
74  if (!setting_value.isArray()) return true;
76  for (const util::SettingsValue& value : setting_value.getValues()) {
77  if (!value.isStr() || value.get_str() != wallet_name) new_value.push_back(value);
78  }
79  if (new_value.size() == setting_value.size()) return true;
80  return chain.updateRwSetting("wallet", new_value);
81 }
82 
84  const std::string& wallet_name,
85  std::optional<bool> load_on_startup,
86  std::vector<bilingual_str>& warnings)
87 {
88  if (!load_on_startup) return;
89  if (load_on_startup.value() && !AddWalletSetting(chain, wallet_name)) {
90  warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may not be loaded next node startup."));
91  } else if (!load_on_startup.value() && !RemoveWalletSetting(chain, wallet_name)) {
92  warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may still be loaded next node startup."));
93  }
94 }
95 
96 bool AddWallet(const std::shared_ptr<CWallet>& wallet)
97 {
99  assert(wallet);
100  std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
101  if (i != vpwallets.end()) return false;
102  vpwallets.push_back(wallet);
103  wallet->ConnectScriptPubKeyManNotifiers();
104  wallet->NotifyCanGetAddressesChanged();
105  return true;
106 }
107 
108 bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings)
109 {
110  assert(wallet);
111 
112  interfaces::Chain& chain = wallet->chain();
113  std::string name = wallet->GetName();
114 
115  // Unregister with the validation interface which also drops shared ponters.
116  wallet->m_chain_notifications_handler.reset();
117  LOCK(cs_wallets);
118  std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
119  if (i == vpwallets.end()) return false;
120  vpwallets.erase(i);
121 
122  // Write the wallet setting
123  UpdateWalletSetting(chain, name, load_on_start, warnings);
124 
125  return true;
126 }
127 
128 bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start)
129 {
130  std::vector<bilingual_str> warnings;
131  return RemoveWallet(wallet, load_on_start, warnings);
132 }
133 
134 std::vector<std::shared_ptr<CWallet>> GetWallets()
135 {
136  LOCK(cs_wallets);
137  return vpwallets;
138 }
139 
140 std::shared_ptr<CWallet> GetWallet(const std::string& name)
141 {
142  LOCK(cs_wallets);
143  for (const std::shared_ptr<CWallet>& wallet : vpwallets) {
144  if (wallet->GetName() == name) return wallet;
145  }
146  return nullptr;
147 }
148 
149 std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet)
150 {
151  LOCK(cs_wallets);
152  auto it = g_load_wallet_fns.emplace(g_load_wallet_fns.end(), std::move(load_wallet));
153  return interfaces::MakeHandler([it] { LOCK(cs_wallets); g_load_wallet_fns.erase(it); });
154 }
155 
158 static std::condition_variable g_wallet_release_cv;
159 static std::set<std::string> g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
160 static std::set<std::string> g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
161 
162 // Custom deleter for shared_ptr<CWallet>.
164 {
165  const std::string name = wallet->GetName();
166  wallet->WalletLogPrintf("Releasing wallet\n");
167  wallet->Flush();
168  delete wallet;
169  // Wallet is now released, notify UnloadWallet, if any.
170  {
172  if (g_unloading_wallet_set.erase(name) == 0) {
173  // UnloadWallet was not called for this wallet, all done.
174  return;
175  }
176  }
177  g_wallet_release_cv.notify_all();
178 }
179 
180 void UnloadWallet(std::shared_ptr<CWallet>&& wallet)
181 {
182  // Mark wallet for unloading.
183  const std::string name = wallet->GetName();
184  {
186  auto it = g_unloading_wallet_set.insert(name);
187  assert(it.second);
188  }
189  // The wallet can be in use so it's not possible to explicitly unload here.
190  // Notify the unload intent so that all remaining shared pointers are
191  // released.
192  wallet->NotifyUnload();
193 
194  // Time to ditch our shared_ptr and wait for ReleaseWallet call.
195  wallet.reset();
196  {
198  while (g_unloading_wallet_set.count(name) == 1) {
199  g_wallet_release_cv.wait(lock);
200  }
201  }
202 }
203 
204 namespace {
205 std::shared_ptr<CWallet> LoadWalletInternal(interfaces::Chain& chain, const std::string& name, std::optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
206 {
207  try {
208  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
209  if (!database) {
210  error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
211  return nullptr;
212  }
213 
214  chain.initMessage(_("Loading wallet…").translated);
215  std::shared_ptr<CWallet> wallet = CWallet::Create(&chain, name, std::move(database), options.create_flags, error, warnings);
216  if (!wallet) {
217  error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error;
219  return nullptr;
220  }
221  AddWallet(wallet);
222  wallet->postInitProcess();
223 
224  // Write the wallet setting
225  UpdateWalletSetting(chain, name, load_on_start, warnings);
226 
227  return wallet;
228  } catch (const std::runtime_error& e) {
229  error = Untranslated(e.what());
231  return nullptr;
232  }
233 }
234 } // namespace
235 
236 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, std::optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
237 {
238  auto result = WITH_LOCK(g_loading_wallet_mutex, return g_loading_wallet_set.insert(name));
239  if (!result.second) {
240  error = Untranslated("Wallet already loading.");
242  return nullptr;
243  }
244  auto wallet = LoadWalletInternal(chain, name, load_on_start, options, status, error, warnings);
245  WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
246  return wallet;
247 }
248 
249 std::shared_ptr<CWallet> CreateWallet(interfaces::Chain& chain, const std::string& name, std::optional<bool> load_on_start, DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
250 {
251  uint64_t wallet_creation_flags = options.create_flags;
252  const SecureString& passphrase = options.create_passphrase;
253 
254  if (wallet_creation_flags & WALLET_FLAG_DESCRIPTORS) options.require_format = DatabaseFormat::SQLITE;
255 
256  // Indicate that the wallet is actually supposed to be blank and not just blank to make it encrypted
257  bool create_blank = (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET);
258 
259  // Born encrypted wallets need to be created blank first.
260  if (!passphrase.empty()) {
261  wallet_creation_flags |= WALLET_FLAG_BLANK_WALLET;
262  }
263 
264  // Private keys must be disabled for an external signer wallet
265  if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
266  error = Untranslated("Private keys must be disabled when using an external signer");
268  return nullptr;
269  }
270 
271  // Descriptor support must be enabled for an external signer wallet
272  if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DESCRIPTORS)) {
273  error = Untranslated("Descriptor support must be enabled when using an external signer");
275  return nullptr;
276  }
277 
278  // Wallet::Verify will check if we're trying to create a wallet with a duplicate name.
279  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
280  if (!database) {
281  error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
283  return nullptr;
284  }
285 
286  // Do not allow a passphrase when private keys are disabled
287  if (!passphrase.empty() && (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
288  error = Untranslated("Passphrase provided but private keys are disabled. A passphrase is only used to encrypt private keys, so cannot be used for wallets with private keys disabled.");
290  return nullptr;
291  }
292 
293  // Make the wallet
294  chain.initMessage(_("Loading wallet…").translated);
295  std::shared_ptr<CWallet> wallet = CWallet::Create(&chain, name, std::move(database), wallet_creation_flags, error, warnings);
296  if (!wallet) {
297  error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
299  return nullptr;
300  }
301 
302  // Encrypt the wallet
303  if (!passphrase.empty() && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
304  if (!wallet->EncryptWallet(passphrase)) {
305  error = Untranslated("Error: Wallet created but failed to encrypt.");
307  return nullptr;
308  }
309  if (!create_blank) {
310  // Unlock the wallet
311  if (!wallet->Unlock(passphrase)) {
312  error = Untranslated("Error: Wallet was encrypted but could not be unlocked");
314  return nullptr;
315  }
316 
317  // Set a seed for the wallet
318  {
319  LOCK(wallet->cs_wallet);
320  if (wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
321  wallet->SetupDescriptorScriptPubKeyMans();
322  } else {
323  for (auto spk_man : wallet->GetActiveScriptPubKeyMans()) {
324  if (!spk_man->SetupGeneration()) {
325  error = Untranslated("Unable to generate initial keys");
327  return nullptr;
328  }
329  }
330  }
331  }
332 
333  // Relock the wallet
334  wallet->Lock();
335  }
336  }
337  AddWallet(wallet);
338  wallet->postInitProcess();
339 
340  // Write the wallet settings
341  UpdateWalletSetting(chain, name, load_on_start, warnings);
342 
343  status = DatabaseStatus::SUCCESS;
344  return wallet;
345 }
346 
352 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
353 {
355  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
356  if (it == mapWallet.end())
357  return nullptr;
358  return &(it->second);
359 }
360 
362 {
364  return;
365  }
366 
367  auto spk_man = GetLegacyScriptPubKeyMan();
368  if (!spk_man) {
369  return;
370  }
371 
372  spk_man->UpgradeKeyMetadata();
373  SetWalletFlag(WALLET_FLAG_KEY_ORIGIN_METADATA);
374 }
375 
376 bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys)
377 {
378  CCrypter crypter;
379  CKeyingMaterial _vMasterKey;
380 
381  {
382  LOCK(cs_wallet);
383  for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
384  {
385  if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
386  return false;
387  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
388  continue; // try another master key
389  if (Unlock(_vMasterKey, accept_no_keys)) {
390  // Now that we've unlocked, upgrade the key metadata
392  return true;
393  }
394  }
395  }
396  return false;
397 }
398 
399 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
400 {
401  bool fWasLocked = IsLocked();
402 
403  {
404  LOCK(cs_wallet);
405  Lock();
406 
407  CCrypter crypter;
408  CKeyingMaterial _vMasterKey;
409  for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
410  {
411  if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
412  return false;
413  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
414  return false;
415  if (Unlock(_vMasterKey))
416  {
417  int64_t nStartTime = GetTimeMillis();
418  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
419  pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
420 
421  nStartTime = GetTimeMillis();
422  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
423  pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
424 
425  if (pMasterKey.second.nDeriveIterations < 25000)
426  pMasterKey.second.nDeriveIterations = 25000;
427 
428  WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
429 
430  if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
431  return false;
432  if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
433  return false;
434  WalletBatch(GetDatabase()).WriteMasterKey(pMasterKey.first, pMasterKey.second);
435  if (fWasLocked)
436  Lock();
437  return true;
438  }
439  }
440  }
441 
442  return false;
443 }
444 
446 {
447  WalletBatch batch(GetDatabase());
448  batch.WriteBestBlock(loc);
449 }
450 
451 void CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in)
452 {
453  LOCK(cs_wallet);
454  if (nWalletVersion >= nVersion)
455  return;
456  nWalletVersion = nVersion;
457 
458  {
459  WalletBatch* batch = batch_in ? batch_in : new WalletBatch(GetDatabase());
460  if (nWalletVersion > 40000)
461  batch->WriteMinVersion(nWalletVersion);
462  if (!batch_in)
463  delete batch;
464  }
465 }
466 
467 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
468 {
469  std::set<uint256> result;
471 
472  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
473  if (it == mapWallet.end())
474  return result;
475  const CWalletTx& wtx = it->second;
476 
477  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
478 
479  for (const CTxIn& txin : wtx.tx->vin)
480  {
481  if (mapTxSpends.count(txin.prevout) <= 1)
482  continue; // No conflict if zero or one spends
483  range = mapTxSpends.equal_range(txin.prevout);
484  for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
485  result.insert(_it->second);
486  }
487  return result;
488 }
489 
490 bool CWallet::HasWalletSpend(const uint256& txid) const
491 {
493  auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
494  return (iter != mapTxSpends.end() && iter->first.hash == txid);
495 }
496 
498 {
499  GetDatabase().Flush();
500 }
501 
503 {
504  GetDatabase().Close();
505 }
506 
507 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
508 {
509  // We want all the wallet transactions in range to have the same metadata as
510  // the oldest (smallest nOrderPos).
511  // So: find smallest nOrderPos:
512 
513  int nMinOrderPos = std::numeric_limits<int>::max();
514  const CWalletTx* copyFrom = nullptr;
515  for (TxSpends::iterator it = range.first; it != range.second; ++it) {
516  const CWalletTx* wtx = &mapWallet.at(it->second);
517  if (wtx->nOrderPos < nMinOrderPos) {
518  nMinOrderPos = wtx->nOrderPos;
519  copyFrom = wtx;
520  }
521  }
522 
523  if (!copyFrom) {
524  return;
525  }
526 
527  // Now copy data from copyFrom to rest:
528  for (TxSpends::iterator it = range.first; it != range.second; ++it)
529  {
530  const uint256& hash = it->second;
531  CWalletTx* copyTo = &mapWallet.at(hash);
532  if (copyFrom == copyTo) continue;
533  assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
534  if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
535  copyTo->mapValue = copyFrom->mapValue;
536  copyTo->vOrderForm = copyFrom->vOrderForm;
537  // fTimeReceivedIsTxTime not copied on purpose
538  // nTimeReceived not copied on purpose
539  copyTo->nTimeSmart = copyFrom->nTimeSmart;
540  copyTo->fFromMe = copyFrom->fFromMe;
541  // nOrderPos not copied on purpose
542  // cached members not copied on purpose
543  }
544 }
545 
550 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
551 {
552  const COutPoint outpoint(hash, n);
553  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
554  range = mapTxSpends.equal_range(outpoint);
555 
556  for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
557  {
558  const uint256& wtxid = it->second;
559  std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
560  if (mit != mapWallet.end()) {
561  int depth = mit->second.GetDepthInMainChain();
562  if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
563  return true; // Spent
564  }
565  }
566  return false;
567 }
568 
569 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
570 {
571  mapTxSpends.insert(std::make_pair(outpoint, wtxid));
572 
573  setLockedCoins.erase(outpoint);
574 
575  std::pair<TxSpends::iterator, TxSpends::iterator> range;
576  range = mapTxSpends.equal_range(outpoint);
577  SyncMetaData(range);
578 }
579 
580 
581 void CWallet::AddToSpends(const uint256& wtxid)
582 {
583  auto it = mapWallet.find(wtxid);
584  assert(it != mapWallet.end());
585  const CWalletTx& thisTx = it->second;
586  if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
587  return;
588 
589  for (const CTxIn& txin : thisTx.tx->vin)
590  AddToSpends(txin.prevout, wtxid);
591 }
592 
593 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
594 {
595  if (IsCrypted())
596  return false;
597 
598  CKeyingMaterial _vMasterKey;
599 
600  _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
601  GetStrongRandBytes(_vMasterKey.data(), WALLET_CRYPTO_KEY_SIZE);
602 
603  CMasterKey kMasterKey;
604 
605  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
607 
608  CCrypter crypter;
609  int64_t nStartTime = GetTimeMillis();
610  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
611  kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
612 
613  nStartTime = GetTimeMillis();
614  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
615  kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
616 
617  if (kMasterKey.nDeriveIterations < 25000)
618  kMasterKey.nDeriveIterations = 25000;
619 
620  WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
621 
622  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
623  return false;
624  if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
625  return false;
626 
627  {
628  LOCK(cs_wallet);
629  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
630  WalletBatch* encrypted_batch = new WalletBatch(GetDatabase());
631  if (!encrypted_batch->TxnBegin()) {
632  delete encrypted_batch;
633  encrypted_batch = nullptr;
634  return false;
635  }
636  encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
637 
638  for (const auto& spk_man_pair : m_spk_managers) {
639  auto spk_man = spk_man_pair.second.get();
640  if (!spk_man->Encrypt(_vMasterKey, encrypted_batch)) {
641  encrypted_batch->TxnAbort();
642  delete encrypted_batch;
643  encrypted_batch = nullptr;
644  // We now probably have half of our keys encrypted in memory, and half not...
645  // die and let the user reload the unencrypted wallet.
646  assert(false);
647  }
648  }
649 
650  // Encryption was introduced in version 0.4.0
651  SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch);
652 
653  if (!encrypted_batch->TxnCommit()) {
654  delete encrypted_batch;
655  encrypted_batch = nullptr;
656  // We now have keys encrypted in memory, but not on disk...
657  // die to avoid confusion and let the user reload the unencrypted wallet.
658  assert(false);
659  }
660 
661  delete encrypted_batch;
662  encrypted_batch = nullptr;
663 
664  Lock();
665  Unlock(strWalletPassphrase);
666 
667  // If we are using descriptors, make new descriptors with a new seed
670  } else if (auto spk_man = GetLegacyScriptPubKeyMan()) {
671  // if we are using HD, replace the HD seed with a new one
672  if (spk_man->IsHDEnabled()) {
673  if (!spk_man->SetupGeneration(true)) {
674  return false;
675  }
676  }
677  }
678  Lock();
679 
680  // Need to completely rewrite the wallet file; if we don't, bdb might keep
681  // bits of the unencrypted private key in slack space in the database file.
682  GetDatabase().Rewrite();
683 
684  // BDB seems to have a bad habit of writing old data into
685  // slack space in .dat files; that is bad if the old data is
686  // unencrypted private keys. So:
688 
689  }
690  NotifyStatusChanged(this);
691 
692  return true;
693 }
694 
696 {
697  LOCK(cs_wallet);
698  WalletBatch batch(GetDatabase());
699 
700  // Old wallets didn't have any defined order for transactions
701  // Probably a bad idea to change the output of this
702 
703  // First: get all CWalletTx into a sorted-by-time multimap.
704  typedef std::multimap<int64_t, CWalletTx*> TxItems;
705  TxItems txByTime;
706 
707  for (auto& entry : mapWallet)
708  {
709  CWalletTx* wtx = &entry.second;
710  txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
711  }
712 
713  nOrderPosNext = 0;
714  std::vector<int64_t> nOrderPosOffsets;
715  for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
716  {
717  CWalletTx *const pwtx = (*it).second;
718  int64_t& nOrderPos = pwtx->nOrderPos;
719 
720  if (nOrderPos == -1)
721  {
722  nOrderPos = nOrderPosNext++;
723  nOrderPosOffsets.push_back(nOrderPos);
724 
725  if (!batch.WriteTx(*pwtx))
726  return DBErrors::LOAD_FAIL;
727  }
728  else
729  {
730  int64_t nOrderPosOff = 0;
731  for (const int64_t& nOffsetStart : nOrderPosOffsets)
732  {
733  if (nOrderPos >= nOffsetStart)
734  ++nOrderPosOff;
735  }
736  nOrderPos += nOrderPosOff;
737  nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
738 
739  if (!nOrderPosOff)
740  continue;
741 
742  // Since we're changing the order, write it back
743  if (!batch.WriteTx(*pwtx))
744  return DBErrors::LOAD_FAIL;
745  }
746  }
747  batch.WriteOrderPosNext(nOrderPosNext);
748 
749  return DBErrors::LOAD_OK;
750 }
751 
753 {
755  int64_t nRet = nOrderPosNext++;
756  if (batch) {
757  batch->WriteOrderPosNext(nOrderPosNext);
758  } else {
759  WalletBatch(GetDatabase()).WriteOrderPosNext(nOrderPosNext);
760  }
761  return nRet;
762 }
763 
765 {
766  {
767  LOCK(cs_wallet);
768  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
769  item.second.MarkDirty();
770  }
771 }
772 
773 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
774 {
775  LOCK(cs_wallet);
776 
777  auto mi = mapWallet.find(originalHash);
778 
779  // There is a bug if MarkReplaced is not called on an existing wallet transaction.
780  assert(mi != mapWallet.end());
781 
782  CWalletTx& wtx = (*mi).second;
783 
784  // Ensure for now that we're not overwriting data
785  assert(wtx.mapValue.count("replaced_by_txid") == 0);
786 
787  wtx.mapValue["replaced_by_txid"] = newHash.ToString();
788 
789  // Refresh mempool status without waiting for transactionRemovedFromMempool
790  // notification so the wallet is in an internally consistent state and
791  // immediately knows the old transaction should not be considered trusted
792  // and is eligible to be abandoned
793  wtx.fInMempool = chain().isInMempool(originalHash);
794 
795  WalletBatch batch(GetDatabase());
796 
797  bool success = true;
798  if (!batch.WriteTx(wtx)) {
799  WalletLogPrintf("%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
800  success = false;
801  }
802 
803  NotifyTransactionChanged(this, originalHash, CT_UPDATED);
804 
805  return success;
806 }
807 
808 void CWallet::SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations)
809 {
811  const CWalletTx* srctx = GetWalletTx(hash);
812  if (!srctx) return;
813 
814  CTxDestination dst;
815  if (ExtractDestination(srctx->tx->vout[n].scriptPubKey, dst)) {
816  if (IsMine(dst)) {
817  if (used != IsAddressUsed(dst)) {
818  if (used) {
819  tx_destinations.insert(dst);
820  }
821  SetAddressUsed(batch, dst, used);
822  }
823  }
824  }
825 }
826 
827 bool CWallet::IsSpentKey(const uint256& hash, unsigned int n) const
828 {
830  const CWalletTx* srctx = GetWalletTx(hash);
831  if (srctx) {
832  assert(srctx->tx->vout.size() > n);
833  CTxDestination dest;
834  if (!ExtractDestination(srctx->tx->vout[n].scriptPubKey, dest)) {
835  return false;
836  }
837  if (IsAddressUsed(dest)) {
838  return true;
839  }
840  if (IsLegacy()) {
842  assert(spk_man != nullptr);
843  for (const auto& keyid : GetAffectedKeys(srctx->tx->vout[n].scriptPubKey, *spk_man)) {
844  WitnessV0KeyHash wpkh_dest(keyid);
845  if (IsAddressUsed(wpkh_dest)) {
846  return true;
847  }
848  ScriptHash sh_wpkh_dest(GetScriptForDestination(wpkh_dest));
849  if (IsAddressUsed(sh_wpkh_dest)) {
850  return true;
851  }
852  PKHash pkh_dest(keyid);
853  if (IsAddressUsed(pkh_dest)) {
854  return true;
855  }
856  }
857  }
858  }
859  return false;
860 }
861 
862 CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx, bool fFlushOnClose)
863 {
864  LOCK(cs_wallet);
865 
866  WalletBatch batch(GetDatabase(), fFlushOnClose);
867 
868  uint256 hash = tx->GetHash();
869 
871  // Mark used destinations
872  std::set<CTxDestination> tx_destinations;
873 
874  for (const CTxIn& txin : tx->vin) {
875  const COutPoint& op = txin.prevout;
876  SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations);
877  }
878 
879  MarkDestinationsDirty(tx_destinations);
880  }
881 
882  // Inserts only if not already there, returns tx inserted or tx found
883  auto ret = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(this, tx));
884  CWalletTx& wtx = (*ret.first).second;
885  bool fInsertedNew = ret.second;
886  bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew);
887  if (fInsertedNew) {
888  wtx.m_confirm = confirm;
890  wtx.nOrderPos = IncOrderPosNext(&batch);
891  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
892  wtx.nTimeSmart = ComputeTimeSmart(wtx);
893  AddToSpends(hash);
894  }
895 
896  if (!fInsertedNew)
897  {
898  if (confirm.status != wtx.m_confirm.status) {
899  wtx.m_confirm.status = confirm.status;
900  wtx.m_confirm.nIndex = confirm.nIndex;
901  wtx.m_confirm.hashBlock = confirm.hashBlock;
902  wtx.m_confirm.block_height = confirm.block_height;
903  fUpdated = true;
904  } else {
905  assert(wtx.m_confirm.nIndex == confirm.nIndex);
906  assert(wtx.m_confirm.hashBlock == confirm.hashBlock);
907  assert(wtx.m_confirm.block_height == confirm.block_height);
908  }
909  // If we have a witness-stripped version of this transaction, and we
910  // see a new version with a witness, then we must be upgrading a pre-segwit
911  // wallet. Store the new version of the transaction with the witness,
912  // as the stripped-version must be invalid.
913  // TODO: Store all versions of the transaction, instead of just one.
914  if (tx->HasWitness() && !wtx.tx->HasWitness()) {
915  wtx.SetTx(tx);
916  fUpdated = true;
917  }
918  }
919 
921  WalletLogPrintf("AddToWallet %s %s%s\n", hash.ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
922 
923  // Write to disk
924  if (fInsertedNew || fUpdated)
925  if (!batch.WriteTx(wtx))
926  return nullptr;
927 
928  // Break debit/credit balance caches:
929  wtx.MarkDirty();
930 
931  // Notify UI of new or updated transaction
932  NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
933 
934 #if HAVE_SYSTEM
935  // notify an external script when a wallet transaction comes in or is updated
936  std::string strCmd = gArgs.GetArg("-walletnotify", "");
937 
938  if (!strCmd.empty())
939  {
940  boost::replace_all(strCmd, "%s", hash.GetHex());
941  if (confirm.status == CWalletTx::Status::CONFIRMED)
942  {
943  boost::replace_all(strCmd, "%b", confirm.hashBlock.GetHex());
944  boost::replace_all(strCmd, "%h", ToString(confirm.block_height));
945  } else {
946  boost::replace_all(strCmd, "%b", "unconfirmed");
947  boost::replace_all(strCmd, "%h", "-1");
948  }
949 #ifndef WIN32
950  // Substituting the wallet name isn't currently supported on windows
951  // because windows shell escaping has not been implemented yet:
952  // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
953  // A few ways it could be implemented in the future are described in:
954  // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
955  boost::replace_all(strCmd, "%w", ShellEscape(GetName()));
956 #endif
957  std::thread t(runCommand, strCmd);
958  t.detach(); // thread runs free
959  }
960 #endif
961 
962  return &wtx;
963 }
964 
965 bool CWallet::LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx)
966 {
967  const auto& ins = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(this, nullptr));
968  CWalletTx& wtx = ins.first->second;
969  if (!fill_wtx(wtx, ins.second)) {
970  return false;
971  }
972  // If wallet doesn't have a chain (e.g wallet-tool), don't bother to update txn.
973  if (HaveChain()) {
974  bool active;
975  int height;
976  if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().inActiveChain(active).height(height)) && active) {
977  // Update cached block height variable since it not stored in the
978  // serialized transaction.
979  wtx.m_confirm.block_height = height;
980  } else if (wtx.isConflicted() || wtx.isConfirmed()) {
981  // If tx block (or conflicting block) was reorged out of chain
982  // while the wallet was shutdown, change tx status to UNCONFIRMED
983  // and reset block height, hash, and index. ABANDONED tx don't have
984  // associated blocks and don't need to be updated. The case where a
985  // transaction was reorged out while online and then reconfirmed
986  // while offline is covered by the rescan logic.
987  wtx.setUnconfirmed();
988  wtx.m_confirm.hashBlock = uint256();
989  wtx.m_confirm.block_height = 0;
990  wtx.m_confirm.nIndex = 0;
991  }
992  }
993  if (/* insertion took place */ ins.second) {
994  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
995  }
996  AddToSpends(hash);
997  for (const CTxIn& txin : wtx.tx->vin) {
998  auto it = mapWallet.find(txin.prevout.hash);
999  if (it != mapWallet.end()) {
1000  CWalletTx& prevtx = it->second;
1001  if (prevtx.isConflicted()) {
1003  }
1004  }
1005  }
1006  return true;
1007 }
1008 
1010 {
1011  const CTransaction& tx = *ptx;
1012  {
1014 
1015  if (!confirm.hashBlock.IsNull()) {
1016  for (const CTxIn& txin : tx.vin) {
1017  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1018  while (range.first != range.second) {
1019  if (range.first->second != tx.GetHash()) {
1020  WalletLogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), confirm.hashBlock.ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1021  MarkConflicted(confirm.hashBlock, confirm.block_height, range.first->second);
1022  }
1023  range.first++;
1024  }
1025  }
1026  }
1027 
1028  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1029  if (fExisted && !fUpdate) return false;
1030  if (fExisted || IsMine(tx) || IsFromMe(tx))
1031  {
1032  /* Check if any keys in the wallet keypool that were supposed to be unused
1033  * have appeared in a new transaction. If so, remove those keys from the keypool.
1034  * This can happen when restoring an old wallet backup that does not contain
1035  * the mostly recently created transactions from newer versions of the wallet.
1036  */
1037 
1038  // loop though all outputs
1039  for (const CTxOut& txout: tx.vout) {
1040  for (const auto& spk_man_pair : m_spk_managers) {
1041  spk_man_pair.second->MarkUnusedAddresses(txout.scriptPubKey);
1042  }
1043  }
1044 
1045  // Block disconnection override an abandoned tx as unconfirmed
1046  // which means user may have to call abandontransaction again
1047  return AddToWallet(MakeTransactionRef(tx), confirm, /* update_wtx= */ nullptr, /* fFlushOnClose= */ false);
1048  }
1049  }
1050  return false;
1051 }
1052 
1054 {
1055  LOCK(cs_wallet);
1056  const CWalletTx* wtx = GetWalletTx(hashTx);
1057  return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() == 0 && !wtx->InMempool();
1058 }
1059 
1061 {
1062  for (const CTxIn& txin : tx->vin) {
1063  auto it = mapWallet.find(txin.prevout.hash);
1064  if (it != mapWallet.end()) {
1065  it->second.MarkDirty();
1066  }
1067  }
1068 }
1069 
1071 {
1072  LOCK(cs_wallet);
1073 
1074  WalletBatch batch(GetDatabase());
1075 
1076  std::set<uint256> todo;
1077  std::set<uint256> done;
1078 
1079  // Can't mark abandoned if confirmed or in mempool
1080  auto it = mapWallet.find(hashTx);
1081  assert(it != mapWallet.end());
1082  const CWalletTx& origtx = it->second;
1083  if (origtx.GetDepthInMainChain() != 0 || origtx.InMempool()) {
1084  return false;
1085  }
1086 
1087  todo.insert(hashTx);
1088 
1089  while (!todo.empty()) {
1090  uint256 now = *todo.begin();
1091  todo.erase(now);
1092  done.insert(now);
1093  auto it = mapWallet.find(now);
1094  assert(it != mapWallet.end());
1095  CWalletTx& wtx = it->second;
1096  int currentconfirm = wtx.GetDepthInMainChain();
1097  // If the orig tx was not in block, none of its spends can be
1098  assert(currentconfirm <= 0);
1099  // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1100  if (currentconfirm == 0 && !wtx.isAbandoned()) {
1101  // If the orig tx was not in block/mempool, none of its spends can be in mempool
1102  assert(!wtx.InMempool());
1103  wtx.setAbandoned();
1104  wtx.MarkDirty();
1105  batch.WriteTx(wtx);
1107  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1108  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1109  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1110  if (!done.count(iter->second)) {
1111  todo.insert(iter->second);
1112  }
1113  iter++;
1114  }
1115  // If a transaction changes 'conflicted' state, that changes the balance
1116  // available of the outputs it spends. So force those to be recomputed
1117  MarkInputsDirty(wtx.tx);
1118  }
1119  }
1120 
1121  return true;
1122 }
1123 
1124 void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx)
1125 {
1126  LOCK(cs_wallet);
1127 
1128  int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
1129  // If number of conflict confirms cannot be determined, this means
1130  // that the block is still unknown or not yet part of the main chain,
1131  // for example when loading the wallet during a reindex. Do nothing in that
1132  // case.
1133  if (conflictconfirms >= 0)
1134  return;
1135 
1136  // Do not flush the wallet here for performance reasons
1137  WalletBatch batch(GetDatabase(), false);
1138 
1139  std::set<uint256> todo;
1140  std::set<uint256> done;
1141 
1142  todo.insert(hashTx);
1143 
1144  while (!todo.empty()) {
1145  uint256 now = *todo.begin();
1146  todo.erase(now);
1147  done.insert(now);
1148  auto it = mapWallet.find(now);
1149  assert(it != mapWallet.end());
1150  CWalletTx& wtx = it->second;
1151  int currentconfirm = wtx.GetDepthInMainChain();
1152  if (conflictconfirms < currentconfirm) {
1153  // Block is 'more conflicted' than current confirm; update.
1154  // Mark transaction as conflicted with this block.
1155  wtx.m_confirm.nIndex = 0;
1156  wtx.m_confirm.hashBlock = hashBlock;
1157  wtx.m_confirm.block_height = conflicting_height;
1158  wtx.setConflicted();
1159  wtx.MarkDirty();
1160  batch.WriteTx(wtx);
1161  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1162  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1163  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1164  if (!done.count(iter->second)) {
1165  todo.insert(iter->second);
1166  }
1167  iter++;
1168  }
1169  // If a transaction changes 'conflicted' state, that changes the balance
1170  // available of the outputs it spends. So force those to be recomputed
1171  MarkInputsDirty(wtx.tx);
1172  }
1173  }
1174 }
1175 
1176 void CWallet::SyncTransaction(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool update_tx)
1177 {
1178  if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx))
1179  return; // Not one of ours
1180 
1181  // If a transaction changes 'conflicted' state, that changes the balance
1182  // available of the outputs it spends. So force those to be
1183  // recomputed, also:
1184  MarkInputsDirty(ptx);
1185 }
1186 
1187 void CWallet::transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) {
1188  LOCK(cs_wallet);
1189  SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
1190 
1191  auto it = mapWallet.find(tx->GetHash());
1192  if (it != mapWallet.end()) {
1193  it->second.fInMempool = true;
1194  }
1195 }
1196 
1197 void CWallet::transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) {
1198  LOCK(cs_wallet);
1199  auto it = mapWallet.find(tx->GetHash());
1200  if (it != mapWallet.end()) {
1201  it->second.fInMempool = false;
1202  }
1203  // Handle transactions that were removed from the mempool because they
1204  // conflict with transactions in a newly connected block.
1205  if (reason == MemPoolRemovalReason::CONFLICT) {
1206  // Trigger external -walletnotify notifications for these transactions.
1207  // Set Status::UNCONFIRMED instead of Status::CONFLICTED for a few reasons:
1208  //
1209  // 1. The transactionRemovedFromMempool callback does not currently
1210  // provide the conflicting block's hash and height, and for backwards
1211  // compatibility reasons it may not be not safe to store conflicted
1212  // wallet transactions with a null block hash. See
1213  // https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
1214  // 2. For most of these transactions, the wallet's internal conflict
1215  // detection in the blockConnected handler will subsequently call
1216  // MarkConflicted and update them with CONFLICTED status anyway. This
1217  // applies to any wallet transaction that has inputs spent in the
1218  // block, or that has ancestors in the wallet with inputs spent by
1219  // the block.
1220  // 3. Longstanding behavior since the sync implementation in
1221  // https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
1222  // implementation before that was to mark these transactions
1223  // unconfirmed rather than conflicted.
1224  //
1225  // Nothing described above should be seen as an unchangeable requirement
1226  // when improving this code in the future. The wallet's heuristics for
1227  // distinguishing between conflicted and unconfirmed transactions are
1228  // imperfect, and could be improved in general, see
1229  // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
1230  SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
1231  }
1232 }
1233 
1234 void CWallet::blockConnected(const CBlock& block, int height)
1235 {
1236  const uint256& block_hash = block.GetHash();
1237  LOCK(cs_wallet);
1238 
1239  m_last_block_processed_height = height;
1240  m_last_block_processed = block_hash;
1241  for (size_t index = 0; index < block.vtx.size(); index++) {
1242  SyncTransaction(block.vtx[index], {CWalletTx::Status::CONFIRMED, height, block_hash, (int)index});
1243  transactionRemovedFromMempool(block.vtx[index], MemPoolRemovalReason::BLOCK, 0 /* mempool_sequence */);
1244  }
1245 }
1246 
1247 void CWallet::blockDisconnected(const CBlock& block, int height)
1248 {
1249  LOCK(cs_wallet);
1250 
1251  // At block disconnection, this will change an abandoned transaction to
1252  // be unconfirmed, whether or not the transaction is added back to the mempool.
1253  // User may have to call abandontransaction again. It may be addressed in the
1254  // future with a stickier abandoned state or even removing abandontransaction call.
1255  m_last_block_processed_height = height - 1;
1256  m_last_block_processed = block.hashPrevBlock;
1257  for (const CTransactionRef& ptx : block.vtx) {
1258  SyncTransaction(ptx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
1259  }
1260 }
1261 
1263 {
1265 }
1266 
1267 
1268 void CWallet::BlockUntilSyncedToCurrentChain() const {
1270  // Skip the queue-draining stuff if we know we're caught up with
1271  // ::ChainActive().Tip(), otherwise put a callback in the validation interface queue and wait
1272  // for the queue to drain enough to execute it (indicating we are caught up
1273  // at least with the time we entered this function).
1274  uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
1275  chain().waitForNotificationsIfTipChanged(last_block_hash);
1276 }
1277 
1278 // Note that this function doesn't distinguish between a 0-valued input,
1279 // and a not-"is mine" (according to the filter) input.
1280 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1281 {
1282  {
1283  LOCK(cs_wallet);
1284  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1285  if (mi != mapWallet.end())
1286  {
1287  const CWalletTx& prev = (*mi).second;
1288  if (txin.prevout.n < prev.tx->vout.size())
1289  if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1290  return prev.tx->vout[txin.prevout.n].nValue;
1291  }
1292  }
1293  return 0;
1294 }
1295 
1296 isminetype CWallet::IsMine(const CTxOut& txout) const
1297 {
1299  return IsMine(txout.scriptPubKey);
1300 }
1301 
1303 {
1305  return IsMine(GetScriptForDestination(dest));
1306 }
1307 
1308 isminetype CWallet::IsMine(const CScript& script) const
1309 {
1311  isminetype result = ISMINE_NO;
1312  for (const auto& spk_man_pair : m_spk_managers) {
1313  result = std::max(result, spk_man_pair.second->IsMine(script));
1314  }
1315  return result;
1316 }
1317 
1318 bool CWallet::IsMine(const CTransaction& tx) const
1319 {
1321  for (const CTxOut& txout : tx.vout)
1322  if (IsMine(txout))
1323  return true;
1324  return false;
1325 }
1326 
1327 bool CWallet::IsFromMe(const CTransaction& tx) const
1328 {
1329  return (GetDebit(tx, ISMINE_ALL) > 0);
1330 }
1331 
1332 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1333 {
1334  CAmount nDebit = 0;
1335  for (const CTxIn& txin : tx.vin)
1336  {
1337  nDebit += GetDebit(txin, filter);
1338  if (!MoneyRange(nDebit))
1339  throw std::runtime_error(std::string(__func__) + ": value out of range");
1340  }
1341  return nDebit;
1342 }
1343 
1345 {
1346  // All Active ScriptPubKeyMans must be HD for this to be true
1347  bool result = true;
1348  for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
1349  result &= spk_man->IsHDEnabled();
1350  }
1351  return result;
1352 }
1353 
1354 bool CWallet::CanGetAddresses(bool internal) const
1355 {
1356  LOCK(cs_wallet);
1357  if (m_spk_managers.empty()) return false;
1358  for (OutputType t : OUTPUT_TYPES) {
1359  auto spk_man = GetScriptPubKeyMan(t, internal);
1360  if (spk_man && spk_man->CanGetAddresses(internal)) {
1361  return true;
1362  }
1363  }
1364  return false;
1365 }
1366 
1367 void CWallet::SetWalletFlag(uint64_t flags)
1368 {
1369  LOCK(cs_wallet);
1370  m_wallet_flags |= flags;
1371  if (!WalletBatch(GetDatabase()).WriteWalletFlags(m_wallet_flags))
1372  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1373 }
1374 
1375 void CWallet::UnsetWalletFlag(uint64_t flag)
1376 {
1377  WalletBatch batch(GetDatabase());
1378  UnsetWalletFlagWithDB(batch, flag);
1379 }
1380 
1381 void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
1382 {
1383  LOCK(cs_wallet);
1384  m_wallet_flags &= ~flag;
1385  if (!batch.WriteWalletFlags(m_wallet_flags))
1386  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1387 }
1388 
1390 {
1392 }
1393 
1394 bool CWallet::IsWalletFlagSet(uint64_t flag) const
1395 {
1396  return (m_wallet_flags & flag);
1397 }
1398 
1400 {
1401  LOCK(cs_wallet);
1402  if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
1403  // contains unknown non-tolerable wallet flags
1404  return false;
1405  }
1407 
1408  return true;
1409 }
1410 
1412 {
1413  LOCK(cs_wallet);
1414  // We should never be writing unknown non-tolerable wallet flags
1415  assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
1416  if (!WalletBatch(GetDatabase()).WriteWalletFlags(flags)) {
1417  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1418  }
1419 
1420  return LoadWalletFlags(flags);
1421 }
1422 
1423 // Helper for producing a max-sized low-S low-R signature (eg 71 bytes)
1424 // or a max-sized low-S signature (e.g. 72 bytes) if use_max_sig is true
1425 bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig) const
1426 {
1427  // Fill in dummy signatures for fee calculation.
1428  const CScript& scriptPubKey = txout.scriptPubKey;
1429  SignatureData sigdata;
1430 
1431  std::unique_ptr<SigningProvider> provider = GetSolvingProvider(scriptPubKey);
1432  if (!provider) {
1433  // We don't know about this scriptpbuKey;
1434  return false;
1435  }
1436 
1437  if (!ProduceSignature(*provider, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigdata)) {
1438  return false;
1439  }
1440  UpdateInput(tx_in, sigdata);
1441  return true;
1442 }
1443 
1444 // Helper for producing a bunch of max-sized low-S low-R signatures (eg 71 bytes)
1445 bool CWallet::DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig) const
1446 {
1447  // Fill in dummy signatures for fee calculation.
1448  int nIn = 0;
1449  for (const auto& txout : txouts)
1450  {
1451  if (!DummySignInput(txNew.vin[nIn], txout, use_max_sig)) {
1452  return false;
1453  }
1454 
1455  nIn++;
1456  }
1457  return true;
1458 }
1459 
1460 bool CWallet::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1461 {
1462  auto spk_man = GetLegacyScriptPubKeyMan();
1463  if (!spk_man) {
1464  return false;
1465  }
1466  LOCK(spk_man->cs_KeyStore);
1467  return spk_man->ImportScripts(scripts, timestamp);
1468 }
1469 
1470 bool CWallet::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1471 {
1472  auto spk_man = GetLegacyScriptPubKeyMan();
1473  if (!spk_man) {
1474  return false;
1475  }
1476  LOCK(spk_man->cs_KeyStore);
1477  return spk_man->ImportPrivKeys(privkey_map, timestamp);
1478 }
1479 
1480 bool CWallet::ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp)
1481 {
1482  auto spk_man = GetLegacyScriptPubKeyMan();
1483  if (!spk_man) {
1484  return false;
1485  }
1486  LOCK(spk_man->cs_KeyStore);
1487  return spk_man->ImportPubKeys(ordered_pubkeys, pubkey_map, key_origins, add_keypool, internal, timestamp);
1488 }
1489 
1490 bool CWallet::ImportScriptPubKeys(const std::string& label, const std::set<CScript>& script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp)
1491 {
1492  auto spk_man = GetLegacyScriptPubKeyMan();
1493  if (!spk_man) {
1494  return false;
1495  }
1496  LOCK(spk_man->cs_KeyStore);
1497  if (!spk_man->ImportScriptPubKeys(script_pub_keys, have_solving_data, timestamp)) {
1498  return false;
1499  }
1500  if (apply_label) {
1501  WalletBatch batch(GetDatabase());
1502  for (const CScript& script : script_pub_keys) {
1503  CTxDestination dest;
1504  ExtractDestination(script, dest);
1505  if (IsValidDestination(dest)) {
1506  SetAddressBookWithDB(batch, dest, label, "receive");
1507  }
1508  }
1509  }
1510  return true;
1511 }
1512 
1521 int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
1522 {
1523  // Find starting block. May be null if nCreateTime is greater than the
1524  // highest blockchain timestamp, in which case there is nothing that needs
1525  // to be scanned.
1526  int start_height = 0;
1527  uint256 start_block;
1528  bool start = chain().findFirstBlockWithTimeAndHeight(startTime - TIMESTAMP_WINDOW, 0, FoundBlock().hash(start_block).height(start_height));
1529  WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, start ? WITH_LOCK(cs_wallet, return GetLastBlockHeight()) - start_height + 1 : 0);
1530 
1531  if (start) {
1532  // TODO: this should take into account failure by ScanResult::USER_ABORT
1533  ScanResult result = ScanForWalletTransactions(start_block, start_height, {} /* max_height */, reserver, update);
1534  if (result.status == ScanResult::FAILURE) {
1535  int64_t time_max;
1536  CHECK_NONFATAL(chain().findBlock(result.last_failed_block, FoundBlock().maxTime(time_max)));
1537  return time_max + TIMESTAMP_WINDOW + 1;
1538  }
1539  }
1540  return startTime;
1541 }
1542 
1564 CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate)
1565 {
1566  int64_t nNow = GetTime();
1567  int64_t start_time = GetTimeMillis();
1568 
1569  assert(reserver.isReserved());
1570 
1571  uint256 block_hash = start_block;
1572  ScanResult result;
1573 
1574  WalletLogPrintf("Rescan started from block %s...\n", start_block.ToString());
1575 
1576  fAbortRescan = false;
1577  ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1578  uint256 tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1579  uint256 end_hash = tip_hash;
1580  if (max_height) chain().findAncestorByHeight(tip_hash, *max_height, FoundBlock().hash(end_hash));
1581  double progress_begin = chain().guessVerificationProgress(block_hash);
1582  double progress_end = chain().guessVerificationProgress(end_hash);
1583  double progress_current = progress_begin;
1584  int block_height = start_height;
1585  while (!fAbortRescan && !chain().shutdownRequested()) {
1586  if (progress_end - progress_begin > 0.0) {
1587  m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);
1588  } else { // avoid divide-by-zero for single block scan range (i.e. start and stop hashes are equal)
1589  m_scanning_progress = 0;
1590  }
1591  if (block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
1592  ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
1593  }
1594  if (GetTime() >= nNow + 60) {
1595  nNow = GetTime();
1596  WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n", block_height, progress_current);
1597  }
1598 
1599  // Read block data
1600  CBlock block;
1601  chain().findBlock(block_hash, FoundBlock().data(block));
1602 
1603  // Find next block separately from reading data above, because reading
1604  // is slow and there might be a reorg while it is read.
1605  bool block_still_active = false;
1606  bool next_block = false;
1607  uint256 next_block_hash;
1608  chain().findBlock(block_hash, FoundBlock().inActiveChain(block_still_active).nextBlock(FoundBlock().inActiveChain(next_block).hash(next_block_hash)));
1609 
1610  if (!block.IsNull()) {
1611  LOCK(cs_wallet);
1612  if (!block_still_active) {
1613  // Abort scan if current block is no longer active, to prevent
1614  // marking transactions as coming from the wrong block.
1615  result.last_failed_block = block_hash;
1616  result.status = ScanResult::FAILURE;
1617  break;
1618  }
1619  for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1620  SyncTransaction(block.vtx[posInBlock], {CWalletTx::Status::CONFIRMED, block_height, block_hash, (int)posInBlock}, fUpdate);
1621  }
1622  // scan succeeded, record block as most recent successfully scanned
1623  result.last_scanned_block = block_hash;
1624  result.last_scanned_height = block_height;
1625  } else {
1626  // could not scan block, keep scanning but record this block as the most recent failure
1627  result.last_failed_block = block_hash;
1628  result.status = ScanResult::FAILURE;
1629  }
1630  if (max_height && block_height >= *max_height) {
1631  break;
1632  }
1633  {
1634  if (!next_block) {
1635  // break successfully when rescan has reached the tip, or
1636  // previous block is no longer on the chain due to a reorg
1637  break;
1638  }
1639 
1640  // increment block and verification progress
1641  block_hash = next_block_hash;
1642  ++block_height;
1643  progress_current = chain().guessVerificationProgress(block_hash);
1644 
1645  // handle updated tip hash
1646  const uint256 prev_tip_hash = tip_hash;
1647  tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1648  if (!max_height && prev_tip_hash != tip_hash) {
1649  // in case the tip has changed, update progress max
1650  progress_end = chain().guessVerificationProgress(tip_hash);
1651  }
1652  }
1653  }
1654  ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), 100); // hide progress dialog in GUI
1655  if (block_height && fAbortRescan) {
1656  WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", block_height, progress_current);
1657  result.status = ScanResult::USER_ABORT;
1658  } else if (block_height && chain().shutdownRequested()) {
1659  WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", block_height, progress_current);
1660  result.status = ScanResult::USER_ABORT;
1661  } else {
1662  WalletLogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - start_time);
1663  }
1664  return result;
1665 }
1666 
1668 {
1669  // If transactions aren't being broadcasted, don't let them into local mempool either
1671  return;
1672  std::map<int64_t, CWalletTx*> mapSorted;
1673 
1674  // Sort pending wallet transactions based on their initial wallet insertion order
1675  for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
1676  const uint256& wtxid = item.first;
1677  CWalletTx& wtx = item.second;
1678  assert(wtx.GetHash() == wtxid);
1679 
1680  int nDepth = wtx.GetDepthInMainChain();
1681 
1682  if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1683  mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1684  }
1685  }
1686 
1687  // Try to add wallet transactions to memory pool
1688  for (const std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
1689  CWalletTx& wtx = *(item.second);
1690  std::string unused_err_string;
1691  wtx.SubmitMemoryPoolAndRelay(unused_err_string, false);
1692  }
1693 }
1694 
1695 bool CWalletTx::SubmitMemoryPoolAndRelay(std::string& err_string, bool relay)
1696 {
1697  // Can't relay if wallet is not broadcasting
1698  if (!pwallet->GetBroadcastTransactions()) return false;
1699  // Don't relay abandoned transactions
1700  if (isAbandoned()) return false;
1701  // Don't try to submit coinbase transactions. These would fail anyway but would
1702  // cause log spam.
1703  if (IsCoinBase()) return false;
1704  // Don't try to submit conflicted or confirmed transactions.
1705  if (GetDepthInMainChain() != 0) return false;
1706 
1707  // Submit transaction to mempool for relay
1708  pwallet->WalletLogPrintf("Submitting wtx %s to mempool for relay\n", GetHash().ToString());
1709  // We must set fInMempool here - while it will be re-set to true by the
1710  // entered-mempool callback, if we did not there would be a race where a
1711  // user could call sendmoney in a loop and hit spurious out of funds errors
1712  // because we think that this newly generated transaction's change is
1713  // unavailable as we're not yet aware that it is in the mempool.
1714  //
1715  // Irrespective of the failure reason, un-marking fInMempool
1716  // out-of-order is incorrect - it should be unmarked when
1717  // TransactionRemovedFromMempool fires.
1718  bool ret = pwallet->chain().broadcastTransaction(tx, pwallet->m_default_max_tx_fee, relay, err_string);
1719  fInMempool |= ret;
1720  return ret;
1721 }
1722 
1723 std::set<uint256> CWalletTx::GetConflicts() const
1724 {
1725  std::set<uint256> result;
1726  if (pwallet != nullptr)
1727  {
1728  uint256 myHash = GetHash();
1729  result = pwallet->GetConflicts(myHash);
1730  result.erase(myHash);
1731  }
1732  return result;
1733 }
1734 
1735 // Rebroadcast transactions from the wallet. We do this on a random timer
1736 // to slightly obfuscate which transactions come from our wallet.
1737 //
1738 // Ideally, we'd only resend transactions that we think should have been
1739 // mined in the most recent block. Any transaction that wasn't in the top
1740 // blockweight of transactions in the mempool shouldn't have been mined,
1741 // and so is probably just sitting in the mempool waiting to be confirmed.
1742 // Rebroadcasting does nothing to speed up confirmation and only damages
1743 // privacy.
1745 {
1746  // During reindex, importing and IBD, old wallet transactions become
1747  // unconfirmed. Don't resend them as that would spam other nodes.
1748  if (!chain().isReadyToBroadcast()) return;
1749 
1750  // Do this infrequently and randomly to avoid giving away
1751  // that these are our transactions.
1752  if (GetTime() < nNextResend || !fBroadcastTransactions) return;
1753  bool fFirst = (nNextResend == 0);
1754  // resend 12-36 hours from now, ~1 day on average.
1755  nNextResend = GetTime() + (12 * 60 * 60) + GetRand(24 * 60 * 60);
1756  if (fFirst) return;
1757 
1758  int submitted_tx_count = 0;
1759 
1760  { // cs_wallet scope
1761  LOCK(cs_wallet);
1762 
1763  // Relay transactions
1764  for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
1765  CWalletTx& wtx = item.second;
1766  // Attempt to rebroadcast all txes more than 5 minutes older than
1767  // the last block. SubmitMemoryPoolAndRelay() will not rebroadcast
1768  // any confirmed or conflicting txs.
1769  if (wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
1770  std::string unused_err_string;
1771  if (wtx.SubmitMemoryPoolAndRelay(unused_err_string, true)) ++submitted_tx_count;
1772  }
1773  } // cs_wallet
1774 
1775  if (submitted_tx_count > 0) {
1776  WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__, submitted_tx_count);
1777  }
1778 }
1779  // end of mapWallet
1781 
1783 {
1784  for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
1785  pwallet->ResendWalletTransactions();
1786  }
1787 }
1788 
1789 
1796 {
1798 
1799  // Build coins map
1800  std::map<COutPoint, Coin> coins;
1801  for (auto& input : tx.vin) {
1802  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
1803  if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
1804  return false;
1805  }
1806  const CWalletTx& wtx = mi->second;
1807  coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], wtx.m_confirm.block_height, wtx.IsCoinBase());
1808  }
1809  std::map<int, std::string> input_errors;
1810  return SignTransaction(tx, coins, SIGHASH_ALL, input_errors);
1811 }
1812 
1813 bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
1814 {
1815  // Try to sign with all ScriptPubKeyMans
1816  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
1817  // spk_man->SignTransaction will return true if the transaction is complete,
1818  // so we can exit early and return true if that happens
1819  if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
1820  return true;
1821  }
1822  }
1823 
1824  // At this point, one input was not fully signed otherwise we would have exited already
1825  return false;
1826 }
1827 
1828 TransactionError CWallet::FillPSBT(PartiallySignedTransaction& psbtx, bool& complete, int sighash_type, bool sign, bool bip32derivs, size_t * n_signed) const
1829 {
1830  if (n_signed) {
1831  *n_signed = 0;
1832  }
1833  LOCK(cs_wallet);
1834  // Get all of the previous transactions
1835  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
1836  const CTxIn& txin = psbtx.tx->vin[i];
1837  PSBTInput& input = psbtx.inputs.at(i);
1838 
1839  if (PSBTInputSigned(input)) {
1840  continue;
1841  }
1842 
1843  // If we have no utxo, grab it from the wallet.
1844  if (!input.non_witness_utxo) {
1845  const uint256& txhash = txin.prevout.hash;
1846  const auto it = mapWallet.find(txhash);
1847  if (it != mapWallet.end()) {
1848  const CWalletTx& wtx = it->second;
1849  // We only need the non_witness_utxo, which is a superset of the witness_utxo.
1850  // The signing code will switch to the smaller witness_utxo if this is ok.
1851  input.non_witness_utxo = wtx.tx;
1852  }
1853  }
1854  }
1855 
1856  // Fill in information from ScriptPubKeyMans
1857  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
1858  int n_signed_this_spkm = 0;
1859  TransactionError res = spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs, &n_signed_this_spkm);
1860  if (res != TransactionError::OK) {
1861  return res;
1862  }
1863 
1864  if (n_signed) {
1865  (*n_signed) += n_signed_this_spkm;
1866  }
1867  }
1868 
1869  // Complete if every input is now signed
1870  complete = true;
1871  for (const auto& input : psbtx.inputs) {
1872  complete &= PSBTInputSigned(input);
1873  }
1874 
1875  return TransactionError::OK;
1876 }
1877 
1878 SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1879 {
1880  SignatureData sigdata;
1881  CScript script_pub_key = GetScriptForDestination(pkhash);
1882  for (const auto& spk_man_pair : m_spk_managers) {
1883  if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
1884  return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
1885  }
1886  }
1888 }
1889 
1890 OutputType CWallet::TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const
1891 {
1892  // If -changetype is specified, always use that change type.
1893  if (change_type) {
1894  return *change_type;
1895  }
1896 
1897  // if m_default_address_type is legacy, use legacy address as change (even
1898  // if some of the outputs are P2WPKH or P2WSH).
1900  return OutputType::LEGACY;
1901  }
1902 
1903  // if any destination is P2WPKH or P2WSH, use P2WPKH for the change
1904  // output.
1905  for (const auto& recipient : vecSend) {
1906  // Check if any destination contains a witness program:
1907  int witnessversion = 0;
1908  std::vector<unsigned char> witnessprogram;
1909  if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1910  return OutputType::BECH32;
1911  }
1912  }
1913 
1914  // else use m_default_address_type for change
1915  return m_default_address_type;
1916 }
1917 
1918 void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
1919 {
1920  LOCK(cs_wallet);
1921  WalletLogPrintf("CommitTransaction:\n%s", tx->ToString()); /* Continued */
1922 
1923  // Add tx to wallet, because if it has change it's also ours,
1924  // otherwise just for transaction history.
1925  AddToWallet(tx, {}, [&](CWalletTx& wtx, bool new_tx) {
1926  CHECK_NONFATAL(wtx.mapValue.empty());
1927  CHECK_NONFATAL(wtx.vOrderForm.empty());
1928  wtx.mapValue = std::move(mapValue);
1929  wtx.vOrderForm = std::move(orderForm);
1930  wtx.fTimeReceivedIsTxTime = true;
1931  wtx.fFromMe = true;
1932  return true;
1933  });
1934 
1935  // Notify that old coins are spent
1936  for (const CTxIn& txin : tx->vin) {
1937  CWalletTx &coin = mapWallet.at(txin.prevout.hash);
1938  coin.MarkDirty();
1940  }
1941 
1942  // Get the inserted-CWalletTx from mapWallet so that the
1943  // fInMempool flag is cached properly
1944  CWalletTx& wtx = mapWallet.at(tx->GetHash());
1945 
1946  if (!fBroadcastTransactions) {
1947  // Don't submit tx to the mempool
1948  return;
1949  }
1950 
1951  std::string err_string;
1952  if (!wtx.SubmitMemoryPoolAndRelay(err_string, true)) {
1953  WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
1954  // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
1955  }
1956 }
1957 
1959 {
1960  LOCK(cs_wallet);
1961 
1962  DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
1963  if (nLoadWalletRet == DBErrors::NEED_REWRITE)
1964  {
1965  if (GetDatabase().Rewrite("\x04pool"))
1966  {
1967  for (const auto& spk_man_pair : m_spk_managers) {
1968  spk_man_pair.second->RewriteDB();
1969  }
1970  }
1971  }
1972 
1973  if (m_spk_managers.empty()) {
1976  }
1977 
1978  if (nLoadWalletRet != DBErrors::LOAD_OK)
1979  return nLoadWalletRet;
1980 
1981  return DBErrors::LOAD_OK;
1982 }
1983 
1984 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
1985 {
1987  DBErrors nZapSelectTxRet = WalletBatch(GetDatabase()).ZapSelectTx(vHashIn, vHashOut);
1988  for (const uint256& hash : vHashOut) {
1989  const auto& it = mapWallet.find(hash);
1990  wtxOrdered.erase(it->second.m_it_wtxOrdered);
1991  for (const auto& txin : it->second.tx->vin)
1992  mapTxSpends.erase(txin.prevout);
1993  mapWallet.erase(it);
1994  NotifyTransactionChanged(this, hash, CT_DELETED);
1995  }
1996 
1997  if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
1998  {
1999  if (GetDatabase().Rewrite("\x04pool"))
2000  {
2001  for (const auto& spk_man_pair : m_spk_managers) {
2002  spk_man_pair.second->RewriteDB();
2003  }
2004  }
2005  }
2006 
2007  if (nZapSelectTxRet != DBErrors::LOAD_OK)
2008  return nZapSelectTxRet;
2009 
2010  MarkDirty();
2011 
2012  return DBErrors::LOAD_OK;
2013 }
2014 
2015 bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
2016 {
2017  bool fUpdated = false;
2018  bool is_mine;
2019  {
2020  LOCK(cs_wallet);
2021  std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
2022  fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
2023  m_address_book[address].SetLabel(strName);
2024  if (!strPurpose.empty()) /* update purpose only if requested */
2025  m_address_book[address].purpose = strPurpose;
2026  is_mine = IsMine(address) != ISMINE_NO;
2027  }
2028  NotifyAddressBookChanged(this, address, strName, is_mine,
2029  strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2030  if (!strPurpose.empty() && !batch.WritePurpose(EncodeDestination(address), strPurpose))
2031  return false;
2032  return batch.WriteName(EncodeDestination(address), strName);
2033 }
2034 
2035 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
2036 {
2037  WalletBatch batch(GetDatabase());
2038  return SetAddressBookWithDB(batch, address, strName, strPurpose);
2039 }
2040 
2042 {
2043  bool is_mine;
2044  WalletBatch batch(GetDatabase());
2045  {
2046  LOCK(cs_wallet);
2047  // If we want to delete receiving addresses, we need to take care that DestData "used" (and possibly newer DestData) gets preserved (and the "deleted" address transformed into a change entry instead of actually being deleted)
2048  // NOTE: This isn't a problem for sending addresses because they never have any DestData yet!
2049  // When adding new DestData, it should be considered here whether to retain or delete it (or move it?).
2050  if (IsMine(address)) {
2051  WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, PACKAGE_BUGREPORT);
2052  return false;
2053  }
2054  // Delete destdata tuples associated with address
2055  std::string strAddress = EncodeDestination(address);
2056  for (const std::pair<const std::string, std::string> &item : m_address_book[address].destdata)
2057  {
2058  batch.EraseDestData(strAddress, item.first);
2059  }
2060  m_address_book.erase(address);
2061  is_mine = IsMine(address) != ISMINE_NO;
2062  }
2063 
2064  NotifyAddressBookChanged(this, address, "", is_mine, "", CT_DELETED);
2065 
2066  batch.ErasePurpose(EncodeDestination(address));
2067  return batch.EraseName(EncodeDestination(address));
2068 }
2069 
2071 {
2073 
2074  unsigned int count = 0;
2075  for (auto spk_man : GetActiveScriptPubKeyMans()) {
2076  count += spk_man->KeypoolCountExternalKeys();
2077  }
2078 
2079  return count;
2080 }
2081 
2082 unsigned int CWallet::GetKeyPoolSize() const
2083 {
2085 
2086  unsigned int count = 0;
2087  for (auto spk_man : GetActiveScriptPubKeyMans()) {
2088  count += spk_man->GetKeyPoolSize();
2089  }
2090  return count;
2091 }
2092 
2093 bool CWallet::TopUpKeyPool(unsigned int kpSize)
2094 {
2095  LOCK(cs_wallet);
2096  bool res = true;
2097  for (auto spk_man : GetActiveScriptPubKeyMans()) {
2098  res &= spk_man->TopUp(kpSize);
2099  }
2100  return res;
2101 }
2102 
2103 bool CWallet::GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error)
2104 {
2105  LOCK(cs_wallet);
2106  error.clear();
2107  bool result = false;
2108  auto spk_man = GetScriptPubKeyMan(type, false /* internal */);
2109  if (spk_man) {
2110  spk_man->TopUp();
2111  result = spk_man->GetNewDestination(type, dest, error);
2112  } else {
2113  error = strprintf("Error: No %s addresses available.", FormatOutputType(type));
2114  }
2115  if (result) {
2116  SetAddressBook(dest, label, "receive");
2117  }
2118 
2119  return result;
2120 }
2121 
2123 {
2124  LOCK(cs_wallet);
2125  error.clear();
2126 
2127  ReserveDestination reservedest(this, type);
2128  if (!reservedest.GetReservedDestination(dest, true)) {
2129  error = _("Error: Keypool ran out, please call keypoolrefill first").translated;
2130  return false;
2131  }
2132 
2133  reservedest.KeepDestination();
2134  return true;
2135 }
2136 
2138 {
2139  LOCK(cs_wallet);
2140  int64_t oldestKey = std::numeric_limits<int64_t>::max();
2141  for (const auto& spk_man_pair : m_spk_managers) {
2142  oldestKey = std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
2143  }
2144  return oldestKey;
2145 }
2146 
2147 void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
2148  for (auto& entry : mapWallet) {
2149  CWalletTx& wtx = entry.second;
2150  if (wtx.m_is_cache_empty) continue;
2151  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
2152  CTxDestination dst;
2153  if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.count(dst)) {
2154  wtx.MarkDirty();
2155  break;
2156  }
2157  }
2158  }
2159 }
2160 
2161 std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
2162 {
2163  LOCK(cs_wallet);
2164  std::set<CTxDestination> result;
2165  for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book)
2166  {
2167  if (item.second.IsChange()) continue;
2168  const CTxDestination& address = item.first;
2169  const std::string& strName = item.second.GetLabel();
2170  if (strName == label)
2171  result.insert(address);
2172  }
2173  return result;
2174 }
2175 
2177 {
2178  m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
2179  if (!m_spk_man) {
2180  return false;
2181  }
2182 
2183 
2184  if (nIndex == -1)
2185  {
2186  m_spk_man->TopUp();
2187 
2188  CKeyPool keypool;
2189  if (!m_spk_man->GetReservedDestination(type, internal, address, nIndex, keypool)) {
2190  return false;
2191  }
2192  fInternal = keypool.fInternal;
2193  }
2194  dest = address;
2195  return true;
2196 }
2197 
2199 {
2200  if (nIndex != -1) {
2202  }
2203  nIndex = -1;
2204  address = CNoDestination();
2205 }
2206 
2208 {
2209  if (nIndex != -1) {
2211  }
2212  nIndex = -1;
2213  address = CNoDestination();
2214 }
2215 
2217 {
2218 #ifdef ENABLE_EXTERNAL_SIGNER
2219  CScript scriptPubKey = GetScriptForDestination(dest);
2220  const auto spk_man = GetScriptPubKeyMan(scriptPubKey);
2221  if (spk_man == nullptr) {
2222  return false;
2223  }
2224  auto signer_spk_man = dynamic_cast<ExternalSignerScriptPubKeyMan*>(spk_man);
2225  if (signer_spk_man == nullptr) {
2226  return false;
2227  }
2229  return signer_spk_man->DisplayAddress(scriptPubKey, signer);
2230 #else
2231  return false;
2232 #endif
2233 }
2234 
2235 void CWallet::LockCoin(const COutPoint& output)
2236 {
2238  setLockedCoins.insert(output);
2239 }
2240 
2241 void CWallet::UnlockCoin(const COutPoint& output)
2242 {
2244  setLockedCoins.erase(output);
2245 }
2246 
2248 {
2250  setLockedCoins.clear();
2251 }
2252 
2253 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2254 {
2256  COutPoint outpt(hash, n);
2257 
2258  return (setLockedCoins.count(outpt) > 0);
2259 }
2260 
2261 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
2262 {
2264  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2265  it != setLockedCoins.end(); it++) {
2266  COutPoint outpt = (*it);
2267  vOutpts.push_back(outpt);
2268  }
2269 }
2270  // end of Actions
2272 
2273 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
2275  mapKeyBirth.clear();
2276 
2278  assert(spk_man != nullptr);
2279  LOCK(spk_man->cs_KeyStore);
2280 
2281  // get birth times for keys with metadata
2282  for (const auto& entry : spk_man->mapKeyMetadata) {
2283  if (entry.second.nCreateTime) {
2284  mapKeyBirth[entry.first] = entry.second.nCreateTime;
2285  }
2286  }
2287 
2288  // map in which we'll infer heights of other keys
2289  std::map<CKeyID, const CWalletTx::Confirmation*> mapKeyFirstBlock;
2290  CWalletTx::Confirmation max_confirm;
2291  max_confirm.block_height = GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
2292  CHECK_NONFATAL(chain().findAncestorByHeight(GetLastBlockHash(), max_confirm.block_height, FoundBlock().hash(max_confirm.hashBlock)));
2293  for (const CKeyID &keyid : spk_man->GetKeys()) {
2294  if (mapKeyBirth.count(keyid) == 0)
2295  mapKeyFirstBlock[keyid] = &max_confirm;
2296  }
2297 
2298  // if there are no such keys, we're done
2299  if (mapKeyFirstBlock.empty())
2300  return;
2301 
2302  // find first block that affects those keys, if there are any left
2303  for (const auto& entry : mapWallet) {
2304  // iterate over all wallet transactions...
2305  const CWalletTx &wtx = entry.second;
2306  if (wtx.m_confirm.status == CWalletTx::CONFIRMED) {
2307  // ... which are already in a block
2308  for (const CTxOut &txout : wtx.tx->vout) {
2309  // iterate over all their outputs
2310  for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
2311  // ... and all their affected keys
2312  auto rit = mapKeyFirstBlock.find(keyid);
2313  if (rit != mapKeyFirstBlock.end() && wtx.m_confirm.block_height < rit->second->block_height) {
2314  rit->second = &wtx.m_confirm;
2315  }
2316  }
2317  }
2318  }
2319  }
2320 
2321  // Extract block timestamps for those keys
2322  for (const auto& entry : mapKeyFirstBlock) {
2323  int64_t block_time;
2324  CHECK_NONFATAL(chain().findBlock(entry.second->hashBlock, FoundBlock().time(block_time)));
2325  mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW; // block times can be 2h off
2326  }
2327 }
2328 
2350 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
2351 {
2352  unsigned int nTimeSmart = wtx.nTimeReceived;
2353  if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
2354  int64_t blocktime;
2355  if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().time(blocktime))) {
2356  int64_t latestNow = wtx.nTimeReceived;
2357  int64_t latestEntry = 0;
2358 
2359  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
2360  int64_t latestTolerated = latestNow + 300;
2361  const TxItems& txOrdered = wtxOrdered;
2362  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
2363  CWalletTx* const pwtx = it->second;
2364  if (pwtx == &wtx) {
2365  continue;
2366  }
2367  int64_t nSmartTime;
2368  nSmartTime = pwtx->nTimeSmart;
2369  if (!nSmartTime) {
2370  nSmartTime = pwtx->nTimeReceived;
2371  }
2372  if (nSmartTime <= latestTolerated) {
2373  latestEntry = nSmartTime;
2374  if (nSmartTime > latestNow) {
2375  latestNow = nSmartTime;
2376  }
2377  break;
2378  }
2379  }
2380 
2381  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
2382  } else {
2383  WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.m_confirm.hashBlock.ToString());
2384  }
2385  }
2386  return nTimeSmart;
2387 }
2388 
2389 bool CWallet::SetAddressUsed(WalletBatch& batch, const CTxDestination& dest, bool used)
2390 {
2391  const std::string key{"used"};
2392  if (std::get_if<CNoDestination>(&dest))
2393  return false;
2394 
2395  if (!used) {
2396  if (auto* data = util::FindKey(m_address_book, dest)) data->destdata.erase(key);
2397  return batch.EraseDestData(EncodeDestination(dest), key);
2398  }
2399 
2400  const std::string value{"1"};
2401  m_address_book[dest].destdata.insert(std::make_pair(key, value));
2402  return batch.WriteDestData(EncodeDestination(dest), key, value);
2403 }
2404 
2405 void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2406 {
2407  m_address_book[dest].destdata.insert(std::make_pair(key, value));
2408 }
2409 
2411 {
2412  const std::string key{"used"};
2413  std::map<CTxDestination, CAddressBookData>::const_iterator i = m_address_book.find(dest);
2414  if(i != m_address_book.end())
2415  {
2416  CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
2417  if(j != i->second.destdata.end())
2418  {
2419  return true;
2420  }
2421  }
2422  return false;
2423 }
2424 
2425 std::vector<std::string> CWallet::GetAddressReceiveRequests() const
2426 {
2427  const std::string prefix{"rr"};
2428  std::vector<std::string> values;
2429  for (const auto& address : m_address_book) {
2430  for (const auto& data : address.second.destdata) {
2431  if (!data.first.compare(0, prefix.size(), prefix)) {
2432  values.emplace_back(data.second);
2433  }
2434  }
2435  }
2436  return values;
2437 }
2438 
2439 bool CWallet::SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value)
2440 {
2441  const std::string key{"rr" + id}; // "rr" prefix = "receive request" in destdata
2442  CAddressBookData& data = m_address_book.at(dest);
2443  if (value.empty()) {
2444  if (!batch.EraseDestData(EncodeDestination(dest), key)) return false;
2445  data.destdata.erase(key);
2446  } else {
2447  if (!batch.WriteDestData(EncodeDestination(dest), key, value)) return false;
2448  data.destdata[key] = value;
2449  }
2450  return true;
2451 }
2452 
2453 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
2454 {
2455  // Do some checking on wallet path. It should be either a:
2456  //
2457  // 1. Path where a directory can be created.
2458  // 2. Path to an existing directory.
2459  // 3. Path to a symlink to a directory.
2460  // 4. For backwards compatibility, the name of a data file in -walletdir.
2461  const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), name);
2462  fs::file_type path_type = fs::symlink_status(wallet_path).type();
2463  if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
2464  (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
2465  (path_type == fs::regular_file && fs::path(name).filename() == name))) {
2466  error_string = Untranslated(strprintf(
2467  "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
2468  "database/log.?????????? files can be stored, a location where such a directory could be created, "
2469  "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
2470  name, GetWalletDir()));
2472  return nullptr;
2473  }
2474  return MakeDatabase(wallet_path, options, status, error_string);
2475 }
2476 
2477 std::shared_ptr<CWallet> CWallet::Create(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings)
2478 {
2479  const std::string& walletFile = database->Filename();
2480 
2481  int64_t nStart = GetTimeMillis();
2482  // TODO: Can't use std::make_shared because we need a custom deleter but
2483  // should be possible to use std::allocate_shared.
2484  std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), ReleaseWallet);
2485  DBErrors nLoadWalletRet = walletInstance->LoadWallet();
2486  if (nLoadWalletRet != DBErrors::LOAD_OK) {
2487  if (nLoadWalletRet == DBErrors::CORRUPT) {
2488  error = strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
2489  return nullptr;
2490  }
2491  else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
2492  {
2493  warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
2494  " or address book entries might be missing or incorrect."),
2495  walletFile));
2496  }
2497  else if (nLoadWalletRet == DBErrors::TOO_NEW) {
2498  error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, PACKAGE_NAME);
2499  return nullptr;
2500  }
2501  else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
2502  {
2503  error = strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME);
2504  return nullptr;
2505  }
2506  else {
2507  error = strprintf(_("Error loading %s"), walletFile);
2508  return nullptr;
2509  }
2510  }
2511 
2512  // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
2513  const bool fFirstRun = walletInstance->m_spk_managers.empty() &&
2514  !walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
2515  !walletInstance->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
2516  if (fFirstRun)
2517  {
2518  // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
2519  walletInstance->SetMinVersion(FEATURE_LATEST);
2520 
2521  walletInstance->AddWalletFlags(wallet_creation_flags);
2522 
2523  // Only create LegacyScriptPubKeyMan when not descriptor wallet
2524  if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2525  walletInstance->SetupLegacyScriptPubKeyMan();
2526  }
2527 
2528  if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) || !(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
2529  LOCK(walletInstance->cs_wallet);
2530  if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2531  walletInstance->SetupDescriptorScriptPubKeyMans();
2532  // SetupDescriptorScriptPubKeyMans already calls SetupGeneration for us so we don't need to call SetupGeneration separately
2533  } else {
2534  // Legacy wallets need SetupGeneration here.
2535  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
2536  if (!spk_man->SetupGeneration()) {
2537  error = _("Unable to generate initial keys");
2538  return nullptr;
2539  }
2540  }
2541  }
2542  }
2543 
2544  if (chain) {
2545  walletInstance->chainStateFlushed(chain->getTipLocator());
2546  }
2547  } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
2548  // Make it impossible to disable private keys after creation
2549  error = strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile);
2550  return NULL;
2551  } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
2552  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
2553  if (spk_man->HavePrivateKeys()) {
2554  warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
2555  break;
2556  }
2557  }
2558  }
2559 
2560  if (!gArgs.GetArg("-addresstype", "").empty()) {
2561  if (!ParseOutputType(gArgs.GetArg("-addresstype", ""), walletInstance->m_default_address_type)) {
2562  error = strprintf(_("Unknown address type '%s'"), gArgs.GetArg("-addresstype", ""));
2563  return nullptr;
2564  }
2565  }
2566 
2567  if (!gArgs.GetArg("-changetype", "").empty()) {
2568  OutputType out_type;
2569  if (!ParseOutputType(gArgs.GetArg("-changetype", ""), out_type)) {
2570  error = strprintf(_("Unknown change type '%s'"), gArgs.GetArg("-changetype", ""));
2571  return nullptr;
2572  }
2573  walletInstance->m_default_change_type = out_type;
2574  }
2575 
2576  if (gArgs.IsArgSet("-mintxfee")) {
2577  CAmount n = 0;
2578  if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n) {
2579  error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""));
2580  return nullptr;
2581  }
2582  if (n > HIGH_TX_FEE_PER_KB) {
2583  warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
2584  _("This is the minimum transaction fee you pay on every transaction."));
2585  }
2586  walletInstance->m_min_fee = CFeeRate(n);
2587  }
2588 
2589  if (gArgs.IsArgSet("-maxapsfee")) {
2590  const std::string max_aps_fee{gArgs.GetArg("-maxapsfee", "")};
2591  CAmount n = 0;
2592  if (max_aps_fee == "-1") {
2593  n = -1;
2594  } else if (!ParseMoney(max_aps_fee, n)) {
2595  error = AmountErrMsg("maxapsfee", max_aps_fee);
2596  return nullptr;
2597  }
2598  if (n > HIGH_APS_FEE) {
2599  warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
2600  _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
2601  }
2602  walletInstance->m_max_aps_fee = n;
2603  }
2604 
2605  if (gArgs.IsArgSet("-fallbackfee")) {
2606  CAmount nFeePerK = 0;
2607  if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
2608  error = strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", ""));
2609  return nullptr;
2610  }
2611  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
2612  warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
2613  _("This is the transaction fee you may pay when fee estimates are not available."));
2614  }
2615  walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
2616  }
2617  // Disable fallback fee in case value was set to 0, enable if non-null value
2618  walletInstance->m_allow_fallback_fee = walletInstance->m_fallback_fee.GetFeePerK() != 0;
2619 
2620  if (gArgs.IsArgSet("-discardfee")) {
2621  CAmount nFeePerK = 0;
2622  if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK)) {
2623  error = strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", ""));
2624  return nullptr;
2625  }
2626  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
2627  warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
2628  _("This is the transaction fee you may discard if change is smaller than dust at this level"));
2629  }
2630  walletInstance->m_discard_rate = CFeeRate(nFeePerK);
2631  }
2632  if (gArgs.IsArgSet("-paytxfee")) {
2633  CAmount nFeePerK = 0;
2634  if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
2635  error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""));
2636  return nullptr;
2637  }
2638  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
2639  warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
2640  _("This is the transaction fee you will pay if you send a transaction."));
2641  }
2642  walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
2643  if (chain && walletInstance->m_pay_tx_fee < chain->relayMinFee()) {
2644  error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
2645  gArgs.GetArg("-paytxfee", ""), chain->relayMinFee().ToString());
2646  return nullptr;
2647  }
2648  }
2649 
2650  if (gArgs.IsArgSet("-maxtxfee")) {
2651  CAmount nMaxFee = 0;
2652  if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
2653  error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""));
2654  return nullptr;
2655  }
2656  if (nMaxFee > HIGH_MAX_TX_FEE) {
2657  warnings.push_back(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
2658  }
2659  if (chain && CFeeRate(nMaxFee, 1000) < chain->relayMinFee()) {
2660  error = strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
2661  gArgs.GetArg("-maxtxfee", ""), chain->relayMinFee().ToString());
2662  return nullptr;
2663  }
2664  walletInstance->m_default_max_tx_fee = nMaxFee;
2665  }
2666 
2668  warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
2669  _("The wallet will avoid paying less than the minimum relay fee."));
2670  }
2671 
2672  walletInstance->m_confirm_target = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
2673  walletInstance->m_spend_zero_conf_change = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
2674  walletInstance->m_signal_rbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
2675 
2676  walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nStart);
2677 
2678  // Try to top up keypool. No-op if the wallet is locked.
2679  walletInstance->TopUpKeyPool();
2680 
2681  LOCK(walletInstance->cs_wallet);
2682 
2683  if (chain && !AttachChain(walletInstance, *chain, error, warnings)) {
2684  return nullptr;
2685  }
2686 
2687  {
2688  LOCK(cs_wallets);
2689  for (auto& load_wallet : g_load_wallet_fns) {
2690  load_wallet(interfaces::MakeWallet(walletInstance));
2691  }
2692  }
2693 
2694  walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
2695 
2696  {
2697  walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
2698  walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
2699  walletInstance->WalletLogPrintf("m_address_book.size() = %u\n", walletInstance->m_address_book.size());
2700  }
2701 
2702  return walletInstance;
2703 }
2704 
2705 bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, bilingual_str& error, std::vector<bilingual_str>& warnings)
2706 {
2707  LOCK(walletInstance->cs_wallet);
2708  // allow setting the chain if it hasn't been set already but prevent changing it
2709  assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
2710  walletInstance->m_chain = &chain;
2711 
2712  // Register wallet with validationinterface. It's done before rescan to avoid
2713  // missing block connections between end of rescan and validation subscribing.
2714  // Because of wallet lock being hold, block connection notifications are going to
2715  // be pending on the validation-side until lock release. It's likely to have
2716  // block processing duplicata (if rescan block range overlaps with notification one)
2717  // but we guarantee at least than wallet state is correct after notifications delivery.
2718  // This is temporary until rescan and notifications delivery are unified under same
2719  // interface.
2720  walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
2721 
2722  int rescan_height = 0;
2723  if (!gArgs.GetBoolArg("-rescan", false))
2724  {
2725  WalletBatch batch(walletInstance->GetDatabase());
2726  CBlockLocator locator;
2727  if (batch.ReadBestBlock(locator)) {
2728  if (const std::optional<int> fork_height = chain.findLocatorFork(locator)) {
2729  rescan_height = *fork_height;
2730  }
2731  }
2732  }
2733 
2734  const std::optional<int> tip_height = chain.getHeight();
2735  if (tip_height) {
2736  walletInstance->m_last_block_processed = chain.getBlockHash(*tip_height);
2737  walletInstance->m_last_block_processed_height = *tip_height;
2738  } else {
2739  walletInstance->m_last_block_processed.SetNull();
2740  walletInstance->m_last_block_processed_height = -1;
2741  }
2742 
2743  if (tip_height && *tip_height != rescan_height)
2744  {
2745  if (chain.havePruned()) {
2746  int block_height = *tip_height;
2747  while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
2748  --block_height;
2749  }
2750 
2751  if (rescan_height != block_height) {
2752  // We can't rescan beyond non-pruned blocks, stop and throw an error.
2753  // This might happen if a user uses an old wallet within a pruned node
2754  // or if they ran -disablewallet for a longer time, then decided to re-enable
2755  // Exit early and print an error.
2756  // If a block is pruned after this check, we will load the wallet,
2757  // but fail the rescan with a generic error.
2758  error = _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)");
2759  return false;
2760  }
2761  }
2762 
2763  chain.initMessage(_("Rescanning…").translated);
2764  walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
2765 
2766  // No need to read and scan block if block was created before
2767  // our wallet birthday (as adjusted for block time variability)
2768  std::optional<int64_t> time_first_key;
2769  for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
2770  int64_t time = spk_man->GetTimeFirstKey();
2771  if (!time_first_key || time < *time_first_key) time_first_key = time;
2772  }
2773  if (time_first_key) {
2774  chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, FoundBlock().height(rescan_height));
2775  }
2776 
2777  {
2778  WalletRescanReserver reserver(*walletInstance);
2779  if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, {} /* max height */, reserver, true /* update */).status)) {
2780  error = _("Failed to rescan the wallet during initialization");
2781  return false;
2782  }
2783  }
2784  walletInstance->chainStateFlushed(chain.getTipLocator());
2785  walletInstance->GetDatabase().IncrementUpdateCounter();
2786  }
2787 
2788  return true;
2789 }
2790 
2791 const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
2792 {
2793  const auto& address_book_it = m_address_book.find(dest);
2794  if (address_book_it == m_address_book.end()) return nullptr;
2795  if ((!allow_change) && address_book_it->second.IsChange()) {
2796  return nullptr;
2797  }
2798  return &address_book_it->second;
2799 }
2800 
2802 {
2803  int prev_version = GetVersion();
2804  if (version == 0) {
2805  WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
2806  version = FEATURE_LATEST;
2807  } else {
2808  WalletLogPrintf("Allowing wallet upgrade up to %i\n", version);
2809  }
2810  if (version < prev_version) {
2811  error = strprintf(_("Cannot downgrade wallet from version %i to version %i. Wallet version unchanged."), prev_version, version);
2812  return false;
2813  }
2814 
2815  LOCK(cs_wallet);
2816 
2817  // Do not upgrade versions to any version between HD_SPLIT and FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
2819  error = strprintf(_("Cannot upgrade a non HD split wallet from version %i to version %i without upgrading to support pre-split keypool. Please use version %i or no version specified."), prev_version, version, FEATURE_PRE_SPLIT_KEYPOOL);
2820  return false;
2821  }
2822 
2823  // Permanently upgrade to the version
2825 
2826  for (auto spk_man : GetActiveScriptPubKeyMans()) {
2827  if (!spk_man->Upgrade(prev_version, version, error)) {
2828  return false;
2829  }
2830  }
2831  return true;
2832 }
2833 
2835 {
2836  LOCK(cs_wallet);
2837 
2838  // Add wallet transactions that aren't already in a block to mempool
2839  // Do this here as mempool requires genesis block to be loaded
2841 
2842  // Update wallet transactions with current mempool transactions.
2844 }
2845 
2846 bool CWallet::BackupWallet(const std::string& strDest) const
2847 {
2848  return GetDatabase().Backup(strDest);
2849 }
2850 
2852 {
2853  nTime = GetTime();
2854  fInternal = false;
2855  m_pre_split = false;
2856 }
2857 
2858 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
2859 {
2860  nTime = GetTime();
2861  vchPubKey = vchPubKeyIn;
2862  fInternal = internalIn;
2863  m_pre_split = false;
2864 }
2865 
2867 {
2868  assert(pwallet != nullptr);
2870  if (isUnconfirmed() || isAbandoned()) return 0;
2871 
2872  return (pwallet->GetLastBlockHeight() - m_confirm.block_height + 1) * (isConflicted() ? -1 : 1);
2873 }
2874 
2876 {
2877  if (!IsCoinBase())
2878  return 0;
2879  int chain_depth = GetDepthInMainChain();
2880  assert(chain_depth >= 0); // coinbase tx should not be conflicted
2881  return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
2882 }
2883 
2885 {
2886  // note GetBlocksToMaturity is 0 for non-coinbase tx
2887  return GetBlocksToMaturity() > 0;
2888 }
2889 
2891 {
2892  return HasEncryptionKeys();
2893 }
2894 
2895 bool CWallet::IsLocked() const
2896 {
2897  if (!IsCrypted()) {
2898  return false;
2899  }
2900  LOCK(cs_wallet);
2901  return vMasterKey.empty();
2902 }
2903 
2905 {
2906  if (!IsCrypted())
2907  return false;
2908 
2909  {
2910  LOCK(cs_wallet);
2911  vMasterKey.clear();
2912  }
2913 
2914  NotifyStatusChanged(this);
2915  return true;
2916 }
2917 
2918 bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys)
2919 {
2920  {
2921  LOCK(cs_wallet);
2922  for (const auto& spk_man_pair : m_spk_managers) {
2923  if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn, accept_no_keys)) {
2924  return false;
2925  }
2926  }
2927  vMasterKey = vMasterKeyIn;
2928  }
2929  NotifyStatusChanged(this);
2930  return true;
2931 }
2932 
2933 std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
2934 {
2935  std::set<ScriptPubKeyMan*> spk_mans;
2936  for (bool internal : {false, true}) {
2937  for (OutputType t : OUTPUT_TYPES) {
2938  auto spk_man = GetScriptPubKeyMan(t, internal);
2939  if (spk_man) {
2940  spk_mans.insert(spk_man);
2941  }
2942  }
2943  }
2944  return spk_mans;
2945 }
2946 
2947 std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
2948 {
2949  std::set<ScriptPubKeyMan*> spk_mans;
2950  for (const auto& spk_man_pair : m_spk_managers) {
2951  spk_mans.insert(spk_man_pair.second.get());
2952  }
2953  return spk_mans;
2954 }
2955 
2956 ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
2957 {
2958  const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
2959  std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
2960  if (it == spk_managers.end()) {
2961  WalletLogPrintf("%s scriptPubKey Manager for output type %d does not exist\n", internal ? "Internal" : "External", static_cast<int>(type));
2962  return nullptr;
2963  }
2964  return it->second;
2965 }
2966 
2967 std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const
2968 {
2969  std::set<ScriptPubKeyMan*> spk_mans;
2970  for (const auto& spk_man_pair : m_spk_managers) {
2971  if (spk_man_pair.second->CanProvide(script, sigdata)) {
2972  spk_mans.insert(spk_man_pair.second.get());
2973  }
2974  }
2975  return spk_mans;
2976 }
2977 
2979 {
2980  SignatureData sigdata;
2981  for (const auto& spk_man_pair : m_spk_managers) {
2982  if (spk_man_pair.second->CanProvide(script, sigdata)) {
2983  return spk_man_pair.second.get();
2984  }
2985  }
2986  return nullptr;
2987 }
2988 
2990 {
2991  if (m_spk_managers.count(id) > 0) {
2992  return m_spk_managers.at(id).get();
2993  }
2994  return nullptr;
2995 }
2996 
2997 std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
2998 {
2999  SignatureData sigdata;
3000  return GetSolvingProvider(script, sigdata);
3001 }
3002 
3003 std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
3004 {
3005  for (const auto& spk_man_pair : m_spk_managers) {
3006  if (spk_man_pair.second->CanProvide(script, sigdata)) {
3007  return spk_man_pair.second->GetSolvingProvider(script);
3008  }
3009  }
3010  return nullptr;
3011 }
3012 
3014 {
3016  return nullptr;
3017  }
3018  // Legacy wallets only have one ScriptPubKeyMan which is a LegacyScriptPubKeyMan.
3019  // Everything in m_internal_spk_managers and m_external_spk_managers point to the same legacyScriptPubKeyMan.
3021  if (it == m_internal_spk_managers.end()) return nullptr;
3022  return dynamic_cast<LegacyScriptPubKeyMan*>(it->second);
3023 }
3024 
3026 {
3028  return GetLegacyScriptPubKeyMan();
3029 }
3030 
3032 {
3034  return;
3035  }
3036 
3037  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this));
3038  for (const auto& type : OUTPUT_TYPES) {
3039  m_internal_spk_managers[type] = spk_manager.get();
3040  m_external_spk_managers[type] = spk_manager.get();
3041  }
3042  m_spk_managers[spk_manager->GetID()] = std::move(spk_manager);
3043 }
3044 
3046 {
3047  return vMasterKey;
3048 }
3049 
3051 {
3052  return !mapMasterKeys.empty();
3053 }
3054 
3056 {
3057  for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
3058  spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
3059  spk_man->NotifyCanGetAddressesChanged.connect(NotifyCanGetAddressesChanged);
3060  }
3061 }
3062 
3064 {
3066 #ifdef ENABLE_EXTERNAL_SIGNER
3067  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new ExternalSignerScriptPubKeyMan(*this, desc));
3068  m_spk_managers[id] = std::move(spk_manager);
3069 #else
3070  throw std::runtime_error(std::string(__func__) + ": Compiled without external signing support (required for external signing)");
3071 #endif
3072  } else {
3073  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc));
3074  m_spk_managers[id] = std::move(spk_manager);
3075  }
3076 }
3077 
3079 {
3081 
3083  // Make a seed
3084  CKey seed_key;
3085  seed_key.MakeNewKey(true);
3086  CPubKey seed = seed_key.GetPubKey();
3087  assert(seed_key.VerifyPubKey(seed));
3088 
3089  // Get the extended key
3090  CExtKey master_key;
3091  master_key.SetSeed(seed_key.begin(), seed_key.size());
3092 
3093  for (bool internal : {false, true}) {
3094  for (OutputType t : OUTPUT_TYPES) {
3095  auto spk_manager = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, internal));
3096  if (IsCrypted()) {
3097  if (IsLocked()) {
3098  throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
3099  }
3100  if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, nullptr)) {
3101  throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
3102  }
3103  }
3104  spk_manager->SetupDescriptorGeneration(master_key, t);
3105  uint256 id = spk_manager->GetID();
3106  m_spk_managers[id] = std::move(spk_manager);
3107  AddActiveScriptPubKeyMan(id, t, internal);
3108  }
3109  }
3110  } else {
3111 #ifdef ENABLE_EXTERNAL_SIGNER
3113 
3114  // TODO: add account parameter
3115  int account = 0;
3116  UniValue signer_res = signer.GetDescriptors(account);
3117 
3118  if (!signer_res.isObject()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
3119  for (bool internal : {false, true}) {
3120  const UniValue& descriptor_vals = find_value(signer_res, internal ? "internal" : "receive");
3121  if (!descriptor_vals.isArray()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
3122  for (const UniValue& desc_val : descriptor_vals.get_array().getValues()) {
3123  std::string desc_str = desc_val.getValStr();
3124  FlatSigningProvider keys;
3125  std::string dummy_error;
3126  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, dummy_error, false);
3127  if (!desc->GetOutputType()) {
3128  continue;
3129  }
3130  OutputType t = *desc->GetOutputType();
3131  auto spk_manager = std::unique_ptr<ExternalSignerScriptPubKeyMan>(new ExternalSignerScriptPubKeyMan(*this, internal));
3132  spk_manager->SetupDescriptor(std::move(desc));
3133  uint256 id = spk_manager->GetID();
3134  m_spk_managers[id] = std::move(spk_manager);
3135  AddActiveScriptPubKeyMan(id, t, internal);
3136  }
3137  }
3138 #else
3139  throw std::runtime_error(std::string(__func__) + ": Compiled without external signing support (required for external signing)");
3140 #endif // ENABLE_EXTERNAL_SIGNER
3141  }
3142 }
3143 
3145 {
3146  WalletBatch batch(GetDatabase());
3147  if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
3148  throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
3149  }
3150  LoadActiveScriptPubKeyMan(id, type, internal);
3151 }
3152 
3154 {
3155  WalletLogPrintf("Setting spkMan to active: id = %s, type = %d, internal = %d\n", id.ToString(), static_cast<int>(type), static_cast<int>(internal));
3156  auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3157  auto spk_man = m_spk_managers.at(id).get();
3158  spk_man->SetInternal(internal);
3159  spk_mans[type] = spk_man;
3160 
3162 }
3163 
3164 bool CWallet::IsLegacy() const
3165 {
3166  if (m_internal_spk_managers.count(OutputType::LEGACY) == 0) {
3167  return false;
3168  }
3169  auto spk_man = dynamic_cast<LegacyScriptPubKeyMan*>(m_internal_spk_managers.at(OutputType::LEGACY));
3170  return spk_man != nullptr;
3171 }
3172 
3174 {
3175  for (auto& spk_man_pair : m_spk_managers) {
3176  // Try to downcast to DescriptorScriptPubKeyMan then check if the descriptors match
3177  DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair.second.get());
3178  if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
3179  return spk_manager;
3180  }
3181  }
3182 
3183  return nullptr;
3184 }
3185 
3186 ScriptPubKeyMan* CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal)
3187 {
3189  WalletLogPrintf("Cannot add WalletDescriptor to a non-descriptor wallet\n");
3190  return nullptr;
3191  }
3192 
3193  LOCK(cs_wallet);
3194  auto new_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc));
3195 
3196  // If we already have this descriptor, remove it from the maps but add the existing cache to desc
3197  auto old_spk_man = GetDescriptorScriptPubKeyMan(desc);
3198  if (old_spk_man) {
3199  WalletLogPrintf("Update existing descriptor: %s\n", desc.descriptor->ToString());
3200 
3201  {
3202  LOCK(old_spk_man->cs_desc_man);
3203  new_spk_man->SetCache(old_spk_man->GetWalletDescriptor().cache);
3204  }
3205 
3206  // Remove from maps of active spkMans
3207  auto old_spk_man_id = old_spk_man->GetID();
3208  for (bool internal : {false, true}) {
3209  for (OutputType t : OUTPUT_TYPES) {
3210  auto active_spk_man = GetScriptPubKeyMan(t, internal);
3211  if (active_spk_man && active_spk_man->GetID() == old_spk_man_id) {
3212  if (internal) {
3213  m_internal_spk_managers.erase(t);
3214  } else {
3215  m_external_spk_managers.erase(t);
3216  }
3217  break;
3218  }
3219  }
3220  }
3221  m_spk_managers.erase(old_spk_man_id);
3222  }
3223 
3224  // Add the private keys to the descriptor
3225  for (const auto& entry : signing_provider.keys) {
3226  const CKey& key = entry.second;
3227  new_spk_man->AddDescriptorKey(key, key.GetPubKey());
3228  }
3229 
3230  // Top up key pool, the manager will generate new scriptPubKeys internally
3231  if (!new_spk_man->TopUp()) {
3232  WalletLogPrintf("Could not top up scriptPubKeys\n");
3233  return nullptr;
3234  }
3235 
3236  // Apply the label if necessary
3237  // Note: we disable labels for ranged descriptors
3238  if (!desc.descriptor->IsRange()) {
3239  auto script_pub_keys = new_spk_man->GetScriptPubKeys();
3240  if (script_pub_keys.empty()) {
3241  WalletLogPrintf("Could not generate scriptPubKeys (cache is empty)\n");
3242  return nullptr;
3243  }
3244 
3245  CTxDestination dest;
3246  if (!internal && ExtractDestination(script_pub_keys.at(0), dest)) {
3247  SetAddressBook(dest, label, "receive");
3248  }
3249  }
3250 
3251  // Save the descriptor to memory
3252  auto ret = new_spk_man.get();
3253  m_spk_managers[new_spk_man->GetID()] = std::move(new_spk_man);
3254 
3255  // Save the descriptor to DB
3256  ret->WriteDescriptor();
3257 
3258  return ret;
3259 }
CWallet::ScanResult::last_failed_block
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:535
CWallet::GetKeyPoolSize
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2082
DatabaseStatus::FAILED_BAD_PATH
@ FAILED_BAD_PATH
DatabaseOptions
Definition: db.h:203
CTxIn
An input of a transaction.
Definition: transaction.h:65
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:822
block.h
policy.h
CMasterKey::vchSalt
std::vector< unsigned char > vchSalt
Definition: crypter.h:37
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:979
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:346
CWallet::ComputeTimeSmart
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:2350
CWallet::ConnectScriptPubKeyManNotifiers
void ConnectScriptPubKeyManNotifiers()
Connect the signals from ScriptPubKeyMans to the signals in CWallet.
Definition: wallet.cpp:3055
ReserveDestination::fInternal
bool fInternal
Whether this is from the internal (change output) keypool.
Definition: wallet.h:167
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:270
CWallet::CWallet
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:371
CWallet::GetActiveScriptPubKeyMans
std::set< ScriptPubKeyMan * > GetActiveScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers.
Definition: wallet.cpp:2933
CWalletTx::GetBlocksToMaturity
int GetBlocksToMaturity() const
Definition: wallet.cpp:2875
bip32.h
Parse
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Definition: descriptor.cpp:1333
CWallet::UnlockCoin
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2241
CWallet::nMasterKeyMaxID
unsigned int nMasterKeyMaxID
Definition: wallet.h:368
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:595
interfaces::Chain::updateRwSetting
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value)=0
Write a setting to <datadir>/settings.json.
WALLET_CRYPTO_KEY_SIZE
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:13
PSBTInput::non_witness_utxo
CTransactionRef non_witness_utxo
Definition: psbt.h:51
interfaces::Chain::guessVerificationProgress
virtual double guessVerificationProgress(const uint256 &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
GetWallets
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: wallet.cpp:134
CWallet::m_external_spk_managers
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:322
_
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:57
OutputType
OutputType
Definition: outputtype.h:17
ToString
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:79
WalletBatch::WriteName
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:65
RemoveWallet
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:108
count
static int count
Definition: tests.c:41
assert
assert(!tx.IsCoinBase())
OUTPUT_TYPES
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:23
FEATURE_HD_SPLIT
@ FEATURE_HD_SPLIT
Definition: walletutil.h:23
ExternalSignerScriptPubKeyMan
Definition: external_signer_scriptpubkeyman.h:13
CWallet::MarkConflicted
void MarkConflicted(const uint256 &hashBlock, int conflicting_height, const uint256 &hashTx)
Mark a transaction (and its in-wallet descendants) as conflicting with a particular block.
Definition: wallet.cpp:1124
DatabaseStatus
DatabaseStatus
Definition: db.h:212
CWallet::ResendWalletTransactions
void ResendWalletTransactions()
Definition: wallet.cpp:1744
check.h
CreateWallet
std::shared_ptr< CWallet > CreateWallet(interfaces::Chain &chain, const std::string &name, std::optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:249
CWalletTx::setConflicted
void setConflicted()
Definition: transaction.h:342
UpdateWalletSetting
static void UpdateWalletSetting(interfaces::Chain &chain, const std::string &wallet_name, std::optional< bool > load_on_startup, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:83
CWallet::GetSolvingProvider
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:2997
wallet.h
CHECK_NONFATAL
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
interfaces::MakeWallet
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Return implementation of Wallet interface.
Definition: dummywallet.cpp:61
CKey::MakeNewKey
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:157
CKeyPool
A key from a CWallet's keypool.
Definition: scriptpubkeyman.h:101
CWallet::blockDisconnected
void blockDisconnected(const CBlock &block, int height) override
Definition: wallet.cpp:1247
COINBASE_MATURITY
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition: consensus.h:19
isminefilter
uint8_t isminefilter
Definition: wallet.h:36
CBlockHeader::IsNull
bool IsNull() const
Definition: block.h:48
fs.h
PACKAGE_BUGREPORT
#define PACKAGE_BUGREPORT
Definition: bitcoin-config.h:362
DBErrors::NEED_REWRITE
@ NEED_REWRITE
CWallet::IsFromMe
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1327
CWallet::ReacceptWalletTransactions
void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1667
flags
int flags
Definition: bitcoin-tx.cpp:512
FormatOutputType
const std::string & FormatOutputType(OutputType type)
Definition: outputtype.cpp:37
key_io.h
CWalletTx::fTimeReceivedIsTxTime
unsigned int fTimeReceivedIsTxTime
Definition: transaction.h:106
ReleaseWallet
static void ReleaseWallet(CWallet *wallet)
Definition: wallet.cpp:163
ISMINE_ALL
@ ISMINE_ALL
Definition: ismine.h:44
CWallet::GetOldestKeyPoolTime
int64_t GetOldestKeyPoolTime() const
Definition: wallet.cpp:2137
GetWallet
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:140
DUMMY_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:434
CWallet::AddWalletDescriptor
ScriptPubKeyMan * AddWalletDescriptor(WalletDescriptor &desc, const FlatSigningProvider &signing_provider, const std::string &label, bool internal)
Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type.
Definition: wallet.cpp:3186
OutputType::LEGACY
@ LEGACY
CWallet::m_wallet_flags
std::atomic< uint64_t > m_wallet_flags
WalletFlags set on this wallet.
Definition: wallet.h:287
moneystr.h
CWallet::GetLastBlockHeight
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:861
DatabaseOptions::create_passphrase
SecureString create_passphrase
Definition: db.h:208
transaction.h
WalletBatch::LoadWallet
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:690
CWallet::IsWalletFlagSet
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
Definition: wallet.cpp:1394
CWallet::ScanResult::SUCCESS
@ SUCCESS
Definition: wallet.h:523
HandleLoadWallet
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: wallet.cpp:149
DescriptorScriptPubKeyMan::HasWalletDescriptor
bool HasWalletDescriptor(const WalletDescriptor &desc) const
Definition: scriptpubkeyman.cpp:2239
COutPoint::hash
uint256 hash
Definition: transaction.h:29
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:351
CWallet::CanSupportFeature
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:420
CCrypter::Encrypt
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
Definition: crypter.cpp:71
string.h
CWalletTx::mapValue
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: transaction.h:104
CWallet::LoadDescriptorScriptPubKeyMan
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:3063
bilingual_str
Bilingual messages:
Definition: translation.h:16
outputtype.h
CWallet::ScanResult::last_scanned_height
std::optional< int > last_scanned_height
Definition: wallet.h:529
CWallet::ScanResult::last_scanned_block
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:528
cs_wallets
RecursiveMutex cs_wallets
Definition: wallet.cpp:56
CKeyingMaterial
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:61
CWalletTx::IsImmatureCoinBase
bool IsImmatureCoinBase() const
Definition: wallet.cpp:2884
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:487
FlatSigningProvider::keys
std::map< CKeyID, CKey > keys
Definition: signingprovider.h:52
validation.h
PartiallySignedTransaction::inputs
std::vector< PSBTInput > inputs
Definition: psbt.h:394
CWallet::GetEncryptionKey
const CKeyingMaterial & GetEncryptionKey() const override
Definition: wallet.cpp:3045
CWallet::chain
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:414
WALLET_FLAG_EXTERNAL_SIGNER
@ WALLET_FLAG_EXTERNAL_SIGNER
Indicates that the wallet needs an external signer.
Definition: walletutil.h:65
ReserveDestination::address
CTxDestination address
The destination.
Definition: wallet.h:165
CWalletTx::setUnconfirmed
void setUnconfirmed()
Definition: transaction.h:344
CT_DELETED
@ CT_DELETED
Definition: ui_change_type.h:12
CWallet::m_scanning_progress
std::atomic< double > m_scanning_progress
Definition: wallet.h:235
CWallet::IsCrypted
bool IsCrypted() const
Definition: wallet.cpp:2890
base_blob::SetNull
void SetNull()
Definition: uint256.h:39
WalletBatch::WriteMasterKey
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:143
ReserveDestination::pwallet
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:158
CWalletTx::GetDepthInMainChain
int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:2866
interfaces::Chain::handleNotifications
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
CWallet::IsSpentKey
bool IsSpentKey(const uint256 &hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:827
GetTime
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
CMasterKey::vchCryptedKey
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:36
MoneyRange
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:26
WalletDatabase::Close
virtual void Close()=0
Flush to the database file and close the database.
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:276
CWallet::ScanForWalletTransactions
ScanResult ScanForWalletTransactions(const uint256 &start_block, int start_height, std::optional< int > max_height, const WalletRescanReserver &reserver, bool fUpdate)
Scan the block chain (starting in start_block) for transactions from or to us.
Definition: wallet.cpp:1564
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
DBErrors::NONCRITICAL_ERROR
@ NONCRITICAL_ERROR
CCrypter::Decrypt
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:89
CWallet::MarkReplaced
bool MarkReplaced(const uint256 &originalHash, const uint256 &newHash)
Mark a transaction as replaced by another transaction (e.g., BIP 125).
Definition: wallet.cpp:773
fsbridge::AbsPathJoin
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:34
AnnotatedMixin< std::recursive_mutex >
CWallet::ShowProgress
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:743
CT_UPDATED
@ CT_UPDATED
Definition: ui_change_type.h:11
ScriptPubKeyMan::KeepDestination
virtual void KeepDestination(int64_t index, const OutputType &type)
Definition: scriptpubkeyman.h:185
ReserveDestination::nIndex
int64_t nIndex
The index of the address's key in the keypool.
Definition: wallet.h:163
FEATURE_WALLETCRYPT
@ FEATURE_WALLETCRYPT
Definition: walletutil.h:18
CWalletTx::isConfirmed
bool isConfirmed() const
Definition: transaction.h:345
CMasterKey
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
Definition: crypter.h:33
CWalletTx::m_confirm
Confirmation m_confirm
Definition: transaction.h:194
wallet
Definition: interfaces.cpp:47
interfaces::Chain::getHeight
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
LegacyScriptPubKeyMan::GetKeys
std::set< CKeyID > GetKeys() const override
Definition: scriptpubkeyman.cpp:1587
WalletRescanReserver::reserve
bool reserve()
Definition: wallet.h:924
CWallet::AddToWallet
CWalletTx * AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation &confirm, const UpdateWalletTxFn &update_wtx=nullptr, bool fFlushOnClose=true)
Definition: wallet.cpp:862
CKeyID
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
CWallet::GetBroadcastTransactions
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:758
ReserveDestination
A wrapper to reserve an address from a wallet.
Definition: wallet.h:154
interfaces::Chain::findBlock
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
WalletDatabase::Backup
virtual bool Backup(const std::string &strDest) const =0
Back up the entire database to a file.
CWalletTx::m_is_cache_empty
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: transaction.h:137
LegacyScriptPubKeyMan
Definition: scriptpubkeyman.h:257
CKeyPool::nTime
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
Definition: scriptpubkeyman.h:105
CWallet::blockConnected
void blockConnected(const CBlock &block, int height) override
Definition: wallet.cpp:1234
chain.h
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
interfaces::Chain::findAncestorByHeight
virtual bool findAncestorByHeight(const uint256 &block_hash, int ancestor_height, const FoundBlock &ancestor_out={})=0
Find ancestor of block at specified height and optionally return ancestor information.
CWallet::SetAddressUsed
bool SetAddressUsed(WalletBatch &batch, const CTxDestination &dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2389
CWalletTx::Confirmation::block_height
int block_height
Definition: transaction.h:188
interfaces::Chain::getRwSetting
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
CWallet::AddToSpends
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:569
GetRand
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:591
GetAffectedKeys
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
Definition: scriptpubkeyman.cpp:1438
CFeeRate
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:11
CWallet::GetNewChangeDestination
bool GetNewChangeDestination(const OutputType type, CTxDestination &dest, std::string &error)
Definition: wallet.cpp:2122
CWallet::IsAddressUsed
bool IsAddressUsed(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2410
CWallet::UnsetBlankWalletFlag
void UnsetBlankWalletFlag(WalletBatch &batch) override
Unset the blank wallet flag and saves it to disk.
Definition: wallet.cpp:1389
HIGH_MAX_TX_FEE
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:102
CWallet::NotifyStatusChanged
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:755
WalletBatch::WriteActiveScriptPubKeyMan
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:206
SigningResult
SigningResult
Definition: message.h:42
UnloadWallet
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:180
CWalletTx::nTimeSmart
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet.
Definition: transaction.h:117
UniValue
Definition: univalue.h:19
CWallet::SignMessage
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Definition: wallet.cpp:1878
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
rbf.h
WalletBatch::TxnCommit
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1005
CWallet::ZapSelectTx
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1984
CWalletTx::SetTx
void SetTx(CTransactionRef arg)
Definition: transaction.h:251
AmountErrMsg
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:53
txmempool.h
WitnessV0KeyHash
Definition: standard.h:108
ShellEscape
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1224
CWallet::GetVersion
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.h:709
prefix
const char * prefix
Definition: rest.cpp:711
CWallet::SetAddressBook
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:2035
AmountHighWarn
bilingual_str AmountHighWarn(const std::string &optname)
Definition: error.cpp:48
MaybeResendWalletTxs
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:1782
LoadWalletFn
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:46
CWallet::GetDisplayName
const std::string GetDisplayName() const override
Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet ha...
Definition: wallet.h:815
CWallet::HasWalletSpend
bool HasWalletSpend(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Check if a given transaction has any of its outputs spent by another transaction in the wallet.
Definition: wallet.cpp:490
DescriptorScriptPubKeyMan
Definition: scriptpubkeyman.h:517
CWallet::MarkDirty
void MarkDirty()
Definition: wallet.cpp:764
FEATURE_PRE_SPLIT_KEYPOOL
@ FEATURE_PRE_SPLIT_KEYPOOL
Definition: walletutil.h:27
signingprovider.h
CWallet::IsLockedCoin
bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2253
CWallet::DelAddressBook
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:2041
CKey::begin
const unsigned char * begin() const
Definition: key.h:89
CWallet::TransactionCanBeAbandoned
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1053
fees.h
MakeWalletDatabase
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2453
CWallet::LoadWallet
DBErrors LoadWallet()
Definition: wallet.cpp:1958
TransactionError
TransactionError
Definition: error.h:22
interfaces::Chain::havePruned
virtual bool havePruned()=0
Check if any block has been pruned.
interfaces::Chain
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:89
CWallet::IsLocked
bool IsLocked() const override
Definition: wallet.cpp:2895
ExternalSigner::GetDescriptors
UniValue GetDescriptors(const int account)
Get receive and change Descriptor(s) from device for a given account.
Definition: external_signer.cpp:68
CWallet::ScanResult::FAILURE
@ FAILURE
Definition: wallet.h:523
SecureString
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:60
CWallet::Flush
void Flush()
Flush wallet (bitdb flush)
Definition: wallet.cpp:497
CWalletTx::IsEquivalentTo
bool IsEquivalentTo(const CWalletTx &tx) const
True if only scriptSigs are different.
Definition: transaction.cpp:7
CWalletTx::nTimeReceived
unsigned int nTimeReceived
time received by this node
Definition: transaction.h:107
CWallet::m_default_max_tx_fee
CAmount m_default_max_tx_fee
Absolute maximum transaction fee (in satoshis) used by default for the wallet.
Definition: wallet.h:646
CWalletTx::isAbandoned
bool isAbandoned() const
Definition: transaction.h:333
CWallet::UpgradeKeyMetadata
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
Definition: wallet.cpp:361
isminetype
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: ismine.h:38
CWalletTx::Confirmation::status
Status status
Definition: transaction.h:187
CKeyPool::m_pre_split
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
Definition: scriptpubkeyman.h:111
WALLET_FLAG_CAVEATS
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:48
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:156
g_loading_wallet_mutex
static Mutex g_loading_wallet_mutex
Definition: wallet.cpp:156
DUMMY_MAXIMUM_SIGNATURE_CREATOR
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:435
CWallet::LoadWalletFlags
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
Definition: wallet.cpp:1399
CWallet::NotifyTransactionChanged
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:740
Untranslated
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:40
CWallet::ScanResult::status
enum CWallet::ScanResult::@16 status
SignatureData
Definition: sign.h:60
AssertLockNotHeld
#define AssertLockNotHeld(cs)
Definition: sync.h:82
IsValidDestination
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:373
CWallet::CommitTransaction
void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string >> orderForm)
Submit the transaction to the node's mempool and then relay to peers.
Definition: wallet.cpp:1918
CWalletTx::nOrderPos
int64_t nOrderPos
position in ordered transaction list
Definition: transaction.h:124
CTxOut
An output of a transaction.
Definition: transaction.h:128
WalletBatch::WriteOrderPosNext
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:181
CExtKey
Definition: key.h:144
CWallet::m_best_block_time
std::atomic< int64_t > m_best_block_time
Definition: wallet.h:247
Coin
A UTXO entry.
Definition: coins.h:30
CWallet::ImportScriptPubKeys
bool ImportScriptPubKeys(const std::string &label, const std::set< CScript > &script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1490
GUARDED_BY
static std::vector< std::shared_ptr< CWallet > > vpwallets GUARDED_BY(cs_wallets)
CWallet::ImportPrivKeys
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1470
interfaces::Chain::getBlockHash
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
WalletBatch::EraseDestData
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:984
PACKAGE_NAME
#define PACKAGE_NAME
Definition: bitcoin-config.h:365
AddWallet
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:96
CTransaction::vout
const std::vector< CTxOut > vout
Definition: transaction.h:271
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:2405
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:132
CWallet::UnsetWalletFlag
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1375
CWallet::m_default_address_type
OutputType m_default_address_type
Definition: wallet.h:637
interfaces::Chain::waitForNotificationsIfTipChanged
virtual void waitForNotificationsIfTipChanged(const uint256 &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip.
CWallet::updatedBlockTip
void updatedBlockTip() override
Definition: wallet.cpp:1262
CWallet::SetupDescriptorScriptPubKeyMans
void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Create new DescriptorScriptPubKeyMans and add them to the wallet.
Definition: wallet.cpp:3078
CWallet::UnsetWalletFlagWithDB
void UnsetWalletFlagWithDB(WalletBatch &batch, uint64_t flag)
Unsets a wallet flag and saves it to disk.
Definition: wallet.cpp:1381
CWalletTx::tx
CTransactionRef tx
Definition: transaction.h:164
HIGH_APS_FEE
constexpr CAmount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:84
WALLET_FLAG_AVOID_REUSE
@ WALLET_FLAG_AVOID_REUSE
Definition: walletutil.h:41
LoadWallet
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const std::string &name, std::optional< bool > load_on_start, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:236
WalletBatch::WritePurpose
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:77
SigningResult::PRIVATE_KEY_NOT_AVAILABLE
@ PRIVATE_KEY_NOT_AVAILABLE
univalue.h
CAddressBookData
Address book data.
Definition: wallet.h:193
consensus.h
CWallet::nNextResend
int64_t nNextResend
The next scheduled rebroadcast of wallet transactions.
Definition: wallet.h:242
DEFAULT_WALLET_RBF
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:94
CWallet::wtxOrdered
TxItems wtxOrdered
Definition: wallet.h:396
ParseOutputType
bool ParseOutputType(const std::string &type, OutputType &output_type)
Definition: outputtype.cpp:22
CWalletTx::pwallet
const CWallet *const pwallet
Definition: transaction.h:71
CWallet::DummySignInput
bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig=false) const
Definition: wallet.cpp:1425
interfaces::Chain::findLocatorFork
virtual std::optional< int > findLocatorFork(const CBlockLocator &locator)=0
Return height of the highest block on chain in common with the locator, which will either be the orig...
CWalletTx::isUnconfirmed
bool isUnconfirmed() const
Definition: transaction.h:343
PartiallySignedTransaction::tx
std::optional< CMutableTransaction > tx
Definition: psbt.h:393
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:583
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
g_wallet_release_mutex
static Mutex g_wallet_release_mutex
Definition: wallet.cpp:157
WalletBatch::WriteBestBlock
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:169
base_blob::GetHex
std::string GetHex() const
Definition: uint256.cpp:20
WalletRescanReserver
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:916
CWallet::AddActiveScriptPubKeyMan
void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Adds the active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3144
CWallet::NotifyWatchonlyChanged
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:746
CKeyPool::vchPubKey
CPubKey vchPubKey
The public key.
Definition: scriptpubkeyman.h:107
CWallet::SetMinVersion
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr) override
signify that a particular wallet feature is now used.
Definition: wallet.cpp:451
CWallet::IsHDEnabled
bool IsHDEnabled() const
Definition: wallet.cpp:1344
interfaces::Chain::relayMinFee
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
error.h
CWallet::fBroadcastTransactions
bool fBroadcastTransactions
Whether this wallet will submit newly created transactions to the node's mempool and prompt rebroadca...
Definition: wallet.h:245
CWallet::GetDatabase
WalletDatabase & GetDatabase() const override
Definition: wallet.h:345
DatabaseStatus::FAILED_VERIFY
@ FAILED_VERIFY
ScriptPubKeyMan::GetReservedDestination
virtual bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool)
Definition: scriptpubkeyman.h:184
interfaces::Chain::broadcastTransaction
virtual bool broadcastTransaction(const CTransactionRef &tx, const CAmount &max_tx_fee, bool relay, std::string &err_string)=0
Transaction is added to memory pool, if the transaction fee is below the amount specified by max_tx_f...
CWallet::NotifyAddressBookChanged
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:733
CWallet::transactionAddedToMempool
void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence) override
Definition: wallet.cpp:1187
interfaces::FoundBlock
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:39
bilingual_str::translated
std::string translated
Definition: translation.h:18
CWallet::SyncTransaction
void SyncTransaction(const CTransactionRef &tx, CWalletTx::Confirmation confirm, bool update_tx=true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1176
CWallet::GetName
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:364
AssertLockHeld
#define AssertLockHeld(cs)
Definition: sync.h:81
CWallet::mapMasterKeys
MasterKeyMap mapMasterKeys
Definition: wallet.h:367
CWallet::ReorderTransactions
DBErrors ReorderTransactions()
Definition: wallet.cpp:695
CWallet::fAbortRescan
std::atomic< bool > fAbortRescan
Definition: wallet.h:232
CWallet::UnlockAllCoins
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2247
CWalletTx::vOrderForm
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: transaction.h:105
base_blob::ToString
std::string ToString() const
Definition: uint256.cpp:64
uint256
256-bit opaque blob.
Definition: uint256.h:124
ISMINE_NO
@ ISMINE_NO
Definition: ismine.h:40
CFeeRate::ToString
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:35
CWallet::ScanResult
Definition: wallet.h:522
CWallet::DummySignTx
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:602
WalletDatabase::ReloadDbEnv
virtual void ReloadDbEnv()=0
WalletBatch::EraseName
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:70
CWallet::AbandonTransaction
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1070
interfaces::Chain::getAdjustedTime
virtual int64_t getAdjustedTime()=0
Get adjusted time.
CWalletTx::CONFIRMED
@ CONFIRMED
Definition: transaction.h:176
CKey::GetPubKey
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:184
CWalletTx::Confirmation
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: transaction.h:186
CWallet::UpgradeWallet
bool UpgradeWallet(int version, bilingual_str &error)
Upgrade the wallet.
Definition: wallet.cpp:2801
CWallet::GetDescriptorScriptPubKeyMan
DescriptorScriptPubKeyMan * GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const
Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet.
Definition: wallet.cpp:3173
GetStrongRandBytes
void GetStrongRandBytes(unsigned char *buf, int num) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
Definition: random.cpp:585
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
UniValue::isArray
bool isArray() const
Definition: univalue.h:83
CWalletTx::Confirmation::hashBlock
uint256 hashBlock
Definition: transaction.h:189
CWallet::GetLegacyScriptPubKeyMan
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:3013
ExtractDestination
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:213
DatabaseFormat::SQLITE
@ SQLITE
CWallet::KeypoolCountExternalKeys
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2070
CWallet::MarkDestinationsDirty
void MarkDestinationsDirty(const std::set< CTxDestination > &destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Marks all outputs in each one of the destinations dirty, so their cache is reset and does not return ...
Definition: wallet.cpp:2147
WALLET_FLAG_BLANK_WALLET
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
Definition: walletutil.h:59
CWallet::ListLockedCoins
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2261
DBErrors::LOAD_OK
@ LOAD_OK
CWallet::GetDebit
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Returns amount of debit if the input matches the filter, otherwise returns 0.
Definition: wallet.cpp:1280
CNoDestination
Definition: standard.h:72
CWallet::TxItems
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:395
ParseMoney
bool ParseMoney(const std::string &money_string, CAmount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:38
CWallet::SetupLegacyScriptPubKeyMan
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:3031
CWallet::GetConflicts
std::set< uint256 > GetConflicts(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get wallet transactions that conflict with given transaction (spend same outputs)
Definition: wallet.cpp:467
CWallet::Create
static std::shared_ptr< CWallet > Create(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database, uint64_t wallet_creation_flags, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:2477
mapValue_t
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:20
CWalletTx::GetConflicts
std::set< uint256 > GetConflicts() const NO_THREAD_SAFETY_ANALYSIS
Definition: wallet.cpp:1723
ExternalSigner
Enables interaction with an external signing device or service, such as a hardware wallet.
Definition: external_signer.h:20
WALLET_FLAG_DISABLE_PRIVATE_KEYS
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:47
WalletDatabase::Flush
virtual void Flush()=0
Make sure all changes are flushed to database file.
name
const char * name
Definition: rest.cpp:43
CKeyPool::CKeyPool
CKeyPool()
Definition: wallet.cpp:2851
CWallet::EncryptWallet
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:593
CBlockHeader::hashPrevBlock
uint256 hashPrevBlock
Definition: block.h:25
WalletBatch::ReadBestBlock
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:175
ProduceSignature
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:199
CWallet::AttachChain
static bool AttachChain(const std::shared_ptr< CWallet > &wallet, interfaces::Chain &chain, bilingual_str &error, std::vector< bilingual_str > &warnings)
Catch wallet up to current chain, scanning new blocks, updating the best block locator and m_last_blo...
Definition: wallet.cpp:2705
OutputType::BECH32
@ BECH32
CBlock
Definition: block.h:62
CWallet::m_internal_spk_managers
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:323
PKHash
Definition: standard.h:78
CWalletTx::Confirmation::nIndex
int nIndex
Definition: transaction.h:190
CWallet::ScanResult::USER_ABORT
@ USER_ABORT
Definition: wallet.h:523
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
key.h
DatabaseStatus::FAILED_LOAD
@ FAILED_LOAD
ReserveDestination::type
const OutputType type
Definition: wallet.h:161
CWalletTx::setAbandoned
void setAbandoned()
Definition: transaction.h:334
DBErrors
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:43
SIGHASH_ALL
@ SIGHASH_ALL
Definition: interpreter.h:27
CExtKey::SetSeed
void SetSeed(const unsigned char *seed, unsigned int nSeedLen)
Definition: key.cpp:301
CWallet::transactionRemovedFromMempool
void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
Definition: wallet.cpp:1197
CPubKey
An encapsulated public key.
Definition: pubkey.h:32
fees.h
DEFAULT_SPEND_ZEROCONF_CHANGE
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:88
FEATURE_LATEST
@ FEATURE_LATEST
Definition: walletutil.h:29
CKey::size
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:88
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:31
GetClosestWalletFeature
WalletFeature GetClosestWalletFeature(int version)
Definition: walletutil.cpp:37
CWalletTx::m_it_wtxOrdered
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: transaction.h:125
CBlock::vtx
std::vector< CTransactionRef > vtx
Definition: block.h:66
ScriptPubKeyMan
Definition: scriptpubkeyman.h:169
CWallet::SetAddressBookWithDB
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::string &strPurpose)
Definition: wallet.cpp:2015
PSBTInput
A structure for PSBTs which contain per-input information.
Definition: psbt.h:49
CWalletTx::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:348
CKey
An encapsulated private key.
Definition: key.h:27
fees.h
CWallet::GetLabelAddresses
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
Definition: wallet.cpp:2161
CWallet::TopUpKeyPool
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2093
CCrypter
Encryption/decryption context with key information.
Definition: crypter.h:69
CWallet::postInitProcess
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:2834
CKey::VerifyPubKey
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:232
util::FindKey
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:100
translation.h
interfaces::Chain::isInMempool
virtual bool isInMempool(const uint256 &txid)=0
Check if transaction is in mempool.
CWallet::AddToWalletIfInvolvingMe
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1009
CAddressBookData::destdata
StringMap destdata
Definition: wallet.h:204
KNOWN_WALLET_FLAGS
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:117
CWallet::IsSpent
bool IsSpent(const uint256 &hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:550
DatabaseStatus::FAILED_CREATE
@ FAILED_CREATE
AddWalletSetting
bool AddWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Add wallet name to persistent configuration so it will be loaded on startup.
Definition: wallet.cpp:60
WalletDatabase::Rewrite
virtual bool Rewrite(const char *pszSkip=nullptr)=0
Rewrite the entire database on disk, with the exception of key pszSkip if non-zero.
COutPoint::n
uint32_t n
Definition: transaction.h:30
CWallet::BackupWallet
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:2846
CWallet::LockCoin
void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2235
MakeDatabase
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: walletdb.cpp:1015
CWalletTx::isConflicted
bool isConflicted() const
Definition: transaction.h:341
PartiallySignedTransaction
A version of CTransaction with the PSBT format.
Definition: psbt.h:391
ReserveDestination::GetReservedDestination
bool GetReservedDestination(CTxDestination &pubkey, bool internal)
Reserve an address.
Definition: wallet.cpp:2176
LOCK
#define LOCK(cs)
Definition: sync.h:232
MemPoolRemovalReason
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:395
gArgs
ArgsManager gArgs
Definition: system.cpp:79
CWallet::SetAddressReceiveRequest
bool SetAddressReceiveRequest(WalletBatch &batch, const CTxDestination &dest, const std::string &id, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2439
CWallet::Lock
bool Lock()
Definition: wallet.cpp:2904
CWallet
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:225
CWalletTx::GetHash
const uint256 & GetHash() const
Definition: transaction.h:347
TransactionError::OK
@ OK
No error.
CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:68
interfaces::Chain::initMessage
virtual void initMessage(const std::string &message)=0
Send init message.
ReserveDestination::m_spk_man
ScriptPubKeyMan * m_spk_man
The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called.
Definition: wallet.h:160
CWallet::IsMine
isminetype IsMine(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1302
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:68
CWallet::m_spk_managers
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:327
CWallet::GetAddressReceiveRequests
std::vector< std::string > GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2425
CWallet::GetAllScriptPubKeyMans
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:2947
DBErrors::CORRUPT
@ CORRUPT
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
RemoveWalletSetting
bool RemoveWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Remove wallet name from persistent configuration so it will not be loaded on startup.
Definition: wallet.cpp:71
ScriptPubKeyMan::TopUp
virtual bool TopUp(unsigned int size=0)
Fills internal address pool.
Definition: scriptpubkeyman.h:192
DEFAULT_WALLETBROADCAST
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:95
ExternalSignerScriptPubKeyMan::GetExternalSigner
static ExternalSigner GetExternalSigner()
Definition: external_signer_scriptpubkeyman.cpp:43
CCrypter::SetKeyFromPassphrase
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:39
CWallet::HasEncryptionKeys
bool HasEncryptionKeys() const override
Definition: wallet.cpp:3050
CWallet::IsLegacy
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:3164
CWallet::IncOrderPosNext
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
Definition: wallet.cpp:752
CKeyPool::fInternal
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
Definition: scriptpubkeyman.h:109
CWallet::GetWalletTx
const CWalletTx * GetWalletTx(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:352
CMasterKey::nDerivationMethod
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:40
CWallet::cs_wallet
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:343
CWallet::SetSpentKeyState
void SetSpentKeyState(WalletBatch &batch, const uint256 &hash, unsigned int n, bool used, std::set< CTxDestination > &tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:808
CWalletTx::fFromMe
bool fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node,...
Definition: transaction.h:123
HIGH_TX_FEE_PER_KB
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:100
UniValue::getValues
const std::vector< UniValue > & getValues() const
Definition: univalue_get.cpp:83
PSBTInputSigned
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:194
CWallet::RescanFromTime
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1521
wallet.h
CWalletTx::fInMempool
bool fInMempool
Definition: transaction.h:139
CWalletTx::MarkDirty
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:257
ScriptPubKeyMan::ReturnDestination
virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr)
Definition: scriptpubkeyman.h:186
CWallet::GetScriptPubKeyMan
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:2956
UniValue::size
size_t size() const
Definition: univalue.h:68
WalletBatch::ErasePurpose
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:82
interfaces::Chain::haveBlockOnDisk
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
CWallet::AddWalletFlags
bool AddWalletFlags(uint64_t flags)
overwrite all flags by the given uint64_t returns false if unknown, non-tolerable flags are present
Definition: wallet.cpp:1411
WalletBatch::ZapSelectTx
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: walletdb.cpp:914
script.h
CWallet::UpdateWalletTxFn
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:512
WalletBatch::WriteMinVersion
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:201
CWallet::FillPSBT
TransactionError FillPSBT(PartiallySignedTransaction &psbtx, bool &complete, int sighash_type=1, bool sign=true, bool bip32derivs=true, size_t *n_signed=nullptr) const
Fills out a PSBT with information from the wallet.
Definition: wallet.cpp:1828
WalletDescriptor
Descriptor with some wallet metadata.
Definition: walletutil.h:72
WALLET_CRYPTO_SALT_SIZE
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:14
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:302
CT_NEW
@ CT_NEW
Definition: ui_change_type.h:10
WalletFeature
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:14
UpdateInput
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:354
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
CWallet::GetScriptPubKeyMans
std::set< ScriptPubKeyMan * > GetScriptPubKeyMans(const CScript &script, SignatureData &sigdata) const
Get all of the ScriptPubKeyMans for a script given additional information in sigdata (populated by e....
Definition: wallet.cpp:2967
find_value
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
WalletBatch::TxnBegin
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:1000
interfaces::Chain::getTipLocator
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
FillableSigningProvider::cs_KeyStore
RecursiveMutex cs_KeyStore
Definition: signingprovider.h:121
MemPoolRemovalReason::BLOCK
@ BLOCK
Removed for block.
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
interfaces::Chain::requestMempoolTransactions
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
WalletBatch::WriteTx
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:87
CWallet::SyncMetaData
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:507
WalletDescriptor::descriptor
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:75
CWallet::ImportPubKeys
bool ImportPubKeys(const std::vector< CKeyID > &ordered_pubkeys, const std::map< CKeyID, CPubKey > &pubkey_map, const std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo >> &key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1480
g_wallet_release_cv
static std::condition_variable g_wallet_release_cv
Definition: wallet.cpp:158
CWallet::ChangeWalletPassphrase
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:399
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:344
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
UniValue::get_array
const UniValue & get_array() const
Definition: univalue_get.cpp:141
UniValue::VARR
@ VARR
Definition: univalue.h:21
DatabaseStatus::SUCCESS
@ SUCCESS
CWallet::LoadActiveScriptPubKeyMan
void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Loads an active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3153
coincontrol.h
GetWalletDir
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:10
CWallet::Close
void Close()
Close wallet database.
Definition: wallet.cpp:502
CWallet::ImportScripts
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1460
CFeeRate::GetFeePerK
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:56
DatabaseStatus::FAILED_ENCRYPT
@ FAILED_ENCRYPT
CWallet::SignTransaction
bool SignTransaction(CMutableTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Fetch the inputs and sign with SIGHASH_ALL.
Definition: wallet.cpp:1795
CWallet::FindAddressBookEntry
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2791
WalletBatch
Access to the wallet database.
Definition: walletdb.h:176
DEFAULT_TX_CONFIRM_TARGET
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:92
CWallet::CanGetAddresses
bool CanGetAddresses(bool internal=false) const
Definition: wallet.cpp:1354
CWallet::NotifyCanGetAddressesChanged
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:749
WALLET_FLAG_KEY_ORIGIN_METADATA
@ WALLET_FLAG_KEY_ORIGIN_METADATA
Definition: walletutil.h:44
external_signer_scriptpubkeyman.h
CWallet::GetKeyBirthTimes
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2273
WalletRescanReserver::isReserved
bool isReserved() const
Definition: wallet.h:936
CWallet::GetNewDestination
bool GetNewDestination(const OutputType type, const std::string label, CTxDestination &dest, std::string &error)
Definition: wallet.cpp:2103
CWallet::LoadToWallet
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:965
DatabaseOptions::require_format
std::optional< DatabaseFormat > require_format
Definition: db.h:206
CMasterKey::nDeriveIterations
unsigned int nDeriveIterations
Definition: crypter.h:41
MemPoolRemovalReason::CONFLICT
@ CONFLICT
Removed for conflict with in-block transaction.
CWallet::HaveChain
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:389
CWallet::MarkInputsDirty
void MarkInputsDirty(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed.
Definition: wallet.cpp:1060
CWallet::Unlock
bool Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys=false)
Definition: wallet.cpp:2918
ScriptHash
Definition: standard.h:88
CWallet::TransactionChangeType
OutputType TransactionChangeType(const std::optional< OutputType > &change_type, const std::vector< CRecipient > &vecSend) const
Definition: wallet.cpp:1890
CWalletTx::SubmitMemoryPoolAndRelay
bool SubmitMemoryPoolAndRelay(std::string &err_string, bool relay)
Pass this transaction to node for mempool insertion and relay to peers if flag set to true.
Definition: wallet.cpp:1695
ReserveDestination::ReturnDestination
void ReturnDestination()
Return reserved address.
Definition: wallet.cpp:2207
CWalletTx::InMempool
bool InMempool() const
Definition: transaction.cpp:16
ReserveDestination::KeepDestination
void KeepDestination()
Keep the address. Do not return it's key to the keypool when this object goes out of scope.
Definition: wallet.cpp:2198
base_blob::begin
unsigned char * begin()
Definition: uint256.h:58
GetTimeMillis
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:117
EncodeDestination
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:256
CWallet::GetOrCreateLegacyScriptPubKeyMan
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:3025
DatabaseOptions::create_flags
uint64_t create_flags
Definition: db.h:207
CWallet::GetLastBlockHash
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:867
interfaces::Chain::findFirstBlockWithTimeAndHeight
virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock &block={})=0
Find first block in the chain with timestamp >= the given time and height >= than the given height,...
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:237
WALLET_FLAG_DESCRIPTORS
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:62
FlatSigningProvider
Definition: signingprovider.h:47
descriptor.h
CWallet::chainStateFlushed
void chainStateFlushed(const CBlockLocator &loc) override
Definition: wallet.cpp:445
interfaces::MakeHandler
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:35
it
auto it
Definition: validation.cpp:355
UniValue::setArray
bool setArray()
Definition: univalue.cpp:94
DBErrors::TOO_NEW
@ TOO_NEW
DBErrors::LOAD_FAIL
@ LOAD_FAIL
WalletBatch::WriteWalletFlags
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:995
TIMESTAMP_WINDOW
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:30
UniValue::isObject
bool isObject() const
Definition: univalue.h:84
WalletBatch::TxnAbort
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:1010
CWallet::DisplayAddress
bool DisplayAddress(const CTxDestination &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Display address on an external signer.
Definition: wallet.cpp:2216