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