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