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