Bitcoin ABC  0.22.12
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 <chainparams.h>
10 #include <config.h>
11 #include <consensus/consensus.h>
12 #include <consensus/validation.h>
13 #include <fs.h>
14 #include <interfaces/wallet.h>
15 #include <key.h>
16 #include <key_io.h>
17 #include <policy/mempool.h>
18 #include <policy/policy.h>
19 #include <primitives/transaction.h>
20 #include <random.h>
21 #include <script/descriptor.h>
22 #include <script/script.h>
23 #include <script/sighashtype.h>
24 #include <script/sign.h>
25 #include <script/signingprovider.h>
26 #include <util/bip32.h>
27 #include <util/check.h>
28 #include <util/error.h>
29 #include <util/moneystr.h>
30 #include <util/string.h>
31 #include <util/translation.h>
32 #include <wallet/coincontrol.h>
33 #include <wallet/fees.h>
34 
35 #include <boost/algorithm/string/replace.hpp>
36 
38 
39 const std::map<uint64_t, std::string> WALLET_FLAG_CAVEATS{
41  "You need to rescan the blockchain in order to correctly mark used "
42  "destinations in the past. Until this is done, some destinations may "
43  "be considered unused, even if the opposite is the case."},
44 };
45 
47 static std::vector<std::shared_ptr<CWallet>> vpwallets GUARDED_BY(cs_wallets);
48 static std::list<LoadWalletFn> g_load_wallet_fns GUARDED_BY(cs_wallets);
49 
50 bool AddWallet(const std::shared_ptr<CWallet> &wallet) {
51  LOCK(cs_wallets);
52  assert(wallet);
53  std::vector<std::shared_ptr<CWallet>>::const_iterator i =
54  std::find(vpwallets.begin(), vpwallets.end(), wallet);
55  if (i != vpwallets.end()) {
56  return false;
57  }
58  vpwallets.push_back(wallet);
59  wallet->ConnectScriptPubKeyManNotifiers();
60  return true;
61 }
62 
63 bool RemoveWallet(const std::shared_ptr<CWallet> &wallet) {
64  assert(wallet);
65  // Unregister with the validation interface which also drops shared ponters.
66  wallet->m_chain_notifications_handler.reset();
67  LOCK(cs_wallets);
68  std::vector<std::shared_ptr<CWallet>>::iterator i =
69  std::find(vpwallets.begin(), vpwallets.end(), wallet);
70  if (i == vpwallets.end()) {
71  return false;
72  }
73  vpwallets.erase(i);
74  return true;
75 }
76 
77 bool HasWallets() {
78  LOCK(cs_wallets);
79  return !vpwallets.empty();
80 }
81 
82 std::vector<std::shared_ptr<CWallet>> GetWallets() {
83  LOCK(cs_wallets);
84  return vpwallets;
85 }
86 
87 std::shared_ptr<CWallet> GetWallet(const std::string &name) {
88  LOCK(cs_wallets);
89  for (const std::shared_ptr<CWallet> &wallet : vpwallets) {
90  if (wallet->GetName() == name) {
91  return wallet;
92  }
93  }
94  return nullptr;
95 }
96 
97 std::unique_ptr<interfaces::Handler>
99  LOCK(cs_wallets);
100  auto it = g_load_wallet_fns.emplace(g_load_wallet_fns.end(),
101  std::move(load_wallet));
102  return interfaces::MakeHandler([it] {
103  LOCK(cs_wallets);
104  g_load_wallet_fns.erase(it);
105  });
106 }
107 
109 static std::condition_variable g_wallet_release_cv;
110 static std::set<std::string> g_unloading_wallet_set;
111 
112 // Custom deleter for shared_ptr<CWallet>.
113 static void ReleaseWallet(CWallet *wallet) {
114  const std::string name = wallet->GetName();
115  wallet->WalletLogPrintf("Releasing wallet\n");
116  wallet->Flush();
117  delete wallet;
118  // Wallet is now released, notify UnloadWallet, if any.
119  {
120  LOCK(g_wallet_release_mutex);
121  if (g_unloading_wallet_set.erase(name) == 0) {
122  // UnloadWallet was not called for this wallet, all done.
123  return;
124  }
125  }
126  g_wallet_release_cv.notify_all();
127 }
128 
129 void UnloadWallet(std::shared_ptr<CWallet> &&wallet) {
130  // Mark wallet for unloading.
131  const std::string name = wallet->GetName();
132  {
133  LOCK(g_wallet_release_mutex);
134  auto it = g_unloading_wallet_set.insert(name);
135  assert(it.second);
136  }
137  // The wallet can be in use so it's not possible to explicitly unload here.
138  // Notify the unload intent so that all remaining shared pointers are
139  // released.
140  wallet->NotifyUnload();
141 
142  // Time to ditch our shared_ptr and wait for ReleaseWallet call.
143  wallet.reset();
144  {
145  WAIT_LOCK(g_wallet_release_mutex, lock);
146  while (g_unloading_wallet_set.count(name) == 1) {
147  g_wallet_release_cv.wait(lock);
148  }
149  }
150 }
151 
152 static const size_t OUTPUT_GROUP_MAX_ENTRIES = 10;
153 
154 std::shared_ptr<CWallet> LoadWallet(const CChainParams &chainParams,
155  interfaces::Chain &chain,
156  const WalletLocation &location,
158  std::vector<bilingual_str> &warnings) {
159  try {
160  if (!CWallet::Verify(chainParams, chain, location, error, warnings)) {
161  error = Untranslated("Wallet file verification failed.") +
162  Untranslated(" ") + error;
163  return nullptr;
164  }
165 
166  std::shared_ptr<CWallet> wallet = CWallet::CreateWalletFromFile(
167  chainParams, chain, location, error, warnings);
168  if (!wallet) {
169  error = Untranslated("Wallet loading failed.") + Untranslated(" ") +
170  error;
171  return nullptr;
172  }
173  AddWallet(wallet);
174  wallet->postInitProcess();
175  return wallet;
176  } catch (const std::runtime_error &e) {
177  error = Untranslated(e.what());
178  return nullptr;
179  }
180 }
181 
182 std::shared_ptr<CWallet> LoadWallet(const CChainParams &chainParams,
183  interfaces::Chain &chain,
184  const std::string &name,
186  std::vector<bilingual_str> &warnings) {
187  return LoadWallet(chainParams, chain, WalletLocation(name), error,
188  warnings);
189 }
190 
192  interfaces::Chain &chain,
193  const SecureString &passphrase,
194  uint64_t wallet_creation_flags,
195  const std::string &name, bilingual_str &error,
196  std::vector<bilingual_str> &warnings,
197  std::shared_ptr<CWallet> &result) {
198  // Indicate that the wallet is actually supposed to be blank and not just
199  // blank to make it encrypted
200  bool create_blank = (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET);
201 
202  // Born encrypted wallets need to be created blank first.
203  if (!passphrase.empty()) {
204  wallet_creation_flags |= WALLET_FLAG_BLANK_WALLET;
205  }
206 
207  // Check the wallet file location
208  WalletLocation location(name);
209  if (location.Exists()) {
210  error = strprintf(Untranslated("Wallet %s already exists."),
211  location.GetName());
213  }
214 
215  // Wallet::Verify will check if we're trying to create a wallet with a
216  // duplicate name.
217  if (!CWallet::Verify(params, chain, location, error, warnings)) {
218  error = Untranslated("Wallet file verification failed.") +
219  Untranslated(" ") + error;
221  }
222 
223  // Do not allow a passphrase when private keys are disabled
224  if (!passphrase.empty() &&
225  (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
226  error = Untranslated(
227  "Passphrase provided but private keys are disabled. A passphrase "
228  "is only used to encrypt private keys, so cannot be used for "
229  "wallets with private keys disabled.");
231  }
232 
233  // Make the wallet
234  std::shared_ptr<CWallet> wallet = CWallet::CreateWalletFromFile(
235  params, chain, location, error, warnings, wallet_creation_flags);
236  if (!wallet) {
237  error =
238  Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
240  }
241 
242  // Encrypt the wallet
243  if (!passphrase.empty() &&
244  !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
245  if (!wallet->EncryptWallet(passphrase)) {
246  error =
247  Untranslated("Error: Wallet created but failed to encrypt.");
249  }
250  if (!create_blank) {
251  // Unlock the wallet
252  if (!wallet->Unlock(passphrase)) {
253  error = Untranslated(
254  "Error: Wallet was encrypted but could not be unlocked");
256  }
257 
258  // Set a seed for the wallet
259  {
260  LOCK(wallet->cs_wallet);
261  if (wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
262  wallet->SetupDescriptorScriptPubKeyMans();
263  } else {
264  for (auto spk_man : wallet->GetActiveScriptPubKeyMans()) {
265  if (!spk_man->SetupGeneration()) {
266  error =
267  Untranslated("Unable to generate initial keys");
269  }
270  }
271  }
272  }
273 
274  // Relock the wallet
275  wallet->Lock();
276  }
277  }
278  AddWallet(wallet);
279  wallet->postInitProcess();
280  result = wallet;
282 }
283 
285 
291 std::string COutput::ToString() const {
292  return strprintf("COutput(%s, %d, %d) [%s]", tx->GetId().ToString(), i,
293  nDepth, FormatMoney(tx->tx->vout[i].nValue));
294 }
295 
297  // Get CChainParams from interfaces::Chain, unless wallet doesn't have a
298  // chain (i.e. bitcoin-wallet), in which case return global Params()
299  return m_chain ? m_chain->params() : Params();
300 }
301 
302 const CWalletTx *CWallet::GetWalletTx(const TxId &txid) const {
303  LOCK(cs_wallet);
304  std::map<TxId, CWalletTx>::const_iterator it = mapWallet.find(txid);
305  if (it == mapWallet.end()) {
306  return nullptr;
307  }
308 
309  return &(it->second);
310 }
311 
313  if (IsLocked() || IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
314  return;
315  }
316 
317  auto spk_man = GetLegacyScriptPubKeyMan();
318  if (!spk_man) {
319  return;
320  }
321 
322  spk_man->UpgradeKeyMetadata();
323  SetWalletFlag(WALLET_FLAG_KEY_ORIGIN_METADATA);
324 }
325 
326 bool CWallet::Unlock(const SecureString &strWalletPassphrase,
327  bool accept_no_keys) {
328  CCrypter crypter;
329  CKeyingMaterial _vMasterKey;
330 
331  {
332  LOCK(cs_wallet);
333  for (const MasterKeyMap::value_type &pMasterKey : mapMasterKeys) {
334  if (!crypter.SetKeyFromPassphrase(
335  strWalletPassphrase, pMasterKey.second.vchSalt,
336  pMasterKey.second.nDeriveIterations,
337  pMasterKey.second.nDerivationMethod)) {
338  return false;
339  }
340  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey,
341  _vMasterKey)) {
342  // try another master key
343  continue;
344  }
345  if (Unlock(_vMasterKey, accept_no_keys)) {
346  // Now that we've unlocked, upgrade the key metadata
347  UpgradeKeyMetadata();
348  return true;
349  }
350  }
351  }
352 
353  return false;
354 }
355 
357  const SecureString &strOldWalletPassphrase,
358  const SecureString &strNewWalletPassphrase) {
359  bool fWasLocked = IsLocked();
360 
361  LOCK(cs_wallet);
362  Lock();
363 
364  CCrypter crypter;
365  CKeyingMaterial _vMasterKey;
366  for (MasterKeyMap::value_type &pMasterKey : mapMasterKeys) {
367  if (!crypter.SetKeyFromPassphrase(
368  strOldWalletPassphrase, pMasterKey.second.vchSalt,
369  pMasterKey.second.nDeriveIterations,
370  pMasterKey.second.nDerivationMethod)) {
371  return false;
372  }
373 
374  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey)) {
375  return false;
376  }
377 
378  if (Unlock(_vMasterKey)) {
379  int64_t nStartTime = GetTimeMillis();
380  crypter.SetKeyFromPassphrase(strNewWalletPassphrase,
381  pMasterKey.second.vchSalt,
382  pMasterKey.second.nDeriveIterations,
383  pMasterKey.second.nDerivationMethod);
384  pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(
385  pMasterKey.second.nDeriveIterations *
386  (100 / ((double)(GetTimeMillis() - nStartTime))));
387 
388  nStartTime = GetTimeMillis();
389  crypter.SetKeyFromPassphrase(strNewWalletPassphrase,
390  pMasterKey.second.vchSalt,
391  pMasterKey.second.nDeriveIterations,
392  pMasterKey.second.nDerivationMethod);
393  pMasterKey.second.nDeriveIterations =
394  (pMasterKey.second.nDeriveIterations +
395  static_cast<unsigned int>(
396  pMasterKey.second.nDeriveIterations * 100 /
397  double(GetTimeMillis() - nStartTime))) /
398  2;
399 
400  if (pMasterKey.second.nDeriveIterations < 25000) {
401  pMasterKey.second.nDeriveIterations = 25000;
402  }
403 
404  WalletLogPrintf(
405  "Wallet passphrase changed to an nDeriveIterations of %i\n",
406  pMasterKey.second.nDeriveIterations);
407 
408  if (!crypter.SetKeyFromPassphrase(
409  strNewWalletPassphrase, pMasterKey.second.vchSalt,
410  pMasterKey.second.nDeriveIterations,
411  pMasterKey.second.nDerivationMethod)) {
412  return false;
413  }
414 
415  if (!crypter.Encrypt(_vMasterKey,
416  pMasterKey.second.vchCryptedKey)) {
417  return false;
418  }
419 
420  WalletBatch(*database).WriteMasterKey(pMasterKey.first,
421  pMasterKey.second);
422  if (fWasLocked) {
423  Lock();
424  }
425 
426  return true;
427  }
428  }
429 
430  return false;
431 }
432 
434  WalletBatch batch(*database);
435  batch.WriteBestBlock(loc);
436 }
437 
438 void CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch *batch_in,
439  bool fExplicit) {
440  LOCK(cs_wallet);
441  if (nWalletVersion >= nVersion) {
442  return;
443  }
444 
445  // When doing an explicit upgrade, if we pass the max version permitted,
446  // upgrade all the way.
447  if (fExplicit && nVersion > nWalletMaxVersion) {
448  nVersion = FEATURE_LATEST;
449  }
450 
451  nWalletVersion = nVersion;
452 
453  if (nVersion > nWalletMaxVersion) {
454  nWalletMaxVersion = nVersion;
455  }
456 
457  WalletBatch *batch = batch_in ? batch_in : new WalletBatch(*database);
458  if (nWalletVersion > 40000) {
459  batch->WriteMinVersion(nWalletVersion);
460  }
461  if (!batch_in) {
462  delete batch;
463  }
464 }
465 
466 bool CWallet::SetMaxVersion(int nVersion) {
467  LOCK(cs_wallet);
468 
469  // Cannot downgrade below current version
470  if (nWalletVersion > nVersion) {
471  return false;
472  }
473 
474  nWalletMaxVersion = nVersion;
475 
476  return true;
477 }
478 
479 std::set<TxId> CWallet::GetConflicts(const TxId &txid) const {
480  std::set<TxId> result;
481  AssertLockHeld(cs_wallet);
482 
483  std::map<TxId, CWalletTx>::const_iterator it = mapWallet.find(txid);
484  if (it == mapWallet.end()) {
485  return result;
486  }
487 
488  const CWalletTx &wtx = it->second;
489 
490  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
491 
492  for (const CTxIn &txin : wtx.tx->vin) {
493  if (mapTxSpends.count(txin.prevout) <= 1) {
494  // No conflict if zero or one spends.
495  continue;
496  }
497 
498  range = mapTxSpends.equal_range(txin.prevout);
499  for (TxSpends::const_iterator _it = range.first; _it != range.second;
500  ++_it) {
501  result.insert(_it->second);
502  }
503  }
504 
505  return result;
506 }
507 
508 bool CWallet::HasWalletSpend(const TxId &txid) const {
509  AssertLockHeld(cs_wallet);
510  auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
511  return (iter != mapTxSpends.end() && iter->first.GetTxId() == txid);
512 }
513 
514 void CWallet::Flush(bool shutdown) {
515  database->Flush(shutdown);
516 }
517 
519  std::pair<TxSpends::iterator, TxSpends::iterator> range) {
520  // We want all the wallet transactions in range to have the same metadata as
521  // the oldest (smallest nOrderPos).
522  // So: find smallest nOrderPos:
523 
524  int nMinOrderPos = std::numeric_limits<int>::max();
525  const CWalletTx *copyFrom = nullptr;
526  for (TxSpends::iterator it = range.first; it != range.second; ++it) {
527  const CWalletTx *wtx = &mapWallet.at(it->second);
528  if (wtx->nOrderPos < nMinOrderPos) {
529  nMinOrderPos = wtx->nOrderPos;
530  copyFrom = wtx;
531  }
532  }
533 
534  if (!copyFrom) {
535  return;
536  }
537 
538  // Now copy data from copyFrom to rest:
539  for (TxSpends::iterator it = range.first; it != range.second; ++it) {
540  const TxId &txid = it->second;
541  CWalletTx *copyTo = &mapWallet.at(txid);
542  if (copyFrom == copyTo) {
543  continue;
544  }
545 
546  assert(
547  copyFrom &&
548  "Oldest wallet transaction in range assumed to have been found.");
549 
550  if (!copyFrom->IsEquivalentTo(*copyTo)) {
551  continue;
552  }
553 
554  copyTo->mapValue = copyFrom->mapValue;
555  copyTo->vOrderForm = copyFrom->vOrderForm;
556  // fTimeReceivedIsTxTime not copied on purpose nTimeReceived not copied
557  // on purpose.
558  copyTo->nTimeSmart = copyFrom->nTimeSmart;
559  copyTo->fFromMe = copyFrom->fFromMe;
560  // nOrderPos not copied on purpose cached members not copied on purpose.
561  }
562 }
563 
567 bool CWallet::IsSpent(const COutPoint &outpoint) const {
568  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range =
569  mapTxSpends.equal_range(outpoint);
570 
571  for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
572  const TxId &wtxid = it->second;
573  std::map<TxId, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
574  if (mit != mapWallet.end()) {
575  int depth = mit->second.GetDepthInMainChain();
576  if (depth > 0 || (depth == 0 && !mit->second.isAbandoned())) {
577  // Spent
578  return true;
579  }
580  }
581  }
582 
583  return false;
584 }
585 
586 void CWallet::AddToSpends(const COutPoint &outpoint, const TxId &wtxid) {
587  mapTxSpends.insert(std::make_pair(outpoint, wtxid));
588 
589  setLockedCoins.erase(outpoint);
590 
591  std::pair<TxSpends::iterator, TxSpends::iterator> range;
592  range = mapTxSpends.equal_range(outpoint);
593  SyncMetaData(range);
594 }
595 
596 void CWallet::AddToSpends(const TxId &wtxid) {
597  auto it = mapWallet.find(wtxid);
598  assert(it != mapWallet.end());
599  CWalletTx &thisTx = it->second;
600  // Coinbases don't spend anything!
601  if (thisTx.IsCoinBase()) {
602  return;
603  }
604 
605  for (const CTxIn &txin : thisTx.tx->vin) {
606  AddToSpends(txin.prevout, wtxid);
607  }
608 }
609 
610 bool CWallet::EncryptWallet(const SecureString &strWalletPassphrase) {
611  if (IsCrypted()) {
612  return false;
613  }
614 
615  CKeyingMaterial _vMasterKey;
616 
617  _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
618  GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
619 
620  CMasterKey kMasterKey;
621 
622  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
624 
625  CCrypter crypter;
626  int64_t nStartTime = GetTimeMillis();
627  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000,
628  kMasterKey.nDerivationMethod);
629  kMasterKey.nDeriveIterations = static_cast<unsigned int>(
630  2500000 / double(GetTimeMillis() - nStartTime));
631 
632  nStartTime = GetTimeMillis();
633  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt,
634  kMasterKey.nDeriveIterations,
635  kMasterKey.nDerivationMethod);
636  kMasterKey.nDeriveIterations =
637  (kMasterKey.nDeriveIterations +
638  static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 /
639  double(GetTimeMillis() - nStartTime))) /
640  2;
641 
642  if (kMasterKey.nDeriveIterations < 25000) {
643  kMasterKey.nDeriveIterations = 25000;
644  }
645 
646  WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n",
647  kMasterKey.nDeriveIterations);
648 
649  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt,
650  kMasterKey.nDeriveIterations,
651  kMasterKey.nDerivationMethod)) {
652  return false;
653  }
654 
655  if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey)) {
656  return false;
657  }
658 
659  {
660  LOCK(cs_wallet);
661  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
662  WalletBatch *encrypted_batch = new WalletBatch(*database);
663  if (!encrypted_batch->TxnBegin()) {
664  delete encrypted_batch;
665  encrypted_batch = nullptr;
666  return false;
667  }
668  encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
669 
670  for (const auto &spk_man_pair : m_spk_managers) {
671  auto spk_man = spk_man_pair.second.get();
672  if (!spk_man->Encrypt(_vMasterKey, encrypted_batch)) {
673  encrypted_batch->TxnAbort();
674  delete encrypted_batch;
675  encrypted_batch = nullptr;
676  // We now probably have half of our keys encrypted in memory,
677  // and half not... die and let the user reload the unencrypted
678  // wallet.
679  assert(false);
680  }
681  }
682 
683  // Encryption was introduced in version 0.4.0
684  SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch, true);
685 
686  if (!encrypted_batch->TxnCommit()) {
687  delete encrypted_batch;
688  encrypted_batch = nullptr;
689  // We now have keys encrypted in memory, but not on disk...
690  // die to avoid confusion and let the user reload the unencrypted
691  // wallet.
692  assert(false);
693  }
694 
695  delete encrypted_batch;
696  encrypted_batch = nullptr;
697 
698  Lock();
699  Unlock(strWalletPassphrase);
700 
701  // If we are using descriptors, make new descriptors with a new seed
702  if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) &&
703  !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET)) {
704  SetupDescriptorScriptPubKeyMans();
705  } else if (auto spk_man = GetLegacyScriptPubKeyMan()) {
706  // if we are using HD, replace the HD seed with a new one
707  if (spk_man->IsHDEnabled()) {
708  if (!spk_man->SetupGeneration(true)) {
709  return false;
710  }
711  }
712  }
713  Lock();
714 
715  // Need to completely rewrite the wallet file; if we don't, bdb might
716  // keep bits of the unencrypted private key in slack space in the
717  // database file.
718  database->Rewrite();
719 
720  // BDB seems to have a bad habit of writing old data into
721  // slack space in .dat files; that is bad if the old data is
722  // unencrypted private keys. So:
723  database->ReloadDbEnv();
724  }
725 
726  NotifyStatusChanged(this);
727  return true;
728 }
729 
731  LOCK(cs_wallet);
732  WalletBatch batch(*database);
733 
734  // Old wallets didn't have any defined order for transactions. Probably a
735  // bad idea to change the output of this.
736 
737  // First: get all CWalletTx into a sorted-by-time
738  // multimap.
739  TxItems txByTime;
740 
741  for (auto &entry : mapWallet) {
742  CWalletTx *wtx = &entry.second;
743  txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
744  }
745 
746  nOrderPosNext = 0;
747  std::vector<int64_t> nOrderPosOffsets;
748  for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) {
749  CWalletTx *const pwtx = (*it).second;
750  int64_t &nOrderPos = pwtx->nOrderPos;
751 
752  if (nOrderPos == -1) {
753  nOrderPos = nOrderPosNext++;
754  nOrderPosOffsets.push_back(nOrderPos);
755 
756  if (!batch.WriteTx(*pwtx)) {
757  return DBErrors::LOAD_FAIL;
758  }
759  } else {
760  int64_t nOrderPosOff = 0;
761  for (const int64_t &nOffsetStart : nOrderPosOffsets) {
762  if (nOrderPos >= nOffsetStart) {
763  ++nOrderPosOff;
764  }
765  }
766 
767  nOrderPos += nOrderPosOff;
768  nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
769 
770  if (!nOrderPosOff) {
771  continue;
772  }
773 
774  // Since we're changing the order, write it back.
775  if (!batch.WriteTx(*pwtx)) {
776  return DBErrors::LOAD_FAIL;
777  }
778  }
779  }
780 
781  batch.WriteOrderPosNext(nOrderPosNext);
782 
783  return DBErrors::LOAD_OK;
784 }
785 
787  AssertLockHeld(cs_wallet);
788  int64_t nRet = nOrderPosNext++;
789  if (batch) {
790  batch->WriteOrderPosNext(nOrderPosNext);
791  } else {
792  WalletBatch(*database).WriteOrderPosNext(nOrderPosNext);
793  }
794 
795  return nRet;
796 }
797 
799  LOCK(cs_wallet);
800  for (std::pair<const TxId, CWalletTx> &item : mapWallet) {
801  item.second.MarkDirty();
802  }
803 }
804 
805 void CWallet::SetSpentKeyState(WalletBatch &batch, const TxId &txid,
806  unsigned int n, bool used,
807  std::set<CTxDestination> &tx_destinations) {
808  AssertLockHeld(cs_wallet);
809  const CWalletTx *srctx = GetWalletTx(txid);
810  if (!srctx) {
811  return;
812  }
813 
814  CTxDestination dst;
815  if (ExtractDestination(srctx->tx->vout[n].scriptPubKey, dst)) {
816  if (IsMine(dst)) {
817  if (used && !GetDestData(dst, "used", nullptr)) {
818  // p for "present", opposite of absent (null)
819  if (AddDestData(batch, dst, "used", "p")) {
820  tx_destinations.insert(dst);
821  }
822  } else if (!used && GetDestData(dst, "used", nullptr)) {
823  EraseDestData(batch, dst, "used");
824  }
825  }
826  }
827 }
828 
829 bool CWallet::IsSpentKey(const TxId &txid, unsigned int n) const {
830  AssertLockHeld(cs_wallet);
831  CTxDestination dst;
832  const CWalletTx *srctx = GetWalletTx(txid);
833  if (srctx) {
834  assert(srctx->tx->vout.size() > n);
835  CTxDestination dest;
836  if (!ExtractDestination(srctx->tx->vout[n].scriptPubKey, dest)) {
837  return false;
838  }
839  if (GetDestData(dest, "used", nullptr)) {
840  return true;
841  }
842  if (IsLegacy()) {
843  LegacyScriptPubKeyMan *spk_man = GetLegacyScriptPubKeyMan();
844  assert(spk_man != nullptr);
845  for (const auto &keyid :
846  GetAffectedKeys(srctx->tx->vout[n].scriptPubKey, *spk_man)) {
847  PKHash pkh_dest(keyid);
848  if (GetDestData(pkh_dest, "used", nullptr)) {
849  return true;
850  }
851  }
852  }
853  }
854  return false;
855 }
856 
857 bool CWallet::AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose) {
858  LOCK(cs_wallet);
859 
860  WalletBatch batch(*database, "r+", fFlushOnClose);
861 
862  const TxId &txid = wtxIn.GetId();
863 
864  if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
865  // Mark used destinations
866  std::set<CTxDestination> tx_destinations;
867 
868  for (const CTxIn &txin : wtxIn.tx->vin) {
869  const COutPoint &op = txin.prevout;
870  SetSpentKeyState(batch, op.GetTxId(), op.GetN(), true,
871  tx_destinations);
872  }
873 
874  MarkDestinationsDirty(tx_destinations);
875  }
876 
877  // Inserts only if not already there, returns tx inserted or tx found.
878  std::pair<std::map<TxId, CWalletTx>::iterator, bool> ret =
879  mapWallet.insert(std::make_pair(txid, wtxIn));
880  CWalletTx &wtx = (*ret.first).second;
881  wtx.BindWallet(this);
882  bool fInsertedNew = ret.second;
883  if (fInsertedNew) {
884  wtx.nTimeReceived = chain().getAdjustedTime();
885  wtx.nOrderPos = IncOrderPosNext(&batch);
886  wtx.m_it_wtxOrdered =
887  wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
888  wtx.nTimeSmart = ComputeTimeSmart(wtx);
889  AddToSpends(txid);
890  }
891 
892  bool fUpdated = false;
893  if (!fInsertedNew) {
894  if (wtxIn.m_confirm.status != wtx.m_confirm.status) {
895  wtx.m_confirm.status = wtxIn.m_confirm.status;
896  wtx.m_confirm.nIndex = wtxIn.m_confirm.nIndex;
899  fUpdated = true;
900  } else {
901  assert(wtx.m_confirm.nIndex == wtxIn.m_confirm.nIndex);
902  assert(wtx.m_confirm.hashBlock == wtxIn.m_confirm.hashBlock);
903  assert(wtx.m_confirm.block_height == wtxIn.m_confirm.block_height);
904  }
905 
906  if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) {
907  wtx.fFromMe = wtxIn.fFromMe;
908  fUpdated = true;
909  }
910  }
911 
913  WalletLogPrintf("AddToWallet %s %s%s\n", wtxIn.GetId().ToString(),
914  (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
915 
916  // Write to disk
917  if ((fInsertedNew || fUpdated) && !batch.WriteTx(wtx)) {
918  return false;
919  }
920 
921  // Break debit/credit balance caches:
922  wtx.MarkDirty();
923 
924  // Notify UI of new or updated transaction.
925  NotifyTransactionChanged(this, txid, fInsertedNew ? CT_NEW : CT_UPDATED);
926 
927 #if defined(HAVE_SYSTEM)
928  // Notify an external script when a wallet transaction comes in or is
929  // updated.
930  std::string strCmd = gArgs.GetArg("-walletnotify", "");
931 
932  if (!strCmd.empty()) {
933  boost::replace_all(strCmd, "%s", wtxIn.GetId().GetHex());
934 #ifndef WIN32
935  // Substituting the wallet name isn't currently supported on windows
936  // because windows shell escaping has not been implemented yet:
937  // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
938  // A few ways it could be implemented in the future are described in:
939  // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
940  boost::replace_all(strCmd, "%w", ShellEscape(GetName()));
941 #endif
942 
943  std::thread t(runCommand, strCmd);
944  // Thread runs free.
945  t.detach();
946  }
947 #endif
948 
949  return true;
950 }
951 
953  // If wallet doesn't have a chain (e.g wallet-tool), don't bother to update
954  // txn.
955  if (HaveChain()) {
956  std::optional<int> block_height =
957  chain().getBlockHeight(wtxIn.m_confirm.hashBlock);
958  if (block_height) {
959  // Update cached block height variable since it not stored in the
960  // serialized transaction.
961  wtxIn.m_confirm.block_height = *block_height;
962  } else if (wtxIn.isConflicted() || wtxIn.isConfirmed()) {
963  // If tx block (or conflicting block) was reorged out of chain
964  // while the wallet was shutdown, change tx status to UNCONFIRMED
965  // and reset block height, hash, and index. ABANDONED tx don't have
966  // associated blocks and don't need to be updated. The case where a
967  // transaction was reorged out while online and then reconfirmed
968  // while offline is covered by the rescan logic.
969  wtxIn.setUnconfirmed();
970  wtxIn.m_confirm.hashBlock = BlockHash();
971  wtxIn.m_confirm.block_height = 0;
972  wtxIn.m_confirm.nIndex = 0;
973  }
974  }
975  const TxId &txid = wtxIn.GetId();
976  const auto &ins = mapWallet.emplace(txid, wtxIn);
977  CWalletTx &wtx = ins.first->second;
978  wtx.BindWallet(this);
979  if (/* insertion took place */ ins.second) {
980  wtx.m_it_wtxOrdered =
981  wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
982  }
983  AddToSpends(txid);
984  for (const CTxIn &txin : wtx.tx->vin) {
985  auto it = mapWallet.find(txin.prevout.GetTxId());
986  if (it != mapWallet.end()) {
987  CWalletTx &prevtx = it->second;
988  if (prevtx.isConflicted()) {
989  MarkConflicted(prevtx.m_confirm.hashBlock,
990  prevtx.m_confirm.block_height, wtx.GetId());
991  }
992  }
993  }
994 }
995 
997  CWalletTx::Confirmation confirm,
998  bool fUpdate) {
999  const CTransaction &tx = *ptx;
1000  AssertLockHeld(cs_wallet);
1001 
1002  if (!confirm.hashBlock.IsNull()) {
1003  for (const CTxIn &txin : tx.vin) {
1004  std::pair<TxSpends::const_iterator, TxSpends::const_iterator>
1005  range = mapTxSpends.equal_range(txin.prevout);
1006  while (range.first != range.second) {
1007  if (range.first->second != tx.GetId()) {
1008  WalletLogPrintf(
1009  "Transaction %s (in block %s) conflicts with wallet "
1010  "transaction %s (both spend %s:%i)\n",
1011  tx.GetId().ToString(), confirm.hashBlock.ToString(),
1012  range.first->second.ToString(),
1013  range.first->first.GetTxId().ToString(),
1014  range.first->first.GetN());
1015  MarkConflicted(confirm.hashBlock, confirm.block_height,
1016  range.first->second);
1017  }
1018  range.first++;
1019  }
1020  }
1021  }
1022 
1023  bool fExisted = mapWallet.count(tx.GetId()) != 0;
1024  if (fExisted && !fUpdate) {
1025  return false;
1026  }
1027  if (fExisted || IsMine(tx) || IsFromMe(tx)) {
1036  // loop though all outputs
1037  for (const CTxOut &txout : tx.vout) {
1038  for (const auto &spk_man_pair : m_spk_managers) {
1039  spk_man_pair.second->MarkUnusedAddresses(txout.scriptPubKey);
1040  }
1041  }
1042 
1043  CWalletTx wtx(this, ptx);
1044 
1045  // Block disconnection override an abandoned tx as unconfirmed
1046  // which means user may have to call abandontransaction again
1047  wtx.m_confirm = confirm;
1048 
1049  return AddToWallet(wtx, false);
1050  }
1051 
1052  return false;
1053 }
1054 
1055 bool CWallet::TransactionCanBeAbandoned(const TxId &txid) const {
1056  LOCK(cs_wallet);
1057  const CWalletTx *wtx = GetWalletTx(txid);
1058  return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() == 0 &&
1059  !wtx->InMempool();
1060 }
1061 
1063  for (const CTxIn &txin : tx->vin) {
1064  auto it = mapWallet.find(txin.prevout.GetTxId());
1065  if (it != mapWallet.end()) {
1066  it->second.MarkDirty();
1067  }
1068  }
1069 }
1070 
1072  LOCK(cs_wallet);
1073 
1074  WalletBatch batch(*database, "r+");
1075 
1076  std::set<TxId> todo;
1077  std::set<TxId> done;
1078 
1079  // Can't mark abandoned if confirmed or in mempool
1080  auto it = mapWallet.find(txid);
1081  assert(it != mapWallet.end());
1082  CWalletTx &origtx = it->second;
1083  if (origtx.GetDepthInMainChain() != 0 || origtx.InMempool()) {
1084  return false;
1085  }
1086 
1087  todo.insert(txid);
1088 
1089  while (!todo.empty()) {
1090  const TxId now = *todo.begin();
1091  todo.erase(now);
1092  done.insert(now);
1093  it = mapWallet.find(now);
1094  assert(it != mapWallet.end());
1095  CWalletTx &wtx = it->second;
1096  int currentconfirm = wtx.GetDepthInMainChain();
1097  // If the orig tx was not in block, none of its spends can be.
1098  assert(currentconfirm <= 0);
1099  // If (currentconfirm < 0) {Tx and spends are already conflicted, no
1100  // need to abandon}
1101  if (currentconfirm == 0 && !wtx.isAbandoned()) {
1102  // If the orig tx was not in block/mempool, none of its spends can
1103  // be in mempool.
1104  assert(!wtx.InMempool());
1105  wtx.setAbandoned();
1106  wtx.MarkDirty();
1107  batch.WriteTx(wtx);
1108  NotifyTransactionChanged(this, wtx.GetId(), CT_UPDATED);
1109  // Iterate over all its outputs, and mark transactions in the wallet
1110  // that spend them abandoned too.
1111  TxSpends::const_iterator iter =
1112  mapTxSpends.lower_bound(COutPoint(now, 0));
1113  while (iter != mapTxSpends.end() && iter->first.GetTxId() == now) {
1114  if (!done.count(iter->second)) {
1115  todo.insert(iter->second);
1116  }
1117  iter++;
1118  }
1119 
1120  // If a transaction changes 'conflicted' state, that changes the
1121  // balance available of the outputs it spends. So force those to be
1122  // recomputed.
1123  MarkInputsDirty(wtx.tx);
1124  }
1125  }
1126 
1127  return true;
1128 }
1129 
1130 void CWallet::MarkConflicted(const BlockHash &hashBlock, int conflicting_height,
1131  const TxId &txid) {
1132  LOCK(cs_wallet);
1133 
1134  int conflictconfirms =
1135  (m_last_block_processed_height - conflicting_height + 1) * -1;
1136 
1137  // If number of conflict confirms cannot be determined, this means that the
1138  // block is still unknown or not yet part of the main chain, for example
1139  // when loading the wallet during a reindex. Do nothing in that case.
1140  if (conflictconfirms >= 0) {
1141  return;
1142  }
1143 
1144  // Do not flush the wallet here for performance reasons.
1145  WalletBatch batch(*database, "r+", false);
1146 
1147  std::set<TxId> todo;
1148  std::set<TxId> done;
1149 
1150  todo.insert(txid);
1151 
1152  while (!todo.empty()) {
1153  const TxId now = *todo.begin();
1154  todo.erase(now);
1155  done.insert(now);
1156  auto it = mapWallet.find(now);
1157  assert(it != mapWallet.end());
1158  CWalletTx &wtx = it->second;
1159  int currentconfirm = wtx.GetDepthInMainChain();
1160  if (conflictconfirms < currentconfirm) {
1161  // Block is 'more conflicted' than current confirm; update.
1162  // Mark transaction as conflicted with this block.
1163  wtx.m_confirm.nIndex = 0;
1164  wtx.m_confirm.hashBlock = hashBlock;
1165  wtx.m_confirm.block_height = conflicting_height;
1166  wtx.setConflicted();
1167  wtx.MarkDirty();
1168  batch.WriteTx(wtx);
1169  // Iterate over all its outputs, and mark transactions in the wallet
1170  // that spend them conflicted too.
1171  TxSpends::const_iterator iter =
1172  mapTxSpends.lower_bound(COutPoint(now, 0));
1173  while (iter != mapTxSpends.end() && iter->first.GetTxId() == now) {
1174  if (!done.count(iter->second)) {
1175  todo.insert(iter->second);
1176  }
1177  iter++;
1178  }
1179  // If a transaction changes 'conflicted' state, that changes the
1180  // balance available of the outputs it spends. So force those to be
1181  // recomputed.
1182  MarkInputsDirty(wtx.tx);
1183  }
1184  }
1185 }
1186 
1188  CWalletTx::Confirmation confirm, bool update_tx) {
1189  if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx)) {
1190  // Not one of ours
1191  return;
1192  }
1193 
1194  // If a transaction changes 'conflicted' state, that changes the balance
1195  // available of the outputs it spends. So force those to be
1196  // recomputed, also:
1197  MarkInputsDirty(ptx);
1198 }
1199 
1201  LOCK(cs_wallet);
1202  CWalletTx::Confirmation confirm(CWalletTx::Status::UNCONFIRMED,
1203  /* block_height */ 0, BlockHash(),
1204  /* nIndex */ 0);
1205  SyncTransaction(ptx, confirm);
1206 
1207  auto it = mapWallet.find(ptx->GetId());
1208  if (it != mapWallet.end()) {
1209  it->second.fInMempool = true;
1210  }
1211 }
1212 
1214  LOCK(cs_wallet);
1215  auto it = mapWallet.find(ptx->GetId());
1216  if (it != mapWallet.end()) {
1217  it->second.fInMempool = false;
1218  }
1219 }
1220 
1221 void CWallet::blockConnected(const CBlock &block, int height) {
1222  const BlockHash &block_hash = block.GetHash();
1223  LOCK(cs_wallet);
1224 
1225  m_last_block_processed_height = height;
1226  m_last_block_processed = block_hash;
1227  for (size_t index = 0; index < block.vtx.size(); index++) {
1228  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, height,
1229  block_hash, index);
1230  SyncTransaction(block.vtx[index], confirm);
1231  transactionRemovedFromMempool(block.vtx[index]);
1232  }
1233 }
1234 
1235 void CWallet::blockDisconnected(const CBlock &block, int height) {
1236  LOCK(cs_wallet);
1237 
1238  // At block disconnection, this will change an abandoned transaction to
1239  // be unconfirmed, whether or not the transaction is added back to the
1240  // mempool. User may have to call abandontransaction again. It may be
1241  // addressed in the future with a stickier abandoned state or even removing
1242  // abandontransaction call.
1243  m_last_block_processed_height = height - 1;
1244  m_last_block_processed = block.hashPrevBlock;
1245  for (const CTransactionRef &ptx : block.vtx) {
1246  CWalletTx::Confirmation confirm(CWalletTx::Status::UNCONFIRMED,
1247  /* block_height */ 0, BlockHash(),
1248  /* nIndex */ 0);
1249  SyncTransaction(ptx, confirm);
1250  }
1251 }
1252 
1254  m_best_block_time = GetTime();
1255 }
1256 
1258  AssertLockNotHeld(cs_wallet);
1259  // Skip the queue-draining stuff if we know we're caught up with
1260  // chainActive.Tip(), otherwise put a callback in the validation interface
1261  // queue and wait for the queue to drain enough to execute it (indicating we
1262  // are caught up at least with the time we entered this function).
1263  const BlockHash last_block_hash =
1264  WITH_LOCK(cs_wallet, return m_last_block_processed);
1265  chain().waitForNotificationsIfTipChanged(last_block_hash);
1266 }
1267 
1268 isminetype CWallet::IsMine(const CTxIn &txin) const {
1269  LOCK(cs_wallet);
1270  std::map<TxId, CWalletTx>::const_iterator mi =
1271  mapWallet.find(txin.prevout.GetTxId());
1272  if (mi != mapWallet.end()) {
1273  const CWalletTx &prev = (*mi).second;
1274  if (txin.prevout.GetN() < prev.tx->vout.size()) {
1275  return IsMine(prev.tx->vout[txin.prevout.GetN()]);
1276  }
1277  }
1278 
1279  return ISMINE_NO;
1280 }
1281 
1282 // Note that this function doesn't distinguish between a 0-valued input, and a
1283 // not-"is mine" (according to the filter) input.
1284 Amount CWallet::GetDebit(const CTxIn &txin, const isminefilter &filter) const {
1285  LOCK(cs_wallet);
1286  std::map<TxId, CWalletTx>::const_iterator mi =
1287  mapWallet.find(txin.prevout.GetTxId());
1288  if (mi != mapWallet.end()) {
1289  const CWalletTx &prev = (*mi).second;
1290  if (txin.prevout.GetN() < prev.tx->vout.size()) {
1291  if (IsMine(prev.tx->vout[txin.prevout.GetN()]) & filter) {
1292  return prev.tx->vout[txin.prevout.GetN()].nValue;
1293  }
1294  }
1295  }
1296 
1297  return Amount::zero();
1298 }
1299 
1300 isminetype CWallet::IsMine(const CTxOut &txout) const {
1301  return IsMine(txout.scriptPubKey);
1302 }
1303 
1305  return IsMine(GetScriptForDestination(dest));
1306 }
1307 
1308 isminetype CWallet::IsMine(const CScript &script) const {
1309  isminetype result = ISMINE_NO;
1310  for (const auto &spk_man_pair : m_spk_managers) {
1311  result = std::max(result, spk_man_pair.second->IsMine(script));
1312  }
1313  return result;
1314 }
1315 
1317  const isminefilter &filter) const {
1318  if (!MoneyRange(txout.nValue)) {
1319  throw std::runtime_error(std::string(__func__) +
1320  ": value out of range");
1321  }
1322 
1323  return (IsMine(txout) & filter) ? txout.nValue : Amount::zero();
1324 }
1325 
1326 bool CWallet::IsChange(const CTxOut &txout) const {
1327  return IsChange(txout.scriptPubKey);
1328 }
1329 
1330 bool CWallet::IsChange(const CScript &script) const {
1331  // TODO: fix handling of 'change' outputs. The assumption is that any
1332  // payment to a script that is ours, but is not in the address book is
1333  // change. That assumption is likely to break when we implement
1334  // multisignature wallets that return change back into a
1335  // multi-signature-protected address; a better way of identifying which
1336  // outputs are 'the send' and which are 'the change' will need to be
1337  // implemented (maybe extend CWalletTx to remember which output, if any, was
1338  // change).
1339  if (IsMine(script)) {
1340  CTxDestination address;
1341  if (!ExtractDestination(script, address)) {
1342  return true;
1343  }
1344 
1345  LOCK(cs_wallet);
1346  if (!FindAddressBookEntry(address)) {
1347  return true;
1348  }
1349  }
1350 
1351  return false;
1352 }
1353 
1354 Amount CWallet::GetChange(const CTxOut &txout) const {
1355  if (!MoneyRange(txout.nValue)) {
1356  throw std::runtime_error(std::string(__func__) +
1357  ": value out of range");
1358  }
1359 
1360  return (IsChange(txout) ? txout.nValue : Amount::zero());
1361 }
1362 
1363 bool CWallet::IsMine(const CTransaction &tx) const {
1364  for (const CTxOut &txout : tx.vout) {
1365  if (IsMine(txout)) {
1366  return true;
1367  }
1368  }
1369 
1370  return false;
1371 }
1372 
1373 bool CWallet::IsFromMe(const CTransaction &tx) const {
1374  return GetDebit(tx, ISMINE_ALL) > Amount::zero();
1375 }
1376 
1378  const isminefilter &filter) const {
1379  Amount nDebit = Amount::zero();
1380  for (const CTxIn &txin : tx.vin) {
1381  nDebit += GetDebit(txin, filter);
1382  if (!MoneyRange(nDebit)) {
1383  throw std::runtime_error(std::string(__func__) +
1384  ": value out of range");
1385  }
1386  }
1387 
1388  return nDebit;
1389 }
1390 
1392  const isminefilter &filter) const {
1393  LOCK(cs_wallet);
1394 
1395  for (const CTxIn &txin : tx.vin) {
1396  auto mi = mapWallet.find(txin.prevout.GetTxId());
1397  if (mi == mapWallet.end()) {
1398  // Any unknown inputs can't be from us.
1399  return false;
1400  }
1401 
1402  const CWalletTx &prev = (*mi).second;
1403 
1404  if (txin.prevout.GetN() >= prev.tx->vout.size()) {
1405  // Invalid input!
1406  return false;
1407  }
1408 
1409  if (!(IsMine(prev.tx->vout[txin.prevout.GetN()]) & filter)) {
1410  return false;
1411  }
1412  }
1413 
1414  return true;
1415 }
1416 
1418  const isminefilter &filter) const {
1419  Amount nCredit = Amount::zero();
1420  for (const CTxOut &txout : tx.vout) {
1421  nCredit += GetCredit(txout, filter);
1422  if (!MoneyRange(nCredit)) {
1423  throw std::runtime_error(std::string(__func__) +
1424  ": value out of range");
1425  }
1426  }
1427 
1428  return nCredit;
1429 }
1430 
1432  Amount nChange = Amount::zero();
1433  for (const CTxOut &txout : tx.vout) {
1434  nChange += GetChange(txout);
1435  if (!MoneyRange(nChange)) {
1436  throw std::runtime_error(std::string(__func__) +
1437  ": value out of range");
1438  }
1439  }
1440 
1441  return nChange;
1442 }
1443 
1444 bool CWallet::IsHDEnabled() const {
1445  // All Active ScriptPubKeyMans must be HD for this to be true
1446  bool result = true;
1447  for (const auto &spk_man : GetActiveScriptPubKeyMans()) {
1448  result &= spk_man->IsHDEnabled();
1449  }
1450  return result;
1451 }
1452 
1453 bool CWallet::CanGetAddresses(bool internal) const {
1454  LOCK(cs_wallet);
1455  if (m_spk_managers.empty()) {
1456  return false;
1457  }
1458  for (OutputType t : OUTPUT_TYPES) {
1459  auto spk_man = GetScriptPubKeyMan(t, internal);
1460  if (spk_man && spk_man->CanGetAddresses(internal)) {
1461  return true;
1462  }
1463  }
1464  return false;
1465 }
1466 
1468  LOCK(cs_wallet);
1469  m_wallet_flags |= flags;
1470  if (!WalletBatch(*database).WriteWalletFlags(m_wallet_flags)) {
1471  throw std::runtime_error(std::string(__func__) +
1472  ": writing wallet flags failed");
1473  }
1474 }
1475 
1476 void CWallet::UnsetWalletFlag(uint64_t flag) {
1477  WalletBatch batch(*database);
1478  UnsetWalletFlagWithDB(batch, flag);
1479 }
1480 
1481 void CWallet::UnsetWalletFlagWithDB(WalletBatch &batch, uint64_t flag) {
1482  LOCK(cs_wallet);
1483  m_wallet_flags &= ~flag;
1484  if (!batch.WriteWalletFlags(m_wallet_flags)) {
1485  throw std::runtime_error(std::string(__func__) +
1486  ": writing wallet flags failed");
1487  }
1488 }
1489 
1491  UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET);
1492 }
1493 
1494 bool CWallet::IsWalletFlagSet(uint64_t flag) const {
1495  return (m_wallet_flags & flag);
1496 }
1497 
1498 bool CWallet::SetWalletFlags(uint64_t overwriteFlags, bool memonly) {
1499  LOCK(cs_wallet);
1500  m_wallet_flags = overwriteFlags;
1501  if (((overwriteFlags & KNOWN_WALLET_FLAGS) >> 32) ^
1502  (overwriteFlags >> 32)) {
1503  // contains unknown non-tolerable wallet flags
1504  return false;
1505  }
1506  if (!memonly && !WalletBatch(*database).WriteWalletFlags(m_wallet_flags)) {
1507  throw std::runtime_error(std::string(__func__) +
1508  ": writing wallet flags failed");
1509  }
1510 
1511  return true;
1512 }
1513 
1514 int64_t CWalletTx::GetTxTime() const {
1515  int64_t n = nTimeSmart;
1516  return n ? n : nTimeReceived;
1517 }
1518 
1519 // Helper for producing a max-sized low-S low-R signature (eg 71 bytes)
1520 // or a max-sized low-S signature (e.g. 72 bytes) if use_max_sig is true
1521 bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout,
1522  bool use_max_sig) const {
1523  // Fill in dummy signatures for fee calculation.
1524  const CScript &scriptPubKey = txout.scriptPubKey;
1525  SignatureData sigdata;
1526 
1527  std::unique_ptr<SigningProvider> provider =
1528  GetSolvingProvider(scriptPubKey);
1529  if (!provider) {
1530  // We don't know about this scriptpbuKey;
1531  return false;
1532  }
1533 
1534  if (!ProduceSignature(*provider,
1535  use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR
1537  scriptPubKey, sigdata)) {
1538  return false;
1539  }
1540 
1541  UpdateInput(tx_in, sigdata);
1542  return true;
1543 }
1544 
1545 // Helper for producing a bunch of max-sized low-S low-R signatures (eg 71
1546 // bytes)
1548  const std::vector<CTxOut> &txouts,
1549  bool use_max_sig) const {
1550  // Fill in dummy signatures for fee calculation.
1551  int nIn = 0;
1552  for (const auto &txout : txouts) {
1553  if (!DummySignInput(txNew.vin[nIn], txout, use_max_sig)) {
1554  return false;
1555  }
1556 
1557  nIn++;
1558  }
1559  return true;
1560 }
1561 
1562 bool CWallet::ImportScripts(const std::set<CScript> scripts,
1563  int64_t timestamp) {
1564  auto spk_man = GetLegacyScriptPubKeyMan();
1565  if (!spk_man) {
1566  return false;
1567  }
1568  LOCK(spk_man->cs_KeyStore);
1569  return spk_man->ImportScripts(scripts, timestamp);
1570 }
1571 
1572 bool CWallet::ImportPrivKeys(const std::map<CKeyID, CKey> &privkey_map,
1573  const int64_t timestamp) {
1574  auto spk_man = GetLegacyScriptPubKeyMan();
1575  if (!spk_man) {
1576  return false;
1577  }
1578  LOCK(spk_man->cs_KeyStore);
1579  return spk_man->ImportPrivKeys(privkey_map, timestamp);
1580 }
1581 
1583  const std::vector<CKeyID> &ordered_pubkeys,
1584  const std::map<CKeyID, CPubKey> &pubkey_map,
1585  const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> &key_origins,
1586  const bool add_keypool, const bool internal, const int64_t timestamp) {
1587  auto spk_man = GetLegacyScriptPubKeyMan();
1588  if (!spk_man) {
1589  return false;
1590  }
1591  LOCK(spk_man->cs_KeyStore);
1592  return spk_man->ImportPubKeys(ordered_pubkeys, pubkey_map, key_origins,
1593  add_keypool, internal, timestamp);
1594 }
1595 
1596 bool CWallet::ImportScriptPubKeys(const std::string &label,
1597  const std::set<CScript> &script_pub_keys,
1598  const bool have_solving_data,
1599  const bool apply_label,
1600  const int64_t timestamp) {
1601  auto spk_man = GetLegacyScriptPubKeyMan();
1602  if (!spk_man) {
1603  return false;
1604  }
1605  LOCK(spk_man->cs_KeyStore);
1606  if (!spk_man->ImportScriptPubKeys(script_pub_keys, have_solving_data,
1607  timestamp)) {
1608  return false;
1609  }
1610  if (apply_label) {
1611  WalletBatch batch(*database);
1612  for (const CScript &script : script_pub_keys) {
1613  CTxDestination dest;
1614  ExtractDestination(script, dest);
1615  if (IsValidDestination(dest)) {
1616  SetAddressBookWithDB(batch, dest, label, "receive");
1617  }
1618  }
1619  }
1620  return true;
1621 }
1622 
1624  const CWallet *wallet, bool use_max_sig) {
1625  std::vector<CTxOut> txouts;
1626  for (auto &input : tx.vin) {
1627  const auto mi = wallet->mapWallet.find(input.prevout.GetTxId());
1628  // Can not estimate size without knowing the input details
1629  if (mi == wallet->mapWallet.end()) {
1630  return -1;
1631  }
1632  assert(input.prevout.GetN() < mi->second.tx->vout.size());
1633  txouts.emplace_back(mi->second.tx->vout[input.prevout.GetN()]);
1634  }
1635  return CalculateMaximumSignedTxSize(tx, wallet, txouts, use_max_sig);
1636 }
1637 
1638 // txouts needs to be in the order of tx.vin
1640  const CWallet *wallet,
1641  const std::vector<CTxOut> &txouts,
1642  bool use_max_sig) {
1643  CMutableTransaction txNew(tx);
1644  if (!wallet->DummySignTx(txNew, txouts, use_max_sig)) {
1645  return -1;
1646  }
1647  return GetSerializeSize(txNew, PROTOCOL_VERSION);
1648 }
1649 
1650 int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet,
1651  bool use_max_sig) {
1652  CMutableTransaction txn;
1653  txn.vin.push_back(CTxIn(COutPoint()));
1654  if (!wallet->DummySignInput(txn.vin[0], txout, use_max_sig)) {
1655  return -1;
1656  }
1657  return GetSerializeSize(txn.vin[0], PROTOCOL_VERSION);
1658 }
1659 
1660 void CWalletTx::GetAmounts(std::list<COutputEntry> &listReceived,
1661  std::list<COutputEntry> &listSent, Amount &nFee,
1662  const isminefilter &filter) const {
1663  nFee = Amount::zero();
1664  listReceived.clear();
1665  listSent.clear();
1666 
1667  // Compute fee:
1668  Amount nDebit = GetDebit(filter);
1669  // debit>0 means we signed/sent this transaction.
1670  if (nDebit > Amount::zero()) {
1671  Amount nValueOut = tx->GetValueOut();
1672  nFee = (nDebit - nValueOut);
1673  }
1674 
1675  // Sent/received.
1676  for (unsigned int i = 0; i < tx->vout.size(); ++i) {
1677  const CTxOut &txout = tx->vout[i];
1678  isminetype fIsMine = pwallet->IsMine(txout);
1679  // Only need to handle txouts if AT LEAST one of these is true:
1680  // 1) they debit from us (sent)
1681  // 2) the output is to us (received)
1682  if (nDebit > Amount::zero()) {
1683  // Don't report 'change' txouts
1684  if (pwallet->IsChange(txout)) {
1685  continue;
1686  }
1687  } else if (!(fIsMine & filter)) {
1688  continue;
1689  }
1690 
1691  // In either case, we need to get the destination address.
1692  CTxDestination address;
1693 
1694  if (!ExtractDestination(txout.scriptPubKey, address) &&
1695  !txout.scriptPubKey.IsUnspendable()) {
1696  pwallet->WalletLogPrintf("CWalletTx::GetAmounts: Unknown "
1697  "transaction type found, txid %s\n",
1698  this->GetId().ToString());
1699  address = CNoDestination();
1700  }
1701 
1702  COutputEntry output = {address, txout.nValue, (int)i};
1703 
1704  // If we are debited by the transaction, add the output as a "sent"
1705  // entry.
1706  if (nDebit > Amount::zero()) {
1707  listSent.push_back(output);
1708  }
1709 
1710  // If we are receiving the output, add it as a "received" entry.
1711  if (fIsMine & filter) {
1712  listReceived.push_back(output);
1713  }
1714  }
1715 }
1716 
1725 int64_t CWallet::RescanFromTime(int64_t startTime,
1726  const WalletRescanReserver &reserver,
1727  bool update) {
1728  // Find starting block. May be null if nCreateTime is greater than the
1729  // highest blockchain timestamp, in which case there is nothing that needs
1730  // to be scanned.
1731  int start_height = 0;
1732  BlockHash start_block;
1733  bool start = chain().findFirstBlockWithTimeAndHeight(
1734  startTime - TIMESTAMP_WINDOW, 0,
1735  FoundBlock().hash(start_block).height(start_height));
1736  WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__,
1737  start ? WITH_LOCK(cs_wallet, return GetLastBlockHeight()) -
1738  start_height + 1
1739  : 0);
1740 
1741  if (start) {
1742  // TODO: this should take into account failure by ScanResult::USER_ABORT
1743  ScanResult result = ScanForWalletTransactions(
1744  start_block, start_height, {} /* max_height */, reserver, update);
1745  if (result.status == ScanResult::FAILURE) {
1746  int64_t time_max;
1747  CHECK_NONFATAL(chain().findBlock(result.last_failed_block,
1748  FoundBlock().maxTime(time_max)));
1749  return time_max + TIMESTAMP_WINDOW + 1;
1750  }
1751  }
1752  return startTime;
1753 }
1754 
1777  const BlockHash &start_block, int start_height,
1778  std::optional<int> max_height, const WalletRescanReserver &reserver,
1779  bool fUpdate) {
1780  int64_t nNow = GetTime();
1781  int64_t start_time = GetTimeMillis();
1782 
1783  assert(reserver.isReserved());
1784 
1785  BlockHash block_hash = start_block;
1786  ScanResult result;
1787 
1788  WalletLogPrintf("Rescan started from block %s...\n",
1789  start_block.ToString());
1790 
1791  fAbortRescan = false;
1792  // Show rescan progress in GUI as dialog or on splashscreen, if -rescan on
1793  // startup.
1794  ShowProgress(
1795  strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), 0);
1796  BlockHash tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1797  BlockHash end_hash = tip_hash;
1798  if (max_height) {
1799  chain().findAncestorByHeight(tip_hash, *max_height,
1800  FoundBlock().hash(end_hash));
1801  }
1802  double progress_begin = chain().guessVerificationProgress(block_hash);
1803  double progress_end = chain().guessVerificationProgress(end_hash);
1804  double progress_current = progress_begin;
1805  int block_height = start_height;
1806  while (!fAbortRescan && !chain().shutdownRequested()) {
1807  m_scanning_progress = (progress_current - progress_begin) /
1808  (progress_end - progress_begin);
1809  if (block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
1810  ShowProgress(
1811  strprintf("%s " + _("Rescanning...").translated,
1812  GetDisplayName()),
1813  std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
1814  }
1815  if (GetTime() >= nNow + 60) {
1816  nNow = GetTime();
1817  WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n",
1818  block_height, progress_current);
1819  }
1820 
1821  CBlock block;
1822  bool next_block;
1823  BlockHash next_block_hash;
1824  bool reorg = false;
1825  if (chain().findBlock(block_hash, FoundBlock().data(block)) &&
1826  !block.IsNull()) {
1827  LOCK(cs_wallet);
1828  next_block = chain().findNextBlock(
1829  block_hash, block_height, FoundBlock().hash(next_block_hash),
1830  &reorg);
1831  if (reorg) {
1832  // Abort scan if current block is no longer active, to prevent
1833  // marking transactions as coming from the wrong block.
1834  // TODO: This should return success instead of failure, see
1835  // https://github.com/bitcoin/bitcoin/pull/14711#issuecomment-458342518
1836  result.last_failed_block = block_hash;
1837  result.status = ScanResult::FAILURE;
1838  break;
1839  }
1840  for (size_t posInBlock = 0; posInBlock < block.vtx.size();
1841  ++posInBlock) {
1842  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED,
1843  block_height, block_hash,
1844  posInBlock);
1845  SyncTransaction(block.vtx[posInBlock], confirm, fUpdate);
1846  }
1847  // scan succeeded, record block as most recent successfully
1848  // scanned
1849  result.last_scanned_block = block_hash;
1850  result.last_scanned_height = block_height;
1851  } else {
1852  // could not scan block, keep scanning but record this block as
1853  // the most recent failure
1854  result.last_failed_block = block_hash;
1855  result.status = ScanResult::FAILURE;
1856  next_block = chain().findNextBlock(
1857  block_hash, block_height, FoundBlock().hash(next_block_hash),
1858  &reorg);
1859  }
1860  if (max_height && block_height >= *max_height) {
1861  break;
1862  }
1863  {
1864  if (!next_block || reorg) {
1865  // break successfully when rescan has reached the tip, or
1866  // previous block is no longer on the chain due to a reorg
1867  break;
1868  }
1869 
1870  // increment block and verification progress
1871  block_hash = next_block_hash;
1872  ++block_height;
1873  progress_current = chain().guessVerificationProgress(block_hash);
1874 
1875  // handle updated tip hash
1876  const BlockHash prev_tip_hash = tip_hash;
1877  tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1878  if (!max_height && prev_tip_hash != tip_hash) {
1879  // in case the tip has changed, update progress max
1880  progress_end = chain().guessVerificationProgress(tip_hash);
1881  }
1882  }
1883  }
1884 
1885  // Hide progress dialog in GUI.
1886  ShowProgress(
1887  strprintf("%s " + _("Rescanning...").translated, GetDisplayName()),
1888  100);
1889  if (block_height && fAbortRescan) {
1890  WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n",
1891  block_height, progress_current);
1892  result.status = ScanResult::USER_ABORT;
1893  } else if (block_height && chain().shutdownRequested()) {
1894  WalletLogPrintf(
1895  "Rescan interrupted by shutdown request at block %d. Progress=%f\n",
1896  block_height, progress_current);
1897  result.status = ScanResult::USER_ABORT;
1898  } else {
1899  WalletLogPrintf("Rescan completed in %15dms\n",
1900  GetTimeMillis() - start_time);
1901  }
1902  return result;
1903 }
1904 
1906  // If transactions aren't being broadcasted, don't let them into local
1907  // mempool either.
1908  if (!fBroadcastTransactions) {
1909  return;
1910  }
1911 
1912  std::map<int64_t, CWalletTx *> mapSorted;
1913 
1914  // Sort pending wallet transactions based on their initial wallet insertion
1915  // order.
1916  for (std::pair<const TxId, CWalletTx> &item : mapWallet) {
1917  const TxId &wtxid = item.first;
1918  CWalletTx &wtx = item.second;
1919  assert(wtx.GetId() == wtxid);
1920 
1921  int nDepth = wtx.GetDepthInMainChain();
1922 
1923  if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1924  mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1925  }
1926  }
1927 
1928  // Try to add wallet transactions to memory pool.
1929  for (const std::pair<const int64_t, CWalletTx *> &item : mapSorted) {
1930  CWalletTx &wtx = *(item.second);
1931  std::string unused_err_string;
1932  wtx.SubmitMemoryPoolAndRelay(unused_err_string, false);
1933  }
1934 }
1935 
1936 bool CWalletTx::SubmitMemoryPoolAndRelay(std::string &err_string, bool relay) {
1937  // Can't relay if wallet is not broadcasting
1938  if (!pwallet->GetBroadcastTransactions()) {
1939  return false;
1940  }
1941  // Don't relay abandoned transactions
1942  if (isAbandoned()) {
1943  return false;
1944  }
1945  // Don't try to submit coinbase transactions. These would fail anyway but
1946  // would cause log spam.
1947  if (IsCoinBase()) {
1948  return false;
1949  }
1950  // Don't try to submit conflicted or confirmed transactions.
1951  if (GetDepthInMainChain() != 0) {
1952  return false;
1953  }
1954 
1955  // Submit transaction to mempool for relay
1956  pwallet->WalletLogPrintf("Submitting wtx %s to mempool for relay\n",
1957  GetId().ToString());
1958  // We must set fInMempool here - while it will be re-set to true by the
1959  // entered-mempool callback, if we did not there would be a race where a
1960  // user could call sendmoney in a loop and hit spurious out of funds errors
1961  // because we think that this newly generated transaction's change is
1962  // unavailable as we're not yet aware that it is in the mempool.
1963  //
1964  // Irrespective of the failure reason, un-marking fInMempool
1965  // out-of-order is incorrect - it should be unmarked when
1966  // TransactionRemovedFromMempool fires.
1967  bool ret = pwallet->chain().broadcastTransaction(
1968  GetConfig(), tx, pwallet->m_default_max_tx_fee, relay, err_string);
1969  fInMempool |= ret;
1970  return ret;
1971 }
1972 
1973 std::set<TxId> CWalletTx::GetConflicts() const {
1974  std::set<TxId> result;
1975  if (pwallet != nullptr) {
1976  const TxId &txid = GetId();
1977  result = pwallet->GetConflicts(txid);
1978  result.erase(txid);
1979  }
1980 
1981  return result;
1982 }
1983 
1985  bool recalculate) const {
1986  auto &amount = m_amounts[type];
1987  if (recalculate || !amount.m_cached[filter]) {
1988  amount.Set(filter, type == DEBIT ? pwallet->GetDebit(*tx, filter)
1989  : pwallet->GetCredit(*tx, filter));
1990  m_is_cache_empty = false;
1991  }
1992  return amount.m_value[filter];
1993 }
1994 
1996  if (tx->vin.empty()) {
1997  return Amount::zero();
1998  }
1999 
2000  Amount debit = Amount::zero();
2001  if (filter & ISMINE_SPENDABLE) {
2002  debit += GetCachableAmount(DEBIT, ISMINE_SPENDABLE);
2003  }
2004  if (filter & ISMINE_WATCH_ONLY) {
2005  debit += GetCachableAmount(DEBIT, ISMINE_WATCH_ONLY);
2006  }
2007 
2008  return debit;
2009 }
2010 
2012  // Must wait until coinbase is safely deep enough in the chain before
2013  // valuing it.
2014  if (IsImmatureCoinBase()) {
2015  return Amount::zero();
2016  }
2017 
2018  Amount credit = Amount::zero();
2019  if (filter & ISMINE_SPENDABLE) {
2020  // GetBalance can assume transactions in mapWallet won't change.
2021  credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE);
2022  }
2023 
2024  if (filter & ISMINE_WATCH_ONLY) {
2025  credit += GetCachableAmount(CREDIT, ISMINE_WATCH_ONLY);
2026  }
2027 
2028  return credit;
2029 }
2030 
2031 Amount CWalletTx::GetImmatureCredit(bool fUseCache) const {
2032  if (IsImmatureCoinBase() && IsInMainChain()) {
2033  return GetCachableAmount(IMMATURE_CREDIT, ISMINE_SPENDABLE, !fUseCache);
2034  }
2035 
2036  return Amount::zero();
2037 }
2038 
2040  const isminefilter &filter) const {
2041  if (pwallet == nullptr) {
2042  return Amount::zero();
2043  }
2044 
2045  // Avoid caching ismine for NO or ALL cases (could remove this check and
2046  // simplify in the future).
2047  bool allow_cache =
2048  (filter & ISMINE_ALL) && (filter & ISMINE_ALL) != ISMINE_ALL;
2049 
2050  // Must wait until coinbase is safely deep enough in the chain before
2051  // valuing it.
2052  if (IsImmatureCoinBase()) {
2053  return Amount::zero();
2054  }
2055 
2056  if (fUseCache && allow_cache &&
2057  m_amounts[AVAILABLE_CREDIT].m_cached[filter]) {
2058  return m_amounts[AVAILABLE_CREDIT].m_value[filter];
2059  }
2060 
2061  bool allow_used_addresses =
2062  (filter & ISMINE_USED) ||
2063  !pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE);
2064  Amount nCredit = Amount::zero();
2065  const TxId &txid = GetId();
2066  for (uint32_t i = 0; i < tx->vout.size(); i++) {
2067  if (!pwallet->IsSpent(COutPoint(txid, i)) &&
2068  (allow_used_addresses || !pwallet->IsSpentKey(txid, i))) {
2069  const CTxOut &txout = tx->vout[i];
2070  nCredit += pwallet->GetCredit(txout, filter);
2071  if (!MoneyRange(nCredit)) {
2072  throw std::runtime_error(std::string(__func__) +
2073  " : value out of range");
2074  }
2075  }
2076  }
2077 
2078  if (allow_cache) {
2079  m_amounts[AVAILABLE_CREDIT].Set(filter, nCredit);
2080  m_is_cache_empty = false;
2081  }
2082 
2083  return nCredit;
2084 }
2085 
2086 Amount CWalletTx::GetImmatureWatchOnlyCredit(const bool fUseCache) const {
2087  if (IsImmatureCoinBase() && IsInMainChain()) {
2088  return GetCachableAmount(IMMATURE_CREDIT, ISMINE_WATCH_ONLY,
2089  !fUseCache);
2090  }
2091 
2092  return Amount::zero();
2093 }
2094 
2096  if (fChangeCached) {
2097  return nChangeCached;
2098  }
2099 
2100  nChangeCached = pwallet->GetChange(*tx);
2101  fChangeCached = true;
2102  return nChangeCached;
2103 }
2104 
2105 bool CWalletTx::InMempool() const {
2106  return fInMempool;
2107 }
2108 
2109 bool CWalletTx::IsTrusted() const {
2110  std::set<TxId> s;
2111  return IsTrusted(s);
2112 }
2113 
2114 bool CWalletTx::IsTrusted(std::set<TxId> &trusted_parents) const {
2115  // Quick answer in most cases
2116  TxValidationState state;
2117  if (!pwallet->chain().contextualCheckTransactionForCurrentBlock(*tx,
2118  state)) {
2119  return false;
2120  }
2121 
2122  int nDepth = GetDepthInMainChain();
2123  if (nDepth >= 1) {
2124  return true;
2125  }
2126 
2127  if (nDepth < 0) {
2128  return false;
2129  }
2130 
2131  // using wtx's cached debit
2132  if (!pwallet->m_spend_zero_conf_change || !IsFromMe(ISMINE_ALL)) {
2133  return false;
2134  }
2135 
2136  // Don't trust unconfirmed transactions from us unless they are in the
2137  // mempool.
2138  if (!InMempool()) {
2139  return false;
2140  }
2141 
2142  // Trusted if all inputs are from us and are in the mempool:
2143  for (const CTxIn &txin : tx->vin) {
2144  // Transactions not sent by us: not trusted
2145  const CWalletTx *parent = pwallet->GetWalletTx(txin.prevout.GetTxId());
2146  if (parent == nullptr) {
2147  return false;
2148  }
2149 
2150  const CTxOut &parentOut = parent->tx->vout[txin.prevout.GetN()];
2151  // Check that this specific input being spent is trusted
2152  if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE) {
2153  return false;
2154  }
2155  // If we've already trusted this parent, continue
2156  if (trusted_parents.count(parent->GetId())) {
2157  continue;
2158  }
2159  // Recurse to check that the parent is also trusted
2160  if (!parent->IsTrusted(trusted_parents)) {
2161  return false;
2162  }
2163  trusted_parents.insert(parent->GetId());
2164  }
2165 
2166  return true;
2167 }
2168 
2169 bool CWalletTx::IsEquivalentTo(const CWalletTx &_tx) const {
2170  CMutableTransaction tx1{*this->tx};
2171  CMutableTransaction tx2{*_tx.tx};
2172  for (auto &txin : tx1.vin) {
2173  txin.scriptSig = CScript();
2174  }
2175 
2176  for (auto &txin : tx2.vin) {
2177  txin.scriptSig = CScript();
2178  }
2179 
2180  return CTransaction(tx1) == CTransaction(tx2);
2181 }
2182 
2183 // Rebroadcast transactions from the wallet. We do this on a random timer
2184 // to slightly obfuscate which transactions come from our wallet.
2185 //
2186 // Ideally, we'd only resend transactions that we think should have been
2187 // mined in the most recent block. Any transaction that wasn't in the top
2188 // blockweight of transactions in the mempool shouldn't have been mined,
2189 // and so is probably just sitting in the mempool waiting to be confirmed.
2190 // Rebroadcasting does nothing to speed up confirmation and only damages
2191 // privacy.
2193  // During reindex, importing and IBD, old wallet transactions become
2194  // unconfirmed. Don't resend them as that would spam other nodes.
2195  if (!chain().isReadyToBroadcast()) {
2196  return;
2197  }
2198 
2199  // Do this infrequently and randomly to avoid giving away that these are our
2200  // transactions.
2201  if (GetTime() < nNextResend || !fBroadcastTransactions) {
2202  return;
2203  }
2204 
2205  bool fFirst = (nNextResend == 0);
2206  nNextResend = GetTime() + GetRand(30 * 60);
2207  if (fFirst) {
2208  return;
2209  }
2210 
2211  // Only do it if there's been a new block since last time
2212  if (m_best_block_time < nLastResend) {
2213  return;
2214  }
2215 
2216  nLastResend = GetTime();
2217 
2218  int submitted_tx_count = 0;
2219 
2220  { // cs_wallet scope
2221  LOCK(cs_wallet);
2222 
2223  // Relay transactions
2224  for (std::pair<const TxId, CWalletTx> &item : mapWallet) {
2225  CWalletTx &wtx = item.second;
2226  // Attempt to rebroadcast all txes more than 5 minutes older than
2227  // the last block. SubmitMemoryPoolAndRelay() will not rebroadcast
2228  // any confirmed or conflicting txs.
2229  if (wtx.nTimeReceived > m_best_block_time - 5 * 60) {
2230  continue;
2231  }
2232  std::string unused_err_string;
2233  if (wtx.SubmitMemoryPoolAndRelay(unused_err_string, true)) {
2234  ++submitted_tx_count;
2235  }
2236  }
2237  } // cs_wallet
2238 
2239  if (submitted_tx_count > 0) {
2240  WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__,
2241  submitted_tx_count);
2242  }
2243 }
2244  // end of mapWallet
2246 
2248  for (const std::shared_ptr<CWallet> &pwallet : GetWallets()) {
2249  pwallet->ResendWalletTransactions();
2250  }
2251 }
2252 
2259  bool avoid_reuse) const {
2260  Balance ret;
2261  isminefilter reuse_filter = avoid_reuse ? ISMINE_NO : ISMINE_USED;
2262  LOCK(cs_wallet);
2263  std::set<TxId> trusted_parents;
2264  for (const auto &entry : mapWallet) {
2265  const CWalletTx &wtx = entry.second;
2266  const bool is_trusted{wtx.IsTrusted(trusted_parents)};
2267  const int tx_depth{wtx.GetDepthInMainChain()};
2268  const Amount tx_credit_mine{wtx.GetAvailableCredit(
2269  /* fUseCache */ true, ISMINE_SPENDABLE | reuse_filter)};
2270  const Amount tx_credit_watchonly{wtx.GetAvailableCredit(
2271  /* fUseCache */ true, ISMINE_WATCH_ONLY | reuse_filter)};
2272  if (is_trusted && tx_depth >= min_depth) {
2273  ret.m_mine_trusted += tx_credit_mine;
2274  ret.m_watchonly_trusted += tx_credit_watchonly;
2275  }
2276  if (!is_trusted && tx_depth == 0 && wtx.InMempool()) {
2277  ret.m_mine_untrusted_pending += tx_credit_mine;
2278  ret.m_watchonly_untrusted_pending += tx_credit_watchonly;
2279  }
2280  ret.m_mine_immature += wtx.GetImmatureCredit();
2282  }
2283  return ret;
2284 }
2285 
2287  LOCK(cs_wallet);
2288 
2290  std::vector<COutput> vCoins;
2291  AvailableCoins(vCoins, true, coinControl);
2292  for (const COutput &out : vCoins) {
2293  if (out.fSpendable) {
2294  balance += out.tx->tx->vout[out.i].nValue;
2295  }
2296  }
2297  return balance;
2298 }
2299 
2300 void CWallet::AvailableCoins(std::vector<COutput> &vCoins, bool fOnlySafe,
2301  const CCoinControl *coinControl,
2302  const Amount nMinimumAmount,
2303  const Amount nMaximumAmount,
2304  const Amount nMinimumSumAmount,
2305  const uint64_t nMaximumCount) const {
2306  AssertLockHeld(cs_wallet);
2307 
2308  vCoins.clear();
2309  Amount nTotal = Amount::zero();
2310  // Either the WALLET_FLAG_AVOID_REUSE flag is not set (in which case we
2311  // always allow), or we default to avoiding, and only in the case where a
2312  // coin control object is provided, and has the avoid address reuse flag set
2313  // to false, do we allow already used addresses
2314  bool allow_used_addresses =
2315  !IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) ||
2316  (coinControl && !coinControl->m_avoid_address_reuse);
2317  const int min_depth = {coinControl ? coinControl->m_min_depth
2318  : DEFAULT_MIN_DEPTH};
2319  const int max_depth = {coinControl ? coinControl->m_max_depth
2320  : DEFAULT_MAX_DEPTH};
2321 
2322  std::set<TxId> trusted_parents;
2323  for (const auto &entry : mapWallet) {
2324  const TxId &wtxid = entry.first;
2325  const CWalletTx &wtx = entry.second;
2326 
2327  TxValidationState state;
2328  if (!chain().contextualCheckTransactionForCurrentBlock(*wtx.tx,
2329  state)) {
2330  continue;
2331  }
2332 
2333  if (wtx.IsImmatureCoinBase()) {
2334  continue;
2335  }
2336 
2337  int nDepth = wtx.GetDepthInMainChain();
2338  if (nDepth < 0) {
2339  continue;
2340  }
2341 
2342  // We should not consider coins which aren't at least in our mempool.
2343  // It's possible for these to be conflicted via ancestors which we may
2344  // never be able to detect.
2345  if (nDepth == 0 && !wtx.InMempool()) {
2346  continue;
2347  }
2348 
2349  bool safeTx = wtx.IsTrusted(trusted_parents);
2350 
2351  // Bitcoin-ABC: Removed check that prevents consideration of coins from
2352  // transactions that are replacing other transactions. This check based
2353  // on wtx.mapValue.count("replaces_txid") which was not being set
2354  // anywhere.
2355 
2356  // Similarly, we should not consider coins from transactions that have
2357  // been replaced. In the example above, we would want to prevent
2358  // creation of a transaction A' spending an output of A, because if
2359  // transaction B were initially confirmed, conflicting with A and A', we
2360  // wouldn't want to the user to create a transaction D intending to
2361  // replace A', but potentially resulting in a scenario where A, A', and
2362  // D could all be accepted (instead of just B and D, or just A and A'
2363  // like the user would want).
2364 
2365  // Bitcoin-ABC: retained this check as 'replaced_by_txid' is still set
2366  // in the wallet code.
2367  if (nDepth == 0 && wtx.mapValue.count("replaced_by_txid")) {
2368  safeTx = false;
2369  }
2370 
2371  if (fOnlySafe && !safeTx) {
2372  continue;
2373  }
2374 
2375  if (nDepth < min_depth || nDepth > max_depth) {
2376  continue;
2377  }
2378 
2379  for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) {
2380  // Only consider selected coins if add_inputs is false
2381  if (coinControl && !coinControl->m_add_inputs &&
2382  !coinControl->IsSelected(COutPoint(entry.first, i))) {
2383  continue;
2384  }
2385 
2386  if (wtx.tx->vout[i].nValue < nMinimumAmount ||
2387  wtx.tx->vout[i].nValue > nMaximumAmount) {
2388  continue;
2389  }
2390 
2391  const COutPoint outpoint(wtxid, i);
2392 
2393  if (coinControl && coinControl->HasSelected() &&
2394  !coinControl->fAllowOtherInputs &&
2395  !coinControl->IsSelected(outpoint)) {
2396  continue;
2397  }
2398 
2399  if (IsLockedCoin(outpoint)) {
2400  continue;
2401  }
2402 
2403  if (IsSpent(outpoint)) {
2404  continue;
2405  }
2406 
2407  isminetype mine = IsMine(wtx.tx->vout[i]);
2408 
2409  if (mine == ISMINE_NO) {
2410  continue;
2411  }
2412 
2413  if (!allow_used_addresses && IsSpentKey(wtxid, i)) {
2414  continue;
2415  }
2416 
2417  std::unique_ptr<SigningProvider> provider =
2418  GetSolvingProvider(wtx.tx->vout[i].scriptPubKey);
2419 
2420  bool solvable =
2421  provider ? IsSolvable(*provider, wtx.tx->vout[i].scriptPubKey)
2422  : false;
2423  bool spendable =
2424  ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
2425  (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) &&
2426  (coinControl && coinControl->fAllowWatchOnly && solvable));
2427 
2428  vCoins.push_back(
2429  COutput(&wtx, i, nDepth, spendable, solvable, safeTx,
2430  (coinControl && coinControl->fAllowWatchOnly)));
2431 
2432  // Checks the sum amount of all UTXO's.
2433  if (nMinimumSumAmount != MAX_MONEY) {
2434  nTotal += wtx.tx->vout[i].nValue;
2435 
2436  if (nTotal >= nMinimumSumAmount) {
2437  return;
2438  }
2439  }
2440 
2441  // Checks the maximum number of UTXO's.
2442  if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2443  return;
2444  }
2445  }
2446  }
2447 }
2448 
2449 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const {
2450  AssertLockHeld(cs_wallet);
2451 
2452  std::map<CTxDestination, std::vector<COutput>> result;
2453  std::vector<COutput> availableCoins;
2454 
2455  AvailableCoins(availableCoins);
2456 
2457  for (const auto &coin : availableCoins) {
2458  CTxDestination address;
2459  if ((coin.fSpendable ||
2460  (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
2461  coin.fSolvable)) &&
2463  FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey,
2464  address)) {
2465  result[address].emplace_back(std::move(coin));
2466  }
2467  }
2468 
2469  std::vector<COutPoint> lockedCoins;
2470  ListLockedCoins(lockedCoins);
2471  // Include watch-only for LegacyScriptPubKeyMan wallets without private keys
2472  const bool include_watch_only =
2473  GetLegacyScriptPubKeyMan() &&
2474  IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
2475  const isminetype is_mine_filter =
2476  include_watch_only ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
2477  for (const auto &output : lockedCoins) {
2478  auto it = mapWallet.find(output.GetTxId());
2479  if (it != mapWallet.end()) {
2480  int depth = it->second.GetDepthInMainChain();
2481  if (depth >= 0 && output.GetN() < it->second.tx->vout.size() &&
2482  IsMine(it->second.tx->vout[output.GetN()]) == is_mine_filter) {
2483  CTxDestination address;
2484  if (ExtractDestination(
2485  FindNonChangeParentOutput(*it->second.tx, output.GetN())
2486  .scriptPubKey,
2487  address)) {
2488  result[address].emplace_back(
2489  &it->second, output.GetN(), depth, true /* spendable */,
2490  true /* solvable */, false /* safe */);
2491  }
2492  }
2493  }
2494  }
2495 
2496  return result;
2497 }
2498 
2500  int output) const {
2501  const CTransaction *ptx = &tx;
2502  int n = output;
2503  while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2504  const COutPoint &prevout = ptx->vin[0].prevout;
2505  auto it = mapWallet.find(prevout.GetTxId());
2506  if (it == mapWallet.end() ||
2507  it->second.tx->vout.size() <= prevout.GetN() ||
2508  !IsMine(it->second.tx->vout[prevout.GetN()])) {
2509  break;
2510  }
2511  ptx = it->second.tx.get();
2512  n = prevout.GetN();
2513  }
2514  return ptx->vout[n];
2515 }
2516 
2518  const Amount nTargetValue, const CoinEligibilityFilter &eligibility_filter,
2519  std::vector<OutputGroup> groups, std::set<CInputCoin> &setCoinsRet,
2521  bool &bnb_used) const {
2522  setCoinsRet.clear();
2523  nValueRet = Amount::zero();
2524 
2525  std::vector<OutputGroup> utxo_pool;
2526  if (coin_selection_params.use_bnb) {
2527  // Get long term estimate
2528  CCoinControl temp;
2529  temp.m_confirm_target = 1008;
2530  CFeeRate long_term_feerate = GetMinimumFeeRate(*this, temp);
2531 
2532  // Calculate cost of change
2533  Amount cost_of_change = chain().relayDustFee().GetFee(
2534  coin_selection_params.change_spend_size) +
2535  coin_selection_params.effective_fee.GetFee(
2536  coin_selection_params.change_output_size);
2537 
2538  // Filter by the min conf specs and add to utxo_pool and calculate
2539  // effective value
2540  for (OutputGroup &group : groups) {
2541  if (!group.EligibleForSpending(eligibility_filter)) {
2542  continue;
2543  }
2544 
2545  group.fee = Amount::zero();
2546  group.long_term_fee = Amount::zero();
2547  group.effective_value = Amount::zero();
2548  for (auto it = group.m_outputs.begin();
2549  it != group.m_outputs.end();) {
2550  const CInputCoin &coin = *it;
2551  Amount effective_value =
2552  coin.txout.nValue -
2553  (coin.m_input_bytes < 0
2554  ? Amount::zero()
2555  : coin_selection_params.effective_fee.GetFee(
2556  coin.m_input_bytes));
2557  // Only include outputs that are positive effective value (i.e.
2558  // not dust)
2559  if (effective_value > Amount::zero()) {
2560  group.fee +=
2561  coin.m_input_bytes < 0
2562  ? Amount::zero()
2563  : coin_selection_params.effective_fee.GetFee(
2564  coin.m_input_bytes);
2565  group.long_term_fee +=
2566  coin.m_input_bytes < 0
2567  ? Amount::zero()
2568  : long_term_feerate.GetFee(coin.m_input_bytes);
2569  if (coin_selection_params.m_subtract_fee_outputs) {
2570  group.effective_value += coin.txout.nValue;
2571  } else {
2572  group.effective_value += effective_value;
2573  }
2574  ++it;
2575  } else {
2576  it = group.Discard(coin);
2577  }
2578  }
2579  if (group.effective_value > Amount::zero()) {
2580  utxo_pool.push_back(group);
2581  }
2582  }
2583  // Calculate the fees for things that aren't inputs
2584  Amount not_input_fees = coin_selection_params.effective_fee.GetFee(
2585  coin_selection_params.tx_noinputs_size);
2586  bnb_used = true;
2587  return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change,
2588  setCoinsRet, nValueRet, not_input_fees);
2589  } else {
2590  // Filter by the min conf specs and add to utxo_pool
2591  for (const OutputGroup &group : groups) {
2592  if (!group.EligibleForSpending(eligibility_filter)) {
2593  continue;
2594  }
2595  utxo_pool.push_back(group);
2596  }
2597  bnb_used = false;
2598  return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
2599  }
2600 }
2601 
2602 bool CWallet::SelectCoins(const std::vector<COutput> &vAvailableCoins,
2603  const Amount nTargetValue,
2604  std::set<CInputCoin> &setCoinsRet, Amount &nValueRet,
2605  const CCoinControl &coin_control,
2607  bool &bnb_used) const {
2608  std::vector<COutput> vCoins(vAvailableCoins);
2609  Amount value_to_select = nTargetValue;
2610 
2611  // Default to bnb was not used. If we use it, we set it later
2612  bnb_used = false;
2613 
2614  // coin control -> return all selected outputs (we want all selected to go
2615  // into the transaction for sure)
2616  if (coin_control.HasSelected() && !coin_control.fAllowOtherInputs) {
2617  for (const COutput &out : vCoins) {
2618  if (!out.fSpendable) {
2619  continue;
2620  }
2621 
2622  nValueRet += out.tx->tx->vout[out.i].nValue;
2623  setCoinsRet.insert(out.GetInputCoin());
2624  }
2625 
2626  return (nValueRet >= nTargetValue);
2627  }
2628 
2629  // Calculate value from preset inputs and store them.
2630  std::set<CInputCoin> setPresetCoins;
2631  Amount nValueFromPresetInputs = Amount::zero();
2632 
2633  std::vector<COutPoint> vPresetInputs;
2634  coin_control.ListSelected(vPresetInputs);
2635 
2636  for (const COutPoint &outpoint : vPresetInputs) {
2637  std::map<TxId, CWalletTx>::const_iterator it =
2638  mapWallet.find(outpoint.GetTxId());
2639  if (it != mapWallet.end()) {
2640  const CWalletTx &wtx = it->second;
2641  // Clearly invalid input, fail
2642  if (wtx.tx->vout.size() <= outpoint.GetN()) {
2643  return false;
2644  }
2645  // Just to calculate the marginal byte size
2646  CInputCoin coin(wtx.tx, outpoint.GetN(),
2647  wtx.GetSpendSize(outpoint.GetN(), false));
2648  nValueFromPresetInputs += coin.txout.nValue;
2649  if (coin.m_input_bytes <= 0) {
2650  // Not solvable, can't estimate size for fee
2651  return false;
2652  }
2653  coin.effective_value =
2654  coin.txout.nValue -
2655  coin_selection_params.effective_fee.GetFee(coin.m_input_bytes);
2656  if (coin_selection_params.use_bnb) {
2657  value_to_select -= coin.effective_value;
2658  } else {
2659  value_to_select -= coin.txout.nValue;
2660  }
2661  setPresetCoins.insert(coin);
2662  } else {
2663  return false; // TODO: Allow non-wallet inputs
2664  }
2665  }
2666 
2667  // Remove preset inputs from vCoins
2668  for (std::vector<COutput>::iterator it = vCoins.begin();
2669  it != vCoins.end() && coin_control.HasSelected();) {
2670  if (setPresetCoins.count(it->GetInputCoin())) {
2671  it = vCoins.erase(it);
2672  } else {
2673  ++it;
2674  }
2675  }
2676 
2677  size_t max_ancestors{0};
2678  size_t max_descendants{0};
2679  chain().getPackageLimits(max_ancestors, max_descendants);
2680  bool fRejectLongChains = gArgs.GetBoolArg(
2681  "-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2682 
2683  // form groups from remaining coins; note that preset coins will not
2684  // automatically have their associated (same address) coins included
2685  if (coin_control.m_avoid_partial_spends &&
2686  vCoins.size() > OUTPUT_GROUP_MAX_ENTRIES) {
2687  // Cases where we have 11+ outputs all pointing to the same destination
2688  // may result in privacy leaks as they will potentially be
2689  // deterministically sorted. We solve that by explicitly shuffling the
2690  // outputs before processing
2691  Shuffle(vCoins.begin(), vCoins.end(), FastRandomContext());
2692  }
2693 
2694  std::vector<OutputGroup> groups = GroupOutputs(
2695  vCoins, !coin_control.m_avoid_partial_spends, max_ancestors);
2696 
2697  bool res =
2698  value_to_select <= Amount::zero() ||
2699  SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 6, 0),
2700  groups, setCoinsRet, nValueRet,
2701  coin_selection_params, bnb_used) ||
2702  SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 1, 0),
2703  groups, setCoinsRet, nValueRet,
2704  coin_selection_params, bnb_used) ||
2705  (m_spend_zero_conf_change &&
2706  SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, 2),
2707  groups, setCoinsRet, nValueRet,
2708  coin_selection_params, bnb_used)) ||
2709  (m_spend_zero_conf_change &&
2710  SelectCoinsMinConf(
2711  value_to_select,
2712  CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors / 3),
2713  std::min((size_t)4, max_descendants / 3)),
2714  groups, setCoinsRet, nValueRet, coin_selection_params,
2715  bnb_used)) ||
2716  (m_spend_zero_conf_change &&
2717  SelectCoinsMinConf(value_to_select,
2718  CoinEligibilityFilter(0, 1, max_ancestors / 2,
2719  max_descendants / 2),
2720  groups, setCoinsRet, nValueRet,
2721  coin_selection_params, bnb_used)) ||
2722  (m_spend_zero_conf_change &&
2723  SelectCoinsMinConf(value_to_select,
2724  CoinEligibilityFilter(0, 1, max_ancestors - 1,
2725  max_descendants - 1),
2726  groups, setCoinsRet, nValueRet,
2727  coin_selection_params, bnb_used)) ||
2728  (m_spend_zero_conf_change && !fRejectLongChains &&
2729  SelectCoinsMinConf(
2730  value_to_select,
2731  CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max()),
2732  groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
2733 
2734  // Because SelectCoinsMinConf clears the setCoinsRet, we now add the
2735  // possible inputs to the coinset.
2736  util::insert(setCoinsRet, setPresetCoins);
2737 
2738  // Add preset inputs to the total value selected.
2739  nValueRet += nValueFromPresetInputs;
2740 
2741  return res;
2742 }
2743 
2745  AssertLockHeld(cs_wallet);
2746 
2747  // Build coins map
2748  std::map<COutPoint, Coin> coins;
2749  for (auto &input : tx.vin) {
2750  auto mi = mapWallet.find(input.prevout.GetTxId());
2751  if (mi == mapWallet.end() ||
2752  input.prevout.GetN() >= mi->second.tx->vout.size()) {
2753  return false;
2754  }
2755  const CWalletTx &wtx = mi->second;
2756  coins[input.prevout] =
2757  Coin(wtx.tx->vout[input.prevout.GetN()], wtx.m_confirm.block_height,
2758  wtx.IsCoinBase());
2759  }
2760  std::map<int, std::string> input_errors;
2761  return SignTransaction(tx, coins, SigHashType().withForkId(), input_errors);
2762 }
2763 
2765  const std::map<COutPoint, Coin> &coins,
2766  SigHashType sighash,
2767  std::map<int, std::string> &input_errors) const {
2768  // Try to sign with all ScriptPubKeyMans
2769  for (ScriptPubKeyMan *spk_man : GetAllScriptPubKeyMans()) {
2770  // spk_man->SignTransaction will return true if the transaction is
2771  // complete, so we can exit early and return true if that happens
2772  if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2773  return true;
2774  }
2775  }
2776 
2777  // At this point, one input was not fully signed otherwise we would have
2778  // exited already Find that input and figure out what went wrong.
2779  for (size_t i = 0; i < tx.vin.size(); i++) {
2780  // Get the prevout
2781  CTxIn &txin = tx.vin[i];
2782  auto coin = coins.find(txin.prevout);
2783  if (coin == coins.end() || coin->second.IsSpent()) {
2784  input_errors[i] = "Input not found or already spent";
2785  continue;
2786  }
2787 
2788  // Check if this input is complete
2789  SignatureData sigdata =
2790  DataFromTransaction(tx, i, coin->second.GetTxOut());
2791  if (!sigdata.complete) {
2792  input_errors[i] = "Unable to sign input, missing keys";
2793  continue;
2794  }
2795  }
2796 
2797  // When there are no available providers for the remaining inputs, use the
2798  // legacy provider so we can get proper error messages.
2799  auto legacy_spk_man = GetLegacyScriptPubKeyMan();
2800  if (legacy_spk_man &&
2801  legacy_spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2802  return true;
2803  }
2804 
2805  return false;
2806 }
2807 
2809  bool &complete, SigHashType sighash_type,
2810  bool sign, bool bip32derivs) const {
2811  LOCK(cs_wallet);
2812  // Get all of the previous transactions
2813  for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
2814  const CTxIn &txin = psbtx.tx->vin[i];
2815  PSBTInput &input = psbtx.inputs.at(i);
2816 
2817  if (PSBTInputSigned(input)) {
2818  continue;
2819  }
2820 
2821  // Verify input looks sane.
2822  if (!input.IsSane()) {
2824  }
2825 
2826  // If we have no utxo, grab it from the wallet.
2827  if (input.utxo.IsNull()) {
2828  const TxId &txid = txin.prevout.GetTxId();
2829  const auto it = mapWallet.find(txid);
2830  if (it != mapWallet.end()) {
2831  const CWalletTx &wtx = it->second;
2832  CTxOut utxo = wtx.tx->vout[txin.prevout.GetN()];
2833  // Update UTXOs from the wallet.
2834  input.utxo = utxo;
2835  }
2836  }
2837  }
2838 
2839  // Fill in information from ScriptPubKeyMans
2840  for (ScriptPubKeyMan *spk_man : GetAllScriptPubKeyMans()) {
2841  TransactionError res =
2842  spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs);
2843  if (res != TransactionError::OK) {
2844  return res;
2845  }
2846  }
2847 
2848  // Complete if every input is now signed
2849  complete = true;
2850  for (const auto &input : psbtx.inputs) {
2851  complete &= PSBTInputSigned(input);
2852  }
2853 
2854  return TransactionError::OK;
2855 }
2856 
2857 SigningResult CWallet::SignMessage(const std::string &message,
2858  const PKHash &pkhash,
2859  std::string &str_sig) const {
2860  SignatureData sigdata;
2861  CScript script_pub_key = GetScriptForDestination(pkhash);
2862  for (const auto &spk_man_pair : m_spk_managers) {
2863  if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2864  return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2865  }
2866  }
2868 }
2869 
2871  int &nChangePosInOut, bilingual_str &error,
2872  bool lockUnspents,
2873  const std::set<int> &setSubtractFeeFromOutputs,
2874  CCoinControl coinControl) {
2875  std::vector<CRecipient> vecSend;
2876 
2877  // Turn the txout set into a CRecipient vector.
2878  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
2879  const CTxOut &txOut = tx.vout[idx];
2880  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue,
2881  setSubtractFeeFromOutputs.count(idx) == 1};
2882  vecSend.push_back(recipient);
2883  }
2884 
2885  coinControl.fAllowOtherInputs = true;
2886 
2887  for (const CTxIn &txin : tx.vin) {
2888  coinControl.Select(txin.prevout);
2889  }
2890 
2891  // Acquire the locks to prevent races to the new locked unspents between the
2892  // CreateTransaction call and LockCoin calls (when lockUnspents is true).
2893  LOCK(cs_wallet);
2894 
2895  CTransactionRef tx_new;
2896  if (!CreateTransaction(vecSend, tx_new, nFeeRet, nChangePosInOut, error,
2897  coinControl, false)) {
2898  return false;
2899  }
2900 
2901  if (nChangePosInOut != -1) {
2902  tx.vout.insert(tx.vout.begin() + nChangePosInOut,
2903  tx_new->vout[nChangePosInOut]);
2904  }
2905 
2906  // Copy output sizes from new transaction; they may have had the fee
2907  // subtracted from them.
2908  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
2909  tx.vout[idx].nValue = tx_new->vout[idx].nValue;
2910  }
2911 
2912  // Add new txins (keeping original txin scriptSig/order)
2913  for (const CTxIn &txin : tx_new->vin) {
2914  if (!coinControl.IsSelected(txin.prevout)) {
2915  tx.vin.push_back(txin);
2916 
2917  if (lockUnspents) {
2918  LockCoin(txin.prevout);
2919  }
2920  }
2921  }
2922 
2923  return true;
2924 }
2925 
2927  const BlockHash &block_hash) {
2928  if (chain.isInitialBlockDownload()) {
2929  return false;
2930  }
2931 
2932  // in seconds
2933  constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60;
2934  int64_t block_time;
2935  CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
2936  if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
2937  return false;
2938  }
2939  return true;
2940 }
2941 
2947  const BlockHash &block_hash,
2948  int block_height) {
2949  uint32_t locktime;
2950  // Discourage fee sniping.
2951  //
2952  // For a large miner the value of the transactions in the best block and
2953  // the mempool can exceed the cost of deliberately attempting to mine two
2954  // blocks to orphan the current best block. By setting nLockTime such that
2955  // only the next block can include the transaction, we discourage this
2956  // practice as the height restricted and limited blocksize gives miners
2957  // considering fee sniping fewer options for pulling off this attack.
2958  //
2959  // A simple way to think about this is from the wallet's point of view we
2960  // always want the blockchain to move forward. By setting nLockTime this
2961  // way we're basically making the statement that we only want this
2962  // transaction to appear in the next block; we don't want to potentially
2963  // encourage reorgs by allowing transactions to appear at lower heights
2964  // than the next block in forks of the best chain.
2965  //
2966  // Of course, the subsidy is high enough, and transaction volume low
2967  // enough, that fee sniping isn't a problem yet, but by implementing a fix
2968  // now we ensure code won't be written that makes assumptions about
2969  // nLockTime that preclude a fix later.
2970  if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
2971  locktime = block_height;
2972 
2973  // Secondly occasionally randomly pick a nLockTime even further back, so
2974  // that transactions that are delayed after signing for whatever reason,
2975  // e.g. high-latency mix networks and some CoinJoin implementations,
2976  // have better privacy.
2977  if (GetRandInt(10) == 0) {
2978  locktime = std::max(0, int(locktime) - GetRandInt(100));
2979  }
2980  } else {
2981  // If our chain is lagging behind, we can't discourage fee sniping nor
2982  // help the privacy of high-latency transactions. To avoid leaking a
2983  // potentially unique "nLockTime fingerprint", set nLockTime to a
2984  // constant.
2985  locktime = 0;
2986  }
2987  assert(locktime < LOCKTIME_THRESHOLD);
2988  return locktime;
2989 }
2990 
2991 OutputType
2993  const std::vector<CRecipient> &vecSend) {
2994  // If -changetype is specified, always use that change type.
2995  if (change_type != OutputType::CHANGE_AUTO) {
2996  return change_type;
2997  }
2998 
2999  // if m_default_address_type is legacy, use legacy address as change.
3000  if (m_default_address_type == OutputType::LEGACY) {
3001  return OutputType::LEGACY;
3002  }
3003 
3004  // else use m_default_address_type for change
3005  return m_default_address_type;
3006 }
3007 
3008 bool CWallet::CreateTransactionInternal(const std::vector<CRecipient> &vecSend,
3009  CTransactionRef &tx, Amount &nFeeRet,
3010  int &nChangePosInOut,
3012  const CCoinControl &coin_control,
3013  bool sign) {
3014  Amount nValue = Amount::zero();
3015  const OutputType change_type = TransactionChangeType(
3016  coin_control.m_change_type ? *coin_control.m_change_type
3017  : m_default_change_type,
3018  vecSend);
3019  ReserveDestination reservedest(this, change_type);
3020  int nChangePosRequest = nChangePosInOut;
3021  unsigned int nSubtractFeeFromAmount = 0;
3022  for (const auto &recipient : vecSend) {
3023  if (nValue < Amount::zero() || recipient.nAmount < Amount::zero()) {
3024  error = _("Transaction amounts must not be negative");
3025  return false;
3026  }
3027 
3028  nValue += recipient.nAmount;
3029 
3030  if (recipient.fSubtractFeeFromAmount) {
3031  nSubtractFeeFromAmount++;
3032  }
3033  }
3034 
3035  if (vecSend.empty()) {
3036  error = _("Transaction must have at least one recipient");
3037  return false;
3038  }
3039 
3040  CMutableTransaction txNew;
3041 
3042  {
3043  std::set<CInputCoin> setCoins;
3044  LOCK(cs_wallet);
3046  chain(), GetLastBlockHash(), GetLastBlockHeight());
3047  std::vector<COutput> vAvailableCoins;
3048  AvailableCoins(vAvailableCoins, true, &coin_control);
3049  // Parameters for coin selection, init with dummy
3051 
3052  // Create change script that will be used if we need change
3053  // TODO: pass in scriptChange instead of reservedest so
3054  // change transaction isn't always pay-to-bitcoin-address
3055  CScript scriptChange;
3056 
3057  // coin control: send change to custom address
3058  if (!boost::get<CNoDestination>(&coin_control.destChange)) {
3059  scriptChange = GetScriptForDestination(coin_control.destChange);
3060 
3061  // no coin control: send change to newly generated address
3062  } else {
3063  // Note: We use a new key here to keep it from being obvious
3064  // which side is the change.
3065  // The drawback is that by not reusing a previous key, the
3066  // change may be lost if a backup is restored, if the backup
3067  // doesn't have the new private key for the change. If we
3068  // reused the old key, it would be possible to add code to look
3069  // for and rediscover unknown transactions that were written
3070  // with keys of ours to recover post-backup change.
3071 
3072  // Reserve a new key pair from key pool. If it fails, provide a
3073  // dummy destination in case we don't need change.
3074  CTxDestination dest;
3075  if (!reservedest.GetReservedDestination(dest, true)) {
3076  error = _("Transaction needs a change address, but we can't "
3077  "generate it. Please call keypoolrefill first.");
3078  }
3079 
3080  scriptChange = GetScriptForDestination(dest);
3081  assert(!dest.empty() || scriptChange.empty());
3082  }
3083  CTxOut change_prototype_txout(Amount::zero(), scriptChange);
3084  coin_selection_params.change_output_size =
3085  GetSerializeSize(change_prototype_txout);
3086 
3087  // Get the fee rate to use effective values in coin selection
3088  CFeeRate nFeeRateNeeded = GetMinimumFeeRate(*this, coin_control);
3089 
3090  nFeeRet = Amount::zero();
3091  bool pick_new_inputs = true;
3092  Amount nValueIn = Amount::zero();
3093 
3094  // BnB selector is the only selector used when this is true.
3095  // That should only happen on the first pass through the loop.
3096  coin_selection_params.use_bnb = true;
3097  // If we are doing subtract fee from recipient, don't use effective
3098  // values
3099  coin_selection_params.m_subtract_fee_outputs =
3100  nSubtractFeeFromAmount != 0;
3101  // Start with no fee and loop until there is enough fee
3102  while (true) {
3103  nChangePosInOut = nChangePosRequest;
3104  txNew.vin.clear();
3105  txNew.vout.clear();
3106  bool fFirst = true;
3107 
3108  Amount nValueToSelect = nValue;
3109  if (nSubtractFeeFromAmount == 0) {
3110  nValueToSelect += nFeeRet;
3111  }
3112 
3113  // vouts to the payees
3114  if (!coin_selection_params.m_subtract_fee_outputs) {
3115  // Static size overhead + outputs vsize. 4 nVersion, 4
3116  // nLocktime, 1 input count, 1 output count
3117  coin_selection_params.tx_noinputs_size = 10;
3118  }
3119  // vouts to the payees
3120  for (const auto &recipient : vecSend) {
3121  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
3122 
3123  if (recipient.fSubtractFeeFromAmount) {
3124  assert(nSubtractFeeFromAmount != 0);
3125  // Subtract fee equally from each selected recipient.
3126  txout.nValue -= nFeeRet / int(nSubtractFeeFromAmount);
3127 
3128  // First receiver pays the remainder not divisible by output
3129  // count.
3130  if (fFirst) {
3131  fFirst = false;
3132  txout.nValue -= nFeeRet % int(nSubtractFeeFromAmount);
3133  }
3134  }
3135 
3136  // Include the fee cost for outputs. Note this is only used for
3137  // BnB right now
3138  if (!coin_selection_params.m_subtract_fee_outputs) {
3139  coin_selection_params.tx_noinputs_size +=
3141  }
3142 
3143  if (IsDust(txout, chain().relayDustFee())) {
3144  if (recipient.fSubtractFeeFromAmount &&
3145  nFeeRet > Amount::zero()) {
3146  if (txout.nValue < Amount::zero()) {
3147  error = _("The transaction amount is too small to "
3148  "pay the fee");
3149  } else {
3150  error = _("The transaction amount is too small to "
3151  "send after the fee has been deducted");
3152  }
3153  } else {
3154  error = _("Transaction amount too small");
3155  }
3156 
3157  return false;
3158  }
3159 
3160  txNew.vout.push_back(txout);
3161  }
3162 
3163  // Choose coins to use
3164  bool bnb_used = false;
3165  if (pick_new_inputs) {
3166  nValueIn = Amount::zero();
3167  setCoins.clear();
3168  int change_spend_size = CalculateMaximumSignedInputSize(
3169  change_prototype_txout, this);
3170  // If the wallet doesn't know how to sign change output, assume
3171  // p2pkh as lower-bound to allow BnB to do it's thing
3172  if (change_spend_size == -1) {
3173  coin_selection_params.change_spend_size =
3175  } else {
3176  coin_selection_params.change_spend_size =
3177  size_t(change_spend_size);
3178  }
3179  coin_selection_params.effective_fee = nFeeRateNeeded;
3180  if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins,
3181  nValueIn, coin_control, coin_selection_params,
3182  bnb_used)) {
3183  // If BnB was used, it was the first pass. No longer the
3184  // first pass and continue loop with knapsack.
3185  if (bnb_used) {
3186  coin_selection_params.use_bnb = false;
3187  continue;
3188  } else {
3189  error = _("Insufficient funds");
3190  return false;
3191  }
3192  }
3193  } else {
3194  bnb_used = false;
3195  }
3196 
3197  const Amount nChange = nValueIn - nValueToSelect;
3198  if (nChange > Amount::zero()) {
3199  // Fill a vout to ourself.
3200  CTxOut newTxOut(nChange, scriptChange);
3201 
3202  // Never create dust outputs; if we would, just add the dust to
3203  // the fee.
3204  // The nChange when BnB is used is always going to go to fees.
3205  if (IsDust(newTxOut, chain().relayDustFee()) || bnb_used) {
3206  nChangePosInOut = -1;
3207  nFeeRet += nChange;
3208  } else {
3209  if (nChangePosInOut == -1) {
3210  // Insert change txn at random position:
3211  nChangePosInOut = GetRandInt(txNew.vout.size() + 1);
3212  } else if ((unsigned int)nChangePosInOut >
3213  txNew.vout.size()) {
3214  error = _("Change index out of range");
3215  return false;
3216  }
3217 
3218  std::vector<CTxOut>::iterator position =
3219  txNew.vout.begin() + nChangePosInOut;
3220  txNew.vout.insert(position, newTxOut);
3221  }
3222  } else {
3223  nChangePosInOut = -1;
3224  }
3225 
3226  // Dummy fill vin for maximum size estimation
3227  //
3228  for (const auto &coin : setCoins) {
3229  txNew.vin.push_back(CTxIn(coin.outpoint, CScript()));
3230  }
3231 
3232  CTransaction txNewConst(txNew);
3233  int nBytes = CalculateMaximumSignedTxSize(
3234  txNewConst, this, coin_control.fAllowWatchOnly);
3235  if (nBytes < 0) {
3236  error = _("Signing transaction failed");
3237  return false;
3238  }
3239 
3240  Amount nFeeNeeded = GetMinimumFee(*this, nBytes, coin_control);
3241 
3242  if (nFeeRet >= nFeeNeeded) {
3243  // Reduce fee to only the needed amount if possible. This
3244  // prevents potential overpayment in fees if the coins selected
3245  // to meet nFeeNeeded result in a transaction that requires less
3246  // fee than the prior iteration.
3247 
3248  // If we have no change and a big enough excess fee, then try to
3249  // construct transaction again only without picking new inputs.
3250  // We now know we only need the smaller fee (because of reduced
3251  // tx size) and so we should add a change output. Only try this
3252  // once.
3253  if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 &&
3254  pick_new_inputs) {
3255  // Add 2 as a buffer in case increasing # of outputs changes
3256  // compact size
3257  unsigned int tx_size_with_change =
3258  nBytes + coin_selection_params.change_output_size + 2;
3259  Amount fee_needed_with_change =
3260  GetMinimumFee(*this, tx_size_with_change, coin_control);
3261  Amount minimum_value_for_change = GetDustThreshold(
3262  change_prototype_txout, chain().relayDustFee());
3263  if (nFeeRet >=
3264  fee_needed_with_change + minimum_value_for_change) {
3265  pick_new_inputs = false;
3266  nFeeRet = fee_needed_with_change;
3267  continue;
3268  }
3269  }
3270 
3271  // If we have change output already, just increase it
3272  if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 &&
3273  nSubtractFeeFromAmount == 0) {
3274  Amount extraFeePaid = nFeeRet - nFeeNeeded;
3275  std::vector<CTxOut>::iterator change_position =
3276  txNew.vout.begin() + nChangePosInOut;
3277  change_position->nValue += extraFeePaid;
3278  nFeeRet -= extraFeePaid;
3279  }
3280 
3281  // Done, enough fee included.
3282  break;
3283  } else if (!pick_new_inputs) {
3284  // This shouldn't happen, we should have had enough excess fee
3285  // to pay for the new output and still meet nFeeNeeded.
3286  // Or we should have just subtracted fee from recipients and
3287  // nFeeNeeded should not have changed.
3288  error = _("Transaction fee and change calculation failed");
3289  return false;
3290  }
3291 
3292  // Try to reduce change to include necessary fee.
3293  if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
3294  Amount additionalFeeNeeded = nFeeNeeded - nFeeRet;
3295  std::vector<CTxOut>::iterator change_position =
3296  txNew.vout.begin() + nChangePosInOut;
3297  // Only reduce change if remaining amount is still a large
3298  // enough output.
3299  if (change_position->nValue >=
3300  MIN_FINAL_CHANGE + additionalFeeNeeded) {
3301  change_position->nValue -= additionalFeeNeeded;
3302  nFeeRet += additionalFeeNeeded;
3303  // Done, able to increase fee from change.
3304  break;
3305  }
3306  }
3307 
3308  // If subtracting fee from recipients, we now know what fee we
3309  // need to subtract, we have no reason to reselect inputs.
3310  if (nSubtractFeeFromAmount > 0) {
3311  pick_new_inputs = false;
3312  }
3313 
3314  // Include more fee and try again.
3315  nFeeRet = nFeeNeeded;
3316  coin_selection_params.use_bnb = false;
3317  continue;
3318  }
3319 
3320  // Give up if change keypool ran out and we failed to find a solution
3321  // without change:
3322  if (scriptChange.empty() && nChangePosInOut != -1) {
3323  return false;
3324  }
3325 
3326  // Shuffle selected coins and fill in final vin
3327  txNew.vin.clear();
3328  std::vector<CInputCoin> selected_coins(setCoins.begin(),
3329  setCoins.end());
3330  Shuffle(selected_coins.begin(), selected_coins.end(),
3331  FastRandomContext());
3332 
3333  // Note how the sequence number is set to non-maxint so that
3334  // the nLockTime set above actually works.
3335  for (const auto &coin : selected_coins) {
3336  txNew.vin.push_back(
3337  CTxIn(coin.outpoint, CScript(),
3338  std::numeric_limits<uint32_t>::max() - 1));
3339  }
3340 
3341  if (sign && !SignTransaction(txNew)) {
3342  error = _("Signing transaction failed");
3343  return false;
3344  }
3345 
3346  // Return the constructed transaction data.
3347  tx = MakeTransactionRef(std::move(txNew));
3348 
3349  // Limit size.
3350  if (tx->GetTotalSize() > MAX_STANDARD_TX_SIZE) {
3351  error = _("Transaction too large");
3352  return false;
3353  }
3354  }
3355 
3356  if (nFeeRet > m_default_max_tx_fee) {
3358  return false;
3359  }
3360 
3361  if (gArgs.GetBoolArg("-walletrejectlongchains",
3363  // Lastly, ensure this tx will pass the mempool's chain limits
3364  if (!chain().checkChainLimits(tx)) {
3365  error = _("Transaction has too long of a mempool chain");
3366  return false;
3367  }
3368  }
3369 
3370  // Before we return success, we assume any change key will be used to
3371  // prevent accidental re-use.
3372  reservedest.KeepDestination();
3373 
3374  return true;
3375 }
3376 
3377 bool CWallet::CreateTransaction(const std::vector<CRecipient> &vecSend,
3378  CTransactionRef &tx, Amount &nFeeRet,
3379  int &nChangePosInOut, bilingual_str &error,
3380  const CCoinControl &coin_control, bool sign) {
3381  int nChangePosIn = nChangePosInOut;
3382  CTransactionRef tx2 = tx;
3383  bool res = CreateTransactionInternal(vecSend, tx, nFeeRet, nChangePosInOut,
3384  error, coin_control, sign);
3385  // try with avoidpartialspends unless it's enabled already
3386  if (res &&
3387  nFeeRet >
3388  Amount::zero() /* 0 means non-functional fee rate estimation */
3389  && m_max_aps_fee > (-1 * SATOSHI) &&
3390  !coin_control.m_avoid_partial_spends) {
3391  CCoinControl tmp_cc = coin_control;
3392  tmp_cc.m_avoid_partial_spends = true;
3393  Amount nFeeRet2;
3394  int nChangePosInOut2 = nChangePosIn;
3395  // fired and forgotten; if an error occurs, we discard the results
3396  bilingual_str error2;
3397  if (CreateTransactionInternal(vecSend, tx2, nFeeRet2, nChangePosInOut2,
3398  error2, tmp_cc, sign)) {
3399  // if fee of this alternative one is within the range of the max
3400  // fee, we use this one
3401  const bool use_aps = nFeeRet2 <= nFeeRet + m_max_aps_fee;
3402  WalletLogPrintf(
3403  "Fee non-grouped = %lld, grouped = %lld, using %s\n", nFeeRet,
3404  nFeeRet2, use_aps ? "grouped" : "non-grouped");
3405  if (use_aps) {
3406  tx = tx2;
3407  nFeeRet = nFeeRet2;
3408  nChangePosInOut = nChangePosInOut2;
3409  }
3410  }
3411  }
3412  return res;
3413 }
3414 
3416  CTransactionRef tx, mapValue_t mapValue,
3417  std::vector<std::pair<std::string, std::string>> orderForm) {
3418  LOCK(cs_wallet);
3419 
3420  CWalletTx wtxNew(this, std::move(tx));
3421  wtxNew.mapValue = std::move(mapValue);
3422  wtxNew.vOrderForm = std::move(orderForm);
3423  wtxNew.fTimeReceivedIsTxTime = true;
3424  wtxNew.fFromMe = true;
3425 
3426  WalletLogPrintfToBeContinued("CommitTransaction:\n%s",
3427  wtxNew.tx->ToString());
3428 
3429  // Add tx to wallet, because if it has change it's also ours, otherwise just
3430  // for transaction history.
3431  AddToWallet(wtxNew);
3432 
3433  // Notify that old coins are spent.
3434  for (const CTxIn &txin : wtxNew.tx->vin) {
3435  CWalletTx &coin = mapWallet.at(txin.prevout.GetTxId());
3436  coin.BindWallet(this);
3437  NotifyTransactionChanged(this, coin.GetId(), CT_UPDATED);
3438  }
3439 
3440  // Get the inserted-CWalletTx from mapWallet so that the
3441  // fInMempool flag is cached properly
3442  CWalletTx &wtx = mapWallet.at(wtxNew.GetId());
3443 
3444  if (!fBroadcastTransactions) {
3445  // Don't submit tx to the mempool
3446  return;
3447  }
3448 
3449  std::string err_string;
3450  if (!wtx.SubmitMemoryPoolAndRelay(err_string, true)) {
3451  WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast "
3452  "immediately, %s\n",
3453  err_string);
3454  // TODO: if we expect the failure to be long term or permanent, instead
3455  // delete wtx from the wallet and return failure.
3456  }
3457 }
3458 
3459 DBErrors CWallet::LoadWallet(bool &fFirstRunRet) {
3460  LOCK(cs_wallet);
3461 
3462  fFirstRunRet = false;
3463  DBErrors nLoadWalletRet = WalletBatch(*database, "cr+").LoadWallet(this);
3464  if (nLoadWalletRet == DBErrors::NEED_REWRITE) {
3465  if (database->Rewrite("\x04pool")) {
3466  for (const auto &spk_man_pair : m_spk_managers) {
3467  spk_man_pair.second->RewriteDB();
3468  }
3469  }
3470  }
3471 
3472  // This wallet is in its first run if there are no ScriptPubKeyMans and it
3473  // isn't blank or no privkeys
3474  fFirstRunRet = m_spk_managers.empty() &&
3475  !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
3476  !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
3477  if (fFirstRunRet) {
3478  assert(m_external_spk_managers.empty());
3479  assert(m_internal_spk_managers.empty());
3480  }
3481 
3482  if (nLoadWalletRet != DBErrors::LOAD_OK) {
3483  return nLoadWalletRet;
3484  }
3485 
3486  return DBErrors::LOAD_OK;
3487 }
3488 
3489 DBErrors CWallet::ZapSelectTx(std::vector<TxId> &txIdsIn,
3490  std::vector<TxId> &txIdsOut) {
3491  AssertLockHeld(cs_wallet);
3492  DBErrors nZapSelectTxRet =
3493  WalletBatch(*database, "cr+").ZapSelectTx(txIdsIn, txIdsOut);
3494  for (const TxId &txid : txIdsOut) {
3495  const auto &it = mapWallet.find(txid);
3496  wtxOrdered.erase(it->second.m_it_wtxOrdered);
3497  mapWallet.erase(it);
3498  NotifyTransactionChanged(this, txid, CT_DELETED);
3499  }
3500 
3501  if (nZapSelectTxRet == DBErrors::NEED_REWRITE) {
3502  if (database->Rewrite("\x04pool")) {
3503  for (const auto &spk_man_pair : m_spk_managers) {
3504  spk_man_pair.second->RewriteDB();
3505  }
3506  }
3507  }
3508 
3509  if (nZapSelectTxRet != DBErrors::LOAD_OK) {
3510  return nZapSelectTxRet;
3511  }
3512 
3513  MarkDirty();
3514 
3515  return DBErrors::LOAD_OK;
3516 }
3517 
3518 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx> &vWtx) {
3519  DBErrors nZapWalletTxRet = WalletBatch(*database, "cr+").ZapWalletTx(vWtx);
3520  if (nZapWalletTxRet == DBErrors::NEED_REWRITE) {
3521  if (database->Rewrite("\x04pool")) {
3522  for (const auto &spk_man_pair : m_spk_managers) {
3523  spk_man_pair.second->RewriteDB();
3524  }
3525  }
3526  }
3527 
3528  if (nZapWalletTxRet != DBErrors::LOAD_OK) {
3529  return nZapWalletTxRet;
3530  }
3531 
3532  return DBErrors::LOAD_OK;
3533 }
3534 
3536  const CTxDestination &address,
3537  const std::string &strName,
3538  const std::string &strPurpose) {
3539  bool fUpdated = false;
3540  {
3541  LOCK(cs_wallet);
3542  std::map<CTxDestination, CAddressBookData>::iterator mi =
3543  m_address_book.find(address);
3544  fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
3545  m_address_book[address].SetLabel(strName);
3546  // Update purpose only if requested.
3547  if (!strPurpose.empty()) {
3548  m_address_book[address].purpose = strPurpose;
3549  }
3550  }
3551 
3552  NotifyAddressBookChanged(this, address, strName,
3553  IsMine(address) != ISMINE_NO, strPurpose,
3554  (fUpdated ? CT_UPDATED : CT_NEW));
3555  if (!strPurpose.empty() && !batch.WritePurpose(address, strPurpose)) {
3556  return false;
3557  }
3558  return batch.WriteName(address, strName);
3559 }
3560 
3562  const std::string &strName,
3563  const std::string &strPurpose) {
3564  WalletBatch batch(*database);
3565  return SetAddressBookWithDB(batch, address, strName, strPurpose);
3566 }
3567 
3569  // If we want to delete receiving addresses, we need to take care that
3570  // DestData "used" (and possibly newer DestData) gets preserved (and the
3571  // "deleted" address transformed into a change entry instead of actually
3572  // being deleted)
3573  // NOTE: This isn't a problem for sending addresses because they never have
3574  // any DestData yet! When adding new DestData, it should be considered here
3575  // whether to retain or delete it (or move it?).
3576  if (IsMine(address)) {
3577  WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please "
3578  "report this bug! %s\n",
3579  __func__, PACKAGE_BUGREPORT);
3580  return false;
3581  }
3582 
3583  {
3584  LOCK(cs_wallet);
3585 
3586  // Delete destdata tuples associated with address
3587  for (const std::pair<const std::string, std::string> &item :
3588  m_address_book[address].destdata) {
3589  WalletBatch(*database).EraseDestData(address, item.first);
3590  }
3591  m_address_book.erase(address);
3592  }
3593 
3594  NotifyAddressBookChanged(this, address, "", IsMine(address) != ISMINE_NO,
3595  "", CT_DELETED);
3596 
3597  WalletBatch(*database).ErasePurpose(address);
3598  return WalletBatch(*database).EraseName(address);
3599 }
3600 
3602  AssertLockHeld(cs_wallet);
3603 
3604  unsigned int count = 0;
3605  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3606  count += spk_man->KeypoolCountExternalKeys();
3607  }
3608 
3609  return count;
3610 }
3611 
3612 unsigned int CWallet::GetKeyPoolSize() const {
3613  AssertLockHeld(cs_wallet);
3614 
3615  unsigned int count = 0;
3616  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3617  count += spk_man->GetKeyPoolSize();
3618  }
3619  return count;
3620 }
3621 
3622 bool CWallet::TopUpKeyPool(unsigned int kpSize) {
3623  LOCK(cs_wallet);
3624  bool res = true;
3625  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3626  res &= spk_man->TopUp(kpSize);
3627  }
3628  return res;
3629 }
3630 
3631 bool CWallet::GetNewDestination(const OutputType type, const std::string label,
3632  CTxDestination &dest, std::string &error) {
3633  LOCK(cs_wallet);
3634  error.clear();
3635  bool result = false;
3636  auto spk_man = GetScriptPubKeyMan(type, false /* internal */);
3637  if (spk_man) {
3638  spk_man->TopUp();
3639  result = spk_man->GetNewDestination(type, dest, error);
3640  } else {
3641  error = strprintf("Error: No %s addresses available.",
3642  FormatOutputType(type));
3643  }
3644  if (result) {
3645  SetAddressBook(dest, label, "receive");
3646  }
3647 
3648  return result;
3649 }
3650 
3652  CTxDestination &dest,
3653  std::string &error) {
3654  LOCK(cs_wallet);
3655  error.clear();
3656 
3657  ReserveDestination reservedest(this, type);
3658  if (!reservedest.GetReservedDestination(dest, true)) {
3659  error = _("Error: Keypool ran out, please call keypoolrefill first")
3660  .translated;
3661  return false;
3662  }
3663 
3664  reservedest.KeepDestination();
3665  return true;
3666 }
3667 
3669  LOCK(cs_wallet);
3670  int64_t oldestKey = std::numeric_limits<int64_t>::max();
3671  for (const auto &spk_man_pair : m_spk_managers) {
3672  oldestKey =
3673  std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
3674  }
3675  return oldestKey;
3676 }
3677 
3679  const std::set<CTxDestination> &destinations) {
3680  for (auto &entry : mapWallet) {
3681  CWalletTx &wtx = entry.second;
3682  if (wtx.m_is_cache_empty) {
3683  continue;
3684  }
3685 
3686  for (size_t i = 0; i < wtx.tx->vout.size(); i++) {
3687  CTxDestination dst;
3688 
3689  if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) &&
3690  destinations.count(dst)) {
3691  wtx.MarkDirty();
3692  break;
3693  }
3694  }
3695  }
3696 }
3697 
3698 std::map<CTxDestination, Amount> CWallet::GetAddressBalances() const {
3699  std::map<CTxDestination, Amount> balances;
3700 
3701  LOCK(cs_wallet);
3702  std::set<TxId> trusted_parents;
3703  for (const auto &walletEntry : mapWallet) {
3704  const CWalletTx &wtx = walletEntry.second;
3705 
3706  if (!wtx.IsTrusted(trusted_parents)) {
3707  continue;
3708  }
3709 
3710  if (wtx.IsImmatureCoinBase()) {
3711  continue;
3712  }
3713 
3714  int nDepth = wtx.GetDepthInMainChain();
3715  if (nDepth < (wtx.IsFromMe(ISMINE_ALL) ? 0 : 1)) {
3716  continue;
3717  }
3718 
3719  for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) {
3720  CTxDestination addr;
3721  if (!IsMine(wtx.tx->vout[i])) {
3722  continue;
3723  }
3724 
3725  if (!ExtractDestination(wtx.tx->vout[i].scriptPubKey, addr)) {
3726  continue;
3727  }
3728 
3729  Amount n = IsSpent(COutPoint(walletEntry.first, i))
3730  ? Amount::zero()
3731  : wtx.tx->vout[i].nValue;
3732 
3733  if (!balances.count(addr)) {
3734  balances[addr] = Amount::zero();
3735  }
3736  balances[addr] += n;
3737  }
3738  }
3739 
3740  return balances;
3741 }
3742 
3743 std::set<std::set<CTxDestination>> CWallet::GetAddressGroupings() const {
3744  AssertLockHeld(cs_wallet);
3745  std::set<std::set<CTxDestination>> groupings;
3746  std::set<CTxDestination> grouping;
3747 
3748  for (const auto &walletEntry : mapWallet) {
3749  const CWalletTx &wtx = walletEntry.second;
3750 
3751  if (wtx.tx->vin.size() > 0) {
3752  bool any_mine = false;
3753  // Group all input addresses with each other.
3754  for (const auto &txin : wtx.tx->vin) {
3755  CTxDestination address;
3756  // If this input isn't mine, ignore it.
3757  if (!IsMine(txin)) {
3758  continue;
3759  }
3760 
3761  if (!ExtractDestination(mapWallet.at(txin.prevout.GetTxId())
3762  .tx->vout[txin.prevout.GetN()]
3763  .scriptPubKey,
3764  address)) {
3765  continue;
3766  }
3767 
3768  grouping.insert(address);
3769  any_mine = true;
3770  }
3771 
3772  // Group change with input addresses.
3773  if (any_mine) {
3774  for (const auto &txout : wtx.tx->vout) {
3775  if (IsChange(txout)) {
3776  CTxDestination txoutAddr;
3777  if (!ExtractDestination(txout.scriptPubKey,
3778  txoutAddr)) {
3779  continue;
3780  }
3781 
3782  grouping.insert(txoutAddr);
3783  }
3784  }
3785  }
3786 
3787  if (grouping.size() > 0) {
3788  groupings.insert(grouping);
3789  grouping.clear();
3790  }
3791  }
3792 
3793  // Group lone addrs by themselves.
3794  for (const auto &txout : wtx.tx->vout) {
3795  if (IsMine(txout)) {
3796  CTxDestination address;
3797  if (!ExtractDestination(txout.scriptPubKey, address)) {
3798  continue;
3799  }
3800 
3801  grouping.insert(address);
3802  groupings.insert(grouping);
3803  grouping.clear();
3804  }
3805  }
3806  }
3807 
3808  // A set of pointers to groups of addresses.
3809  std::set<std::set<CTxDestination> *> uniqueGroupings;
3810  // Map addresses to the unique group containing it.
3811  std::map<CTxDestination, std::set<CTxDestination> *> setmap;
3812  for (std::set<CTxDestination> _grouping : groupings) {
3813  // Make a set of all the groups hit by this new group.
3814  std::set<std::set<CTxDestination> *> hits;
3815  std::map<CTxDestination, std::set<CTxDestination> *>::iterator it;
3816  for (const CTxDestination &address : _grouping) {
3817  if ((it = setmap.find(address)) != setmap.end()) {
3818  hits.insert((*it).second);
3819  }
3820  }
3821 
3822  // Merge all hit groups into a new single group and delete old groups.
3823  std::set<CTxDestination> *merged =
3824  new std::set<CTxDestination>(_grouping);
3825  for (std::set<CTxDestination> *hit : hits) {
3826  merged->insert(hit->begin(), hit->end());
3827  uniqueGroupings.erase(hit);
3828  delete hit;
3829  }
3830  uniqueGroupings.insert(merged);
3831 
3832  // Update setmap.
3833  for (const CTxDestination &element : *merged) {
3834  setmap[element] = merged;
3835  }
3836  }
3837 
3838  std::set<std::set<CTxDestination>> ret;
3839  for (const std::set<CTxDestination> *uniqueGrouping : uniqueGroupings) {
3840  ret.insert(*uniqueGrouping);
3841  delete uniqueGrouping;
3842  }
3843 
3844  return ret;
3845 }
3846 
3847 std::set<CTxDestination>
3848 CWallet::GetLabelAddresses(const std::string &label) const {
3849  LOCK(cs_wallet);
3850  std::set<CTxDestination> result;
3851  for (const std::pair<const CTxDestination, CAddressBookData> &item :
3852  m_address_book) {
3853  if (item.second.IsChange()) {
3854  continue;
3855  }
3856  const CTxDestination &address = item.first;
3857  const std::string &strName = item.second.GetLabel();
3858  if (strName == label) {
3859  result.insert(address);
3860  }
3861  }
3862 
3863  return result;
3864 }
3865 
3867  bool internal) {
3868  m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
3869  if (!m_spk_man) {
3870  return false;
3871  }
3872 
3873  if (nIndex == -1) {
3874  m_spk_man->TopUp();
3875 
3876  CKeyPool keypool;
3877  if (!m_spk_man->GetReservedDestination(type, internal, address, nIndex,
3878  keypool)) {
3879  return false;
3880  }
3881  fInternal = keypool.fInternal;
3882  }
3883  dest = address;
3884  return true;
3885 }
3886 
3888  if (nIndex != -1) {
3889  m_spk_man->KeepDestination(nIndex, type);
3890  }
3891 
3892  nIndex = -1;
3893  address = CNoDestination();
3894 }
3895 
3897  if (nIndex != -1) {
3898  m_spk_man->ReturnDestination(nIndex, fInternal, address);
3899  }
3900  nIndex = -1;
3901  address = CNoDestination();
3902 }
3903 
3904 void CWallet::LockCoin(const COutPoint &output) {
3905  AssertLockHeld(cs_wallet);
3906  setLockedCoins.insert(output);
3907 }
3908 
3909 void CWallet::UnlockCoin(const COutPoint &output) {
3910  AssertLockHeld(cs_wallet);
3911  setLockedCoins.erase(output);
3912 }
3913 
3915  AssertLockHeld(cs_wallet);
3916  setLockedCoins.clear();
3917 }
3918 
3919 bool CWallet::IsLockedCoin(const COutPoint &outpoint) const {
3920  AssertLockHeld(cs_wallet);
3921 
3922  return setLockedCoins.count(outpoint) > 0;
3923 }
3924 
3925 void CWallet::ListLockedCoins(std::vector<COutPoint> &vOutpts) const {
3926  AssertLockHeld(cs_wallet);
3927  for (COutPoint outpoint : setLockedCoins) {
3928  vOutpts.push_back(outpoint);
3929  }
3930 }
3931  // end of Actions
3933 
3934 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
3935  AssertLockHeld(cs_wallet);
3936  mapKeyBirth.clear();
3937 
3938  LegacyScriptPubKeyMan *spk_man = GetLegacyScriptPubKeyMan();
3939  assert(spk_man != nullptr);
3940  LOCK(spk_man->cs_KeyStore);
3941 
3942  // Get birth times for keys with metadata.
3943  for (const auto &entry : spk_man->mapKeyMetadata) {
3944  if (entry.second.nCreateTime) {
3945  mapKeyBirth[entry.first] = entry.second.nCreateTime;
3946  }
3947  }
3948 
3949  // map in which we'll infer heights of other keys
3950  std::map<CKeyID, const CWalletTx::Confirmation *> mapKeyFirstBlock;
3951  CWalletTx::Confirmation max_confirm;
3952  // the tip can be reorganized; use a 144-block safety margin
3953  max_confirm.block_height =
3954  GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0;
3955  CHECK_NONFATAL(chain().findAncestorByHeight(
3956  GetLastBlockHash(), max_confirm.block_height,
3957  FoundBlock().hash(max_confirm.hashBlock)));
3958  for (const CKeyID &keyid : spk_man->GetKeys()) {
3959  if (mapKeyBirth.count(keyid) == 0) {
3960  mapKeyFirstBlock[keyid] = &max_confirm;
3961  }
3962  }
3963 
3964  // If there are no such keys, we're done.
3965  if (mapKeyFirstBlock.empty()) {
3966  return;
3967  }
3968 
3969  // Find first block that affects those keys, if there are any left.
3970  for (const auto &entry : mapWallet) {
3971  // iterate over all wallet transactions...
3972  const CWalletTx &wtx = entry.second;
3973  if (wtx.m_confirm.status == CWalletTx::CONFIRMED) {
3974  // ... which are already in a block
3975  for (const CTxOut &txout : wtx.tx->vout) {
3976  // Iterate over all their outputs...
3977  for (const auto &keyid :
3978  GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
3979  // ... and all their affected keys.
3980  auto rit = mapKeyFirstBlock.find(keyid);
3981  if (rit != mapKeyFirstBlock.end() &&
3982  wtx.m_confirm.block_height <
3983  rit->second->block_height) {
3984  rit->second = &wtx.m_confirm;
3985  }
3986  }
3987  }
3988  }
3989  }
3990 
3991  // Extract block timestamps for those keys.
3992  for (const auto &entry : mapKeyFirstBlock) {
3993  int64_t block_time;
3994  CHECK_NONFATAL(chain().findBlock(entry.second->hashBlock,
3995  FoundBlock().time(block_time)));
3996  // block times can be 2h off
3997  mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW;
3998  }
3999 }
4000 
4022 unsigned int CWallet::ComputeTimeSmart(const CWalletTx &wtx) const {
4023  unsigned int nTimeSmart = wtx.nTimeReceived;
4024  if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
4025  int64_t blocktime;
4026  if (chain().findBlock(wtx.m_confirm.hashBlock,
4027  FoundBlock().time(blocktime))) {
4028  int64_t latestNow = wtx.nTimeReceived;
4029  int64_t latestEntry = 0;
4030 
4031  // Tolerate times up to the last timestamp in the wallet not more
4032  // than 5 minutes into the future
4033  int64_t latestTolerated = latestNow + 300;
4034  const TxItems &txOrdered = wtxOrdered;
4035  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
4036  CWalletTx *const pwtx = it->second;
4037  if (pwtx == &wtx) {
4038  continue;
4039  }
4040  int64_t nSmartTime;
4041  nSmartTime = pwtx->nTimeSmart;
4042  if (!nSmartTime) {
4043  nSmartTime = pwtx->nTimeReceived;
4044  }
4045  if (nSmartTime <= latestTolerated) {
4046  latestEntry = nSmartTime;
4047  if (nSmartTime > latestNow) {
4048  latestNow = nSmartTime;
4049  }
4050  break;
4051  }
4052  }
4053 
4054  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
4055  } else {
4056  WalletLogPrintf("%s: found %s in block %s not in index\n", __func__,
4057  wtx.GetId().ToString(),
4058  wtx.m_confirm.hashBlock.ToString());
4059  }
4060  }
4061  return nTimeSmart;
4062 }
4063 
4065  const std::string &key, const std::string &value) {
4066  if (boost::get<CNoDestination>(&dest)) {
4067  return false;
4068  }
4069 
4070  m_address_book[dest].destdata.insert(std::make_pair(key, value));
4071  return batch.WriteDestData(dest, key, value);
4072 }
4073 
4075  const std::string &key) {
4076  if (!m_address_book[dest].destdata.erase(key)) {
4077  return false;
4078  }
4079 
4080  return batch.EraseDestData(dest, key);
4081 }
4082 
4083 void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key,
4084  const std::string &value) {
4085  m_address_book[dest].destdata.insert(std::make_pair(key, value));
4086 }
4087 
4088 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key,
4089  std::string *value) const {
4090  std::map<CTxDestination, CAddressBookData>::const_iterator i =
4091  m_address_book.find(dest);
4092  if (i != m_address_book.end()) {
4093  CAddressBookData::StringMap::const_iterator j =
4094  i->second.destdata.find(key);
4095  if (j != i->second.destdata.end()) {
4096  if (value) {
4097  *value = j->second;
4098  }
4099 
4100  return true;
4101  }
4102  }
4103  return false;
4104 }
4105 
4106 std::vector<std::string>
4107 CWallet::GetDestValues(const std::string &prefix) const {
4108  std::vector<std::string> values;
4109  for (const auto &address : m_address_book) {
4110  for (const auto &data : address.second.destdata) {
4111  if (!data.first.compare(0, prefix.size(), prefix)) {
4112  values.emplace_back(data.second);
4113  }
4114  }
4115  }
4116  return values;
4117 }
4118 
4119 bool CWallet::Verify(const CChainParams &chainParams, interfaces::Chain &chain,
4120  const WalletLocation &location,
4121  bilingual_str &error_string,
4122  std::vector<bilingual_str> &warnings) {
4123  // Do some checking on wallet path. It should be either a:
4124  //
4125  // 1. Path where a directory can be created.
4126  // 2. Path to an existing directory.
4127  // 3. Path to a symlink to a directory.
4128  // 4. For backwards compatibility, the name of a data file in -walletdir.
4129  LOCK(cs_wallets);
4130  const fs::path &wallet_path = location.GetPath();
4131  fs::file_type path_type = fs::symlink_status(wallet_path).type();
4132  if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
4133  (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
4134  (path_type == fs::regular_file &&
4135  fs::path(location.GetName()).filename() == location.GetName()))) {
4136  error_string = Untranslated(
4137  strprintf("Invalid -wallet path '%s'. -wallet path should point to "
4138  "a directory where wallet.dat and "
4139  "database/log.?????????? files can be stored, a location "
4140  "where such a directory could be created, "
4141  "or (for backwards compatibility) the name of an "
4142  "existing data file in -walletdir (%s)",
4143  location.GetName(), GetWalletDir()));
4144  return false;
4145  }
4146 
4147  // Make sure that the wallet path doesn't clash with an existing wallet path
4148  if (IsWalletLoaded(wallet_path)) {
4149  error_string = Untranslated(strprintf(
4150  "Error loading wallet %s. Duplicate -wallet filename specified.",
4151  location.GetName()));
4152  return false;
4153  }
4154 
4155  // Keep same database environment instance across Verify/Recover calls
4156  // below.
4157  std::unique_ptr<WalletDatabase> database =
4158  WalletDatabase::Create(wallet_path);
4159 
4160  try {
4161  return database->Verify(error_string);
4162  } catch (const fs::filesystem_error &e) {
4163  error_string = Untranslated(
4164  strprintf("Error loading wallet %s. %s", location.GetName(),
4166  return false;
4167  }
4168 }
4169 
4170 std::shared_ptr<CWallet> CWallet::CreateWalletFromFile(
4171  const CChainParams &chainParams, interfaces::Chain &chain,
4172  const WalletLocation &location, bilingual_str &error,
4173  std::vector<bilingual_str> &warnings, uint64_t wallet_creation_flags) {
4174  const std::string walletFile =
4175  WalletDataFilePath(location.GetPath()).string();
4176 
4177  // Needed to restore wallet transaction meta data after -zapwallettxes
4178  std::vector<CWalletTx> vWtx;
4179 
4180  if (gArgs.GetBoolArg("-zapwallettxes", false)) {
4181  chain.initMessage(
4182  _("Zapping all transactions from wallet...").translated);
4183 
4184  std::unique_ptr<CWallet> tempWallet = std::make_unique<CWallet>(
4185  &chain, location, WalletDatabase::Create(location.GetPath()));
4186  DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
4187  if (nZapWalletRet != DBErrors::LOAD_OK) {
4188  error =
4189  strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
4190  return nullptr;
4191  }
4192  }
4193 
4194  chain.initMessage(_("Loading wallet...").translated);
4195 
4196  int64_t nStart = GetTimeMillis();
4197  bool fFirstRun = true;
4198  // TODO: Can't use std::make_shared because we need a custom deleter but
4199  // should be possible to use std::allocate_shared.
4200  std::shared_ptr<CWallet> walletInstance(
4201  new CWallet(&chain, location,
4202  WalletDatabase::Create(location.GetPath())),
4203  ReleaseWallet);
4204  DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
4205  if (nLoadWalletRet != DBErrors::LOAD_OK) {
4206  if (nLoadWalletRet == DBErrors::CORRUPT) {
4207  error =
4208  strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
4209  return nullptr;
4210  }
4211 
4212  if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR) {
4213  warnings.push_back(
4214  strprintf(_("Error reading %s! All keys read correctly, but "
4215  "transaction data or address book entries might be "
4216  "missing or incorrect."),
4217  walletFile));
4218  } else if (nLoadWalletRet == DBErrors::TOO_NEW) {
4219  error = strprintf(
4220  _("Error loading %s: Wallet requires newer version of %s"),
4221  walletFile, PACKAGE_NAME);
4222  return nullptr;
4223  } else if (nLoadWalletRet == DBErrors::NEED_REWRITE) {
4224  error = strprintf(
4225  _("Wallet needed to be rewritten: restart %s to complete"),
4226  PACKAGE_NAME);
4227  return nullptr;
4228  } else {
4229  error = strprintf(_("Error loading %s"), walletFile);
4230  return nullptr;
4231  }
4232  }
4233 
4234  if (fFirstRun) {
4235  // Ensure this wallet.dat can only be opened by clients supporting
4236  // HD with chain split and expects no default key.
4237  walletInstance->SetMinVersion(FEATURE_LATEST);
4238 
4239  walletInstance->SetWalletFlags(wallet_creation_flags, false);
4240 
4241  // Only create LegacyScriptPubKeyMan when not descriptor wallet
4242  if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
4243  walletInstance->SetupLegacyScriptPubKeyMan();
4244  }
4245 
4246  if (!(wallet_creation_flags &
4248  LOCK(walletInstance->cs_wallet);
4249  if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
4250  walletInstance->SetupDescriptorScriptPubKeyMans();
4251  // SetupDescriptorScriptPubKeyMans already calls SetupGeneration
4252  // for us so we don't need to call SetupGeneration separately
4253  } else {
4254  // Legacy wallets need SetupGeneration here.
4255  for (auto spk_man :
4256  walletInstance->GetActiveScriptPubKeyMans()) {
4257  if (!spk_man->SetupGeneration()) {
4258  error = _("Unable to generate initial keys");
4259  return nullptr;
4260  }
4261  }
4262  }
4263  }
4264 
4265  walletInstance->chainStateFlushed(chain.getTipLocator());
4266  } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
4267  // Make it impossible to disable private keys after creation
4268  error = strprintf(_("Error loading %s: Private keys can only be "
4269  "disabled during creation"),
4270  walletFile);
4271  return nullptr;
4272  } else if (walletInstance->IsWalletFlagSet(
4273  WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
4274  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
4275  if (spk_man->HavePrivateKeys()) {
4276  warnings.push_back(
4277  strprintf(_("Warning: Private keys detected in wallet {%s} "
4278  "with disabled private keys"),
4279  walletFile));
4280  }
4281  }
4282  }
4283 
4284  if (gArgs.IsArgSet("-mintxfee")) {
4285  Amount n = Amount::zero();
4286  if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) ||
4287  n == Amount::zero()) {
4288  error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""));
4289  return nullptr;
4290  }
4291  if (n > HIGH_TX_FEE_PER_KB) {
4292  warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
4293  _("This is the minimum transaction fee you pay "
4294  "on every transaction."));
4295  }
4296  walletInstance->m_min_fee = CFeeRate(n);
4297  }
4298 
4299  if (gArgs.IsArgSet("-maxapsfee")) {
4300  Amount n = Amount::zero();
4301  if (gArgs.GetArg("-maxapsfee", "") == "-1") {
4302  n = -1 * SATOSHI;
4303  } else if (!ParseMoney(gArgs.GetArg("-maxapsfee", ""), n)) {
4304  error = AmountErrMsg("maxapsfee", gArgs.GetArg("-maxapsfee", ""));
4305  return nullptr;
4306  }
4307  if (n > HIGH_APS_FEE) {
4308  warnings.push_back(
4309  AmountHighWarn("-maxapsfee") + Untranslated(" ") +
4310  _("This is the maximum transaction fee you pay to prioritize "
4311  "partial spend avoidance over regular coin selection."));
4312  }
4313  walletInstance->m_max_aps_fee = n;
4314  }
4315 
4316  if (gArgs.IsArgSet("-fallbackfee")) {
4317  Amount nFeePerK = Amount::zero();
4318  if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
4319  error =
4320  strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"),
4321  gArgs.GetArg("-fallbackfee", ""));
4322  return nullptr;
4323  }
4324  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
4325  warnings.push_back(AmountHighWarn("-fallbackfee") +
4326  Untranslated(" ") +
4327  _("This is the transaction fee you may pay when "
4328  "fee estimates are not available."));
4329  }
4330  walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
4331  }
4332  // Disable fallback fee in case value was set to 0, enable if non-null value
4333  walletInstance->m_allow_fallback_fee =
4334  walletInstance->m_fallback_fee.GetFeePerK() != Amount::zero();
4335 
4336  if (gArgs.IsArgSet("-paytxfee")) {
4337  Amount nFeePerK = Amount::zero();
4338  if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
4339  error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""));
4340  return nullptr;
4341  }
4342  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
4343  warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
4344  _("This is the transaction fee you will pay if "
4345  "you send a transaction."));
4346  }
4347  walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
4348  if (walletInstance->m_pay_tx_fee < chain.relayMinFee()) {
4349  error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' "
4350  "(must be at least %s)"),
4351  gArgs.GetArg("-paytxfee", ""),
4352  chain.relayMinFee().ToString());
4353  return nullptr;
4354  }
4355  }
4356 
4357  if (gArgs.IsArgSet("-maxtxfee")) {
4358  Amount nMaxFee = Amount::zero();
4359  if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
4360  error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""));
4361  return nullptr;
4362  }
4363  if (nMaxFee > HIGH_MAX_TX_FEE) {
4364  warnings.push_back(_("-maxtxfee is set very high! Fees this large "
4365  "could be paid on a single transaction."));
4366  }
4367  if (CFeeRate(nMaxFee, 1000) < chain.relayMinFee()) {
4368  error = strprintf(
4369  _("Invalid amount for -maxtxfee=<amount>: '%s' (must be at "
4370  "least the minrelay fee of %s to prevent stuck "
4371  "transactions)"),
4372  gArgs.GetArg("-maxtxfee", ""), chain.relayMinFee().ToString());
4373  return nullptr;
4374  }
4375  walletInstance->m_default_max_tx_fee = nMaxFee;
4376  }
4377 
4378  if (chain.relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
4379  warnings.push_back(
4380  AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
4381  _("The wallet will avoid paying less than the minimum relay fee."));
4382  }
4383 
4384  walletInstance->m_spend_zero_conf_change =
4385  gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4386 
4387  walletInstance->m_default_address_type = DEFAULT_ADDRESS_TYPE;
4388  walletInstance->m_default_change_type = DEFAULT_CHANGE_TYPE;
4389 
4390  walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n",
4391  GetTimeMillis() - nStart);
4392 
4393  // Try to top up keypool. No-op if the wallet is locked.
4394  walletInstance->TopUpKeyPool();
4395 
4396  LOCK(walletInstance->cs_wallet);
4397 
4398  // Register wallet with validationinterface. It's done before rescan to
4399  // avoid missing block connections between end of rescan and validation
4400  // subscribing. Because of wallet lock being hold, block connection
4401  // notifications are going to be pending on the validation-side until lock
4402  // release. It's likely to have block processing duplicata (if rescan block
4403  // range overlaps with notification one) but we guarantee at least than
4404  // wallet state is correct after notifications delivery. This is temporary
4405  // until rescan and notifications delivery are unified under same interface.
4406  walletInstance->m_chain_notifications_handler =
4407  walletInstance->chain().handleNotifications(walletInstance);
4408 
4409  int rescan_height = 0;
4410  if (!gArgs.GetBoolArg("-rescan", false)) {
4411  WalletBatch batch(*walletInstance->database);
4412  CBlockLocator locator;
4413  if (batch.ReadBestBlock(locator)) {
4414  if (const std::optional<int> fork_height =
4415  chain.findLocatorFork(locator)) {
4416  rescan_height = *fork_height;
4417  }
4418  }
4419  }
4420 
4421  const std::optional<int> tip_height = chain.getHeight();
4422  if (tip_height) {
4423  walletInstance->m_last_block_processed =
4424  chain.getBlockHash(*tip_height);
4425  walletInstance->m_last_block_processed_height = *tip_height;
4426  } else {
4427  walletInstance->m_last_block_processed.SetNull();
4428  walletInstance->m_last_block_processed_height = -1;
4429  }
4430 
4431  if (tip_height && *tip_height != rescan_height) {
4432  // We can't rescan beyond non-pruned blocks, stop and throw an error.
4433  // This might happen if a user uses an old wallet within a pruned node
4434  // or if they ran -disablewallet for a longer time, then decided to
4435  // re-enable
4436  if (chain.havePruned()) {
4437  // Exit early and print an error.
4438  // If a block is pruned after this check, we will load the wallet,
4439  // but fail the rescan with a generic error.
4440  int block_height = *tip_height;
4441  while (block_height > 0 &&
4442  chain.haveBlockOnDisk(block_height - 1) &&
4443  rescan_height != block_height) {
4444  --block_height;
4445  }
4446 
4447  if (rescan_height != block_height) {
4448  error = _("Prune: last wallet synchronisation goes beyond "
4449  "pruned data. You need to -reindex (download the "
4450  "whole blockchain again in case of pruned node)");
4451  return nullptr;
4452  }
4453  }
4454 
4455  chain.initMessage(_("Rescanning...").translated);
4456  walletInstance->WalletLogPrintf(
4457  "Rescanning last %i blocks (from block %i)...\n",
4458  *tip_height - rescan_height, rescan_height);
4459 
4460  // No need to read and scan block if block was created before our wallet
4461  // birthday (as adjusted for block time variability)
4462  std::optional<int64_t> time_first_key;
4463  for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
4464  int64_t time = spk_man->GetTimeFirstKey();
4465  if (!time_first_key || time < *time_first_key) {
4466  time_first_key = time;
4467  }
4468  }
4469  if (time_first_key) {
4470  if (std::optional<int> first_block =
4472  *time_first_key - TIMESTAMP_WINDOW, rescan_height,
4473  nullptr)) {
4474  rescan_height = *first_block;
4475  }
4476  }
4477 
4478  {
4479  WalletRescanReserver reserver(*walletInstance);
4480  if (!reserver.reserve() ||
4481  (ScanResult::SUCCESS !=
4482  walletInstance
4483  ->ScanForWalletTransactions(
4484  chain.getBlockHash(rescan_height), rescan_height,
4485  {} /* max height */, reserver, true /* update */)
4486  .status)) {
4487  error = _("Failed to rescan the wallet during initialization");
4488  return nullptr;
4489  }
4490  }
4491  walletInstance->chainStateFlushed(chain.getTipLocator());
4492  walletInstance->database->IncrementUpdateCounter();
4493 
4494  // Restore wallet transaction metadata after -zapwallettxes=1
4495  if (gArgs.GetBoolArg("-zapwallettxes", false) &&
4496  gArgs.GetArg("-zapwallettxes", "1") != "2") {
4497  WalletBatch batch(*walletInstance->database);
4498 
4499  for (const CWalletTx &wtxOld : vWtx) {
4500  const TxId txid = wtxOld.GetId();
4501  std::map<TxId, CWalletTx>::iterator mi =
4502  walletInstance->mapWallet.find(txid);
4503  if (mi != walletInstance->mapWallet.end()) {
4504  const CWalletTx *copyFrom = &wtxOld;
4505  CWalletTx *copyTo = &mi->second;
4506  copyTo->mapValue = copyFrom->mapValue;
4507  copyTo->vOrderForm = copyFrom->vOrderForm;
4508  copyTo->nTimeReceived = copyFrom->nTimeReceived;
4509  copyTo->nTimeSmart = copyFrom->nTimeSmart;
4510  copyTo->fFromMe = copyFrom->fFromMe;
4511  copyTo->nOrderPos = copyFrom->nOrderPos;
4512  batch.WriteTx(*copyTo);
4513  }
4514  }
4515  }
4516  }
4517 
4518  {
4519  LOCK(cs_wallets);
4520  for (auto &load_wallet : g_load_wallet_fns) {
4521  load_wallet(interfaces::MakeWallet(walletInstance));
4522  }
4523  }
4524 
4525  walletInstance->SetBroadcastTransactions(
4526  gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4527 
4528  walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n",
4529  walletInstance->GetKeyPoolSize());
4530  walletInstance->WalletLogPrintf("mapWallet.size() = %u\n",
4531  walletInstance->mapWallet.size());
4532  walletInstance->WalletLogPrintf("m_address_book.size() = %u\n",
4533  walletInstance->m_address_book.size());
4534 
4535  return walletInstance;
4536 }
4537 
4538 const CAddressBookData *
4540  bool allow_change) const {
4541  const auto &address_book_it = m_address_book.find(dest);
4542  if (address_book_it == m_address_book.end()) {
4543  return nullptr;
4544  }
4545  if ((!allow_change) && address_book_it->second.IsChange()) {
4546  return nullptr;
4547  }
4548  return &address_book_it->second;
4549 }
4550 
4552  std::vector<bilingual_str> &warnings) {
4553  int prev_version = GetVersion();
4554  int nMaxVersion = version;
4555  // The -upgradewallet without argument case
4556  if (nMaxVersion == 0) {
4557  WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
4558  nMaxVersion = FEATURE_LATEST;
4559  // permanently upgrade the wallet immediately
4560  SetMinVersion(FEATURE_LATEST);
4561  } else {
4562  WalletLogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
4563  }
4564 
4565  if (nMaxVersion < GetVersion()) {
4566  error = _("Cannot downgrade wallet");
4567  return false;
4568  }
4569 
4570  SetMaxVersion(nMaxVersion);
4571 
4572  LOCK(cs_wallet);
4573 
4574  // Do not upgrade versions to any version between HD_SPLIT and
4575  // FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
4576  int max_version = GetVersion();
4577  if (!CanSupportFeature(FEATURE_HD_SPLIT) &&
4578  max_version >= FEATURE_HD_SPLIT &&
4579  max_version < FEATURE_PRE_SPLIT_KEYPOOL) {
4580  error = _("Cannot upgrade a non HD split wallet without upgrading to "
4581  "support pre split keypool. Please use version 200300 or no "
4582  "version specified.");
4583  return false;
4584  }
4585 
4586  for (auto spk_man : GetActiveScriptPubKeyMans()) {
4587  if (!spk_man->Upgrade(prev_version, error)) {
4588  return false;
4589  }
4590  }
4591 
4592  return true;
4593 }
4594 
4596  LOCK(cs_wallet);
4597 
4598  // Add wallet transactions that aren't already in a block to mempool.
4599  // Do this here as mempool requires genesis block to be loaded.
4600  ReacceptWalletTransactions();
4601 
4602  // Update wallet transactions with current mempool transactions.
4603  chain().requestMempoolTransactions(*this);
4604 }
4605 
4606 bool CWallet::BackupWallet(const std::string &strDest) const {
4607  return database->Backup(strDest);
4608 }
4609 
4611  nTime = GetTime();
4612  fInternal = false;
4613  m_pre_split = false;
4614 }
4615 
4616 CKeyPool::CKeyPool(const CPubKey &vchPubKeyIn, bool internalIn) {
4617  nTime = GetTime();
4618  vchPubKey = vchPubKeyIn;
4619  fInternal = internalIn;
4620  m_pre_split = false;
4621 }
4622 
4624  assert(pwallet != nullptr);
4625  AssertLockHeld(pwallet->cs_wallet);
4626  if (isUnconfirmed() || isAbandoned()) {
4627  return 0;
4628  }
4629 
4630  return (pwallet->GetLastBlockHeight() - m_confirm.block_height + 1) *
4631  (isConflicted() ? -1 : 1);
4632 }
4633 
4635  if (!IsCoinBase()) {
4636  return 0;
4637  }
4638 
4639  int chain_depth = GetDepthInMainChain();
4640  // coinbase tx should not be conflicted
4641  assert(chain_depth >= 0);
4642  return std::max(0, (COINBASE_MATURITY + 1) - chain_depth);
4643 }
4644 
4646  // note GetBlocksToMaturity is 0 for non-coinbase tx
4647  return GetBlocksToMaturity() > 0;
4648 }
4649 
4650 std::vector<OutputGroup>
4651 CWallet::GroupOutputs(const std::vector<COutput> &outputs, bool single_coin,
4652  const size_t max_ancestors) const {
4653  std::vector<OutputGroup> groups;
4654  std::map<CTxDestination, OutputGroup> gmap;
4655  std::set<CTxDestination> full_groups;
4656 
4657  for (const auto &output : outputs) {
4658  if (output.fSpendable) {
4659  CTxDestination dst;
4660  CInputCoin input_coin = output.GetInputCoin();
4661 
4662  size_t ancestors, descendants;
4663  chain().getTransactionAncestry(output.tx->GetId(), ancestors,
4664  descendants);
4665  if (!single_coin &&
4666  ExtractDestination(output.tx->tx->vout[output.i].scriptPubKey,
4667  dst)) {
4668  auto it = gmap.find(dst);
4669  if (it != gmap.end()) {
4670  // Limit output groups to no more than
4671  // OUTPUT_GROUP_MAX_ENTRIES number of entries, to protect
4672  // against inadvertently creating a too-large transaction
4673  // when using -avoidpartialspends to prevent breaking
4674  // consensus or surprising users with a very high amount of
4675  // fees.
4676  if (it->second.m_outputs.size() >=
4678  groups.push_back(it->second);
4679  it->second = OutputGroup{};
4680  full_groups.insert(dst);
4681  }
4682  it->second.Insert(input_coin, output.nDepth,
4683  output.tx->IsFromMe(ISMINE_ALL),
4684  ancestors, descendants);
4685  } else {
4686  gmap[dst].Insert(input_coin, output.nDepth,
4687  output.tx->IsFromMe(ISMINE_ALL), ancestors,
4688  descendants);
4689  }
4690  } else {
4691  groups.emplace_back(input_coin, output.nDepth,
4692  output.tx->IsFromMe(ISMINE_ALL), ancestors,
4693  descendants);
4694  }
4695  }
4696  }
4697  if (!single_coin) {
4698  for (auto &it : gmap) {
4699  auto &group = it.second;
4700  if (full_groups.count(it.first) > 0) {
4701  // Make this unattractive as we want coin selection to avoid it
4702  // if possible
4703  group.m_ancestors = max_ancestors - 1;
4704  }
4705  groups.push_back(group);
4706  }
4707  }
4708  return groups;
4709 }
4710 
4711 bool CWallet::IsCrypted() const {
4712  return HasEncryptionKeys();
4713 }
4714 
4715 bool CWallet::IsLocked() const {
4716  if (!IsCrypted()) {
4717  return false;
4718  }
4719  LOCK(cs_wallet);
4720  return vMasterKey.empty();
4721 }
4722 
4724  if (!IsCrypted()) {
4725  return false;
4726  }
4727 
4728  {
4729  LOCK(cs_wallet);
4730  vMasterKey.clear();
4731  }
4732 
4733  NotifyStatusChanged(this);
4734  return true;
4735 }
4736 
4737 bool CWallet::Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys) {
4738  {
4739  LOCK(cs_wallet);
4740  for (const auto &spk_man_pair : m_spk_managers) {
4741  if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn,
4742  accept_no_keys)) {
4743  return false;
4744  }
4745  }
4746  vMasterKey = vMasterKeyIn;
4747  }
4748  NotifyStatusChanged(this);
4749  return true;
4750 }
4751 
4752 std::set<ScriptPubKeyMan *> CWallet::GetActiveScriptPubKeyMans() const {
4753  std::set<ScriptPubKeyMan *> spk_mans;
4754  for (bool internal : {false, true}) {
4755  for (OutputType t : OUTPUT_TYPES) {
4756  auto spk_man = GetScriptPubKeyMan(t, internal);
4757  if (spk_man) {
4758  spk_mans.insert(spk_man);
4759  }
4760  }
4761  }
4762  return spk_mans;
4763 }
4764 
4765 std::set<ScriptPubKeyMan *> CWallet::GetAllScriptPubKeyMans() const {
4766  std::set<ScriptPubKeyMan *> spk_mans;
4767  for (const auto &spk_man_pair : m_spk_managers) {
4768  spk_mans.insert(spk_man_pair.second.get());
4769  }
4770  return spk_mans;
4771 }
4772 
4774  bool internal) const {
4775  const std::map<OutputType, ScriptPubKeyMan *> &spk_managers =
4776  internal ? m_internal_spk_managers : m_external_spk_managers;
4777  std::map<OutputType, ScriptPubKeyMan *>::const_iterator it =
4778  spk_managers.find(type);
4779  if (it == spk_managers.end()) {
4780  WalletLogPrintf(
4781  "%s scriptPubKey Manager for output type %d does not exist\n",
4782  internal ? "Internal" : "External", static_cast<int>(type));
4783  return nullptr;
4784  }
4785  return it->second;
4786 }
4787 
4788 std::set<ScriptPubKeyMan *>
4790  SignatureData &sigdata) const {
4791  std::set<ScriptPubKeyMan *> spk_mans;
4792  for (const auto &spk_man_pair : m_spk_managers) {
4793  if (spk_man_pair.second->CanProvide(script, sigdata)) {
4794  spk_mans.insert(spk_man_pair.second.get());
4795  }
4796  }
4797  return spk_mans;
4798 }
4799 
4801  SignatureData sigdata;
4802  for (const auto &spk_man_pair : m_spk_managers) {
4803  if (spk_man_pair.second->CanProvide(script, sigdata)) {
4804  return spk_man_pair.second.get();
4805  }
4806  }
4807  return nullptr;
4808 }
4809 
4811  if (m_spk_managers.count(id) > 0) {
4812  return m_spk_managers.at(id).get();
4813  }
4814  return nullptr;
4815 }
4816 
4817 std::unique_ptr<SigningProvider>
4818 CWallet::GetSolvingProvider(const CScript &script) const {
4819  SignatureData sigdata;
4820  return GetSolvingProvider(script, sigdata);
4821 }
4822 
4823 std::unique_ptr<SigningProvider>
4825  SignatureData &sigdata) const {
4826  for (const auto &spk_man_pair : m_spk_managers) {
4827  if (spk_man_pair.second->CanProvide(script, sigdata)) {
4828  return spk_man_pair.second->GetSolvingProvider(script);
4829  }
4830  }
4831  return nullptr;
4832 }
4833 
4835  if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
4836  return nullptr;
4837  }
4838  // Legacy wallets only have one ScriptPubKeyMan which is a
4839  // LegacyScriptPubKeyMan. Everything in m_internal_spk_managers and
4840  // m_external_spk_managers point to the same legacyScriptPubKeyMan.
4841  auto it = m_internal_spk_managers.find(OutputType::LEGACY);
4842  if (it == m_internal_spk_managers.end()) {
4843  return nullptr;
4844  }
4845  return dynamic_cast<LegacyScriptPubKeyMan *>(it->second);
4846 }
4847 
4849  SetupLegacyScriptPubKeyMan();
4850  return GetLegacyScriptPubKeyMan();
4851 }
4852 
4854  if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() ||
4855  !m_spk_managers.empty() || IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
4856  return;
4857  }
4858 
4859  auto spk_manager =
4860  std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this));
4861  for (const auto &type : OUTPUT_TYPES) {
4862  m_internal_spk_managers[type] = spk_manager.get();
4863  m_external_spk_managers[type] = spk_manager.get();
4864  }
4865  m_spk_managers[spk_manager->GetID()] = std::move(spk_manager);
4866 }
4867 
4869  return vMasterKey;
4870 }
4871 
4873  return !mapMasterKeys.empty();
4874 }
4875 
4877  for (const auto &spk_man : GetActiveScriptPubKeyMans()) {
4878  spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
4879  spk_man->NotifyCanGetAddressesChanged.connect(
4881  }
4882 }
4883 
4885  WalletDescriptor &desc) {
4886  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(
4887  new DescriptorScriptPubKeyMan(*this, desc));
4888  m_spk_managers[id] = std::move(spk_manager);
4889 }
4890 
4892  AssertLockHeld(cs_wallet);
4893 
4894  // Make a seed
4895  CKey seed_key;
4896  seed_key.MakeNewKey(true);
4897  CPubKey seed = seed_key.GetPubKey();
4898  assert(seed_key.VerifyPubKey(seed));
4899 
4900  // Get the extended key
4901  CExtKey master_key;
4902  master_key.SetSeed(seed_key.begin(), seed_key.size());
4903 
4904  for (bool internal : {false, true}) {
4905  for (OutputType t : OUTPUT_TYPES) {
4906  auto spk_manager =
4907  std::make_unique<DescriptorScriptPubKeyMan>(*this, t, internal);
4908  if (IsCrypted()) {
4909  if (IsLocked()) {
4910  throw std::runtime_error(
4911  std::string(__func__) +
4912  ": Wallet is locked, cannot setup new descriptors");
4913  }
4914  if (!spk_manager->CheckDecryptionKey(vMasterKey) &&
4915  !spk_manager->Encrypt(vMasterKey, nullptr)) {
4916  throw std::runtime_error(
4917  std::string(__func__) +
4918  ": Could not encrypt new descriptors");
4919  }
4920  }
4921  spk_manager->SetupDescriptorGeneration(master_key);
4922  uint256 id = spk_manager->GetID();
4923  m_spk_managers[id] = std::move(spk_manager);
4924  SetActiveScriptPubKeyMan(id, t, internal);
4925  }
4926  }
4927 }
4928 
4930  bool internal, bool memonly) {
4931  WalletLogPrintf(
4932  "Setting spkMan to active: id = %s, type = %d, internal = %d\n",
4933  id.ToString(), static_cast<int>(type), static_cast<int>(internal));
4934  auto &spk_mans =
4935  internal ? m_internal_spk_managers : m_external_spk_managers;
4936  auto spk_man = m_spk_managers.at(id).get();
4937  spk_man->SetType(type, internal);
4938  spk_mans[type] = spk_man;
4939 
4940  if (!memonly) {
4941  WalletBatch batch(*database);
4942  if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id,
4943  internal)) {
4944  throw std::runtime_error(
4945  std::string(__func__) +
4946  ": writing active ScriptPubKeyMan id failed");
4947  }
4948  }
4950 }
4951 
4952 bool CWallet::IsLegacy() const {
4953  if (m_internal_spk_managers.count(OutputType::LEGACY) == 0) {
4954  return false;
4955  }
4956  auto spk_man = dynamic_cast<LegacyScriptPubKeyMan *>(
4957  m_internal_spk_managers.at(OutputType::LEGACY));
4958  return spk_man != nullptr;
4959 }
4960 
4963  for (auto &spk_man_pair : m_spk_managers) {
4964  // Try to downcast to DescriptorScriptPubKeyMan then check if the
4965  // descriptors match
4966  DescriptorScriptPubKeyMan *spk_manager =
4967  dynamic_cast<DescriptorScriptPubKeyMan *>(
4968  spk_man_pair.second.get());
4969  if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
4970  return spk_manager;
4971  }
4972  }
4973 
4974  return nullptr;
4975 }
4976 
4979  const FlatSigningProvider &signing_provider,
4980  const std::string &label) {
4981  if (!IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
4982  WalletLogPrintf(
4983  "Cannot add WalletDescriptor to a non-descriptor wallet\n");
4984  return nullptr;
4985  }
4986 
4987  LOCK(cs_wallet);
4988  auto new_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(*this, desc);
4989 
4990  // If we already have this descriptor, remove it from the maps but add the
4991  // existing cache to desc
4992  auto old_spk_man = GetDescriptorScriptPubKeyMan(desc);
4993  if (old_spk_man) {
4994  WalletLogPrintf("Update existing descriptor: %s\n",
4995  desc.descriptor->ToString());
4996 
4997  {
4998  LOCK(old_spk_man->cs_desc_man);
4999  new_spk_man->SetCache(old_spk_man->GetWalletDescriptor().cache);
5000  }
5001 
5002  // Remove from maps of active spkMans
5003  auto old_spk_man_id = old_spk_man->GetID();
5004  for (bool internal : {false, true}) {
5005  for (OutputType t : OUTPUT_TYPES) {
5006  auto active_spk_man = GetScriptPubKeyMan(t, internal);
5007  if (active_spk_man &&
5008  active_spk_man->GetID() == old_spk_man_id) {
5009  if (internal) {
5010  m_internal_spk_managers.erase(t);
5011  } else {
5012  m_external_spk_managers.erase(t);
5013  }
5014  break;
5015  }
5016  }
5017  }
5018  m_spk_managers.erase(old_spk_man_id);
5019  }
5020 
5021  // Add the private keys to the descriptor
5022  for (const auto &entry : signing_provider.keys) {
5023  const CKey &key = entry.second;
5024  new_spk_man->AddDescriptorKey(key, key.GetPubKey());
5025  }
5026 
5027  // Top up key pool, the manager will generate new scriptPubKeys internally
5028  new_spk_man->TopUp();
5029 
5030  // Apply the label if necessary
5031  // Note: we disable labels for ranged descriptors
5032  if (!desc.descriptor->IsRange()) {
5033  auto script_pub_keys = new_spk_man->GetScriptPubKeys();
5034  if (script_pub_keys.empty()) {
5035  WalletLogPrintf(
5036  "Could not generate scriptPubKeys (cache is empty)\n");
5037  return nullptr;
5038  }
5039 
5040  CTxDestination dest;
5041  if (ExtractDestination(script_pub_keys.at(0), dest)) {
5042  SetAddressBook(dest, label, "receive");
5043  }
5044  }
5045 
5046  // Save the descriptor to memory
5047  auto ret = new_spk_man.get();
5048  m_spk_managers[new_spk_man->GetID()] = std::move(new_spk_man);
5049 
5050  // Save the descriptor to DB
5051  ret->WriteDescriptor();
5052 
5053  return ret;
5054 }
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: wallet.cpp:2169
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:338
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:996
uint32_t GetN() const
Definition: transaction.h:44
AmountType
Definition: wallet.h:342
bool AddDestData(WalletBatch &batch, const CTxDestination &dest, const std::string &key, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a destination data tuple to the store, and saves it to disk When adding new fields, take care to consider how DelAddressBook should handle it!
Definition: wallet.cpp:4064
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:4853
const fs::path & GetPath() const
Get wallet absolute path.
Definition: walletutil.h:92
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:43
void SetActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal, bool memonly=false)
Sets the active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:4929
Amount m_watchonly_immature
Definition: wallet.h:1090
bool IsWalletFlagSet(uint64_t flag) const override
Check if a certain wallet flag is set.
Definition: wallet.cpp:1494
Amount GetImmatureWatchOnlyCredit(const bool fUseCache=true) const
Definition: wallet.cpp:2086
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:390
Amount m_mine_untrusted_pending
Untrusted, but in mempool (pending)
Definition: wallet.h:1085
void blockConnected(const CBlock &block, int height) override
Definition: wallet.cpp:1221
int i
Definition: wallet.h:601
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:641
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3612
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:495
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:37
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:4952
Amount effective_value
Definition: coinselection.h:39
static std::vector< std::shared_ptr< CWallet > > vpwallets GUARDED_BY(cs_wallets)
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: wallet.h:358
static constexpr Amount zero()
Definition: amount.h:35
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:152
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:30
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:174
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:226
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:50
void SetNull()
Definition: uint256.h:35
static uint32_t GetLocktimeForNewTransaction(interfaces::Chain &chain, const BlockHash &block_hash, int block_height)
Return a height-based locktime for new transactions (uses the height of the current chain tip unless ...
Definition: wallet.cpp:2946
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:101
bool isConfirmed() const
Definition: wallet.h:589
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:110
TransactionError FillPSBT(PartiallySignedTransaction &psbtx, bool &complete, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=true) const
Fills out a PSBT with information from the wallet.
Definition: wallet.cpp:2808
CScript scriptPubKey
Definition: transaction.h:144
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
Definition: wallet.cpp:312
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:12
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3909
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:129
bool TransactionCanBeAbandoned(const TxId &txid) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1055
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:87
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:4595
std::map< CTxDestination, std::vector< COutput > > ListCoins() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Return list of available coins and locked coins grouped by non-change output address.
Definition: wallet.cpp:2449
size_t change_output_size
Definition: wallet.h:656
A UTXO entry.
Definition: coins.h:27
Bilingual messages:
Definition: translation.h:17
Definition: block.h:62
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:59
Amount GetAvailableBalance(const CCoinControl *coinControl=nullptr) const
Definition: wallet.cpp:2286
static Mutex g_wallet_release_mutex
Definition: wallet.cpp:108
virtual BlockHash getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:50
Encryption/decryption context with key information.
Definition: crypter.h:70
RecursiveMutex cs_KeyStore
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:526
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:303
const CTxOut & FindNonChangeParentOutput(const CTransaction &tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Find non-change parent output.
Definition: wallet.cpp:2499
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
std::vector< uint8_t, secure_allocator< uint8_t > > CKeyingMaterial
Definition: crypter.h:63
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1373
std::optional< int > last_scanned_height
Definition: wallet.h:1065
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:1163
constexpr OutputType DEFAULT_CHANGE_TYPE
Default for -changetype.
Definition: wallet.h:126
bool FundTransaction(CMutableTransaction &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, CCoinControl coinControl)
Insert additional inputs into the transaction by calling CreateTransaction();.
Definition: wallet.cpp:2870
bool UpgradeWallet(int version, bilingual_str &error, std::vector< bilingual_str > &warnings)
Upgrade the wallet.
Definition: wallet.cpp:4551
std::map< CKeyID, CKey > keys
bool use_max_sig
Whether to use the maximum sized, 72 byte signature when calculating the size of the input spend...
Definition: wallet.h:621
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:197
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(Amount::zero()), 0)
SigningResult
Definition: message.h:47
void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1905
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
const char * prefix
Definition: rest.cpp:754
Definition: key.h:158
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key...
Definition: crypter.h:31
bool EraseDestData(const CTxDestination &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:974
virtual bool isInitialBlockDownload()=0
Check if in IBD.
int64_t GetOldestKeyPoolTime() const
Definition: wallet.cpp:3668
void ListSelected(std::vector< COutPoint > &vOutpoints) const
Definition: coincontrol.h:62
bool Lock()
Definition: wallet.cpp:4723
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:34
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:339
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:269
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:418
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:56
Definition: amount.h:17
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:338
bool isConflicted() const
Definition: wallet.h:581
Balance GetBalance(int min_depth=0, bool avoid_reuse=true) const
Definition: wallet.cpp:2258
void blockDisconnected(const CBlock &block, int height) override
Definition: wallet.cpp:1235
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)...
Definition: consensus.h:32
void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(cs_main
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
Definition: wallet.cpp:1257
bool HasSelected() const
Definition: coincontrol.h:50
bool SelectCoinsMinConf(const Amount nTargetValue, const CoinEligibilityFilter &eligibility_filter, std::vector< OutputGroup > groups, std::set< CInputCoin > &setCoinsRet, Amount &nValueRet, const CoinSelectionParams &coin_selection_params, bool &bnb_used) const
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
Definition: wallet.cpp:2517
const CKeyingMaterial & GetEncryptionKey() const override
Definition: wallet.cpp:4868
bool CanGetAddresses(bool internal=false) const
Returns true if the wallet can give out new addresses.
Definition: wallet.cpp:1453
bool SetMaxVersion(int nVersion)
change which version we&#39;re allowed to upgrade to (note that this does not immediately imply upgrading...
Definition: wallet.cpp:466
const TxId & GetTxId() const
Definition: transaction.h:43
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:420
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Definition: system.h:476
int m_min_depth
Minimum chain depth value for coin availability.
Definition: coincontrol.h:42
static constexpr Amount SATOSHI
Definition: amount.h:151
static const Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:165
int m_input_bytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: coinselection.h:45
std::vector< CTxOut > vout
Definition: transaction.h:300
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:486
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: wallet.cpp:82
bool IsLocked() const override
Definition: wallet.cpp:4715
bool SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const Amount &target_value, const Amount &cost_of_change, std::set< CInputCoin > &out_set, Amount &value_ret, const Amount not_input_fees)
std::string translated
Definition: translation.h:19
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2247
A version of CTransaction with the PSBT format.
Definition: psbt.h:335
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:48
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:992
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:498
constexpr Amount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:107
bool IsCoinBase() const
Definition: wallet.h:594
ScriptPubKeyMan * AddWalletDescriptor(WalletDescriptor &desc, const FlatSigningProvider &signing_provider, const std::string &label)
Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type.
Definition: wallet.cpp:4978
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:4083
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: walletdb.cpp:916
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:1064
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:39
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:96
static RecursiveMutex cs_wallets
Definition: wallet.cpp:46
bool WriteName(const CTxDestination &address, const std::string &strName)
Definition: walletdb.cpp:57
WalletCreationStatus
Definition: wallet.h:68
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:654
isminetype IsMine(const CTxDestination &dest) const
Definition: wallet.cpp:1304
void chainStateFlushed(const CBlockLocator &loc) override
Definition: wallet.cpp:433
static bool Verify(const CChainParams &chainParams, interfaces::Chain &chain, const WalletLocation &location, bilingual_str &error_string, std::vector< bilingual_str > &warnings)
Verify wallet naming and perform salvage on the wallet if required.
Definition: wallet.cpp:4119
bool isUnconfirmed() const
Definition: wallet.h:585
uint256 & UINT256_ONE()
Definition: uint256.cpp:70
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:49
Amount GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.cpp:2031
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:610
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:1071
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:988
enum CWallet::ScanResult::@23 status
bool Exists() const
Return whether the wallet exists.
Definition: walletutil.cpp:114
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:36
bool IsChange(const CTxOut &txout) const
Definition: wallet.cpp:1326
bool IsNull() const
Definition: uint256.h:26
constexpr Amount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:95
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1562
ScanResult ScanForWalletTransactions(const BlockHash &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:1776
OutputType
Definition: outputtype.h:17
void LoadToWallet(CWalletTx &wtxIn) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:952
bool fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
Definition: wallet.h:336
Coin Control Features.
Definition: coincontrol.h:19
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr, bool fExplicit=false) override
signify that a particular wallet feature is now used.
Definition: wallet.cpp:438
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:14
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:4606
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< uint8_t > &vchCiphertext) const
Definition: crypter.cpp:79
const std::vector< CTxIn > vin
Definition: transaction.h:227
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:4818
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1193
std::string ToString() const
Definition: wallet.cpp:291
bool KnapsackSolver(const Amount nTargetValue, std::vector< OutputGroup > &groups, std::set< CInputCoin > &setCoinsRet, Amount &nValueRet)
bool CreateTransactionInternal(const std::vector< CRecipient > &vecSend, CTransactionRef &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, bool sign)
Definition: wallet.cpp:3008
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Definition: wallet.cpp:2857
void SetSpentKeyState(WalletBatch &batch, const TxId &txid, unsigned int n, bool used, std::set< CTxDestination > &tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:805
bool IsNull() const
Definition: transaction.h:164
Access to the wallet database.
Definition: walletdb.h:183
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
Definition: script.h:552
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:316
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:4765
std::vector< CTxIn > vin
Definition: transaction.h:299
bool GetNewChangeDestination(const OutputType type, CTxDestination &dest, std::string &error)
Definition: wallet.cpp:3651
Amount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:14
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
Definition: coincontrol.h:38
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...
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:167
size_t change_spend_size
Definition: wallet.h:657
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:1000
bool MoneyRange(const Amount nValue)
Definition: amount.h:166
CTxOut utxo
Definition: psbt.h:44
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3561
bool done
bool HasEncryptionKeys() const override
Definition: wallet.cpp:4872
void MarkDirty()
Definition: wallet.cpp:798
DBErrors ReorderTransactions()
Definition: wallet.cpp:730
Amount GetAvailableCredit(bool fUseCache=true, const isminefilter &filter=ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS
Definition: wallet.cpp:2039
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in=false)
Definition: wallet.h:630
Amount GetCachableAmount(AmountType type, const isminefilter &filter, bool recalculate=false) const
Definition: wallet.cpp:1984
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
static void NotifyCanGetAddressesChanged(WalletModel *walletmodel)
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1476
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:3568
void Insert(const CInputCoin &output, int depth, bool from_me, size_t ancestors, size_t descendants)
constexpr Amount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:110
Amount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:51
bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig=false) const
Definition: wallet.cpp:1521
void transactionRemovedFromMempool(const CTransactionRef &ptx) override
Definition: wallet.cpp:1213
const int DEFAULT_MAX_DEPTH
Definition: coincontrol.h:13
static std::set< std::string > g_unloading_wallet_set
Definition: wallet.cpp:110
virtual std::optional< int > findFirstBlockWithTimeAndHeight(int64_t time, int height, BlockHash *hash)=0
Return height of the first block in the chain with timestamp equal or greater than the given time and...
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:4022
void UnsetBlankWalletFlag(WalletBatch &batch) override
Unset the blank wallet flag and saves it to disk.
Definition: wallet.cpp:1490
A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet...
void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string >> orderForm)
Submit the transaction to the node&#39;s mempool and then relay to peers.
Definition: wallet.cpp:3415
Amount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Returns amount of debit if the input matches the filter, otherwise returns 0.
Definition: wallet.cpp:1284
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:3459
std::map< CTxDestination, Amount > GetAddressBalances() const
Definition: wallet.cpp:3698
int nDepth
Definition: wallet.h:602
const std::string & GetName() const
Get wallet name.
Definition: walletutil.h:89
void SetSeed(const uint8_t *seed, unsigned int nSeedLen)
Definition: key.cpp:386
Confirmation m_confirm
Definition: wallet.h:414
static std::shared_ptr< CWallet > CreateWalletFromFile(const CChainParams &chainParams, interfaces::Chain &chain, const WalletLocation &location, bilingual_str &error, std::vector< bilingual_str > &warnings, uint64_t wallet_creation_flags=0)
Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error...
Definition: wallet.cpp:4170
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< uint8_t > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:41
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:4789
bool IsLockedCoin(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3919
DescriptorScriptPubKeyMan * GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const
Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet...
Definition: wallet.cpp:4962
void MarkConflicted(const BlockHash &hashBlock, int conflicting_height, const TxId &txid)
Mark a transaction (and its in-wallet descendants) as conflicting with a particular block...
Definition: wallet.cpp:1130
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:1437
bool AbandonTransaction(const TxId &txid)
Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent...
Definition: wallet.cpp:1071
Amount GetCredit(const isminefilter &filter) const
Definition: wallet.cpp:2011
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:996
DBErrors ZapSelectTx(std::vector< TxId > &txIdsIn, std::vector< TxId > &txIdsOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3489
An input of a transaction.
Definition: transaction.h:67
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:4834
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3934
bool WritePurpose(const CTxDestination &address, const std::string &purpose)
Definition: walletdb.cpp:78
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet, bool use_max_sig)
Definition: wallet.cpp:1650
bool IsHDEnabled() const
Definition: wallet.cpp:1444
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:43
bool InMempool() const
Definition: wallet.cpp:2105
bool m_add_inputs
If false, only selected inputs are used.
Definition: coincontrol.h:25
static void NotifyAddressBookChanged(WalletModel *walletmodel, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:55
fs::path WalletDataFilePath(const fs::path &wallet_path)
Given a wallet directory path or legacy file path, return path to main data file in the wallet databa...
Definition: db.cpp:27
CKeyPool()
Definition: wallet.cpp:4610
static const BlockHash ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned, only used at serialization/deserializat...
Definition: wallet.h:288
CTxDestination destChange
Definition: coincontrol.h:21
bilingual_str AmountHighWarn(const std::string &optname)
Definition: error.cpp:46
Fast randomness source.
Definition: random.h:111
void Select(const COutPoint &output)
Definition: coincontrol.h:56
An encapsulated public key.
Definition: pubkey.h:31
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:28
Amount GetCredit(const CTxOut &txout, const isminefilter &filter) const
Definition: wallet.cpp:1316
int GetBlocksToMaturity() const
Definition: wallet.cpp:4634
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, Amount &nFee, const isminefilter &filter) const
Definition: wallet.cpp:1660
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
Definition: wallet.h:661
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3914
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:183
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:102
const std::vector< CTxOut > vout
Definition: transaction.h:228
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: walletutil.h:67
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:142
uint8_t isminefilter
Definition: wallet.h:38
const int DEFAULT_MIN_DEPTH
Definition: coincontrol.h:12
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
Definition: wallet.cpp:514
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1572
bool EraseName(const CTxDestination &address)
Definition: walletdb.cpp:67
bool IsTrusted() const
Definition: wallet.cpp:2109
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
Definition: coincontrol.h:40
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: wallet.cpp:98
bool EraseDestData(WalletBatch &batch, const CTxDestination &dest, const std::string &key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Erases a destination data tuple in the store and on disk.
Definition: wallet.cpp:4074
const Config & GetConfig()
Definition: config.cpp:34
Amount m_watchonly_trusted
Definition: wallet.h:1088
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:1596
A structure for PSBTs which contain per-input information.
Definition: psbt.h:43
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:99
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:4848
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:123
isminetype
IsMine() return codes.
Definition: ismine.h:18
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:82
WalletCreationStatus CreateWallet(const CChainParams &params, interfaces::Chain &chain, const SecureString &passphrase, uint64_t wallet_creation_flags, const std::string &name, bilingual_str &error, std::vector< bilingual_str > &warnings, std::shared_ptr< CWallet > &result)
Definition: wallet.cpp:191
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:181
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:4773
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:4884
#define WAIT_LOCK(cs, name)
Definition: sync.h:238
An output of a transaction.
Definition: transaction.h:141
uint8_t * begin()
Definition: uint256.h:76
std::string ToString() const
Definition: uint256.h:74
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:1582
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:246
Descriptor with some wallet metadata.
Definition: walletutil.h:99
static void NotifyTransactionChanged(TransactionTableModel *ttm, const TxId &txid, ChangeType status)
bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly)
Overwrite all flags by the given uint64_t.
Definition: wallet.cpp:1498
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: dummywallet.cpp:76
BlockHash hashBlock
Definition: wallet.h:407
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
bool HasWalletSpend(const TxId &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:508
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:339
size_t tx_noinputs_size
Definition: wallet.h:659
const uint8_t * begin() const
Definition: key.h:83
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:318
bool IsAllFromMe(const CTransaction &tx, const isminefilter &filter) const
Returns whether all of the inputs match the filter.
Definition: wallet.cpp:1391
Amount GetChange(const CTxOut &txout) const
Definition: wallet.cpp:1354
static const size_t OUTPUT_GROUP_MAX_ENTRIES
Definition: wallet.cpp:152
void ConnectScriptPubKeyManNotifiers()
Connect the signals from ScriptPubKeyMans to the signals in CWallet.
Definition: wallet.cpp:4876
Special output type for change outputs only.
std::vector< PSBTInput > inputs
Definition: psbt.h:337
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:261
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
Definition: wallet.cpp:857
static std::unique_ptr< BerkeleyDatabase > Create(const fs::path &path)
Return object for accessing database at specified path.
Definition: bdb.h:125
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Return implementation of Wallet interface.
Definition: dummywallet.cpp:84
void updatedBlockTip() override
Definition: wallet.cpp:1253
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:518
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1554
bool HasWalletDescriptor(const WalletDescriptor &desc) const
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:280
std::shared_ptr< CWallet > LoadWallet(const CChainParams &chainParams, interfaces::Chain &chain, const WalletLocation &location, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:154
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3601
std::vector< uint8_t > vchCryptedKey
Definition: crypter.h:33
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Check whether we know how to sign for an output like this, assuming we have all private keys...
Definition: sign.cpp:423
static void ReleaseWallet(CWallet *wallet)
Definition: wallet.cpp:113
static Amount balance
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3925
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:26
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
Amount GetChange() const
Definition: wallet.cpp:2095
bool IsImmatureCoinBase() const
Definition: wallet.cpp:4645
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:3678
Amount m_watchonly_untrusted_pending
Definition: wallet.h:1089
int flags
Definition: bitcoin-tx.cpp:529
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1260
void SyncTransaction(const CTransactionRef &tx, CWalletTx::Confirmation confirm, bool update_tx=true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
Definition: wallet.cpp:1187
const std::string & FormatOutputType(OutputType type)
Definition: outputtype.cpp:27
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
Definition: wallet.cpp:786
std::vector< OutputGroup > GroupOutputs(const std::vector< COutput > &outputs, bool single_coin, const size_t max_ancestors) const
Definition: wallet.cpp:4651
void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3904
void GetStrongRandBytes(uint8_t *buf, int num) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
Definition: random.cpp:628
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:101
std::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
Definition: coincontrol.h:36
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:129
void AddToSpends(const COutPoint &outpoint, const TxId &wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:586
bool ErasePurpose(const CTxDestination &address)
Definition: walletdb.cpp:88
256-bit opaque blob.
Definition: uint256.h:120
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:13
bool WriteDestData(const CTxDestination &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
Definition: walletdb.cpp:961
void setUnconfirmed()
Definition: wallet.h:588
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:233
std::vector< CTransactionRef > vtx
Definition: block.h:65
int m_max_depth
Maximum chain depth value for coin availability.
Definition: coincontrol.h:44
bool IsSane() const
Definition: psbt.cpp:137
Amount GetMinimumFee(const CWallet &wallet, unsigned int nTxBytes, const CCoinControl &coin_control)
Estimate the minimum fee considering user set parameters and the required fee.
Definition: fees.cpp:17
bool IsSpentKey(const TxId &txid, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:829
bool HasWallets()
Definition: wallet.cpp:77
std::set< ScriptPubKeyMan * > GetActiveScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers.
Definition: wallet.cpp:4752
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:3518
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:356
void SetWalletFlag(uint64_t flags)
Set a single wallet flag.
Definition: wallet.cpp:1467
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:849
int64_t GetTxTime() const
Definition: wallet.cpp:1514
bool CreateTransaction(const std::vector< CRecipient > &vecSend, CTransactionRef &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, bool sign=true)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: wallet.cpp:3377
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:274
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:105
Address book data.
Definition: wallet.h:199
void transactionAddedToMempool(const CTransactionRef &tx) override
Definition: wallet.cpp:1200
void ResendWalletTransactions()
Definition: wallet.cpp:2192
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:201
const CChainParams & Params()
Return the currently selected parameters.
Amount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:1995
BlockHash GetHash() const
Definition: block.cpp:11
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
Definition: wallet.cpp:3848
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:429
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:34
bool IsSpent(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Outpoint is spent if any non-conflicted transaction, spends it:
Definition: wallet.cpp:567
A TxId is the identifier of a transaction.
Definition: txid.h:14
bool IsNull() const
Definition: block.h:55
bool IsSelected(const COutPoint &output) const
Definition: coincontrol.h:52
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:3622
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::string &strPurpose)
Definition: wallet.cpp:3535
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:330
static std::condition_variable g_wallet_release_cv
Definition: wallet.cpp:109
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:479
bool empty() const
Definition: prevector.h:386
int GetSpendSize(unsigned int out, bool use_max_sig=false) const
Definition: wallet.h:517