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