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