Bitcoin Core  0.21.0rc3
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  // Get long term estimate
2366  FeeCalculation feeCalc;
2367  CCoinControl temp;
2368  temp.m_confirm_target = 1008;
2369  CFeeRate long_term_feerate = GetMinimumFeeRate(*this, temp, &feeCalc);
2370 
2371  // Calculate cost of change
2372  CAmount cost_of_change = GetDiscardRate(*this).GetFee(coin_selection_params.change_spend_size) + coin_selection_params.effective_fee.GetFee(coin_selection_params.change_output_size);
2373 
2374  // Filter by the min conf specs and add to utxo_pool and calculate effective value
2375  for (OutputGroup& group : groups) {
2376  if (!group.EligibleForSpending(eligibility_filter)) continue;
2377 
2378  if (coin_selection_params.m_subtract_fee_outputs) {
2379  // 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
2380  group.SetFees(CFeeRate(0) /* effective_feerate */, long_term_feerate);
2381  } else {
2382  group.SetFees(coin_selection_params.effective_fee, long_term_feerate);
2383  }
2384 
2385  OutputGroup pos_group = group.GetPositiveOnlyGroup();
2386  if (pos_group.effective_value > 0) utxo_pool.push_back(pos_group);
2387  }
2388  // Calculate the fees for things that aren't inputs
2389  CAmount not_input_fees = coin_selection_params.effective_fee.GetFee(coin_selection_params.tx_noinputs_size);
2390  bnb_used = true;
2391  return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change, setCoinsRet, nValueRet, not_input_fees);
2392  } else {
2393  // Filter by the min conf specs and add to utxo_pool
2394  for (const OutputGroup& group : groups) {
2395  if (!group.EligibleForSpending(eligibility_filter)) continue;
2396  utxo_pool.push_back(group);
2397  }
2398  bnb_used = false;
2399  return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
2400  }
2401 }
2402 
2403 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
2404 {
2405  std::vector<COutput> vCoins(vAvailableCoins);
2406  CAmount value_to_select = nTargetValue;
2407 
2408  // Default to bnb was not used. If we use it, we set it later
2409  bnb_used = false;
2410 
2411  // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2412  if (coin_control.HasSelected() && !coin_control.fAllowOtherInputs)
2413  {
2414  for (const COutput& out : vCoins)
2415  {
2416  if (!out.fSpendable)
2417  continue;
2418  nValueRet += out.tx->tx->vout[out.i].nValue;
2419  setCoinsRet.insert(out.GetInputCoin());
2420  }
2421  return (nValueRet >= nTargetValue);
2422  }
2423 
2424  // calculate value from preset inputs and store them
2425  std::set<CInputCoin> setPresetCoins;
2426  CAmount nValueFromPresetInputs = 0;
2427 
2428  std::vector<COutPoint> vPresetInputs;
2429  coin_control.ListSelected(vPresetInputs);
2430  for (const COutPoint& outpoint : vPresetInputs)
2431  {
2432  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2433  if (it != mapWallet.end())
2434  {
2435  const CWalletTx& wtx = it->second;
2436  // Clearly invalid input, fail
2437  if (wtx.tx->vout.size() <= outpoint.n) {
2438  return false;
2439  }
2440  // Just to calculate the marginal byte size
2441  CInputCoin coin(wtx.tx, outpoint.n, wtx.GetSpendSize(outpoint.n, false));
2442  nValueFromPresetInputs += coin.txout.nValue;
2443  if (coin.m_input_bytes <= 0) {
2444  return false; // Not solvable, can't estimate size for fee
2445  }
2446  coin.effective_value = coin.txout.nValue - coin_selection_params.effective_fee.GetFee(coin.m_input_bytes);
2447  if (coin_selection_params.use_bnb) {
2448  value_to_select -= coin.effective_value;
2449  } else {
2450  value_to_select -= coin.txout.nValue;
2451  }
2452  setPresetCoins.insert(coin);
2453  } else {
2454  return false; // TODO: Allow non-wallet inputs
2455  }
2456  }
2457 
2458  // remove preset inputs from vCoins
2459  for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coin_control.HasSelected();)
2460  {
2461  if (setPresetCoins.count(it->GetInputCoin()))
2462  it = vCoins.erase(it);
2463  else
2464  ++it;
2465  }
2466 
2467  unsigned int limit_ancestor_count = 0;
2468  unsigned int limit_descendant_count = 0;
2469  chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
2470  size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
2471  size_t max_descendants = (size_t)std::max<int64_t>(1, limit_descendant_count);
2472  bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2473 
2474  // form groups from remaining coins; note that preset coins will not
2475  // automatically have their associated (same address) coins included
2476  if (coin_control.m_avoid_partial_spends && vCoins.size() > OUTPUT_GROUP_MAX_ENTRIES) {
2477  // Cases where we have 11+ outputs all pointing to the same destination may result in
2478  // privacy leaks as they will potentially be deterministically sorted. We solve that by
2479  // explicitly shuffling the outputs before processing
2480  Shuffle(vCoins.begin(), vCoins.end(), FastRandomContext());
2481  }
2482  std::vector<OutputGroup> groups = GroupOutputs(vCoins, !coin_control.m_avoid_partial_spends, max_ancestors);
2483 
2484  bool res = value_to_select <= 0 ||
2485  SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 6, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
2486  SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 1, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
2487  (m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, 2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
2488  (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)) ||
2489  (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)) ||
2490  (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)) ||
2491  (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));
2492 
2493  // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2494  util::insert(setCoinsRet, setPresetCoins);
2495 
2496  // add preset inputs to the total value selected
2497  nValueRet += nValueFromPresetInputs;
2498 
2499  return res;
2500 }
2501 
2503 {
2505 
2506  // Build coins map
2507  std::map<COutPoint, Coin> coins;
2508  for (auto& input : tx.vin) {
2509  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2510  if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2511  return false;
2512  }
2513  const CWalletTx& wtx = mi->second;
2514  coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], wtx.m_confirm.block_height, wtx.IsCoinBase());
2515  }
2516  std::map<int, std::string> input_errors;
2517  return SignTransaction(tx, coins, SIGHASH_ALL, input_errors);
2518 }
2519 
2520 bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
2521 {
2522  // Try to sign with all ScriptPubKeyMans
2523  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2524  // spk_man->SignTransaction will return true if the transaction is complete,
2525  // so we can exit early and return true if that happens
2526  if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2527  return true;
2528  }
2529  }
2530 
2531  // At this point, one input was not fully signed otherwise we would have exited already
2532  return false;
2533 }
2534 
2535 TransactionError CWallet::FillPSBT(PartiallySignedTransaction& psbtx, bool& complete, int sighash_type, bool sign, bool bip32derivs, size_t * n_signed) const
2536 {
2537  if (n_signed) {
2538  *n_signed = 0;
2539  }
2540  LOCK(cs_wallet);
2541  // Get all of the previous transactions
2542  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2543  const CTxIn& txin = psbtx.tx->vin[i];
2544  PSBTInput& input = psbtx.inputs.at(i);
2545 
2546  if (PSBTInputSigned(input)) {
2547  continue;
2548  }
2549 
2550  // If we have no utxo, grab it from the wallet.
2551  if (!input.non_witness_utxo) {
2552  const uint256& txhash = txin.prevout.hash;
2553  const auto it = mapWallet.find(txhash);
2554  if (it != mapWallet.end()) {
2555  const CWalletTx& wtx = it->second;
2556  // We only need the non_witness_utxo, which is a superset of the witness_utxo.
2557  // The signing code will switch to the smaller witness_utxo if this is ok.
2558  input.non_witness_utxo = wtx.tx;
2559  }
2560  }
2561  }
2562 
2563  // Fill in information from ScriptPubKeyMans
2564  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2565  int n_signed_this_spkm = 0;
2566  TransactionError res = spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs, &n_signed_this_spkm);
2567  if (res != TransactionError::OK) {
2568  return res;
2569  }
2570 
2571  if (n_signed) {
2572  (*n_signed) += n_signed_this_spkm;
2573  }
2574  }
2575 
2576  // Complete if every input is now signed
2577  complete = true;
2578  for (const auto& input : psbtx.inputs) {
2579  complete &= PSBTInputSigned(input);
2580  }
2581 
2582  return TransactionError::OK;
2583 }
2584 
2585 SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2586 {
2587  SignatureData sigdata;
2588  CScript script_pub_key = GetScriptForDestination(pkhash);
2589  for (const auto& spk_man_pair : m_spk_managers) {
2590  if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2591  return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2592  }
2593  }
2595 }
2596 
2597 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2598 {
2599  std::vector<CRecipient> vecSend;
2600 
2601  // Turn the txout set into a CRecipient vector.
2602  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
2603  const CTxOut& txOut = tx.vout[idx];
2604  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2605  vecSend.push_back(recipient);
2606  }
2607 
2608  coinControl.fAllowOtherInputs = true;
2609 
2610  for (const CTxIn& txin : tx.vin) {
2611  coinControl.Select(txin.prevout);
2612  }
2613 
2614  // Acquire the locks to prevent races to the new locked unspents between the
2615  // CreateTransaction call and LockCoin calls (when lockUnspents is true).
2616  LOCK(cs_wallet);
2617 
2618  CTransactionRef tx_new;
2619  FeeCalculation fee_calc_out;
2620  if (!CreateTransaction(vecSend, tx_new, nFeeRet, nChangePosInOut, error, coinControl, fee_calc_out, false)) {
2621  return false;
2622  }
2623 
2624  if (nChangePosInOut != -1) {
2625  tx.vout.insert(tx.vout.begin() + nChangePosInOut, tx_new->vout[nChangePosInOut]);
2626  }
2627 
2628  // Copy output sizes from new transaction; they may have had the fee
2629  // subtracted from them.
2630  for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
2631  tx.vout[idx].nValue = tx_new->vout[idx].nValue;
2632  }
2633 
2634  // Add new txins while keeping original txin scriptSig/order.
2635  for (const CTxIn& txin : tx_new->vin) {
2636  if (!coinControl.IsSelected(txin.prevout)) {
2637  tx.vin.push_back(txin);
2638 
2639  }
2640  if (lockUnspents) {
2641  LockCoin(txin.prevout);
2642  }
2643 
2644  }
2645 
2646  return true;
2647 }
2648 
2649 static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256& block_hash)
2650 {
2651  if (chain.isInitialBlockDownload()) {
2652  return false;
2653  }
2654  constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
2655  int64_t block_time;
2656  CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
2657  if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
2658  return false;
2659  }
2660  return true;
2661 }
2662 
2667 static uint32_t GetLocktimeForNewTransaction(interfaces::Chain& chain, const uint256& block_hash, int block_height)
2668 {
2669  uint32_t locktime;
2670  // Discourage fee sniping.
2671  //
2672  // For a large miner the value of the transactions in the best block and
2673  // the mempool can exceed the cost of deliberately attempting to mine two
2674  // blocks to orphan the current best block. By setting nLockTime such that
2675  // only the next block can include the transaction, we discourage this
2676  // practice as the height restricted and limited blocksize gives miners
2677  // considering fee sniping fewer options for pulling off this attack.
2678  //
2679  // A simple way to think about this is from the wallet's point of view we
2680  // always want the blockchain to move forward. By setting nLockTime this
2681  // way we're basically making the statement that we only want this
2682  // transaction to appear in the next block; we don't want to potentially
2683  // encourage reorgs by allowing transactions to appear at lower heights
2684  // than the next block in forks of the best chain.
2685  //
2686  // Of course, the subsidy is high enough, and transaction volume low
2687  // enough, that fee sniping isn't a problem yet, but by implementing a fix
2688  // now we ensure code won't be written that makes assumptions about
2689  // nLockTime that preclude a fix later.
2690  if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
2691  locktime = block_height;
2692 
2693  // Secondly occasionally randomly pick a nLockTime even further back, so
2694  // that transactions that are delayed after signing for whatever reason,
2695  // e.g. high-latency mix networks and some CoinJoin implementations, have
2696  // better privacy.
2697  if (GetRandInt(10) == 0)
2698  locktime = std::max(0, (int)locktime - GetRandInt(100));
2699  } else {
2700  // If our chain is lagging behind, we can't discourage fee sniping nor help
2701  // the privacy of high-latency transactions. To avoid leaking a potentially
2702  // unique "nLockTime fingerprint", set nLockTime to a constant.
2703  locktime = 0;
2704  }
2705  assert(locktime < LOCKTIME_THRESHOLD);
2706  return locktime;
2707 }
2708 
2709 OutputType CWallet::TransactionChangeType(const Optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend)
2710 {
2711  // If -changetype is specified, always use that change type.
2712  if (change_type) {
2713  return *change_type;
2714  }
2715 
2716  // if m_default_address_type is legacy, use legacy address as change (even
2717  // if some of the outputs are P2WPKH or P2WSH).
2719  return OutputType::LEGACY;
2720  }
2721 
2722  // if any destination is P2WPKH or P2WSH, use P2WPKH for the change
2723  // output.
2724  for (const auto& recipient : vecSend) {
2725  // Check if any destination contains a witness program:
2726  int witnessversion = 0;
2727  std::vector<unsigned char> witnessprogram;
2728  if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2729  return OutputType::BECH32;
2730  }
2731  }
2732 
2733  // else use m_default_address_type for change
2734  return m_default_address_type;
2735 }
2736 
2738  const std::vector<CRecipient>& vecSend,
2739  CTransactionRef& tx,
2740  CAmount& nFeeRet,
2741  int& nChangePosInOut,
2742  bilingual_str& error,
2743  const CCoinControl& coin_control,
2744  FeeCalculation& fee_calc_out,
2745  bool sign)
2746 {
2747  CAmount nValue = 0;
2748  const OutputType change_type = TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : m_default_change_type, vecSend);
2749  ReserveDestination reservedest(this, change_type);
2750  int nChangePosRequest = nChangePosInOut;
2751  unsigned int nSubtractFeeFromAmount = 0;
2752  for (const auto& recipient : vecSend)
2753  {
2754  if (nValue < 0 || recipient.nAmount < 0)
2755  {
2756  error = _("Transaction amounts must not be negative");
2757  return false;
2758  }
2759  nValue += recipient.nAmount;
2760 
2761  if (recipient.fSubtractFeeFromAmount)
2762  nSubtractFeeFromAmount++;
2763  }
2764  if (vecSend.empty())
2765  {
2766  error = _("Transaction must have at least one recipient");
2767  return false;
2768  }
2769 
2770  CMutableTransaction txNew;
2771  FeeCalculation feeCalc;
2772  CAmount nFeeNeeded;
2773  int nBytes;
2774  {
2775  std::set<CInputCoin> setCoins;
2776  LOCK(cs_wallet);
2778  {
2779  std::vector<COutput> vAvailableCoins;
2780  AvailableCoins(vAvailableCoins, true, &coin_control, 1, MAX_MONEY, MAX_MONEY, 0);
2781  CoinSelectionParams coin_selection_params; // Parameters for coin selection, init with dummy
2782 
2783  // Create change script that will be used if we need change
2784  // TODO: pass in scriptChange instead of reservedest so
2785  // change transaction isn't always pay-to-bitcoin-address
2786  CScript scriptChange;
2787 
2788  // coin control: send change to custom address
2789  if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2790  scriptChange = GetScriptForDestination(coin_control.destChange);
2791  } else { // no coin control: send change to newly generated address
2792  // Note: We use a new key here to keep it from being obvious which side is the change.
2793  // The drawback is that by not reusing a previous key, the change may be lost if a
2794  // backup is restored, if the backup doesn't have the new private key for the change.
2795  // If we reused the old key, it would be possible to add code to look for and
2796  // rediscover unknown transactions that were written with keys of ours to recover
2797  // post-backup change.
2798 
2799  // Reserve a new key pair from key pool. If it fails, provide a dummy
2800  // destination in case we don't need change.
2801  CTxDestination dest;
2802  if (!reservedest.GetReservedDestination(dest, true)) {
2803  error = _("Transaction needs a change address, but we can't generate it. Please call keypoolrefill first.");
2804  }
2805  scriptChange = GetScriptForDestination(dest);
2806  // A valid destination implies a change script (and
2807  // vice-versa). An empty change script will abort later, if the
2808  // change keypool ran out, but change is required.
2809  CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
2810  }
2811  CTxOut change_prototype_txout(0, scriptChange);
2812  coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
2813 
2814  CFeeRate discard_rate = GetDiscardRate(*this);
2815 
2816  // Get the fee rate to use effective values in coin selection
2817  CFeeRate nFeeRateNeeded = GetMinimumFeeRate(*this, coin_control, &feeCalc);
2818  // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
2819  // provided one
2820  if (coin_control.m_feerate && nFeeRateNeeded > *coin_control.m_feerate) {
2821  error = strprintf(_("Fee rate (%s) is lower than the minimum fee rate setting (%s)"), coin_control.m_feerate->ToString(FeeEstimateMode::SAT_VB), nFeeRateNeeded.ToString(FeeEstimateMode::SAT_VB));
2822  return false;
2823  }
2824 
2825  nFeeRet = 0;
2826  bool pick_new_inputs = true;
2827  CAmount nValueIn = 0;
2828 
2829  // BnB selector is the only selector used when this is true.
2830  // That should only happen on the first pass through the loop.
2831  coin_selection_params.use_bnb = true;
2832  coin_selection_params.m_subtract_fee_outputs = nSubtractFeeFromAmount != 0; // If we are doing subtract fee from recipient, don't use effective values
2833  // Start with no fee and loop until there is enough fee
2834  while (true)
2835  {
2836  nChangePosInOut = nChangePosRequest;
2837  txNew.vin.clear();
2838  txNew.vout.clear();
2839  bool fFirst = true;
2840 
2841  CAmount nValueToSelect = nValue;
2842  if (nSubtractFeeFromAmount == 0)
2843  nValueToSelect += nFeeRet;
2844 
2845  // vouts to the payees
2846  if (!coin_selection_params.m_subtract_fee_outputs) {
2847  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)
2848  }
2849  for (const auto& recipient : vecSend)
2850  {
2851  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2852 
2853  if (recipient.fSubtractFeeFromAmount)
2854  {
2855  assert(nSubtractFeeFromAmount != 0);
2856  txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2857 
2858  if (fFirst) // first receiver pays the remainder not divisible by output count
2859  {
2860  fFirst = false;
2861  txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2862  }
2863  }
2864  // Include the fee cost for outputs. Note this is only used for BnB right now
2865  if (!coin_selection_params.m_subtract_fee_outputs) {
2866  coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, PROTOCOL_VERSION);
2867  }
2868 
2869  if (IsDust(txout, chain().relayDustFee()))
2870  {
2871  if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2872  {
2873  if (txout.nValue < 0)
2874  error = _("The transaction amount is too small to pay the fee");
2875  else
2876  error = _("The transaction amount is too small to send after the fee has been deducted");
2877  }
2878  else
2879  error = _("Transaction amount too small");
2880  return false;
2881  }
2882  txNew.vout.push_back(txout);
2883  }
2884 
2885  // Choose coins to use
2886  bool bnb_used = false;
2887  if (pick_new_inputs) {
2888  nValueIn = 0;
2889  setCoins.clear();
2890  int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, this);
2891  // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
2892  // as lower-bound to allow BnB to do it's thing
2893  if (change_spend_size == -1) {
2894  coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
2895  } else {
2896  coin_selection_params.change_spend_size = (size_t)change_spend_size;
2897  }
2898  coin_selection_params.effective_fee = nFeeRateNeeded;
2899  if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coin_control, coin_selection_params, bnb_used))
2900  {
2901  // If BnB was used, it was the first pass. No longer the first pass and continue loop with knapsack.
2902  if (bnb_used) {
2903  coin_selection_params.use_bnb = false;
2904  continue;
2905  }
2906  else {
2907  error = _("Insufficient funds");
2908  return false;
2909  }
2910  }
2911  } else {
2912  bnb_used = false;
2913  }
2914 
2915  const CAmount nChange = nValueIn - nValueToSelect;
2916  if (nChange > 0)
2917  {
2918  // Fill a vout to ourself
2919  CTxOut newTxOut(nChange, scriptChange);
2920 
2921  // Never create dust outputs; if we would, just
2922  // add the dust to the fee.
2923  // The nChange when BnB is used is always going to go to fees.
2924  if (IsDust(newTxOut, discard_rate) || bnb_used)
2925  {
2926  nChangePosInOut = -1;
2927  nFeeRet += nChange;
2928  }
2929  else
2930  {
2931  if (nChangePosInOut == -1)
2932  {
2933  // Insert change txn at random position:
2934  nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2935  }
2936  else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2937  {
2938  error = _("Change index out of range");
2939  return false;
2940  }
2941 
2942  std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2943  txNew.vout.insert(position, newTxOut);
2944  }
2945  } else {
2946  nChangePosInOut = -1;
2947  }
2948 
2949  // Dummy fill vin for maximum size estimation
2950  //
2951  for (const auto& coin : setCoins) {
2952  txNew.vin.push_back(CTxIn(coin.outpoint,CScript()));
2953  }
2954 
2955  nBytes = CalculateMaximumSignedTxSize(CTransaction(txNew), this, coin_control.fAllowWatchOnly);
2956  if (nBytes < 0) {
2957  error = _("Signing transaction failed");
2958  return false;
2959  }
2960 
2961  nFeeNeeded = GetMinimumFee(*this, nBytes, coin_control, &feeCalc);
2962  if (feeCalc.reason == FeeReason::FALLBACK && !m_allow_fallback_fee) {
2963  // eventually allow a fallback fee
2964  error = _("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.");
2965  return false;
2966  }
2967 
2968  if (nFeeRet >= nFeeNeeded) {
2969  // Reduce fee to only the needed amount if possible. This
2970  // prevents potential overpayment in fees if the coins
2971  // selected to meet nFeeNeeded result in a transaction that
2972  // requires less fee than the prior iteration.
2973 
2974  // If we have no change and a big enough excess fee, then
2975  // try to construct transaction again only without picking
2976  // new inputs. We now know we only need the smaller fee
2977  // (because of reduced tx size) and so we should add a
2978  // change output. Only try this once.
2979  if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2980  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
2981  CAmount fee_needed_with_change = GetMinimumFee(*this, tx_size_with_change, coin_control, nullptr);
2982  CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2983  if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2984  pick_new_inputs = false;
2985  nFeeRet = fee_needed_with_change;
2986  continue;
2987  }
2988  }
2989 
2990  // If we have change output already, just increase it
2991  if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2992  CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2993  std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2994  change_position->nValue += extraFeePaid;
2995  nFeeRet -= extraFeePaid;
2996  }
2997  break; // Done, enough fee included.
2998  }
2999  else if (!pick_new_inputs) {
3000  // This shouldn't happen, we should have had enough excess
3001  // fee to pay for the new output and still meet nFeeNeeded
3002  // Or we should have just subtracted fee from recipients and
3003  // nFeeNeeded should not have changed
3004  error = _("Transaction fee and change calculation failed");
3005  return false;
3006  }
3007 
3008  // Try to reduce change to include necessary fee
3009  if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
3010  CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
3011  std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
3012  // Only reduce change if remaining amount is still a large enough output.
3013  if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
3014  change_position->nValue -= additionalFeeNeeded;
3015  nFeeRet += additionalFeeNeeded;
3016  break; // Done, able to increase fee from change
3017  }
3018  }
3019 
3020  // If subtracting fee from recipients, we now know what fee we
3021  // need to subtract, we have no reason to reselect inputs
3022  if (nSubtractFeeFromAmount > 0) {
3023  pick_new_inputs = false;
3024  }
3025 
3026  // Include more fee and try again.
3027  nFeeRet = nFeeNeeded;
3028  coin_selection_params.use_bnb = false;
3029  continue;
3030  }
3031 
3032  // Give up if change keypool ran out and change is required
3033  if (scriptChange.empty() && nChangePosInOut != -1) {
3034  return false;
3035  }
3036  }
3037 
3038  // Shuffle selected coins and fill in final vin
3039  txNew.vin.clear();
3040  std::vector<CInputCoin> selected_coins(setCoins.begin(), setCoins.end());
3041  Shuffle(selected_coins.begin(), selected_coins.end(), FastRandomContext());
3042 
3043  // Note how the sequence number is set to non-maxint so that
3044  // the nLockTime set above actually works.
3045  //
3046  // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
3047  // we use the highest possible value in that range (maxint-2)
3048  // to avoid conflicting with other possible uses of nSequence,
3049  // and in the spirit of "smallest possible change from prior
3050  // behavior."
3051  const uint32_t nSequence = coin_control.m_signal_bip125_rbf.get_value_or(m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
3052  for (const auto& coin : selected_coins) {
3053  txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));
3054  }
3055 
3056  if (sign && !SignTransaction(txNew)) {
3057  error = _("Signing transaction failed");
3058  return false;
3059  }
3060 
3061  // Return the constructed transaction data.
3062  tx = MakeTransactionRef(std::move(txNew));
3063 
3064  // Limit size
3066  {
3067  error = _("Transaction too large");
3068  return false;
3069  }
3070  }
3071 
3072  if (nFeeRet > m_default_max_tx_fee) {
3074  return false;
3075  }
3076 
3077  if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
3078  // Lastly, ensure this tx will pass the mempool's chain limits
3079  if (!chain().checkChainLimits(tx)) {
3080  error = _("Transaction has too long of a mempool chain");
3081  return false;
3082  }
3083  }
3084 
3085  // Before we return success, we assume any change key will be used to prevent
3086  // accidental re-use.
3087  reservedest.KeepDestination();
3088  fee_calc_out = feeCalc;
3089 
3090  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",
3091  nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
3092  feeCalc.est.pass.start, feeCalc.est.pass.end,
3093  (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,
3094  feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
3095  feeCalc.est.fail.start, feeCalc.est.fail.end,
3096  (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,
3097  feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
3098  return true;
3099 }
3100 
3102  const std::vector<CRecipient>& vecSend,
3103  CTransactionRef& tx,
3104  CAmount& nFeeRet,
3105  int& nChangePosInOut,
3106  bilingual_str& error,
3107  const CCoinControl& coin_control,
3108  FeeCalculation& fee_calc_out,
3109  bool sign)
3110 {
3111  int nChangePosIn = nChangePosInOut;
3112  CTransactionRef tx2 = tx;
3113  bool res = CreateTransactionInternal(vecSend, tx, nFeeRet, nChangePosInOut, error, coin_control, fee_calc_out, sign);
3114  // try with avoidpartialspends unless it's enabled already
3115  if (res && nFeeRet > 0 /* 0 means non-functional fee rate estimation */ && m_max_aps_fee > -1 && !coin_control.m_avoid_partial_spends) {
3116  CCoinControl tmp_cc = coin_control;
3117  tmp_cc.m_avoid_partial_spends = true;
3118  CAmount nFeeRet2;
3119  int nChangePosInOut2 = nChangePosIn;
3120  bilingual_str error2; // fired and forgotten; if an error occurs, we discard the results
3121  if (CreateTransactionInternal(vecSend, tx2, nFeeRet2, nChangePosInOut2, error2, tmp_cc, fee_calc_out, sign)) {
3122  // if fee of this alternative one is within the range of the max fee, we use this one
3123  const bool use_aps = nFeeRet2 <= nFeeRet + m_max_aps_fee;
3124  WalletLogPrintf("Fee non-grouped = %lld, grouped = %lld, using %s\n", nFeeRet, nFeeRet2, use_aps ? "grouped" : "non-grouped");
3125  if (use_aps) {
3126  tx = tx2;
3127  nFeeRet = nFeeRet2;
3128  nChangePosInOut = nChangePosInOut2;
3129  }
3130  }
3131  }
3132  return res;
3133 }
3134 
3135 void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
3136 {
3137  LOCK(cs_wallet);
3138  WalletLogPrintf("CommitTransaction:\n%s", tx->ToString()); /* Continued */
3139 
3140  // Add tx to wallet, because if it has change it's also ours,
3141  // otherwise just for transaction history.
3142  AddToWallet(tx, {}, [&](CWalletTx& wtx, bool new_tx) {
3143  CHECK_NONFATAL(wtx.mapValue.empty());
3144  CHECK_NONFATAL(wtx.vOrderForm.empty());
3145  wtx.mapValue = std::move(mapValue);
3146  wtx.vOrderForm = std::move(orderForm);
3147  wtx.fTimeReceivedIsTxTime = true;
3148  wtx.fFromMe = true;
3149  return true;
3150  });
3151 
3152  // Notify that old coins are spent
3153  for (const CTxIn& txin : tx->vin) {
3154  CWalletTx &coin = mapWallet.at(txin.prevout.hash);
3155  coin.MarkDirty();
3157  }
3158 
3159  // Get the inserted-CWalletTx from mapWallet so that the
3160  // fInMempool flag is cached properly
3161  CWalletTx& wtx = mapWallet.at(tx->GetHash());
3162 
3163  if (!fBroadcastTransactions) {
3164  // Don't submit tx to the mempool
3165  return;
3166  }
3167 
3168  std::string err_string;
3169  if (!wtx.SubmitMemoryPoolAndRelay(err_string, true)) {
3170  WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
3171  // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3172  }
3173 }
3174 
3175 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3176 {
3177  LOCK(cs_wallet);
3178 
3179  fFirstRunRet = false;
3180  DBErrors nLoadWalletRet = WalletBatch(*database).LoadWallet(this);
3181  if (nLoadWalletRet == DBErrors::NEED_REWRITE)
3182  {
3183  if (database->Rewrite("\x04pool"))
3184  {
3185  for (const auto& spk_man_pair : m_spk_managers) {
3186  spk_man_pair.second->RewriteDB();
3187  }
3188  }
3189  }
3190 
3191  // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
3193  if (fFirstRunRet) {
3194  assert(m_external_spk_managers.empty());
3195  assert(m_internal_spk_managers.empty());
3196  }
3197 
3198  if (nLoadWalletRet != DBErrors::LOAD_OK)
3199  return nLoadWalletRet;
3200 
3201  return DBErrors::LOAD_OK;
3202 }
3203 
3204 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3205 {
3207  DBErrors nZapSelectTxRet = WalletBatch(*database).ZapSelectTx(vHashIn, vHashOut);
3208  for (const uint256& hash : vHashOut) {
3209  const auto& it = mapWallet.find(hash);
3210  wtxOrdered.erase(it->second.m_it_wtxOrdered);
3211  for (const auto& txin : it->second.tx->vin)
3212  mapTxSpends.erase(txin.prevout);
3213  mapWallet.erase(it);
3214  NotifyTransactionChanged(this, hash, CT_DELETED);
3215  }
3216 
3217  if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
3218  {
3219  if (database->Rewrite("\x04pool"))
3220  {
3221  for (const auto& spk_man_pair : m_spk_managers) {
3222  spk_man_pair.second->RewriteDB();
3223  }
3224  }
3225  }
3226 
3227  if (nZapSelectTxRet != DBErrors::LOAD_OK)
3228  return nZapSelectTxRet;
3229 
3230  MarkDirty();
3231 
3232  return DBErrors::LOAD_OK;
3233 }
3234 
3235 bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3236 {
3237  bool fUpdated = false;
3238  bool is_mine;
3239  {
3240  LOCK(cs_wallet);
3241  std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
3242  fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
3243  m_address_book[address].SetLabel(strName);
3244  if (!strPurpose.empty()) /* update purpose only if requested */
3245  m_address_book[address].purpose = strPurpose;
3246  is_mine = IsMine(address) != ISMINE_NO;
3247  }
3248  NotifyAddressBookChanged(this, address, strName, is_mine,
3249  strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3250  if (!strPurpose.empty() && !batch.WritePurpose(EncodeDestination(address), strPurpose))
3251  return false;
3252  return batch.WriteName(EncodeDestination(address), strName);
3253 }
3254 
3255 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3256 {
3257  WalletBatch batch(*database);
3258  return SetAddressBookWithDB(batch, address, strName, strPurpose);
3259 }
3260 
3262 {
3263  bool is_mine;
3264  WalletBatch batch(*database);
3265  {
3266  LOCK(cs_wallet);
3267  // 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)
3268  // NOTE: This isn't a problem for sending addresses because they never have any DestData yet!
3269  // When adding new DestData, it should be considered here whether to retain or delete it (or move it?).
3270  if (IsMine(address)) {
3271  WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, PACKAGE_BUGREPORT);
3272  return false;
3273  }
3274  // Delete destdata tuples associated with address
3275  std::string strAddress = EncodeDestination(address);
3276  for (const std::pair<const std::string, std::string> &item : m_address_book[address].destdata)
3277  {
3278  batch.EraseDestData(strAddress, item.first);
3279  }
3280  m_address_book.erase(address);
3281  is_mine = IsMine(address) != ISMINE_NO;
3282  }
3283 
3284  NotifyAddressBookChanged(this, address, "", is_mine, "", CT_DELETED);
3285 
3286  batch.ErasePurpose(EncodeDestination(address));
3287  return batch.EraseName(EncodeDestination(address));
3288 }
3289 
3291 {
3293 
3294  unsigned int count = 0;
3295  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3296  count += spk_man->KeypoolCountExternalKeys();
3297  }
3298 
3299  return count;
3300 }
3301 
3302 unsigned int CWallet::GetKeyPoolSize() const
3303 {
3305 
3306  unsigned int count = 0;
3307  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3308  count += spk_man->GetKeyPoolSize();
3309  }
3310  return count;
3311 }
3312 
3313 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3314 {
3315  LOCK(cs_wallet);
3316  bool res = true;
3317  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3318  res &= spk_man->TopUp(kpSize);
3319  }
3320  return res;
3321 }
3322 
3323 bool CWallet::GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error)
3324 {
3325  LOCK(cs_wallet);
3326  error.clear();
3327  bool result = false;
3328  auto spk_man = GetScriptPubKeyMan(type, false /* internal */);
3329  if (spk_man) {
3330  spk_man->TopUp();
3331  result = spk_man->GetNewDestination(type, dest, error);
3332  } else {
3333  error = strprintf("Error: No %s addresses available.", FormatOutputType(type));
3334  }
3335  if (result) {
3336  SetAddressBook(dest, label, "receive");
3337  }
3338 
3339  return result;
3340 }
3341 
3342 bool CWallet::GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error)
3343 {
3344  LOCK(cs_wallet);
3345  error.clear();
3346 
3347  ReserveDestination reservedest(this, type);
3348  if (!reservedest.GetReservedDestination(dest, true)) {
3349  error = _("Error: Keypool ran out, please call keypoolrefill first").translated;
3350  return false;
3351  }
3352 
3353  reservedest.KeepDestination();
3354  return true;
3355 }
3356 
3358 {
3359  LOCK(cs_wallet);
3360  int64_t oldestKey = std::numeric_limits<int64_t>::max();
3361  for (const auto& spk_man_pair : m_spk_managers) {
3362  oldestKey = std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
3363  }
3364  return oldestKey;
3365 }
3366 
3367 void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
3368  for (auto& entry : mapWallet) {
3369  CWalletTx& wtx = entry.second;
3370  if (wtx.m_is_cache_empty) continue;
3371  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
3372  CTxDestination dst;
3373  if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.count(dst)) {
3374  wtx.MarkDirty();
3375  break;
3376  }
3377  }
3378  }
3379 }
3380 
3381 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() const
3382 {
3383  std::map<CTxDestination, CAmount> balances;
3384 
3385  {
3386  LOCK(cs_wallet);
3387  std::set<uint256> trusted_parents;
3388  for (const auto& walletEntry : mapWallet)
3389  {
3390  const CWalletTx& wtx = walletEntry.second;
3391 
3392  if (!IsTrusted(wtx, trusted_parents))
3393  continue;
3394 
3395  if (wtx.IsImmatureCoinBase())
3396  continue;
3397 
3398  int nDepth = wtx.GetDepthInMainChain();
3399  if (nDepth < (wtx.IsFromMe(ISMINE_ALL) ? 0 : 1))
3400  continue;
3401 
3402  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++)
3403  {
3404  CTxDestination addr;
3405  if (!IsMine(wtx.tx->vout[i]))
3406  continue;
3407  if(!ExtractDestination(wtx.tx->vout[i].scriptPubKey, addr))
3408  continue;
3409 
3410  CAmount n = IsSpent(walletEntry.first, i) ? 0 : wtx.tx->vout[i].nValue;
3411  balances[addr] += n;
3412  }
3413  }
3414  }
3415 
3416  return balances;
3417 }
3418 
3419 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings() const
3420 {
3422  std::set< std::set<CTxDestination> > groupings;
3423  std::set<CTxDestination> grouping;
3424 
3425  for (const auto& walletEntry : mapWallet)
3426  {
3427  const CWalletTx& wtx = walletEntry.second;
3428 
3429  if (wtx.tx->vin.size() > 0)
3430  {
3431  bool any_mine = false;
3432  // group all input addresses with each other
3433  for (const CTxIn& txin : wtx.tx->vin)
3434  {
3435  CTxDestination address;
3436  if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3437  continue;
3438  if(!ExtractDestination(mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
3439  continue;
3440  grouping.insert(address);
3441  any_mine = true;
3442  }
3443 
3444  // group change with input addresses
3445  if (any_mine)
3446  {
3447  for (const CTxOut& txout : wtx.tx->vout)
3448  if (IsChange(txout))
3449  {
3450  CTxDestination txoutAddr;
3451  if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3452  continue;
3453  grouping.insert(txoutAddr);
3454  }
3455  }
3456  if (grouping.size() > 0)
3457  {
3458  groupings.insert(grouping);
3459  grouping.clear();
3460  }
3461  }
3462 
3463  // group lone addrs by themselves
3464  for (const auto& txout : wtx.tx->vout)
3465  if (IsMine(txout))
3466  {
3467  CTxDestination address;
3468  if(!ExtractDestination(txout.scriptPubKey, address))
3469  continue;
3470  grouping.insert(address);
3471  groupings.insert(grouping);
3472  grouping.clear();
3473  }
3474  }
3475 
3476  std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3477  std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3478  for (std::set<CTxDestination> _grouping : groupings)
3479  {
3480  // make a set of all the groups hit by this new group
3481  std::set< std::set<CTxDestination>* > hits;
3482  std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3483  for (const CTxDestination& address : _grouping)
3484  if ((it = setmap.find(address)) != setmap.end())
3485  hits.insert((*it).second);
3486 
3487  // merge all hit groups into a new single group and delete old groups
3488  std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3489  for (std::set<CTxDestination>* hit : hits)
3490  {
3491  merged->insert(hit->begin(), hit->end());
3492  uniqueGroupings.erase(hit);
3493  delete hit;
3494  }
3495  uniqueGroupings.insert(merged);
3496 
3497  // update setmap
3498  for (const CTxDestination& element : *merged)
3499  setmap[element] = merged;
3500  }
3501 
3502  std::set< std::set<CTxDestination> > ret;
3503  for (const std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3504  {
3505  ret.insert(*uniqueGrouping);
3506  delete uniqueGrouping;
3507  }
3508 
3509  return ret;
3510 }
3511 
3512 std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
3513 {
3514  LOCK(cs_wallet);
3515  std::set<CTxDestination> result;
3516  for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book)
3517  {
3518  if (item.second.IsChange()) continue;
3519  const CTxDestination& address = item.first;
3520  const std::string& strName = item.second.GetLabel();
3521  if (strName == label)
3522  result.insert(address);
3523  }
3524  return result;
3525 }
3526 
3528 {
3529  m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
3530  if (!m_spk_man) {
3531  return false;
3532  }
3533 
3534 
3535  if (nIndex == -1)
3536  {
3537  m_spk_man->TopUp();
3538 
3539  CKeyPool keypool;
3540  if (!m_spk_man->GetReservedDestination(type, internal, address, nIndex, keypool)) {
3541  return false;
3542  }
3543  fInternal = keypool.fInternal;
3544  }
3545  dest = address;
3546  return true;
3547 }
3548 
3550 {
3551  if (nIndex != -1) {
3553  }
3554  nIndex = -1;
3555  address = CNoDestination();
3556 }
3557 
3559 {
3560  if (nIndex != -1) {
3562  }
3563  nIndex = -1;
3564  address = CNoDestination();
3565 }
3566 
3567 void CWallet::LockCoin(const COutPoint& output)
3568 {
3570  setLockedCoins.insert(output);
3571 }
3572 
3573 void CWallet::UnlockCoin(const COutPoint& output)
3574 {
3576  setLockedCoins.erase(output);
3577 }
3578 
3580 {
3582  setLockedCoins.clear();
3583 }
3584 
3585 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3586 {
3588  COutPoint outpt(hash, n);
3589 
3590  return (setLockedCoins.count(outpt) > 0);
3591 }
3592 
3593 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3594 {
3596  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3597  it != setLockedCoins.end(); it++) {
3598  COutPoint outpt = (*it);
3599  vOutpts.push_back(outpt);
3600  }
3601 }
3602  // end of Actions
3604 
3605 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
3607  mapKeyBirth.clear();
3608 
3610  assert(spk_man != nullptr);
3611  LOCK(spk_man->cs_KeyStore);
3612 
3613  // get birth times for keys with metadata
3614  for (const auto& entry : spk_man->mapKeyMetadata) {
3615  if (entry.second.nCreateTime) {
3616  mapKeyBirth[entry.first] = entry.second.nCreateTime;
3617  }
3618  }
3619 
3620  // map in which we'll infer heights of other keys
3621  std::map<CKeyID, const CWalletTx::Confirmation*> mapKeyFirstBlock;
3622  CWalletTx::Confirmation max_confirm;
3623  max_confirm.block_height = GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
3624  CHECK_NONFATAL(chain().findAncestorByHeight(GetLastBlockHash(), max_confirm.block_height, FoundBlock().hash(max_confirm.hashBlock)));
3625  for (const CKeyID &keyid : spk_man->GetKeys()) {
3626  if (mapKeyBirth.count(keyid) == 0)
3627  mapKeyFirstBlock[keyid] = &max_confirm;
3628  }
3629 
3630  // if there are no such keys, we're done
3631  if (mapKeyFirstBlock.empty())
3632  return;
3633 
3634  // find first block that affects those keys, if there are any left
3635  for (const auto& entry : mapWallet) {
3636  // iterate over all wallet transactions...
3637  const CWalletTx &wtx = entry.second;
3638  if (wtx.m_confirm.status == CWalletTx::CONFIRMED) {
3639  // ... which are already in a block
3640  for (const CTxOut &txout : wtx.tx->vout) {
3641  // iterate over all their outputs
3642  for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
3643  // ... and all their affected keys
3644  auto rit = mapKeyFirstBlock.find(keyid);
3645  if (rit != mapKeyFirstBlock.end() && wtx.m_confirm.block_height < rit->second->block_height) {
3646  rit->second = &wtx.m_confirm;
3647  }
3648  }
3649  }
3650  }
3651  }
3652 
3653  // Extract block timestamps for those keys
3654  for (const auto& entry : mapKeyFirstBlock) {
3655  int64_t block_time;
3656  CHECK_NONFATAL(chain().findBlock(entry.second->hashBlock, FoundBlock().time(block_time)));
3657  mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW; // block times can be 2h off
3658  }
3659 }
3660 
3682 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3683 {
3684  unsigned int nTimeSmart = wtx.nTimeReceived;
3685  if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
3686  int64_t blocktime;
3687  if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().time(blocktime))) {
3688  int64_t latestNow = wtx.nTimeReceived;
3689  int64_t latestEntry = 0;
3690 
3691  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3692  int64_t latestTolerated = latestNow + 300;
3693  const TxItems& txOrdered = wtxOrdered;
3694  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3695  CWalletTx* const pwtx = it->second;
3696  if (pwtx == &wtx) {
3697  continue;
3698  }
3699  int64_t nSmartTime;
3700  nSmartTime = pwtx->nTimeSmart;
3701  if (!nSmartTime) {
3702  nSmartTime = pwtx->nTimeReceived;
3703  }
3704  if (nSmartTime <= latestTolerated) {
3705  latestEntry = nSmartTime;
3706  if (nSmartTime > latestNow) {
3707  latestNow = nSmartTime;
3708  }
3709  break;
3710  }
3711  }
3712 
3713  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3714  } else {
3715  WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.m_confirm.hashBlock.ToString());
3716  }
3717  }
3718  return nTimeSmart;
3719 }
3720 
3721 bool CWallet::AddDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key, const std::string &value)
3722 {
3723  if (boost::get<CNoDestination>(&dest))
3724  return false;
3725 
3726  m_address_book[dest].destdata.insert(std::make_pair(key, value));
3727  return batch.WriteDestData(EncodeDestination(dest), key, value);
3728 }
3729 
3730 bool CWallet::EraseDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key)
3731 {
3732  if (!m_address_book[dest].destdata.erase(key))
3733  return false;
3734  return batch.EraseDestData(EncodeDestination(dest), key);
3735 }
3736 
3737 void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3738 {
3739  m_address_book[dest].destdata.insert(std::make_pair(key, value));
3740 }
3741 
3742 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3743 {
3744  std::map<CTxDestination, CAddressBookData>::const_iterator i = m_address_book.find(dest);
3745  if(i != m_address_book.end())
3746  {
3747  CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3748  if(j != i->second.destdata.end())
3749  {
3750  if(value)
3751  *value = j->second;
3752  return true;
3753  }
3754  }
3755  return false;
3756 }
3757 
3758 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3759 {
3760  std::vector<std::string> values;
3761  for (const auto& address : m_address_book) {
3762  for (const auto& data : address.second.destdata) {
3763  if (!data.first.compare(0, prefix.size(), prefix)) {
3764  values.emplace_back(data.second);
3765  }
3766  }
3767  }
3768  return values;
3769 }
3770 
3771 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
3772 {
3773  // Do some checking on wallet path. It should be either a:
3774  //
3775  // 1. Path where a directory can be created.
3776  // 2. Path to an existing directory.
3777  // 3. Path to a symlink to a directory.
3778  // 4. For backwards compatibility, the name of a data file in -walletdir.
3779  const fs::path& wallet_path = fs::absolute(name, GetWalletDir());
3780  fs::file_type path_type = fs::symlink_status(wallet_path).type();
3781  if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
3782  (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
3783  (path_type == fs::regular_file && fs::path(name).filename() == name))) {
3784  error_string = Untranslated(strprintf(
3785  "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
3786  "database/log.?????????? files can be stored, a location where such a directory could be created, "
3787  "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
3788  name, GetWalletDir()));
3790  return nullptr;
3791  }
3792  return MakeDatabase(wallet_path, options, status, error_string);
3793 }
3794 
3795 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)
3796 {
3797  const std::string& walletFile = database->Filename();
3798 
3799  chain.initMessage(_("Loading wallet...").translated);
3800 
3801  int64_t nStart = GetTimeMillis();
3802  bool fFirstRun = true;
3803  // TODO: Can't use std::make_shared because we need a custom deleter but
3804  // should be possible to use std::allocate_shared.
3805  std::shared_ptr<CWallet> walletInstance(new CWallet(&chain, name, std::move(database)), ReleaseWallet);
3806  DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3807  if (nLoadWalletRet != DBErrors::LOAD_OK) {
3808  if (nLoadWalletRet == DBErrors::CORRUPT) {
3809  error = strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
3810  return nullptr;
3811  }
3812  else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
3813  {
3814  warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3815  " or address book entries might be missing or incorrect."),
3816  walletFile));
3817  }
3818  else if (nLoadWalletRet == DBErrors::TOO_NEW) {
3819  error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, PACKAGE_NAME);
3820  return nullptr;
3821  }
3822  else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
3823  {
3824  error = strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME);
3825  return nullptr;
3826  }
3827  else {
3828  error = strprintf(_("Error loading %s"), walletFile);
3829  return nullptr;
3830  }
3831  }
3832 
3833  if (fFirstRun)
3834  {
3835  // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3836  walletInstance->SetMinVersion(FEATURE_LATEST);
3837 
3838  walletInstance->AddWalletFlags(wallet_creation_flags);
3839 
3840  // Only create LegacyScriptPubKeyMan when not descriptor wallet
3841  if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
3842  walletInstance->SetupLegacyScriptPubKeyMan();
3843  }
3844 
3845  if (!(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
3846  LOCK(walletInstance->cs_wallet);
3847  if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
3848  walletInstance->SetupDescriptorScriptPubKeyMans();
3849  // SetupDescriptorScriptPubKeyMans already calls SetupGeneration for us so we don't need to call SetupGeneration separately
3850  } else {
3851  // Legacy wallets need SetupGeneration here.
3852  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
3853  if (!spk_man->SetupGeneration()) {
3854  error = _("Unable to generate initial keys");
3855  return nullptr;
3856  }
3857  }
3858  }
3859  }
3860 
3861  walletInstance->chainStateFlushed(chain.getTipLocator());
3862  } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
3863  // Make it impossible to disable private keys after creation
3864  error = strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile);
3865  return NULL;
3866  } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
3867  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
3868  if (spk_man->HavePrivateKeys()) {
3869  warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
3870  break;
3871  }
3872  }
3873  }
3874 
3875  if (!gArgs.GetArg("-addresstype", "").empty()) {
3876  if (!ParseOutputType(gArgs.GetArg("-addresstype", ""), walletInstance->m_default_address_type)) {
3877  error = strprintf(_("Unknown address type '%s'"), gArgs.GetArg("-addresstype", ""));
3878  return nullptr;
3879  }
3880  }
3881 
3882  if (!gArgs.GetArg("-changetype", "").empty()) {
3883  OutputType out_type;
3884  if (!ParseOutputType(gArgs.GetArg("-changetype", ""), out_type)) {
3885  error = strprintf(_("Unknown change type '%s'"), gArgs.GetArg("-changetype", ""));
3886  return nullptr;
3887  }
3888  walletInstance->m_default_change_type = out_type;
3889  }
3890 
3891  if (gArgs.IsArgSet("-mintxfee")) {
3892  CAmount n = 0;
3893  if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n) {
3894  error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""));
3895  return nullptr;
3896  }
3897  if (n > HIGH_TX_FEE_PER_KB) {
3898  warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
3899  _("This is the minimum transaction fee you pay on every transaction."));
3900  }
3901  walletInstance->m_min_fee = CFeeRate(n);
3902  }
3903 
3904  if (gArgs.IsArgSet("-maxapsfee")) {
3905  const std::string max_aps_fee{gArgs.GetArg("-maxapsfee", "")};
3906  CAmount n = 0;
3907  if (max_aps_fee == "-1") {
3908  n = -1;
3909  } else if (!ParseMoney(max_aps_fee, n)) {
3910  error = AmountErrMsg("maxapsfee", max_aps_fee);
3911  return nullptr;
3912  }
3913  if (n > HIGH_APS_FEE) {
3914  warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
3915  _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
3916  }
3917  walletInstance->m_max_aps_fee = n;
3918  }
3919 
3920  if (gArgs.IsArgSet("-fallbackfee")) {
3921  CAmount nFeePerK = 0;
3922  if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
3923  error = strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", ""));
3924  return nullptr;
3925  }
3926  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
3927  warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
3928  _("This is the transaction fee you may pay when fee estimates are not available."));
3929  }
3930  walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
3931  }
3932  // Disable fallback fee in case value was set to 0, enable if non-null value
3933  walletInstance->m_allow_fallback_fee = walletInstance->m_fallback_fee.GetFeePerK() != 0;
3934 
3935  if (gArgs.IsArgSet("-discardfee")) {
3936  CAmount nFeePerK = 0;
3937  if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK)) {
3938  error = strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", ""));
3939  return nullptr;
3940  }
3941  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
3942  warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
3943  _("This is the transaction fee you may discard if change is smaller than dust at this level"));
3944  }
3945  walletInstance->m_discard_rate = CFeeRate(nFeePerK);
3946  }
3947  if (gArgs.IsArgSet("-paytxfee")) {
3948  CAmount nFeePerK = 0;
3949  if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
3950  error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""));
3951  return nullptr;
3952  }
3953  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
3954  warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
3955  _("This is the transaction fee you will pay if you send a transaction."));
3956  }
3957  walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
3958  if (walletInstance->m_pay_tx_fee < chain.relayMinFee()) {
3959  error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
3960  gArgs.GetArg("-paytxfee", ""), chain.relayMinFee().ToString());
3961  return nullptr;
3962  }
3963  }
3964 
3965  if (gArgs.IsArgSet("-maxtxfee")) {
3966  CAmount nMaxFee = 0;
3967  if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
3968  error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""));
3969  return nullptr;
3970  }
3971  if (nMaxFee > HIGH_MAX_TX_FEE) {
3972  warnings.push_back(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
3973  }
3974  if (CFeeRate(nMaxFee, 1000) < chain.relayMinFee()) {
3975  error = strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3976  gArgs.GetArg("-maxtxfee", ""), chain.relayMinFee().ToString());
3977  return nullptr;
3978  }
3979  walletInstance->m_default_max_tx_fee = nMaxFee;
3980  }
3981 
3982  if (chain.relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
3983  warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
3984  _("The wallet will avoid paying less than the minimum relay fee."));
3985  }
3986 
3987  walletInstance->m_confirm_target = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3988  walletInstance->m_spend_zero_conf_change = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3989  walletInstance->m_signal_rbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
3990 
3991  walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nStart);
3992 
3993  // Try to top up keypool. No-op if the wallet is locked.
3994  walletInstance->TopUpKeyPool();
3995 
3996  LOCK(walletInstance->cs_wallet);
3997 
3998  // Register wallet with validationinterface. It's done before rescan to avoid
3999  // missing block connections between end of rescan and validation subscribing.
4000  // Because of wallet lock being hold, block connection notifications are going to
4001  // be pending on the validation-side until lock release. It's likely to have
4002  // block processing duplicata (if rescan block range overlaps with notification one)
4003  // but we guarantee at least than wallet state is correct after notifications delivery.
4004  // This is temporary until rescan and notifications delivery are unified under same
4005  // interface.
4006  walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
4007 
4008  int rescan_height = 0;
4009  if (!gArgs.GetBoolArg("-rescan", false))
4010  {
4011  WalletBatch batch(*walletInstance->database);
4012  CBlockLocator locator;
4013  if (batch.ReadBestBlock(locator)) {
4014  if (const Optional<int> fork_height = chain.findLocatorFork(locator)) {
4015  rescan_height = *fork_height;
4016  }
4017  }
4018  }
4019 
4020  const Optional<int> tip_height = chain.getHeight();
4021  if (tip_height) {
4022  walletInstance->m_last_block_processed = chain.getBlockHash(*tip_height);
4023  walletInstance->m_last_block_processed_height = *tip_height;
4024  } else {
4025  walletInstance->m_last_block_processed.SetNull();
4026  walletInstance->m_last_block_processed_height = -1;
4027  }
4028 
4029  if (tip_height && *tip_height != rescan_height)
4030  {
4031  // We can't rescan beyond non-pruned blocks, stop and throw an error.
4032  // This might happen if a user uses an old wallet within a pruned node
4033  // or if they ran -disablewallet for a longer time, then decided to re-enable
4034  if (chain.havePruned()) {
4035  // Exit early and print an error.
4036  // If a block is pruned after this check, we will load the wallet,
4037  // but fail the rescan with a generic error.
4038  int block_height = *tip_height;
4039  while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
4040  --block_height;
4041  }
4042 
4043  if (rescan_height != block_height) {
4044  error = _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)");
4045  return nullptr;
4046  }
4047  }
4048 
4049  chain.initMessage(_("Rescanning...").translated);
4050  walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
4051 
4052  // No need to read and scan block if block was created before
4053  // our wallet birthday (as adjusted for block time variability)
4054  // The way the 'time_first_key' is initialized is just a workaround for the gcc bug #47679 since version 4.6.0.
4055  Optional<int64_t> time_first_key = MakeOptional(false, int64_t());;
4056  for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
4057  int64_t time = spk_man->GetTimeFirstKey();
4058  if (!time_first_key || time < *time_first_key) time_first_key = time;
4059  }
4060  if (time_first_key) {
4061  if (Optional<int> first_block = chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, nullptr)) {
4062  rescan_height = *first_block;
4063  }
4064  }
4065 
4066  {
4067  WalletRescanReserver reserver(*walletInstance);
4068  if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, {} /* max height */, reserver, true /* update */).status)) {
4069  error = _("Failed to rescan the wallet during initialization");
4070  return nullptr;
4071  }
4072  }
4073  walletInstance->chainStateFlushed(chain.getTipLocator());
4074  walletInstance->database->IncrementUpdateCounter();
4075  }
4076 
4077  {
4078  LOCK(cs_wallets);
4079  for (auto& load_wallet : g_load_wallet_fns) {
4080  load_wallet(interfaces::MakeWallet(walletInstance));
4081  }
4082  }
4083 
4084  walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4085 
4086  {
4087  walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4088  walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4089  walletInstance->WalletLogPrintf("m_address_book.size() = %u\n", walletInstance->m_address_book.size());
4090  }
4091 
4092  return walletInstance;
4093 }
4094 
4095 const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
4096 {
4097  const auto& address_book_it = m_address_book.find(dest);
4098  if (address_book_it == m_address_book.end()) return nullptr;
4099  if ((!allow_change) && address_book_it->second.IsChange()) {
4100  return nullptr;
4101  }
4102  return &address_book_it->second;
4103 }
4104 
4105 bool CWallet::UpgradeWallet(int version, bilingual_str& error)
4106 {
4107  int prev_version = GetVersion();
4108  if (version == 0) {
4109  WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
4110  version = FEATURE_LATEST;
4111  } else {
4112  WalletLogPrintf("Allowing wallet upgrade up to %i\n", version);
4113  }
4114  if (version < prev_version)
4115  {
4116  error = _("Cannot downgrade wallet");
4117  return false;
4118  }
4119 
4120  LOCK(cs_wallet);
4121 
4122  // Do not upgrade versions to any version between HD_SPLIT and FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
4124  error = _("Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use version 169900 or no version specified.");
4125  return false;
4126  }
4127 
4128  // Permanently upgrade to the version
4130 
4131  for (auto spk_man : GetActiveScriptPubKeyMans()) {
4132  if (!spk_man->Upgrade(prev_version, version, error)) {
4133  return false;
4134  }
4135  }
4136  return true;
4137 }
4138 
4140 {
4141  LOCK(cs_wallet);
4142 
4143  // Add wallet transactions that aren't already in a block to mempool
4144  // Do this here as mempool requires genesis block to be loaded
4146 
4147  // Update wallet transactions with current mempool transactions.
4149 }
4150 
4151 bool CWallet::BackupWallet(const std::string& strDest) const
4152 {
4153  return database->Backup(strDest);
4154 }
4155 
4157 {
4158  nTime = GetTime();
4159  fInternal = false;
4160  m_pre_split = false;
4161 }
4162 
4163 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4164 {
4165  nTime = GetTime();
4166  vchPubKey = vchPubKeyIn;
4167  fInternal = internalIn;
4168  m_pre_split = false;
4169 }
4170 
4172 {
4173  assert(pwallet != nullptr);
4175  if (isUnconfirmed() || isAbandoned()) return 0;
4176 
4177  return (pwallet->GetLastBlockHeight() - m_confirm.block_height + 1) * (isConflicted() ? -1 : 1);
4178 }
4179 
4181 {
4182  if (!IsCoinBase())
4183  return 0;
4184  int chain_depth = GetDepthInMainChain();
4185  assert(chain_depth >= 0); // coinbase tx should not be conflicted
4186  return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
4187 }
4188 
4190 {
4191  // note GetBlocksToMaturity is 0 for non-coinbase tx
4192  return GetBlocksToMaturity() > 0;
4193 }
4194 
4195 std::vector<OutputGroup> CWallet::GroupOutputs(const std::vector<COutput>& outputs, bool single_coin, const size_t max_ancestors) const {
4196  std::vector<OutputGroup> groups;
4197  std::map<CTxDestination, OutputGroup> gmap;
4198  std::set<CTxDestination> full_groups;
4199 
4200  for (const auto& output : outputs) {
4201  if (output.fSpendable) {
4202  CTxDestination dst;
4203  CInputCoin input_coin = output.GetInputCoin();
4204 
4205  size_t ancestors, descendants;
4206  chain().getTransactionAncestry(output.tx->GetHash(), ancestors, descendants);
4207  if (!single_coin && ExtractDestination(output.tx->tx->vout[output.i].scriptPubKey, dst)) {
4208  auto it = gmap.find(dst);
4209  if (it != gmap.end()) {
4210  // Limit output groups to no more than OUTPUT_GROUP_MAX_ENTRIES
4211  // number of entries, to protect against inadvertently creating
4212  // a too-large transaction when using -avoidpartialspends to
4213  // prevent breaking consensus or surprising users with a very
4214  // high amount of fees.
4215  if (it->second.m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
4216  groups.push_back(it->second);
4217  it->second = OutputGroup{};
4218  full_groups.insert(dst);
4219  }
4220  it->second.Insert(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
4221  } else {
4222  gmap[dst].Insert(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
4223  }
4224  } else {
4225  groups.emplace_back(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
4226  }
4227  }
4228  }
4229  if (!single_coin) {
4230  for (auto& it : gmap) {
4231  auto& group = it.second;
4232  if (full_groups.count(it.first) > 0) {
4233  // Make this unattractive as we want coin selection to avoid it if possible
4234  group.m_ancestors = max_ancestors - 1;
4235  }
4236  groups.push_back(group);
4237  }
4238  }
4239  return groups;
4240 }
4241 
4243 {
4244  return HasEncryptionKeys();
4245 }
4246 
4247 bool CWallet::IsLocked() const
4248 {
4249  if (!IsCrypted()) {
4250  return false;
4251  }
4252  LOCK(cs_wallet);
4253  return vMasterKey.empty();
4254 }
4255 
4257 {
4258  if (!IsCrypted())
4259  return false;
4260 
4261  {
4262  LOCK(cs_wallet);
4263  vMasterKey.clear();
4264  }
4265 
4266  NotifyStatusChanged(this);
4267  return true;
4268 }
4269 
4270 bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys)
4271 {
4272  {
4273  LOCK(cs_wallet);
4274  for (const auto& spk_man_pair : m_spk_managers) {
4275  if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn, accept_no_keys)) {
4276  return false;
4277  }
4278  }
4279  vMasterKey = vMasterKeyIn;
4280  }
4281  NotifyStatusChanged(this);
4282  return true;
4283 }
4284 
4285 std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
4286 {
4287  std::set<ScriptPubKeyMan*> spk_mans;
4288  for (bool internal : {false, true}) {
4289  for (OutputType t : OUTPUT_TYPES) {
4290  auto spk_man = GetScriptPubKeyMan(t, internal);
4291  if (spk_man) {
4292  spk_mans.insert(spk_man);
4293  }
4294  }
4295  }
4296  return spk_mans;
4297 }
4298 
4299 std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
4300 {
4301  std::set<ScriptPubKeyMan*> spk_mans;
4302  for (const auto& spk_man_pair : m_spk_managers) {
4303  spk_mans.insert(spk_man_pair.second.get());
4304  }
4305  return spk_mans;
4306 }
4307 
4308 ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
4309 {
4310  const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
4311  std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
4312  if (it == spk_managers.end()) {
4313  WalletLogPrintf("%s scriptPubKey Manager for output type %d does not exist\n", internal ? "Internal" : "External", static_cast<int>(type));
4314  return nullptr;
4315  }
4316  return it->second;
4317 }
4318 
4319 std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const
4320 {
4321  std::set<ScriptPubKeyMan*> spk_mans;
4322  for (const auto& spk_man_pair : m_spk_managers) {
4323  if (spk_man_pair.second->CanProvide(script, sigdata)) {
4324  spk_mans.insert(spk_man_pair.second.get());
4325  }
4326  }
4327  return spk_mans;
4328 }
4329 
4331 {
4332  SignatureData sigdata;
4333  for (const auto& spk_man_pair : m_spk_managers) {
4334  if (spk_man_pair.second->CanProvide(script, sigdata)) {
4335  return spk_man_pair.second.get();
4336  }
4337  }
4338  return nullptr;
4339 }
4340 
4342 {
4343  if (m_spk_managers.count(id) > 0) {
4344  return m_spk_managers.at(id).get();
4345  }
4346  return nullptr;
4347 }
4348 
4349 std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
4350 {
4351  SignatureData sigdata;
4352  return GetSolvingProvider(script, sigdata);
4353 }
4354 
4355 std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
4356 {
4357  for (const auto& spk_man_pair : m_spk_managers) {
4358  if (spk_man_pair.second->CanProvide(script, sigdata)) {
4359  return spk_man_pair.second->GetSolvingProvider(script);
4360  }
4361  }
4362  return nullptr;
4363 }
4364 
4366 {
4368  return nullptr;
4369  }
4370  // Legacy wallets only have one ScriptPubKeyMan which is a LegacyScriptPubKeyMan.
4371  // Everything in m_internal_spk_managers and m_external_spk_managers point to the same legacyScriptPubKeyMan.
4373  if (it == m_internal_spk_managers.end()) return nullptr;
4374  return dynamic_cast<LegacyScriptPubKeyMan*>(it->second);
4375 }
4376 
4378 {
4380  return GetLegacyScriptPubKeyMan();
4381 }
4382 
4384 {
4386  return;
4387  }
4388 
4389  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this));
4390  for (const auto& type : OUTPUT_TYPES) {
4391  m_internal_spk_managers[type] = spk_manager.get();
4392  m_external_spk_managers[type] = spk_manager.get();
4393  }
4394  m_spk_managers[spk_manager->GetID()] = std::move(spk_manager);
4395 }
4396 
4398 {
4399  return vMasterKey;
4400 }
4401 
4403 {
4404  return !mapMasterKeys.empty();
4405 }
4406 
4408 {
4409  for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
4410  spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
4411  spk_man->NotifyCanGetAddressesChanged.connect(NotifyCanGetAddressesChanged);
4412  }
4413 }
4414 
4416 {
4417  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc));
4418  m_spk_managers[id] = std::move(spk_manager);
4419 }
4420 
4422 {
4424 
4425  // Make a seed
4426  CKey seed_key;
4427  seed_key.MakeNewKey(true);
4428  CPubKey seed = seed_key.GetPubKey();
4429  assert(seed_key.VerifyPubKey(seed));
4430 
4431  // Get the extended key
4432  CExtKey master_key;
4433  master_key.SetSeed(seed_key.begin(), seed_key.size());
4434 
4435  for (bool internal : {false, true}) {
4436  for (OutputType t : OUTPUT_TYPES) {
4437  auto spk_manager = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, internal));
4438  if (IsCrypted()) {
4439  if (IsLocked()) {
4440  throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
4441  }
4442  if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, nullptr)) {
4443  throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
4444  }
4445  }
4446  spk_manager->SetupDescriptorGeneration(master_key, t);
4447  uint256 id = spk_manager->GetID();
4448  m_spk_managers[id] = std::move(spk_manager);
4449  AddActiveScriptPubKeyMan(id, t, internal);
4450  }
4451  }
4452 }
4453 
4455 {
4456  WalletBatch batch(*database);
4457  if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
4458  throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
4459  }
4460  LoadActiveScriptPubKeyMan(id, type, internal);
4461 }
4462 
4464 {
4465  WalletLogPrintf("Setting spkMan to active: id = %s, type = %d, internal = %d\n", id.ToString(), static_cast<int>(type), static_cast<int>(internal));
4466  auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
4467  auto spk_man = m_spk_managers.at(id).get();
4468  spk_man->SetInternal(internal);
4469  spk_mans[type] = spk_man;
4470 
4472 }
4473 
4474 bool CWallet::IsLegacy() const
4475 {
4476  if (m_internal_spk_managers.count(OutputType::LEGACY) == 0) {
4477  return false;
4478  }
4479  auto spk_man = dynamic_cast<LegacyScriptPubKeyMan*>(m_internal_spk_managers.at(OutputType::LEGACY));
4480  return spk_man != nullptr;
4481 }
4482 
4484 {
4485  for (auto& spk_man_pair : m_spk_managers) {
4486  // Try to downcast to DescriptorScriptPubKeyMan then check if the descriptors match
4487  DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair.second.get());
4488  if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
4489  return spk_manager;
4490  }
4491  }
4492 
4493  return nullptr;
4494 }
4495 
4496 ScriptPubKeyMan* CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal)
4497 {
4499  WalletLogPrintf("Cannot add WalletDescriptor to a non-descriptor wallet\n");
4500  return nullptr;
4501  }
4502 
4503  LOCK(cs_wallet);
4504  auto new_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc));
4505 
4506  // If we already have this descriptor, remove it from the maps but add the existing cache to desc
4507  auto old_spk_man = GetDescriptorScriptPubKeyMan(desc);
4508  if (old_spk_man) {
4509  WalletLogPrintf("Update existing descriptor: %s\n", desc.descriptor->ToString());
4510 
4511  {
4512  LOCK(old_spk_man->cs_desc_man);
4513  new_spk_man->SetCache(old_spk_man->GetWalletDescriptor().cache);
4514  }
4515 
4516  // Remove from maps of active spkMans
4517  auto old_spk_man_id = old_spk_man->GetID();
4518  for (bool internal : {false, true}) {
4519  for (OutputType t : OUTPUT_TYPES) {
4520  auto active_spk_man = GetScriptPubKeyMan(t, internal);
4521  if (active_spk_man && active_spk_man->GetID() == old_spk_man_id) {
4522  if (internal) {
4523  m_internal_spk_managers.erase(t);
4524  } else {
4525  m_external_spk_managers.erase(t);
4526  }
4527  break;
4528  }
4529  }
4530  }
4531  m_spk_managers.erase(old_spk_man_id);
4532  }
4533 
4534  // Add the private keys to the descriptor
4535  for (const auto& entry : signing_provider.keys) {
4536  const CKey& key = entry.second;
4537  new_spk_man->AddDescriptorKey(key, key.GetPubKey());
4538  }
4539 
4540  // Top up key pool, the manager will generate new scriptPubKeys internally
4541  if (!new_spk_man->TopUp()) {
4542  WalletLogPrintf("Could not top up scriptPubKeys\n");
4543  return nullptr;
4544  }
4545 
4546  // Apply the label if necessary
4547  // Note: we disable labels for ranged descriptors
4548  if (!desc.descriptor->IsRange()) {
4549  auto script_pub_keys = new_spk_man->GetScriptPubKeys();
4550  if (script_pub_keys.empty()) {
4551  WalletLogPrintf("Could not generate scriptPubKeys (cache is empty)\n");
4552  return nullptr;
4553  }
4554 
4555  CTxDestination dest;
4556  if (!internal && ExtractDestination(script_pub_keys.at(0), dest)) {
4557  SetAddressBook(dest, label, "receive");
4558  }
4559  }
4560 
4561  // Save the descriptor to memory
4562  auto ret = new_spk_man.get();
4563  m_spk_managers[new_spk_man->GetID()] = std::move(new_spk_man);
4564 
4565  // Save the descriptor to DB
4566  ret->WriteDescriptor();
4567 
4568  return ret;
4569 }
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:3721
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:896
bool fChangeCached
Definition: wallet.h:340
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:4349
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:4383
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:751
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:639
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:3302
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:4474
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:1193
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:986
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:1307
CAmount GetImmatureWatchOnlyCredit(const bool fUseCache=true) const
Definition: wallet.cpp:1995
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:1120
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:3573
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:4139
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:2535
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:717
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:4308
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:642
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:57
Optional< T > MakeOptional(bool condition, T &&value)
Substitute for C++17 std::make_optional.
Definition: optional.h:18
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:25
static Mutex g_wallet_release_mutex
Definition: wallet.cpp: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:927
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:912
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:781
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:4256
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
FeeReason reason
Definition: fees.h:71
CAmount GetMinimumFee(const CWallet &wallet, unsigned int nTxBytes, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee considering user set parameters and the required fee.
Definition: fees.cpp:18
bool IsChange(const CTxOut &txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp: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:1002
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:4397
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:926
CAmount m_watchonly_untrusted_pending
Definition: wallet.h:930
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:931
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:4247
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:1023
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:3737
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:1126
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:4195
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:581
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:716
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:1232
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:929
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:1013
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:4463
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:4319
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1129
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:795
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:3204
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:3342
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:1111
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3255
bool isAbandoned() const
Definition: wallet.h:535
bool HasEncryptionKeys() const override
Definition: wallet.cpp:4402
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:4299
bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3585
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1453
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:3261
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:2403
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:1080
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
unsigned int nMasterKeyMaxID
Definition: wallet.h:755
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:3135
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:3175
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:758
CAmount m_mine_immature
Immature coinbases in the main chain.
Definition: wallet.h:928
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:4496
bool IsImmatureCoinBase() const
Definition: wallet.cpp:4189
int GetBlocksToMaturity() const
Definition: wallet.cpp:4180
int nDepth
Definition: wallet.h:565
Confirmation m_confirm
Definition: wallet.h:396
int64_t GetOldestKeyPoolTime() const
Definition: wallet.cpp:3357
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:2597
OutputType m_default_address_type
Definition: wallet.h:1014
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3605
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:4421
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:4156
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:4285
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:776
DescriptorScriptPubKeyMan * GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const
Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet...
Definition: wallet.cpp:4483
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:612
uint32_t n
Definition: transaction.h:30
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3579
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:2585
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:1238
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:3771
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:3730
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:3682
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:4377
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:4415
#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:610
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:4407
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:3381
#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:2667
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1287
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:3290
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:3593
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:721
bool isConflicted() const
Definition: wallet.h:543
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
bool fBroadcastTransactions
Definition: wallet.h:640
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:3795
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:3367
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:3567
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:4105
uint256 GetHash() const
Definition: block.cpp:11
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
Definition: wallet.cpp:3512
void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence) override
Definition: wallet.cpp:1161
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0)
bool setArray()
Definition: univalue.cpp:94
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return &lt;datadir&gt;/settings.json setting value.
Optional< OutputType > m_default_change_type
Default output type for change outputs.
Definition: wallet.h:1021
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:1104
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:681
MasterKeyMap mapMasterKeys
Definition: wallet.h:754
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:3101
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:83
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:3313
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::string &strPurpose)
Definition: wallet.cpp:3235
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:2709
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:4365
static bool IsCurrentForAntiFeeSniping(interfaces::Chain &chain, const uint256 &block_hash)
Definition: wallet.cpp:2649
CTransactionRef non_witness_utxo
Definition: psbt.h:50
CAmount effective_value
Definition: coinselection.h:79
bool IsCrypted() const
Definition: wallet.cpp:4242
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:4171
bool GetReservedDestination(CTxDestination &pubkey, bool internal)
Reserve an address.
Definition: wallet.cpp:3527
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:622
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:730
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:210
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:913
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:919
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
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:801
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
CFeeRate effective_fee
Definition: wallet.h:609
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:3758
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:1004
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:4151
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:23
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:1117
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:780
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:4095
bool m_signal_rbf
Definition: wallet.h:1003
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:4270
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:2502
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:3742
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:4454
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:3323
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:3549
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:2737
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:3558
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:3419
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:100