Bitcoin Core  21.99.0
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <wallet/wallet.h>
7 
8 #include <chain.h>
9 #include <consensus/consensus.h>
10 #include <consensus/validation.h>
11 #include <fs.h>
12 #include <interfaces/chain.h>
13 #include <interfaces/wallet.h>
14 #include <key.h>
15 #include <key_io.h>
16 #include <optional.h>
17 #include <policy/fees.h>
18 #include <policy/policy.h>
19 #include <primitives/block.h>
20 #include <primitives/transaction.h>
21 #include <script/descriptor.h>
22 #include <script/script.h>
23 #include <script/signingprovider.h>
24 #include <txmempool.h>
25 #include <util/bip32.h>
26 #include <util/check.h>
27 #include <util/error.h>
28 #include <util/fees.h>
29 #include <util/moneystr.h>
30 #include <util/rbf.h>
31 #include <util/string.h>
32 #include <util/translation.h>
33 #include <wallet/coincontrol.h>
34 #include <wallet/fees.h>
35 
36 #include <univalue.h>
37 
38 #include <algorithm>
39 #include <assert.h>
40 
41 #include <boost/algorithm/string/replace.hpp>
42 
44 
45 const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS{
47  "You need to rescan the blockchain in order to correctly mark used "
48  "destinations in the past. Until this is done, some destinations may "
49  "be considered unused, even if the opposite is the case."
50  },
51 };
52 
53 static const size_t OUTPUT_GROUP_MAX_ENTRIES = 10;
54 
56 static std::vector<std::shared_ptr<CWallet>> vpwallets GUARDED_BY(cs_wallets);
57 static std::list<LoadWalletFn> g_load_wallet_fns GUARDED_BY(cs_wallets);
58 
59 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
60 {
61  util::SettingsValue setting_value = chain.getRwSetting("wallet");
62  if (!setting_value.isArray()) setting_value.setArray();
63  for (const util::SettingsValue& value : setting_value.getValues()) {
64  if (value.isStr() && value.get_str() == wallet_name) return true;
65  }
66  setting_value.push_back(wallet_name);
67  return chain.updateRwSetting("wallet", setting_value);
68 }
69 
70 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
71 {
72  util::SettingsValue setting_value = chain.getRwSetting("wallet");
73  if (!setting_value.isArray()) return true;
75  for (const util::SettingsValue& value : setting_value.getValues()) {
76  if (!value.isStr() || value.get_str() != wallet_name) new_value.push_back(value);
77  }
78  if (new_value.size() == setting_value.size()) return true;
79  return chain.updateRwSetting("wallet", new_value);
80 }
81 
83  const std::string& wallet_name,
84  Optional<bool> load_on_startup,
85  std::vector<bilingual_str>& warnings)
86 {
87  if (load_on_startup == nullopt) return;
88  if (load_on_startup.value() && !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.value() && !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>.
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 {
342  AssertLockHeld(cs_wallet);
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 {
351  if (IsLocked() || IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
352  return;
353  }
354 
355  auto spk_man = GetLegacyScriptPubKeyMan();
356  if (!spk_man) {
357  return;
358  }
359 
360  spk_man->UpgradeKeyMetadata();
361  SetWalletFlag(WALLET_FLAG_KEY_ORIGIN_METADATA);
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
379  UpgradeKeyMetadata();
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(GetDatabase()).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(GetDatabase());
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(GetDatabase());
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;
458  AssertLockHeld(cs_wallet);
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 {
480  AssertLockHeld(cs_wallet);
481  auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
482  return (iter != mapTxSpends.end() && iter->first.hash == txid);
483 }
484 
486 {
487  GetDatabase().Flush();
488 }
489 
491 {
492  GetDatabase().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  const 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(GetDatabase());
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
656  if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) && !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET)) {
657  SetupDescriptorScriptPubKeyMans();
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  GetDatabase().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  GetDatabase().ReloadDbEnv();
676 
677  }
678  NotifyStatusChanged(this);
679 
680  return true;
681 }
682 
684 {
685  LOCK(cs_wallet);
686  WalletBatch batch(GetDatabase());
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 {
742  AssertLockHeld(cs_wallet);
743  int64_t nRet = nOrderPosNext++;
744  if (batch) {
745  batch->WriteOrderPosNext(nOrderPosNext);
746  } else {
747  WalletBatch(GetDatabase()).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(GetDatabase());
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 {
792  AssertLockHeld(cs_wallet);
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 {
812  AssertLockHeld(cs_wallet);
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()) {
824  LegacyScriptPubKeyMan* spk_man = GetLegacyScriptPubKeyMan();
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(GetDatabase(), fFlushOnClose);
850 
851  uint256 hash = tx->GetHash();
852 
853  if (IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
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;
872  wtx.nTimeReceived = chain().getAdjustedTime();
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  bool active;
950  int height;
951  if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().inActiveChain(active).height(height)) && active) {
952  // Update cached block height variable since it not stored in the
953  // serialized transaction.
954  wtx.m_confirm.block_height = height;
955  } else if (wtx.isConflicted() || wtx.isConfirmed()) {
956  // If tx block (or conflicting block) was reorged out of chain
957  // while the wallet was shutdown, change tx status to UNCONFIRMED
958  // and reset block height, hash, and index. ABANDONED tx don't have
959  // associated blocks and don't need to be updated. The case where a
960  // transaction was reorged out while online and then reconfirmed
961  // while offline is covered by the rescan logic.
962  wtx.setUnconfirmed();
963  wtx.m_confirm.hashBlock = uint256();
964  wtx.m_confirm.block_height = 0;
965  wtx.m_confirm.nIndex = 0;
966  }
967  }
968  if (/* insertion took place */ ins.second) {
969  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
970  }
971  AddToSpends(hash);
972  for (const CTxIn& txin : wtx.tx->vin) {
973  auto it = mapWallet.find(txin.prevout.hash);
974  if (it != mapWallet.end()) {
975  CWalletTx& prevtx = it->second;
976  if (prevtx.isConflicted()) {
977  MarkConflicted(prevtx.m_confirm.hashBlock, prevtx.m_confirm.block_height, wtx.GetHash());
978  }
979  }
980  }
981  return true;
982 }
983 
985 {
986  const CTransaction& tx = *ptx;
987  {
988  AssertLockHeld(cs_wallet);
989 
990  if (!confirm.hashBlock.IsNull()) {
991  for (const CTxIn& txin : tx.vin) {
992  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
993  while (range.first != range.second) {
994  if (range.first->second != tx.GetHash()) {
995  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);
996  MarkConflicted(confirm.hashBlock, confirm.block_height, range.first->second);
997  }
998  range.first++;
999  }
1000  }
1001  }
1002 
1003  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1004  if (fExisted && !fUpdate) return false;
1005  if (fExisted || IsMine(tx) || IsFromMe(tx))
1006  {
1007  /* Check if any keys in the wallet keypool that were supposed to be unused
1008  * have appeared in a new transaction. If so, remove those keys from the keypool.
1009  * This can happen when restoring an old wallet backup that does not contain
1010  * the mostly recently created transactions from newer versions of the wallet.
1011  */
1012 
1013  // loop though all outputs
1014  for (const CTxOut& txout: tx.vout) {
1015  for (const auto& spk_man_pair : m_spk_managers) {
1016  spk_man_pair.second->MarkUnusedAddresses(txout.scriptPubKey);
1017  }
1018  }
1019 
1020  // Block disconnection override an abandoned tx as unconfirmed
1021  // which means user may have to call abandontransaction again
1022  return AddToWallet(MakeTransactionRef(tx), confirm, /* update_wtx= */ nullptr, /* fFlushOnClose= */ false);
1023  }
1024  }
1025  return false;
1026 }
1027 
1029 {
1030  LOCK(cs_wallet);
1031  const CWalletTx* wtx = GetWalletTx(hashTx);
1032  return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() == 0 && !wtx->InMempool();
1033 }
1034 
1036 {
1037  for (const CTxIn& txin : tx->vin) {
1038  auto it = mapWallet.find(txin.prevout.hash);
1039  if (it != mapWallet.end()) {
1040  it->second.MarkDirty();
1041  }
1042  }
1043 }
1044 
1046 {
1047  LOCK(cs_wallet);
1048 
1049  WalletBatch batch(GetDatabase());
1050 
1051  std::set<uint256> todo;
1052  std::set<uint256> done;
1053 
1054  // Can't mark abandoned if confirmed or in mempool
1055  auto it = mapWallet.find(hashTx);
1056  assert(it != mapWallet.end());
1057  const CWalletTx& origtx = it->second;
1058  if (origtx.GetDepthInMainChain() != 0 || origtx.InMempool()) {
1059  return false;
1060  }
1061 
1062  todo.insert(hashTx);
1063 
1064  while (!todo.empty()) {
1065  uint256 now = *todo.begin();
1066  todo.erase(now);
1067  done.insert(now);
1068  auto it = mapWallet.find(now);
1069  assert(it != mapWallet.end());
1070  CWalletTx& wtx = it->second;
1071  int currentconfirm = wtx.GetDepthInMainChain();
1072  // If the orig tx was not in block, none of its spends can be
1073  assert(currentconfirm <= 0);
1074  // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1075  if (currentconfirm == 0 && !wtx.isAbandoned()) {
1076  // If the orig tx was not in block/mempool, none of its spends can be in mempool
1077  assert(!wtx.InMempool());
1078  wtx.setAbandoned();
1079  wtx.MarkDirty();
1080  batch.WriteTx(wtx);
1081  NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1082  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1083  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1084  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1085  if (!done.count(iter->second)) {
1086  todo.insert(iter->second);
1087  }
1088  iter++;
1089  }
1090  // If a transaction changes 'conflicted' state, that changes the balance
1091  // available of the outputs it spends. So force those to be recomputed
1092  MarkInputsDirty(wtx.tx);
1093  }
1094  }
1095 
1096  return true;
1097 }
1098 
1099 void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx)
1100 {
1101  LOCK(cs_wallet);
1102 
1103  int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
1104  // If number of conflict confirms cannot be determined, this means
1105  // that the block is still unknown or not yet part of the main chain,
1106  // for example when loading the wallet during a reindex. Do nothing in that
1107  // case.
1108  if (conflictconfirms >= 0)
1109  return;
1110 
1111  // Do not flush the wallet here for performance reasons
1112  WalletBatch batch(GetDatabase(), false);
1113 
1114  std::set<uint256> todo;
1115  std::set<uint256> done;
1116 
1117  todo.insert(hashTx);
1118 
1119  while (!todo.empty()) {
1120  uint256 now = *todo.begin();
1121  todo.erase(now);
1122  done.insert(now);
1123  auto it = mapWallet.find(now);
1124  assert(it != mapWallet.end());
1125  CWalletTx& wtx = it->second;
1126  int currentconfirm = wtx.GetDepthInMainChain();
1127  if (conflictconfirms < currentconfirm) {
1128  // Block is 'more conflicted' than current confirm; update.
1129  // Mark transaction as conflicted with this block.
1130  wtx.m_confirm.nIndex = 0;
1131  wtx.m_confirm.hashBlock = hashBlock;
1132  wtx.m_confirm.block_height = conflicting_height;
1133  wtx.setConflicted();
1134  wtx.MarkDirty();
1135  batch.WriteTx(wtx);
1136  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1137  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1138  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1139  if (!done.count(iter->second)) {
1140  todo.insert(iter->second);
1141  }
1142  iter++;
1143  }
1144  // If a transaction changes 'conflicted' state, that changes the balance
1145  // available of the outputs it spends. So force those to be recomputed
1146  MarkInputsDirty(wtx.tx);
1147  }
1148  }
1149 }
1150 
1151 void CWallet::SyncTransaction(const CTransactionRef& ptx, CWalletTx::Confirmation confirm, bool update_tx)
1152 {
1153  if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx))
1154  return; // Not one of ours
1155 
1156  // If a transaction changes 'conflicted' state, that changes the balance
1157  // available of the outputs it spends. So force those to be
1158  // recomputed, also:
1159  MarkInputsDirty(ptx);
1160 }
1161 
1162 void CWallet::transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) {
1163  LOCK(cs_wallet);
1164  SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
1165 
1166  auto it = mapWallet.find(tx->GetHash());
1167  if (it != mapWallet.end()) {
1168  it->second.fInMempool = true;
1169  }
1170 }
1171 
1172 void CWallet::transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) {
1173  LOCK(cs_wallet);
1174  auto it = mapWallet.find(tx->GetHash());
1175  if (it != mapWallet.end()) {
1176  it->second.fInMempool = false;
1177  }
1178  // Handle transactions that were removed from the mempool because they
1179  // conflict with transactions in a newly connected block.
1180  if (reason == MemPoolRemovalReason::CONFLICT) {
1181  // Trigger external -walletnotify notifications for these transactions.
1182  // Set Status::UNCONFIRMED instead 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 {
1239  m_best_block_time = GetTime();
1240 }
1241 
1242 
1243 void CWallet::BlockUntilSyncedToCurrentChain() const {
1244  AssertLockNotHeld(cs_wallet);
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 {
1256  AssertLockHeld(cs_wallet);
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 {
1287  AssertLockHeld(cs_wallet);
1288  return IsMine(txout.scriptPubKey);
1289 }
1290 
1292 {
1293  AssertLockHeld(cs_wallet);
1294  return IsMine(GetScriptForDestination(dest));
1295 }
1296 
1297 isminetype CWallet::IsMine(const CScript& script) const
1298 {
1299  AssertLockHeld(cs_wallet);
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).
1329  AssertLockHeld(cs_wallet);
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 {
1344  AssertLockHeld(cs_wallet);
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 {
1352  AssertLockHeld(cs_wallet);
1353  for (const CTxOut& txout : tx.vout)
1354  if (IsMine(txout))
1355  return true;
1356  return false;
1357 }
1358 
1360 {
1361  return (GetDebit(tx, ISMINE_ALL) > 0);
1362 }
1363 
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 
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(GetDatabase()).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(GetDatabase());
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 {
1469  UnsetWalletFlagWithDB(batch, WALLET_FLAG_BLANK_WALLET);
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  }
1484  m_wallet_flags = flags;
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(GetDatabase()).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(GetDatabase());
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 
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 
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 
1647  LOCK(pwallet->cs_wallet);
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  // Read block data
1775  CBlock block;
1776  chain().findBlock(block_hash, FoundBlock().data(block));
1777 
1778  // Find next block separately from reading data above, because reading
1779  // is slow and there might be a reorg while it is read.
1780  bool block_still_active = false;
1781  bool next_block = false;
1782  uint256 next_block_hash;
1783  chain().findBlock(block_hash, FoundBlock().inActiveChain(block_still_active).nextBlock(FoundBlock().inActiveChain(next_block).hash(next_block_hash)));
1784 
1785  if (!block.IsNull()) {
1786  LOCK(cs_wallet);
1787  if (!block_still_active) {
1788  // Abort scan if current block is no longer active, to prevent
1789  // marking transactions as coming from the wrong block.
1790  result.last_failed_block = block_hash;
1791  result.status = ScanResult::FAILURE;
1792  break;
1793  }
1794  for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1795  SyncTransaction(block.vtx[posInBlock], {CWalletTx::Status::CONFIRMED, block_height, block_hash, (int)posInBlock}, fUpdate);
1796  }
1797  // scan succeeded, record block as most recent successfully scanned
1798  result.last_scanned_block = block_hash;
1799  result.last_scanned_height = block_height;
1800  } else {
1801  // could not scan block, keep scanning but record this block as the most recent failure
1802  result.last_failed_block = block_hash;
1803  result.status = ScanResult::FAILURE;
1804  }
1805  if (max_height && block_height >= *max_height) {
1806  break;
1807  }
1808  {
1809  if (!next_block) {
1810  // break successfully when rescan has reached the tip, or
1811  // previous block is no longer on the chain due to a reorg
1812  break;
1813  }
1814 
1815  // increment block and verification progress
1816  block_hash = next_block_hash;
1817  ++block_height;
1818  progress_current = chain().guessVerificationProgress(block_hash);
1819 
1820  // handle updated tip hash
1821  const uint256 prev_tip_hash = tip_hash;
1822  tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1823  if (!max_height && prev_tip_hash != tip_hash) {
1824  // in case the tip has changed, update progress max
1825  progress_end = chain().guessVerificationProgress(tip_hash);
1826  }
1827  }
1828  }
1829  ShowProgress(strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), 100); // hide progress dialog in GUI
1830  if (block_height && fAbortRescan) {
1831  WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", block_height, progress_current);
1832  result.status = ScanResult::USER_ABORT;
1833  } else if (block_height && chain().shutdownRequested()) {
1834  WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", block_height, progress_current);
1835  result.status = ScanResult::USER_ABORT;
1836  } else {
1837  WalletLogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - start_time);
1838  }
1839  return result;
1840 }
1841 
1843 {
1844  // If transactions aren't being broadcasted, don't let them into local mempool either
1845  if (!fBroadcastTransactions)
1846  return;
1847  std::map<int64_t, CWalletTx*> mapSorted;
1848 
1849  // Sort pending wallet transactions based on their initial wallet insertion order
1850  for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
1851  const uint256& wtxid = item.first;
1852  CWalletTx& wtx = item.second;
1853  assert(wtx.GetHash() == wtxid);
1854 
1855  int nDepth = wtx.GetDepthInMainChain();
1856 
1857  if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1858  mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1859  }
1860  }
1861 
1862  // Try to add wallet transactions to memory pool
1863  for (const std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
1864  CWalletTx& wtx = *(item.second);
1865  std::string unused_err_string;
1866  wtx.SubmitMemoryPoolAndRelay(unused_err_string, false);
1867  }
1868 }
1869 
1870 bool CWalletTx::SubmitMemoryPoolAndRelay(std::string& err_string, bool relay)
1871 {
1872  // Can't relay if wallet is not broadcasting
1873  if (!pwallet->GetBroadcastTransactions()) return false;
1874  // Don't relay abandoned transactions
1875  if (isAbandoned()) return false;
1876  // Don't try to submit coinbase transactions. These would fail anyway but would
1877  // cause log spam.
1878  if (IsCoinBase()) return false;
1879  // Don't try to submit conflicted or confirmed transactions.
1880  if (GetDepthInMainChain() != 0) return false;
1881 
1882  // Submit transaction to mempool for relay
1883  pwallet->WalletLogPrintf("Submitting wtx %s to mempool for relay\n", GetHash().ToString());
1884  // We must set fInMempool here - while it will be re-set to true by the
1885  // entered-mempool callback, if we did not there would be a race where a
1886  // user could call sendmoney in a loop and hit spurious out of funds errors
1887  // because we think that this newly generated transaction's change is
1888  // unavailable as we're not yet aware that it is in the mempool.
1889  //
1890  // Irrespective of the failure reason, un-marking fInMempool
1891  // out-of-order is incorrect - it should be unmarked when
1892  // TransactionRemovedFromMempool fires.
1893  bool ret = pwallet->chain().broadcastTransaction(tx, pwallet->m_default_max_tx_fee, relay, err_string);
1894  fInMempool |= ret;
1895  return ret;
1896 }
1897 
1898 std::set<uint256> CWalletTx::GetConflicts() const
1899 {
1900  std::set<uint256> result;
1901  if (pwallet != nullptr)
1902  {
1903  uint256 myHash = GetHash();
1904  result = pwallet->GetConflicts(myHash);
1905  result.erase(myHash);
1906  }
1907  return result;
1908 }
1909 
1910 CAmount CWalletTx::GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate) const
1911 {
1912  auto& amount = m_amounts[type];
1913  if (recalculate || !amount.m_cached[filter]) {
1914  amount.Set(filter, type == DEBIT ? pwallet->GetDebit(*tx, filter) : pwallet->GetCredit(*tx, filter));
1915  m_is_cache_empty = false;
1916  }
1917  return amount.m_value[filter];
1918 }
1919 
1921 {
1922  if (tx->vin.empty())
1923  return 0;
1924 
1925  CAmount debit = 0;
1926  if (filter & ISMINE_SPENDABLE) {
1927  debit += GetCachableAmount(DEBIT, ISMINE_SPENDABLE);
1928  }
1929  if (filter & ISMINE_WATCH_ONLY) {
1930  debit += GetCachableAmount(DEBIT, ISMINE_WATCH_ONLY);
1931  }
1932  return debit;
1933 }
1934 
1936 {
1937  // Must wait until coinbase is safely deep enough in the chain before valuing it
1938  if (IsImmatureCoinBase())
1939  return 0;
1940 
1941  CAmount credit = 0;
1942  if (filter & ISMINE_SPENDABLE) {
1943  // GetBalance can assume transactions in mapWallet won't change
1944  credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE);
1945  }
1946  if (filter & ISMINE_WATCH_ONLY) {
1947  credit += GetCachableAmount(CREDIT, ISMINE_WATCH_ONLY);
1948  }
1949  return credit;
1950 }
1951 
1953 {
1954  if (IsImmatureCoinBase() && IsInMainChain()) {
1955  return GetCachableAmount(IMMATURE_CREDIT, ISMINE_SPENDABLE, !fUseCache);
1956  }
1957 
1958  return 0;
1959 }
1960 
1961 CAmount CWalletTx::GetAvailableCredit(bool fUseCache, const isminefilter& filter) const
1962 {
1963  if (pwallet == nullptr)
1964  return 0;
1965 
1966  // Avoid caching ismine for NO or ALL cases (could remove this check and simplify in the future).
1967  bool allow_cache = (filter & ISMINE_ALL) && (filter & ISMINE_ALL) != ISMINE_ALL;
1968 
1969  // Must wait until coinbase is safely deep enough in the chain before valuing it
1970  if (IsImmatureCoinBase())
1971  return 0;
1972 
1973  if (fUseCache && allow_cache && m_amounts[AVAILABLE_CREDIT].m_cached[filter]) {
1974  return m_amounts[AVAILABLE_CREDIT].m_value[filter];
1975  }
1976 
1977  bool allow_used_addresses = (filter & ISMINE_USED) || !pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE);
1978  CAmount nCredit = 0;
1979  uint256 hashTx = GetHash();
1980  for (unsigned int i = 0; i < tx->vout.size(); i++)
1981  {
1982  if (!pwallet->IsSpent(hashTx, i) && (allow_used_addresses || !pwallet->IsSpentKey(hashTx, i))) {
1983  const CTxOut &txout = tx->vout[i];
1984  nCredit += pwallet->GetCredit(txout, filter);
1985  if (!MoneyRange(nCredit))
1986  throw std::runtime_error(std::string(__func__) + " : value out of range");
1987  }
1988  }
1989 
1990  if (allow_cache) {
1991  m_amounts[AVAILABLE_CREDIT].Set(filter, nCredit);
1992  m_is_cache_empty = false;
1993  }
1994 
1995  return nCredit;
1996 }
1997 
1999 {
2000  if (IsImmatureCoinBase() && IsInMainChain()) {
2001  return GetCachableAmount(IMMATURE_CREDIT, ISMINE_WATCH_ONLY, !fUseCache);
2002  }
2003 
2004  return 0;
2005 }
2006 
2008 {
2009  if (fChangeCached)
2010  return nChangeCached;
2011  nChangeCached = pwallet->GetChange(*tx);
2012  fChangeCached = true;
2013  return nChangeCached;
2014 }
2015 
2017 {
2018  return fInMempool;
2019 }
2020 
2022 {
2023  std::set<uint256> trusted_parents;
2024  LOCK(pwallet->cs_wallet);
2025  return pwallet->IsTrusted(*this, trusted_parents);
2026 }
2027 
2028 bool CWallet::IsTrusted(const CWalletTx& wtx, std::set<uint256>& trusted_parents) const
2029 {
2030  AssertLockHeld(cs_wallet);
2031  // Quick answer in most cases
2032  if (!chain().checkFinalTx(*wtx.tx)) return false;
2033  int nDepth = wtx.GetDepthInMainChain();
2034  if (nDepth >= 1) return true;
2035  if (nDepth < 0) return false;
2036  // using wtx's cached debit
2037  if (!m_spend_zero_conf_change || !wtx.IsFromMe(ISMINE_ALL)) return false;
2038 
2039  // Don't trust unconfirmed transactions from us unless they are in the mempool.
2040  if (!wtx.InMempool()) return false;
2041 
2042  // Trusted if all inputs are from us and are in the mempool:
2043  for (const CTxIn& txin : wtx.tx->vin)
2044  {
2045  // Transactions not sent by us: not trusted
2046  const CWalletTx* parent = GetWalletTx(txin.prevout.hash);
2047  if (parent == nullptr) return false;
2048  const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
2049  // Check that this specific input being spent is trusted
2050  if (IsMine(parentOut) != ISMINE_SPENDABLE) return false;
2051  // If we've already trusted this parent, continue
2052  if (trusted_parents.count(parent->GetHash())) continue;
2053  // Recurse to check that the parent is also trusted
2054  if (!IsTrusted(*parent, trusted_parents)) return false;
2055  trusted_parents.insert(parent->GetHash());
2056  }
2057  return true;
2058 }
2059 
2060 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
2061 {
2062  CMutableTransaction tx1 {*this->tx};
2063  CMutableTransaction tx2 {*_tx.tx};
2064  for (auto& txin : tx1.vin) txin.scriptSig = CScript();
2065  for (auto& txin : tx2.vin) txin.scriptSig = CScript();
2066  return CTransaction(tx1) == CTransaction(tx2);
2067 }
2068 
2069 // Rebroadcast transactions from the wallet. We do this on a random timer
2070 // to slightly obfuscate which transactions come from our wallet.
2071 //
2072 // Ideally, we'd only resend transactions that we think should have been
2073 // mined in the most recent block. Any transaction that wasn't in the top
2074 // blockweight of transactions in the mempool shouldn't have been mined,
2075 // and so is probably just sitting in the mempool waiting to be confirmed.
2076 // Rebroadcasting does nothing to speed up confirmation and only damages
2077 // privacy.
2079 {
2080  // During reindex, importing and IBD, old wallet transactions become
2081  // unconfirmed. Don't resend them as that would spam other nodes.
2082  if (!chain().isReadyToBroadcast()) return;
2083 
2084  // Do this infrequently and randomly to avoid giving away
2085  // that these are our transactions.
2086  if (GetTime() < nNextResend || !fBroadcastTransactions) return;
2087  bool fFirst = (nNextResend == 0);
2088  // resend 12-36 hours from now, ~1 day on average.
2089  nNextResend = GetTime() + (12 * 60 * 60) + GetRand(24 * 60 * 60);
2090  if (fFirst) return;
2091 
2092  int submitted_tx_count = 0;
2093 
2094  { // cs_wallet scope
2095  LOCK(cs_wallet);
2096 
2097  // Relay transactions
2098  for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
2099  CWalletTx& wtx = item.second;
2100  // Attempt to rebroadcast all txes more than 5 minutes older than
2101  // the last block. SubmitMemoryPoolAndRelay() will not rebroadcast
2102  // any confirmed or conflicting txs.
2103  if (wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
2104  std::string unused_err_string;
2105  if (wtx.SubmitMemoryPoolAndRelay(unused_err_string, true)) ++submitted_tx_count;
2106  }
2107  } // cs_wallet
2108 
2109  if (submitted_tx_count > 0) {
2110  WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__, submitted_tx_count);
2111  }
2112 }
2113  // end of mapWallet
2115 
2117 {
2118  for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
2119  pwallet->ResendWalletTransactions();
2120  }
2121 }
2122 
2123 
2130 CWallet::Balance CWallet::GetBalance(const int min_depth, bool avoid_reuse) const
2131 {
2132  Balance ret;
2133  isminefilter reuse_filter = avoid_reuse ? ISMINE_NO : ISMINE_USED;
2134  {
2135  LOCK(cs_wallet);
2136  std::set<uint256> trusted_parents;
2137  for (const auto& entry : mapWallet)
2138  {
2139  const CWalletTx& wtx = entry.second;
2140  const bool is_trusted{IsTrusted(wtx, trusted_parents)};
2141  const int tx_depth{wtx.GetDepthInMainChain()};
2142  const CAmount tx_credit_mine{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_SPENDABLE | reuse_filter)};
2143  const CAmount tx_credit_watchonly{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_WATCH_ONLY | reuse_filter)};
2144  if (is_trusted && tx_depth >= min_depth) {
2145  ret.m_mine_trusted += tx_credit_mine;
2146  ret.m_watchonly_trusted += tx_credit_watchonly;
2147  }
2148  if (!is_trusted && tx_depth == 0 && wtx.InMempool()) {
2149  ret.m_mine_untrusted_pending += tx_credit_mine;
2150  ret.m_watchonly_untrusted_pending += tx_credit_watchonly;
2151  }
2152  ret.m_mine_immature += wtx.GetImmatureCredit();
2154  }
2155  }
2156  return ret;
2157 }
2158 
2160 {
2161  LOCK(cs_wallet);
2162 
2163  CAmount balance = 0;
2164  std::vector<COutput> vCoins;
2165  AvailableCoins(vCoins, true, coinControl);
2166  for (const COutput& out : vCoins) {
2167  if (out.fSpendable) {
2168  balance += out.tx->tx->vout[out.i].nValue;
2169  }
2170  }
2171  return balance;
2172 }
2173 
2174 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
2175 {
2176  AssertLockHeld(cs_wallet);
2177 
2178  vCoins.clear();
2179  CAmount nTotal = 0;
2180  // 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
2181  // a coin control object is provided, and has the avoid address reuse flag set to false, do we allow already used addresses
2182  bool allow_used_addresses = !IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
2183  const int min_depth = {coinControl ? coinControl->m_min_depth : DEFAULT_MIN_DEPTH};
2184  const int max_depth = {coinControl ? coinControl->m_max_depth : DEFAULT_MAX_DEPTH};
2185 
2186  std::set<uint256> trusted_parents;
2187  for (const auto& entry : mapWallet)
2188  {
2189  const uint256& wtxid = entry.first;
2190  const CWalletTx& wtx = entry.second;
2191 
2192  if (!chain().checkFinalTx(*wtx.tx)) {
2193  continue;
2194  }
2195 
2196  if (wtx.IsImmatureCoinBase())
2197  continue;
2198 
2199  int nDepth = wtx.GetDepthInMainChain();
2200  if (nDepth < 0)
2201  continue;
2202 
2203  // We should not consider coins which aren't at least in our mempool
2204  // It's possible for these to be conflicted via ancestors which we may never be able to detect
2205  if (nDepth == 0 && !wtx.InMempool())
2206  continue;
2207 
2208  bool safeTx = IsTrusted(wtx, trusted_parents);
2209 
2210  // We should not consider coins from transactions that are replacing
2211  // other transactions.
2212  //
2213  // Example: There is a transaction A which is replaced by bumpfee
2214  // transaction B. In this case, we want to prevent creation of
2215  // a transaction B' which spends an output of B.
2216  //
2217  // Reason: If transaction A were initially confirmed, transactions B
2218  // and B' would no longer be valid, so the user would have to create
2219  // a new transaction C to replace B'. However, in the case of a
2220  // one-block reorg, transactions B' and C might BOTH be accepted,
2221  // when the user only wanted one of them. Specifically, there could
2222  // be a 1-block reorg away from the chain where transactions A and C
2223  // were accepted to another chain where B, B', and C were all
2224  // accepted.
2225  if (nDepth == 0 && wtx.mapValue.count("replaces_txid")) {
2226  safeTx = false;
2227  }
2228 
2229  // Similarly, we should not consider coins from transactions that
2230  // have been replaced. In the example above, we would want to prevent
2231  // creation of a transaction A' spending an output of A, because if
2232  // transaction B were initially confirmed, conflicting with A and
2233  // A', we wouldn't want to the user to create a transaction D
2234  // intending to replace A', but potentially resulting in a scenario
2235  // where A, A', and D could all be accepted (instead of just B and
2236  // D, or just A and A' like the user would want).
2237  if (nDepth == 0 && wtx.mapValue.count("replaced_by_txid")) {
2238  safeTx = false;
2239  }
2240 
2241  if (fOnlySafe && !safeTx) {
2242  continue;
2243  }
2244 
2245  if (nDepth < min_depth || nDepth > max_depth) {
2246  continue;
2247  }
2248 
2249  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
2250  // Only consider selected coins if add_inputs is false
2251  if (coinControl && !coinControl->m_add_inputs && !coinControl->IsSelected(COutPoint(entry.first, i))) {
2252  continue;
2253  }
2254 
2255  if (wtx.tx->vout[i].nValue < nMinimumAmount || wtx.tx->vout[i].nValue > nMaximumAmount)
2256  continue;
2257 
2258  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
2259  continue;
2260 
2261  if (IsLockedCoin(entry.first, i))
2262  continue;
2263 
2264  if (IsSpent(wtxid, i))
2265  continue;
2266 
2267  isminetype mine = IsMine(wtx.tx->vout[i]);
2268 
2269  if (mine == ISMINE_NO) {
2270  continue;
2271  }
2272 
2273  if (!allow_used_addresses && IsSpentKey(wtxid, i)) {
2274  continue;
2275  }
2276 
2277  std::unique_ptr<SigningProvider> provider = GetSolvingProvider(wtx.tx->vout[i].scriptPubKey);
2278 
2279  bool solvable = provider ? IsSolvable(*provider, wtx.tx->vout[i].scriptPubKey) : false;
2280  bool spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && solvable));
2281 
2282  vCoins.push_back(COutput(&wtx, i, nDepth, spendable, solvable, safeTx, (coinControl && coinControl->fAllowWatchOnly)));
2283 
2284  // Checks the sum amount of all UTXO's.
2285  if (nMinimumSumAmount != MAX_MONEY) {
2286  nTotal += wtx.tx->vout[i].nValue;
2287 
2288  if (nTotal >= nMinimumSumAmount) {
2289  return;
2290  }
2291  }
2292 
2293  // Checks the maximum number of UTXO's.
2294  if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2295  return;
2296  }
2297  }
2298  }
2299 }
2300 
2301 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2302 {
2303  AssertLockHeld(cs_wallet);
2304 
2305  std::map<CTxDestination, std::vector<COutput>> result;
2306  std::vector<COutput> availableCoins;
2307 
2308  AvailableCoins(availableCoins);
2309 
2310  for (const COutput& coin : availableCoins) {
2311  CTxDestination address;
2312  if ((coin.fSpendable || (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && coin.fSolvable)) &&
2313  ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2314  result[address].emplace_back(std::move(coin));
2315  }
2316  }
2317 
2318  std::vector<COutPoint> lockedCoins;
2319  ListLockedCoins(lockedCoins);
2320  // Include watch-only for LegacyScriptPubKeyMan wallets without private keys
2321  const bool include_watch_only = GetLegacyScriptPubKeyMan() && IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
2322  const isminetype is_mine_filter = include_watch_only ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
2323  for (const COutPoint& output : lockedCoins) {
2324  auto it = mapWallet.find(output.hash);
2325  if (it != mapWallet.end()) {
2326  int depth = it->second.GetDepthInMainChain();
2327  if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2328  IsMine(it->second.tx->vout[output.n]) == is_mine_filter
2329  ) {
2330  CTxDestination address;
2331  if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2332  result[address].emplace_back(
2333  &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2334  }
2335  }
2336  }
2337  }
2338 
2339  return result;
2340 }
2341 
2343 {
2344  AssertLockHeld(cs_wallet);
2345  const CTransaction* ptx = &tx;
2346  int n = output;
2347  while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2348  const COutPoint& prevout = ptx->vin[0].prevout;
2349  auto it = mapWallet.find(prevout.hash);
2350  if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2351  !IsMine(it->second.tx->vout[prevout.n])) {
2352  break;
2353  }
2354  ptx = it->second.tx.get();
2355  n = prevout.n;
2356  }
2357  return ptx->vout[n];
2358 }
2359 
2360 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
2361  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const
2362 {
2363  setCoinsRet.clear();
2364  nValueRet = 0;
2365 
2366  std::vector<OutputGroup> utxo_pool;
2367  if (coin_selection_params.use_bnb) {
2368  // Get long term estimate
2369  FeeCalculation feeCalc;
2370  CCoinControl temp;
2371  temp.m_confirm_target = 1008;
2372  CFeeRate long_term_feerate = GetMinimumFeeRate(*this, temp, &feeCalc);
2373 
2374  // Calculate cost of change
2375  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);
2376 
2377  // Filter by the min conf specs and add to utxo_pool and calculate effective value
2378  for (OutputGroup& group : groups) {
2379  if (!group.EligibleForSpending(eligibility_filter)) continue;
2380 
2381  if (coin_selection_params.m_subtract_fee_outputs) {
2382  // 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
2383  group.SetFees(CFeeRate(0) /* effective_feerate */, long_term_feerate);
2384  } else {
2385  group.SetFees(coin_selection_params.effective_fee, long_term_feerate);
2386  }
2387 
2388  OutputGroup pos_group = group.GetPositiveOnlyGroup();
2389  if (pos_group.effective_value > 0) utxo_pool.push_back(pos_group);
2390  }
2391  // Calculate the fees for things that aren't inputs
2392  CAmount not_input_fees = coin_selection_params.effective_fee.GetFee(coin_selection_params.tx_noinputs_size);
2393  bnb_used = true;
2394  return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change, setCoinsRet, nValueRet, not_input_fees);
2395  } else {
2396  // Filter by the min conf specs and add to utxo_pool
2397  for (const OutputGroup& group : groups) {
2398  if (!group.EligibleForSpending(eligibility_filter)) continue;
2399  utxo_pool.push_back(group);
2400  }
2401  bnb_used = false;
2402  return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
2403  }
2404 }
2405 
2406 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
2407 {
2408  std::vector<COutput> vCoins(vAvailableCoins);
2409  CAmount value_to_select = nTargetValue;
2410 
2411  // Default to bnb was not used. If we use it, we set it later
2412  bnb_used = false;
2413 
2414  // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2415  if (coin_control.HasSelected() && !coin_control.fAllowOtherInputs)
2416  {
2417  for (const COutput& out : vCoins)
2418  {
2419  if (!out.fSpendable)
2420  continue;
2421  nValueRet += out.tx->tx->vout[out.i].nValue;
2422  setCoinsRet.insert(out.GetInputCoin());
2423  }
2424  return (nValueRet >= nTargetValue);
2425  }
2426 
2427  // calculate value from preset inputs and store them
2428  std::set<CInputCoin> setPresetCoins;
2429  CAmount nValueFromPresetInputs = 0;
2430 
2431  std::vector<COutPoint> vPresetInputs;
2432  coin_control.ListSelected(vPresetInputs);
2433  for (const COutPoint& outpoint : vPresetInputs)
2434  {
2435  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2436  if (it != mapWallet.end())
2437  {
2438  const CWalletTx& wtx = it->second;
2439  // Clearly invalid input, fail
2440  if (wtx.tx->vout.size() <= outpoint.n) {
2441  return false;
2442  }
2443  // Just to calculate the marginal byte size
2444  CInputCoin coin(wtx.tx, outpoint.n, wtx.GetSpendSize(outpoint.n, false));
2445  nValueFromPresetInputs += coin.txout.nValue;
2446  if (coin.m_input_bytes <= 0) {
2447  return false; // Not solvable, can't estimate size for fee
2448  }
2449  coin.effective_value = coin.txout.nValue - coin_selection_params.effective_fee.GetFee(coin.m_input_bytes);
2450  if (coin_selection_params.use_bnb) {
2451  value_to_select -= coin.effective_value;
2452  } else {
2453  value_to_select -= coin.txout.nValue;
2454  }
2455  setPresetCoins.insert(coin);
2456  } else {
2457  return false; // TODO: Allow non-wallet inputs
2458  }
2459  }
2460 
2461  // remove preset inputs from vCoins
2462  for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coin_control.HasSelected();)
2463  {
2464  if (setPresetCoins.count(it->GetInputCoin()))
2465  it = vCoins.erase(it);
2466  else
2467  ++it;
2468  }
2469 
2470  unsigned int limit_ancestor_count = 0;
2471  unsigned int limit_descendant_count = 0;
2472  chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
2473  size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
2474  size_t max_descendants = (size_t)std::max<int64_t>(1, limit_descendant_count);
2475  bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2476 
2477  // form groups from remaining coins; note that preset coins will not
2478  // automatically have their associated (same address) coins included
2479  if (coin_control.m_avoid_partial_spends && vCoins.size() > OUTPUT_GROUP_MAX_ENTRIES) {
2480  // Cases where we have 11+ outputs all pointing to the same destination may result in
2481  // privacy leaks as they will potentially be deterministically sorted. We solve that by
2482  // explicitly shuffling the outputs before processing
2483  Shuffle(vCoins.begin(), vCoins.end(), FastRandomContext());
2484  }
2485  std::vector<OutputGroup> groups = GroupOutputs(vCoins, !coin_control.m_avoid_partial_spends, max_ancestors);
2486 
2487  bool res = value_to_select <= 0 ||
2488  SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 6, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
2489  SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(1, 1, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
2490  (m_spend_zero_conf_change && SelectCoinsMinConf(value_to_select, CoinEligibilityFilter(0, 1, 2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
2491  (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)) ||
2492  (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)) ||
2493  (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)) ||
2494  (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));
2495 
2496  // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2497  util::insert(setCoinsRet, setPresetCoins);
2498 
2499  // add preset inputs to the total value selected
2500  nValueRet += nValueFromPresetInputs;
2501 
2502  return res;
2503 }
2504 
2506 {
2507  AssertLockHeld(cs_wallet);
2508 
2509  // Build coins map
2510  std::map<COutPoint, Coin> coins;
2511  for (auto& input : tx.vin) {
2512  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2513  if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2514  return false;
2515  }
2516  const CWalletTx& wtx = mi->second;
2517  coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], wtx.m_confirm.block_height, wtx.IsCoinBase());
2518  }
2519  std::map<int, std::string> input_errors;
2520  return SignTransaction(tx, coins, SIGHASH_ALL, input_errors);
2521 }
2522 
2523 bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
2524 {
2525  // Try to sign with all ScriptPubKeyMans
2526  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2527  // spk_man->SignTransaction will return true if the transaction is complete,
2528  // so we can exit early and return true if that happens
2529  if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2530  return true;
2531  }
2532  }
2533 
2534  // At this point, one input was not fully signed otherwise we would have exited already
2535  return false;
2536 }
2537 
2538 TransactionError CWallet::FillPSBT(PartiallySignedTransaction& psbtx, bool& complete, int sighash_type, bool sign, bool bip32derivs, size_t * n_signed) const
2539 {
2540  if (n_signed) {
2541  *n_signed = 0;
2542  }
2543  LOCK(cs_wallet);
2544  // Get all of the previous transactions
2545  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2546  const CTxIn& txin = psbtx.tx->vin[i];
2547  PSBTInput& input = psbtx.inputs.at(i);
2548 
2549  if (PSBTInputSigned(input)) {
2550  continue;
2551  }
2552 
2553  // If we have no utxo, grab it from the wallet.
2554  if (!input.non_witness_utxo) {
2555  const uint256& txhash = txin.prevout.hash;
2556  const auto it = mapWallet.find(txhash);
2557  if (it != mapWallet.end()) {
2558  const CWalletTx& wtx = it->second;
2559  // We only need the non_witness_utxo, which is a superset of the witness_utxo.
2560  // The signing code will switch to the smaller witness_utxo if this is ok.
2561  input.non_witness_utxo = wtx.tx;
2562  }
2563  }
2564  }
2565 
2566  // Fill in information from ScriptPubKeyMans
2567  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2568  int n_signed_this_spkm = 0;
2569  TransactionError res = spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs, &n_signed_this_spkm);
2570  if (res != TransactionError::OK) {
2571  return res;
2572  }
2573 
2574  if (n_signed) {
2575  (*n_signed) += n_signed_this_spkm;
2576  }
2577  }
2578 
2579  // Complete if every input is now signed
2580  complete = true;
2581  for (const auto& input : psbtx.inputs) {
2582  complete &= PSBTInputSigned(input);
2583  }
2584 
2585  return TransactionError::OK;
2586 }
2587 
2588 SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2589 {
2590  SignatureData sigdata;
2591  CScript script_pub_key = GetScriptForDestination(pkhash);
2592  for (const auto& spk_man_pair : m_spk_managers) {
2593  if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2594  return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2595  }
2596  }
2598 }
2599 
2600 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2601 {
2602  std::vector<CRecipient> vecSend;
2603 
2604  // Turn the txout set into a CRecipient vector.
2605  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
2606  const CTxOut& txOut = tx.vout[idx];
2607  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2608  vecSend.push_back(recipient);
2609  }
2610 
2611  coinControl.fAllowOtherInputs = true;
2612 
2613  for (const CTxIn& txin : tx.vin) {
2614  coinControl.Select(txin.prevout);
2615  }
2616 
2617  // Acquire the locks to prevent races to the new locked unspents between the
2618  // CreateTransaction call and LockCoin calls (when lockUnspents is true).
2619  LOCK(cs_wallet);
2620 
2621  CTransactionRef tx_new;
2622  FeeCalculation fee_calc_out;
2623  if (!CreateTransaction(vecSend, tx_new, nFeeRet, nChangePosInOut, error, coinControl, fee_calc_out, false)) {
2624  return false;
2625  }
2626 
2627  if (nChangePosInOut != -1) {
2628  tx.vout.insert(tx.vout.begin() + nChangePosInOut, tx_new->vout[nChangePosInOut]);
2629  }
2630 
2631  // Copy output sizes from new transaction; they may have had the fee
2632  // subtracted from them.
2633  for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
2634  tx.vout[idx].nValue = tx_new->vout[idx].nValue;
2635  }
2636 
2637  // Add new txins while keeping original txin scriptSig/order.
2638  for (const CTxIn& txin : tx_new->vin) {
2639  if (!coinControl.IsSelected(txin.prevout)) {
2640  tx.vin.push_back(txin);
2641 
2642  }
2643  if (lockUnspents) {
2644  LockCoin(txin.prevout);
2645  }
2646 
2647  }
2648 
2649  return true;
2650 }
2651 
2652 static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256& block_hash)
2653 {
2654  if (chain.isInitialBlockDownload()) {
2655  return false;
2656  }
2657  constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
2658  int64_t block_time;
2659  CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
2660  if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
2661  return false;
2662  }
2663  return true;
2664 }
2665 
2670 static uint32_t GetLocktimeForNewTransaction(interfaces::Chain& chain, const uint256& block_hash, int block_height)
2671 {
2672  uint32_t locktime;
2673  // Discourage fee sniping.
2674  //
2675  // For a large miner the value of the transactions in the best block and
2676  // the mempool can exceed the cost of deliberately attempting to mine two
2677  // blocks to orphan the current best block. By setting nLockTime such that
2678  // only the next block can include the transaction, we discourage this
2679  // practice as the height restricted and limited blocksize gives miners
2680  // considering fee sniping fewer options for pulling off this attack.
2681  //
2682  // A simple way to think about this is from the wallet's point of view we
2683  // always want the blockchain to move forward. By setting nLockTime this
2684  // way we're basically making the statement that we only want this
2685  // transaction to appear in the next block; we don't want to potentially
2686  // encourage reorgs by allowing transactions to appear at lower heights
2687  // than the next block in forks of the best chain.
2688  //
2689  // Of course, the subsidy is high enough, and transaction volume low
2690  // enough, that fee sniping isn't a problem yet, but by implementing a fix
2691  // now we ensure code won't be written that makes assumptions about
2692  // nLockTime that preclude a fix later.
2693  if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
2694  locktime = block_height;
2695 
2696  // Secondly occasionally randomly pick a nLockTime even further back, so
2697  // that transactions that are delayed after signing for whatever reason,
2698  // e.g. high-latency mix networks and some CoinJoin implementations, have
2699  // better privacy.
2700  if (GetRandInt(10) == 0)
2701  locktime = std::max(0, (int)locktime - GetRandInt(100));
2702  } else {
2703  // If our chain is lagging behind, we can't discourage fee sniping nor help
2704  // the privacy of high-latency transactions. To avoid leaking a potentially
2705  // unique "nLockTime fingerprint", set nLockTime to a constant.
2706  locktime = 0;
2707  }
2708  assert(locktime < LOCKTIME_THRESHOLD);
2709  return locktime;
2710 }
2711 
2712 OutputType CWallet::TransactionChangeType(const Optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const
2713 {
2714  // If -changetype is specified, always use that change type.
2715  if (change_type) {
2716  return *change_type;
2717  }
2718 
2719  // if m_default_address_type is legacy, use legacy address as change (even
2720  // if some of the outputs are P2WPKH or P2WSH).
2721  if (m_default_address_type == OutputType::LEGACY) {
2722  return OutputType::LEGACY;
2723  }
2724 
2725  // if any destination is P2WPKH or P2WSH, use P2WPKH for the change
2726  // output.
2727  for (const auto& recipient : vecSend) {
2728  // Check if any destination contains a witness program:
2729  int witnessversion = 0;
2730  std::vector<unsigned char> witnessprogram;
2731  if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2732  return OutputType::BECH32;
2733  }
2734  }
2735 
2736  // else use m_default_address_type for change
2737  return m_default_address_type;
2738 }
2739 
2741  const std::vector<CRecipient>& vecSend,
2743  CAmount& nFeeRet,
2744  int& nChangePosInOut,
2746  const CCoinControl& coin_control,
2747  FeeCalculation& fee_calc_out,
2748  bool sign)
2749 {
2750  CAmount nValue = 0;
2751  const OutputType change_type = TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : m_default_change_type, vecSend);
2752  ReserveDestination reservedest(this, change_type);
2753  int nChangePosRequest = nChangePosInOut;
2754  unsigned int nSubtractFeeFromAmount = 0;
2755  for (const auto& recipient : vecSend)
2756  {
2757  if (nValue < 0 || recipient.nAmount < 0)
2758  {
2759  error = _("Transaction amounts must not be negative");
2760  return false;
2761  }
2762  nValue += recipient.nAmount;
2763 
2764  if (recipient.fSubtractFeeFromAmount)
2765  nSubtractFeeFromAmount++;
2766  }
2767  if (vecSend.empty())
2768  {
2769  error = _("Transaction must have at least one recipient");
2770  return false;
2771  }
2772 
2773  CMutableTransaction txNew;
2774  FeeCalculation feeCalc;
2775  CAmount nFeeNeeded;
2776  int nBytes;
2777  {
2778  std::set<CInputCoin> setCoins;
2779  LOCK(cs_wallet);
2780  txNew.nLockTime = GetLocktimeForNewTransaction(chain(), GetLastBlockHash(), GetLastBlockHeight());
2781  {
2782  std::vector<COutput> vAvailableCoins;
2783  AvailableCoins(vAvailableCoins, true, &coin_control, 1, MAX_MONEY, MAX_MONEY, 0);
2784  CoinSelectionParams coin_selection_params; // Parameters for coin selection, init with dummy
2785 
2786  // Create change script that will be used if we need change
2787  // TODO: pass in scriptChange instead of reservedest so
2788  // change transaction isn't always pay-to-bitcoin-address
2789  CScript scriptChange;
2790 
2791  // coin control: send change to custom address
2792  if (!std::get_if<CNoDestination>(&coin_control.destChange)) {
2793  scriptChange = GetScriptForDestination(coin_control.destChange);
2794  } else { // no coin control: send change to newly generated address
2795  // Note: We use a new key here to keep it from being obvious which side is the change.
2796  // The drawback is that by not reusing a previous key, the change may be lost if a
2797  // backup is restored, if the backup doesn't have the new private key for the change.
2798  // If we reused the old key, it would be possible to add code to look for and
2799  // rediscover unknown transactions that were written with keys of ours to recover
2800  // post-backup change.
2801 
2802  // Reserve a new key pair from key pool. If it fails, provide a dummy
2803  // destination in case we don't need change.
2804  CTxDestination dest;
2805  if (!reservedest.GetReservedDestination(dest, true)) {
2806  error = _("Transaction needs a change address, but we can't generate it. Please call keypoolrefill first.");
2807  }
2808  scriptChange = GetScriptForDestination(dest);
2809  // A valid destination implies a change script (and
2810  // vice-versa). An empty change script will abort later, if the
2811  // change keypool ran out, but change is required.
2812  CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
2813  }
2814  CTxOut change_prototype_txout(0, scriptChange);
2815  coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
2816 
2817  CFeeRate discard_rate = GetDiscardRate(*this);
2818 
2819  // Get the fee rate to use effective values in coin selection
2820  CFeeRate nFeeRateNeeded = GetMinimumFeeRate(*this, coin_control, &feeCalc);
2821  // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
2822  // provided one
2823  if (coin_control.m_feerate && nFeeRateNeeded > *coin_control.m_feerate) {
2824  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));
2825  return false;
2826  }
2827 
2828  nFeeRet = 0;
2829  bool pick_new_inputs = true;
2830  CAmount nValueIn = 0;
2831 
2832  // BnB selector is the only selector used when this is true.
2833  // That should only happen on the first pass through the loop.
2834  coin_selection_params.use_bnb = true;
2835  coin_selection_params.m_subtract_fee_outputs = nSubtractFeeFromAmount != 0; // If we are doing subtract fee from recipient, don't use effective values
2836  // Start with no fee and loop until there is enough fee
2837  while (true)
2838  {
2839  nChangePosInOut = nChangePosRequest;
2840  txNew.vin.clear();
2841  txNew.vout.clear();
2842  bool fFirst = true;
2843 
2844  CAmount nValueToSelect = nValue;
2845  if (nSubtractFeeFromAmount == 0)
2846  nValueToSelect += nFeeRet;
2847 
2848  // vouts to the payees
2849  if (!coin_selection_params.m_subtract_fee_outputs) {
2850  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)
2851  }
2852  for (const auto& recipient : vecSend)
2853  {
2854  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2855 
2856  if (recipient.fSubtractFeeFromAmount)
2857  {
2858  assert(nSubtractFeeFromAmount != 0);
2859  txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2860 
2861  if (fFirst) // first receiver pays the remainder not divisible by output count
2862  {
2863  fFirst = false;
2864  txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2865  }
2866  }
2867  // Include the fee cost for outputs. Note this is only used for BnB right now
2868  if (!coin_selection_params.m_subtract_fee_outputs) {
2869  coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, PROTOCOL_VERSION);
2870  }
2871 
2872  if (IsDust(txout, chain().relayDustFee()))
2873  {
2874  if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2875  {
2876  if (txout.nValue < 0)
2877  error = _("The transaction amount is too small to pay the fee");
2878  else
2879  error = _("The transaction amount is too small to send after the fee has been deducted");
2880  }
2881  else
2882  error = _("Transaction amount too small");
2883  return false;
2884  }
2885  txNew.vout.push_back(txout);
2886  }
2887 
2888  // Choose coins to use
2889  bool bnb_used = false;
2890  if (pick_new_inputs) {
2891  nValueIn = 0;
2892  setCoins.clear();
2893  int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, this);
2894  // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
2895  // as lower-bound to allow BnB to do it's thing
2896  if (change_spend_size == -1) {
2897  coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
2898  } else {
2899  coin_selection_params.change_spend_size = (size_t)change_spend_size;
2900  }
2901  coin_selection_params.effective_fee = nFeeRateNeeded;
2902  if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coin_control, coin_selection_params, bnb_used))
2903  {
2904  // If BnB was used, it was the first pass. No longer the first pass and continue loop with knapsack.
2905  if (bnb_used) {
2906  coin_selection_params.use_bnb = false;
2907  continue;
2908  }
2909  else {
2910  error = _("Insufficient funds");
2911  return false;
2912  }
2913  }
2914  } else {
2915  bnb_used = false;
2916  }
2917 
2918  const CAmount nChange = nValueIn - nValueToSelect;
2919  if (nChange > 0)
2920  {
2921  // Fill a vout to ourself
2922  CTxOut newTxOut(nChange, scriptChange);
2923 
2924  // Never create dust outputs; if we would, just
2925  // add the dust to the fee.
2926  // The nChange when BnB is used is always going to go to fees.
2927  if (IsDust(newTxOut, discard_rate) || bnb_used)
2928  {
2929  nChangePosInOut = -1;
2930  nFeeRet += nChange;
2931  }
2932  else
2933  {
2934  if (nChangePosInOut == -1)
2935  {
2936  // Insert change txn at random position:
2937  nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2938  }
2939  else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2940  {
2941  error = _("Change index out of range");
2942  return false;
2943  }
2944 
2945  std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2946  txNew.vout.insert(position, newTxOut);
2947  }
2948  } else {
2949  nChangePosInOut = -1;
2950  }
2951 
2952  // Dummy fill vin for maximum size estimation
2953  //
2954  for (const auto& coin : setCoins) {
2955  txNew.vin.push_back(CTxIn(coin.outpoint,CScript()));
2956  }
2957 
2958  nBytes = CalculateMaximumSignedTxSize(CTransaction(txNew), this, coin_control.fAllowWatchOnly);
2959  if (nBytes < 0) {
2960  error = _("Signing transaction failed");
2961  return false;
2962  }
2963 
2964  nFeeNeeded = GetMinimumFee(*this, nBytes, coin_control, &feeCalc);
2965  if (feeCalc.reason == FeeReason::FALLBACK && !m_allow_fallback_fee) {
2966  // eventually allow a fallback fee
2967  error = _("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.");
2968  return false;
2969  }
2970 
2971  if (nFeeRet >= nFeeNeeded) {
2972  // Reduce fee to only the needed amount if possible. This
2973  // prevents potential overpayment in fees if the coins
2974  // selected to meet nFeeNeeded result in a transaction that
2975  // requires less fee than the prior iteration.
2976 
2977  // If we have no change and a big enough excess fee, then
2978  // try to construct transaction again only without picking
2979  // new inputs. We now know we only need the smaller fee
2980  // (because of reduced tx size) and so we should add a
2981  // change output. Only try this once.
2982  if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2983  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
2984  CAmount fee_needed_with_change = GetMinimumFee(*this, tx_size_with_change, coin_control, nullptr);
2985  CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2986  if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2987  pick_new_inputs = false;
2988  nFeeRet = fee_needed_with_change;
2989  continue;
2990  }
2991  }
2992 
2993  // If we have change output already, just increase it
2994  if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2995  CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2996  std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2997  change_position->nValue += extraFeePaid;
2998  nFeeRet -= extraFeePaid;
2999  }
3000  break; // Done, enough fee included.
3001  }
3002  else if (!pick_new_inputs) {
3003  // This shouldn't happen, we should have had enough excess
3004  // fee to pay for the new output and still meet nFeeNeeded
3005  // Or we should have just subtracted fee from recipients and
3006  // nFeeNeeded should not have changed
3007  error = _("Transaction fee and change calculation failed");
3008  return false;
3009  }
3010 
3011  // Try to reduce change to include necessary fee
3012  if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
3013  CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
3014  std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
3015  // Only reduce change if remaining amount is still a large enough output.
3016  if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
3017  change_position->nValue -= additionalFeeNeeded;
3018  nFeeRet += additionalFeeNeeded;
3019  break; // Done, able to increase fee from change
3020  }
3021  }
3022 
3023  // If subtracting fee from recipients, we now know what fee we
3024  // need to subtract, we have no reason to reselect inputs
3025  if (nSubtractFeeFromAmount > 0) {
3026  pick_new_inputs = false;
3027  }
3028 
3029  // Include more fee and try again.
3030  nFeeRet = nFeeNeeded;
3031  coin_selection_params.use_bnb = false;
3032  continue;
3033  }
3034 
3035  // Give up if change keypool ran out and change is required
3036  if (scriptChange.empty() && nChangePosInOut != -1) {
3037  return false;
3038  }
3039  }
3040 
3041  // Shuffle selected coins and fill in final vin
3042  txNew.vin.clear();
3043  std::vector<CInputCoin> selected_coins(setCoins.begin(), setCoins.end());
3044  Shuffle(selected_coins.begin(), selected_coins.end(), FastRandomContext());
3045 
3046  // Note how the sequence number is set to non-maxint so that
3047  // the nLockTime set above actually works.
3048  //
3049  // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
3050  // we use the highest possible value in that range (maxint-2)
3051  // to avoid conflicting with other possible uses of nSequence,
3052  // and in the spirit of "smallest possible change from prior
3053  // behavior."
3054  const uint32_t nSequence = coin_control.m_signal_bip125_rbf.value_or(m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
3055  for (const auto& coin : selected_coins) {
3056  txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));
3057  }
3058 
3059  if (sign && !SignTransaction(txNew)) {
3060  error = _("Signing transaction failed");
3061  return false;
3062  }
3063 
3064  // Return the constructed transaction data.
3065  tx = MakeTransactionRef(std::move(txNew));
3066 
3067  // Limit size
3069  {
3070  error = _("Transaction too large");
3071  return false;
3072  }
3073  }
3074 
3075  if (nFeeRet > m_default_max_tx_fee) {
3077  return false;
3078  }
3079 
3080  if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
3081  // Lastly, ensure this tx will pass the mempool's chain limits
3082  if (!chain().checkChainLimits(tx)) {
3083  error = _("Transaction has too long of a mempool chain");
3084  return false;
3085  }
3086  }
3087 
3088  // Before we return success, we assume any change key will be used to prevent
3089  // accidental re-use.
3090  reservedest.KeepDestination();
3091  fee_calc_out = feeCalc;
3092 
3093  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",
3094  nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
3095  feeCalc.est.pass.start, feeCalc.est.pass.end,
3096  (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,
3097  feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
3098  feeCalc.est.fail.start, feeCalc.est.fail.end,
3099  (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,
3100  feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
3101  return true;
3102 }
3103 
3105  const std::vector<CRecipient>& vecSend,
3107  CAmount& nFeeRet,
3108  int& nChangePosInOut,
3110  const CCoinControl& coin_control,
3111  FeeCalculation& fee_calc_out,
3112  bool sign)
3113 {
3114  int nChangePosIn = nChangePosInOut;
3115  Assert(!tx); // tx is an out-param. TODO change the return type from bool to tx (or nullptr)
3116  bool res = CreateTransactionInternal(vecSend, tx, nFeeRet, nChangePosInOut, error, coin_control, fee_calc_out, sign);
3117  // try with avoidpartialspends unless it's enabled already
3118  if (res && nFeeRet > 0 /* 0 means non-functional fee rate estimation */ && m_max_aps_fee > -1 && !coin_control.m_avoid_partial_spends) {
3119  CCoinControl tmp_cc = coin_control;
3120  tmp_cc.m_avoid_partial_spends = true;
3121  CAmount nFeeRet2;
3122  CTransactionRef tx2;
3123  int nChangePosInOut2 = nChangePosIn;
3124  bilingual_str error2; // fired and forgotten; if an error occurs, we discard the results
3125  if (CreateTransactionInternal(vecSend, tx2, nFeeRet2, nChangePosInOut2, error2, tmp_cc, fee_calc_out, sign)) {
3126  // if fee of this alternative one is within the range of the max fee, we use this one
3127  const bool use_aps = nFeeRet2 <= nFeeRet + m_max_aps_fee;
3128  WalletLogPrintf("Fee non-grouped = %lld, grouped = %lld, using %s\n", nFeeRet, nFeeRet2, use_aps ? "grouped" : "non-grouped");
3129  if (use_aps) {
3130  tx = tx2;
3131  nFeeRet = nFeeRet2;
3132  nChangePosInOut = nChangePosInOut2;
3133  }
3134  }
3135  }
3136  return res;
3137 }
3138 
3139 void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
3140 {
3141  LOCK(cs_wallet);
3142  WalletLogPrintf("CommitTransaction:\n%s", tx->ToString()); /* Continued */
3143 
3144  // Add tx to wallet, because if it has change it's also ours,
3145  // otherwise just for transaction history.
3146  AddToWallet(tx, {}, [&](CWalletTx& wtx, bool new_tx) {
3147  CHECK_NONFATAL(wtx.mapValue.empty());
3148  CHECK_NONFATAL(wtx.vOrderForm.empty());
3149  wtx.mapValue = std::move(mapValue);
3150  wtx.vOrderForm = std::move(orderForm);
3151  wtx.fTimeReceivedIsTxTime = true;
3152  wtx.fFromMe = true;
3153  return true;
3154  });
3155 
3156  // Notify that old coins are spent
3157  for (const CTxIn& txin : tx->vin) {
3158  CWalletTx &coin = mapWallet.at(txin.prevout.hash);
3159  coin.MarkDirty();
3161  }
3162 
3163  // Get the inserted-CWalletTx from mapWallet so that the
3164  // fInMempool flag is cached properly
3165  CWalletTx& wtx = mapWallet.at(tx->GetHash());
3166 
3167  if (!fBroadcastTransactions) {
3168  // Don't submit tx to the mempool
3169  return;
3170  }
3171 
3172  std::string err_string;
3173  if (!wtx.SubmitMemoryPoolAndRelay(err_string, true)) {
3174  WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
3175  // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3176  }
3177 }
3178 
3179 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3180 {
3181  LOCK(cs_wallet);
3182 
3183  fFirstRunRet = false;
3184  DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
3185  if (nLoadWalletRet == DBErrors::NEED_REWRITE)
3186  {
3187  if (GetDatabase().Rewrite("\x04pool"))
3188  {
3189  for (const auto& spk_man_pair : m_spk_managers) {
3190  spk_man_pair.second->RewriteDB();
3191  }
3192  }
3193  }
3194 
3195  // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
3196  fFirstRunRet = m_spk_managers.empty() && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
3197  if (fFirstRunRet) {
3198  assert(m_external_spk_managers.empty());
3199  assert(m_internal_spk_managers.empty());
3200  }
3201 
3202  if (nLoadWalletRet != DBErrors::LOAD_OK)
3203  return nLoadWalletRet;
3204 
3205  return DBErrors::LOAD_OK;
3206 }
3207 
3208 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3209 {
3210  AssertLockHeld(cs_wallet);
3211  DBErrors nZapSelectTxRet = WalletBatch(GetDatabase()).ZapSelectTx(vHashIn, vHashOut);
3212  for (const uint256& hash : vHashOut) {
3213  const auto& it = mapWallet.find(hash);
3214  wtxOrdered.erase(it->second.m_it_wtxOrdered);
3215  for (const auto& txin : it->second.tx->vin)
3216  mapTxSpends.erase(txin.prevout);
3217  mapWallet.erase(it);
3218  NotifyTransactionChanged(this, hash, CT_DELETED);
3219  }
3220 
3221  if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
3222  {
3223  if (GetDatabase().Rewrite("\x04pool"))
3224  {
3225  for (const auto& spk_man_pair : m_spk_managers) {
3226  spk_man_pair.second->RewriteDB();
3227  }
3228  }
3229  }
3230 
3231  if (nZapSelectTxRet != DBErrors::LOAD_OK)
3232  return nZapSelectTxRet;
3233 
3234  MarkDirty();
3235 
3236  return DBErrors::LOAD_OK;
3237 }
3238 
3239 bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3240 {
3241  bool fUpdated = false;
3242  bool is_mine;
3243  {
3244  LOCK(cs_wallet);
3245  std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
3246  fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
3247  m_address_book[address].SetLabel(strName);
3248  if (!strPurpose.empty()) /* update purpose only if requested */
3249  m_address_book[address].purpose = strPurpose;
3250  is_mine = IsMine(address) != ISMINE_NO;
3251  }
3252  NotifyAddressBookChanged(this, address, strName, is_mine,
3253  strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3254  if (!strPurpose.empty() && !batch.WritePurpose(EncodeDestination(address), strPurpose))
3255  return false;
3256  return batch.WriteName(EncodeDestination(address), strName);
3257 }
3258 
3259 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3260 {
3261  WalletBatch batch(GetDatabase());
3262  return SetAddressBookWithDB(batch, address, strName, strPurpose);
3263 }
3264 
3266 {
3267  bool is_mine;
3268  WalletBatch batch(GetDatabase());
3269  {
3270  LOCK(cs_wallet);
3271  // 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)
3272  // NOTE: This isn't a problem for sending addresses because they never have any DestData yet!
3273  // When adding new DestData, it should be considered here whether to retain or delete it (or move it?).
3274  if (IsMine(address)) {
3275  WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, PACKAGE_BUGREPORT);
3276  return false;
3277  }
3278  // Delete destdata tuples associated with address
3279  std::string strAddress = EncodeDestination(address);
3280  for (const std::pair<const std::string, std::string> &item : m_address_book[address].destdata)
3281  {
3282  batch.EraseDestData(strAddress, item.first);
3283  }
3284  m_address_book.erase(address);
3285  is_mine = IsMine(address) != ISMINE_NO;
3286  }
3287 
3288  NotifyAddressBookChanged(this, address, "", is_mine, "", CT_DELETED);
3289 
3290  batch.ErasePurpose(EncodeDestination(address));
3291  return batch.EraseName(EncodeDestination(address));
3292 }
3293 
3295 {
3296  AssertLockHeld(cs_wallet);
3297 
3298  unsigned int count = 0;
3299  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3300  count += spk_man->KeypoolCountExternalKeys();
3301  }
3302 
3303  return count;
3304 }
3305 
3306 unsigned int CWallet::GetKeyPoolSize() const
3307 {
3308  AssertLockHeld(cs_wallet);
3309 
3310  unsigned int count = 0;
3311  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3312  count += spk_man->GetKeyPoolSize();
3313  }
3314  return count;
3315 }
3316 
3317 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3318 {
3319  LOCK(cs_wallet);
3320  bool res = true;
3321  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3322  res &= spk_man->TopUp(kpSize);
3323  }
3324  return res;
3325 }
3326 
3327 bool CWallet::GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error)
3328 {
3329  LOCK(cs_wallet);
3330  error.clear();
3331  bool result = false;
3332  auto spk_man = GetScriptPubKeyMan(type, false /* internal */);
3333  if (spk_man) {
3334  spk_man->TopUp();
3335  result = spk_man->GetNewDestination(type, dest, error);
3336  } else {
3337  error = strprintf("Error: No %s addresses available.", FormatOutputType(type));
3338  }
3339  if (result) {
3340  SetAddressBook(dest, label, "receive");
3341  }
3342 
3343  return result;
3344 }
3345 
3347 {
3348  LOCK(cs_wallet);
3349  error.clear();
3350 
3351  ReserveDestination reservedest(this, type);
3352  if (!reservedest.GetReservedDestination(dest, true)) {
3353  error = _("Error: Keypool ran out, please call keypoolrefill first").translated;
3354  return false;
3355  }
3356 
3357  reservedest.KeepDestination();
3358  return true;
3359 }
3360 
3362 {
3363  LOCK(cs_wallet);
3364  int64_t oldestKey = std::numeric_limits<int64_t>::max();
3365  for (const auto& spk_man_pair : m_spk_managers) {
3366  oldestKey = std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
3367  }
3368  return oldestKey;
3369 }
3370 
3371 void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
3372  for (auto& entry : mapWallet) {
3373  CWalletTx& wtx = entry.second;
3374  if (wtx.m_is_cache_empty) continue;
3375  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
3376  CTxDestination dst;
3377  if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.count(dst)) {
3378  wtx.MarkDirty();
3379  break;
3380  }
3381  }
3382  }
3383 }
3384 
3385 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() const
3386 {
3387  std::map<CTxDestination, CAmount> balances;
3388 
3389  {
3390  LOCK(cs_wallet);
3391  std::set<uint256> trusted_parents;
3392  for (const auto& walletEntry : mapWallet)
3393  {
3394  const CWalletTx& wtx = walletEntry.second;
3395 
3396  if (!IsTrusted(wtx, trusted_parents))
3397  continue;
3398 
3399  if (wtx.IsImmatureCoinBase())
3400  continue;
3401 
3402  int nDepth = wtx.GetDepthInMainChain();
3403  if (nDepth < (wtx.IsFromMe(ISMINE_ALL) ? 0 : 1))
3404  continue;
3405 
3406  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++)
3407  {
3408  CTxDestination addr;
3409  if (!IsMine(wtx.tx->vout[i]))
3410  continue;
3411  if(!ExtractDestination(wtx.tx->vout[i].scriptPubKey, addr))
3412  continue;
3413 
3414  CAmount n = IsSpent(walletEntry.first, i) ? 0 : wtx.tx->vout[i].nValue;
3415  balances[addr] += n;
3416  }
3417  }
3418  }
3419 
3420  return balances;
3421 }
3422 
3423 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings() const
3424 {
3425  AssertLockHeld(cs_wallet);
3426  std::set< std::set<CTxDestination> > groupings;
3427  std::set<CTxDestination> grouping;
3428 
3429  for (const auto& walletEntry : mapWallet)
3430  {
3431  const CWalletTx& wtx = walletEntry.second;
3432 
3433  if (wtx.tx->vin.size() > 0)
3434  {
3435  bool any_mine = false;
3436  // group all input addresses with each other
3437  for (const CTxIn& txin : wtx.tx->vin)
3438  {
3439  CTxDestination address;
3440  if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3441  continue;
3442  if(!ExtractDestination(mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
3443  continue;
3444  grouping.insert(address);
3445  any_mine = true;
3446  }
3447 
3448  // group change with input addresses
3449  if (any_mine)
3450  {
3451  for (const CTxOut& txout : wtx.tx->vout)
3452  if (IsChange(txout))
3453  {
3454  CTxDestination txoutAddr;
3455  if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3456  continue;
3457  grouping.insert(txoutAddr);
3458  }
3459  }
3460  if (grouping.size() > 0)
3461  {
3462  groupings.insert(grouping);
3463  grouping.clear();
3464  }
3465  }
3466 
3467  // group lone addrs by themselves
3468  for (const auto& txout : wtx.tx->vout)
3469  if (IsMine(txout))
3470  {
3471  CTxDestination address;
3472  if(!ExtractDestination(txout.scriptPubKey, address))
3473  continue;
3474  grouping.insert(address);
3475  groupings.insert(grouping);
3476  grouping.clear();
3477  }
3478  }
3479 
3480  std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3481  std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3482  for (std::set<CTxDestination> _grouping : groupings)
3483  {
3484  // make a set of all the groups hit by this new group
3485  std::set< std::set<CTxDestination>* > hits;
3486  std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3487  for (const CTxDestination& address : _grouping)
3488  if ((it = setmap.find(address)) != setmap.end())
3489  hits.insert((*it).second);
3490 
3491  // merge all hit groups into a new single group and delete old groups
3492  std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3493  for (std::set<CTxDestination>* hit : hits)
3494  {
3495  merged->insert(hit->begin(), hit->end());
3496  uniqueGroupings.erase(hit);
3497  delete hit;
3498  }
3499  uniqueGroupings.insert(merged);
3500 
3501  // update setmap
3502  for (const CTxDestination& element : *merged)
3503  setmap[element] = merged;
3504  }
3505 
3506  std::set< std::set<CTxDestination> > ret;
3507  for (const std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3508  {
3509  ret.insert(*uniqueGrouping);
3510  delete uniqueGrouping;
3511  }
3512 
3513  return ret;
3514 }
3515 
3516 std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
3517 {
3518  LOCK(cs_wallet);
3519  std::set<CTxDestination> result;
3520  for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book)
3521  {
3522  if (item.second.IsChange()) continue;
3523  const CTxDestination& address = item.first;
3524  const std::string& strName = item.second.GetLabel();
3525  if (strName == label)
3526  result.insert(address);
3527  }
3528  return result;
3529 }
3530 
3532 {
3533  m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
3534  if (!m_spk_man) {
3535  return false;
3536  }
3537 
3538 
3539  if (nIndex == -1)
3540  {
3541  m_spk_man->TopUp();
3542 
3543  CKeyPool keypool;
3544  if (!m_spk_man->GetReservedDestination(type, internal, address, nIndex, keypool)) {
3545  return false;
3546  }
3547  fInternal = keypool.fInternal;
3548  }
3549  dest = address;
3550  return true;
3551 }
3552 
3554 {
3555  if (nIndex != -1) {
3556  m_spk_man->KeepDestination(nIndex, type);
3557  }
3558  nIndex = -1;
3559  address = CNoDestination();
3560 }
3561 
3563 {
3564  if (nIndex != -1) {
3565  m_spk_man->ReturnDestination(nIndex, fInternal, address);
3566  }
3567  nIndex = -1;
3568  address = CNoDestination();
3569 }
3570 
3571 void CWallet::LockCoin(const COutPoint& output)
3572 {
3573  AssertLockHeld(cs_wallet);
3574  setLockedCoins.insert(output);
3575 }
3576 
3577 void CWallet::UnlockCoin(const COutPoint& output)
3578 {
3579  AssertLockHeld(cs_wallet);
3580  setLockedCoins.erase(output);
3581 }
3582 
3584 {
3585  AssertLockHeld(cs_wallet);
3586  setLockedCoins.clear();
3587 }
3588 
3589 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3590 {
3591  AssertLockHeld(cs_wallet);
3592  COutPoint outpt(hash, n);
3593 
3594  return (setLockedCoins.count(outpt) > 0);
3595 }
3596 
3597 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3598 {
3599  AssertLockHeld(cs_wallet);
3600  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3601  it != setLockedCoins.end(); it++) {
3602  COutPoint outpt = (*it);
3603  vOutpts.push_back(outpt);
3604  }
3605 }
3606  // end of Actions
3608 
3609 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
3610  AssertLockHeld(cs_wallet);
3611  mapKeyBirth.clear();
3612 
3613  LegacyScriptPubKeyMan* spk_man = GetLegacyScriptPubKeyMan();
3614  assert(spk_man != nullptr);
3615  LOCK(spk_man->cs_KeyStore);
3616 
3617  // get birth times for keys with metadata
3618  for (const auto& entry : spk_man->mapKeyMetadata) {
3619  if (entry.second.nCreateTime) {
3620  mapKeyBirth[entry.first] = entry.second.nCreateTime;
3621  }
3622  }
3623 
3624  // map in which we'll infer heights of other keys
3625  std::map<CKeyID, const CWalletTx::Confirmation*> mapKeyFirstBlock;
3626  CWalletTx::Confirmation max_confirm;
3627  max_confirm.block_height = GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
3628  CHECK_NONFATAL(chain().findAncestorByHeight(GetLastBlockHash(), max_confirm.block_height, FoundBlock().hash(max_confirm.hashBlock)));
3629  for (const CKeyID &keyid : spk_man->GetKeys()) {
3630  if (mapKeyBirth.count(keyid) == 0)
3631  mapKeyFirstBlock[keyid] = &max_confirm;
3632  }
3633 
3634  // if there are no such keys, we're done
3635  if (mapKeyFirstBlock.empty())
3636  return;
3637 
3638  // find first block that affects those keys, if there are any left
3639  for (const auto& entry : mapWallet) {
3640  // iterate over all wallet transactions...
3641  const CWalletTx &wtx = entry.second;
3642  if (wtx.m_confirm.status == CWalletTx::CONFIRMED) {
3643  // ... which are already in a block
3644  for (const CTxOut &txout : wtx.tx->vout) {
3645  // iterate over all their outputs
3646  for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
3647  // ... and all their affected keys
3648  auto rit = mapKeyFirstBlock.find(keyid);
3649  if (rit != mapKeyFirstBlock.end() && wtx.m_confirm.block_height < rit->second->block_height) {
3650  rit->second = &wtx.m_confirm;
3651  }
3652  }
3653  }
3654  }
3655  }
3656 
3657  // Extract block timestamps for those keys
3658  for (const auto& entry : mapKeyFirstBlock) {
3659  int64_t block_time;
3660  CHECK_NONFATAL(chain().findBlock(entry.second->hashBlock, FoundBlock().time(block_time)));
3661  mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW; // block times can be 2h off
3662  }
3663 }
3664 
3686 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3687 {
3688  unsigned int nTimeSmart = wtx.nTimeReceived;
3689  if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
3690  int64_t blocktime;
3691  if (chain().findBlock(wtx.m_confirm.hashBlock, FoundBlock().time(blocktime))) {
3692  int64_t latestNow = wtx.nTimeReceived;
3693  int64_t latestEntry = 0;
3694 
3695  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3696  int64_t latestTolerated = latestNow + 300;
3697  const TxItems& txOrdered = wtxOrdered;
3698  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3699  CWalletTx* const pwtx = it->second;
3700  if (pwtx == &wtx) {
3701  continue;
3702  }
3703  int64_t nSmartTime;
3704  nSmartTime = pwtx->nTimeSmart;
3705  if (!nSmartTime) {
3706  nSmartTime = pwtx->nTimeReceived;
3707  }
3708  if (nSmartTime <= latestTolerated) {
3709  latestEntry = nSmartTime;
3710  if (nSmartTime > latestNow) {
3711  latestNow = nSmartTime;
3712  }
3713  break;
3714  }
3715  }
3716 
3717  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3718  } else {
3719  WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.m_confirm.hashBlock.ToString());
3720  }
3721  }
3722  return nTimeSmart;
3723 }
3724 
3725 bool CWallet::AddDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key, const std::string &value)
3726 {
3727  if (std::get_if<CNoDestination>(&dest))
3728  return false;
3729 
3730  m_address_book[dest].destdata.insert(std::make_pair(key, value));
3731  return batch.WriteDestData(EncodeDestination(dest), key, value);
3732 }
3733 
3734 bool CWallet::EraseDestData(WalletBatch& batch, const CTxDestination &dest, const std::string &key)
3735 {
3736  if (!m_address_book[dest].destdata.erase(key))
3737  return false;
3738  return batch.EraseDestData(EncodeDestination(dest), key);
3739 }
3740 
3741 void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3742 {
3743  m_address_book[dest].destdata.insert(std::make_pair(key, value));
3744 }
3745 
3746 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3747 {
3748  std::map<CTxDestination, CAddressBookData>::const_iterator i = m_address_book.find(dest);
3749  if(i != m_address_book.end())
3750  {
3751  CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3752  if(j != i->second.destdata.end())
3753  {
3754  if(value)
3755  *value = j->second;
3756  return true;
3757  }
3758  }
3759  return false;
3760 }
3761 
3762 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3763 {
3764  std::vector<std::string> values;
3765  for (const auto& address : m_address_book) {
3766  for (const auto& data : address.second.destdata) {
3767  if (!data.first.compare(0, prefix.size(), prefix)) {
3768  values.emplace_back(data.second);
3769  }
3770  }
3771  }
3772  return values;
3773 }
3774 
3775 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
3776 {
3777  // Do some checking on wallet path. It should be either a:
3778  //
3779  // 1. Path where a directory can be created.
3780  // 2. Path to an existing directory.
3781  // 3. Path to a symlink to a directory.
3782  // 4. For backwards compatibility, the name of a data file in -walletdir.
3783  const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), name);
3784  fs::file_type path_type = fs::symlink_status(wallet_path).type();
3785  if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
3786  (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
3787  (path_type == fs::regular_file && fs::path(name).filename() == name))) {
3788  error_string = Untranslated(strprintf(
3789  "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
3790  "database/log.?????????? files can be stored, a location where such a directory could be created, "
3791  "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
3792  name, GetWalletDir()));
3794  return nullptr;
3795  }
3796  return MakeDatabase(wallet_path, options, status, error_string);
3797 }
3798 
3799 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)
3800 {
3801  const std::string& walletFile = database->Filename();
3802 
3803  chain.initMessage(_("Loading wallet...").translated);
3804 
3805  int64_t nStart = GetTimeMillis();
3806  bool fFirstRun = true;
3807  // TODO: Can't use std::make_shared because we need a custom deleter but
3808  // should be possible to use std::allocate_shared.
3809  std::shared_ptr<CWallet> walletInstance(new CWallet(&chain, name, std::move(database)), ReleaseWallet);
3810  DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3811  if (nLoadWalletRet != DBErrors::LOAD_OK) {
3812  if (nLoadWalletRet == DBErrors::CORRUPT) {
3813  error = strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
3814  return nullptr;
3815  }
3816  else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
3817  {
3818  warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3819  " or address book entries might be missing or incorrect."),
3820  walletFile));
3821  }
3822  else if (nLoadWalletRet == DBErrors::TOO_NEW) {
3823  error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, PACKAGE_NAME);
3824  return nullptr;
3825  }
3826  else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
3827  {
3828  error = strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME);
3829  return nullptr;
3830  }
3831  else {
3832  error = strprintf(_("Error loading %s"), walletFile);
3833  return nullptr;
3834  }
3835  }
3836 
3837  if (fFirstRun)
3838  {
3839  // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3840  walletInstance->SetMinVersion(FEATURE_LATEST);
3841 
3842  walletInstance->AddWalletFlags(wallet_creation_flags);
3843 
3844  // Only create LegacyScriptPubKeyMan when not descriptor wallet
3845  if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
3846  walletInstance->SetupLegacyScriptPubKeyMan();
3847  }
3848 
3849  if (!(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
3850  LOCK(walletInstance->cs_wallet);
3851  if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
3852  walletInstance->SetupDescriptorScriptPubKeyMans();
3853  // SetupDescriptorScriptPubKeyMans already calls SetupGeneration for us so we don't need to call SetupGeneration separately
3854  } else {
3855  // Legacy wallets need SetupGeneration here.
3856  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
3857  if (!spk_man->SetupGeneration()) {
3858  error = _("Unable to generate initial keys");
3859  return nullptr;
3860  }
3861  }
3862  }
3863  }
3864 
3865  walletInstance->chainStateFlushed(chain.getTipLocator());
3866  } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
3867  // Make it impossible to disable private keys after creation
3868  error = strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile);
3869  return NULL;
3870  } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
3871  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
3872  if (spk_man->HavePrivateKeys()) {
3873  warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
3874  break;
3875  }
3876  }
3877  }
3878 
3879  if (!gArgs.GetArg("-addresstype", "").empty()) {
3880  if (!ParseOutputType(gArgs.GetArg("-addresstype", ""), walletInstance->m_default_address_type)) {
3881  error = strprintf(_("Unknown address type '%s'"), gArgs.GetArg("-addresstype", ""));
3882  return nullptr;
3883  }
3884  }
3885 
3886  if (!gArgs.GetArg("-changetype", "").empty()) {
3887  OutputType out_type;
3888  if (!ParseOutputType(gArgs.GetArg("-changetype", ""), out_type)) {
3889  error = strprintf(_("Unknown change type '%s'"), gArgs.GetArg("-changetype", ""));
3890  return nullptr;
3891  }
3892  walletInstance->m_default_change_type = out_type;
3893  }
3894 
3895  if (gArgs.IsArgSet("-mintxfee")) {
3896  CAmount n = 0;
3897  if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n) {
3898  error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""));
3899  return nullptr;
3900  }
3901  if (n > HIGH_TX_FEE_PER_KB) {
3902  warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
3903  _("This is the minimum transaction fee you pay on every transaction."));
3904  }
3905  walletInstance->m_min_fee = CFeeRate(n);
3906  }
3907 
3908  if (gArgs.IsArgSet("-maxapsfee")) {
3909  const std::string max_aps_fee{gArgs.GetArg("-maxapsfee", "")};
3910  CAmount n = 0;
3911  if (max_aps_fee == "-1") {
3912  n = -1;
3913  } else if (!ParseMoney(max_aps_fee, n)) {
3914  error = AmountErrMsg("maxapsfee", max_aps_fee);
3915  return nullptr;
3916  }
3917  if (n > HIGH_APS_FEE) {
3918  warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
3919  _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
3920  }
3921  walletInstance->m_max_aps_fee = n;
3922  }
3923 
3924  if (gArgs.IsArgSet("-fallbackfee")) {
3925  CAmount nFeePerK = 0;
3926  if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
3927  error = strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", ""));
3928  return nullptr;
3929  }
3930  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
3931  warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
3932  _("This is the transaction fee you may pay when fee estimates are not available."));
3933  }
3934  walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
3935  }
3936  // Disable fallback fee in case value was set to 0, enable if non-null value
3937  walletInstance->m_allow_fallback_fee = walletInstance->m_fallback_fee.GetFeePerK() != 0;
3938 
3939  if (gArgs.IsArgSet("-discardfee")) {
3940  CAmount nFeePerK = 0;
3941  if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK)) {
3942  error = strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", ""));
3943  return nullptr;
3944  }
3945  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
3946  warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
3947  _("This is the transaction fee you may discard if change is smaller than dust at this level"));
3948  }
3949  walletInstance->m_discard_rate = CFeeRate(nFeePerK);
3950  }
3951  if (gArgs.IsArgSet("-paytxfee")) {
3952  CAmount nFeePerK = 0;
3953  if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
3954  error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""));
3955  return nullptr;
3956  }
3957  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
3958  warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
3959  _("This is the transaction fee you will pay if you send a transaction."));
3960  }
3961  walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
3962  if (walletInstance->m_pay_tx_fee < chain.relayMinFee()) {
3963  error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
3964  gArgs.GetArg("-paytxfee", ""), chain.relayMinFee().ToString());
3965  return nullptr;
3966  }
3967  }
3968 
3969  if (gArgs.IsArgSet("-maxtxfee")) {
3970  CAmount nMaxFee = 0;
3971  if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
3972  error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""));
3973  return nullptr;
3974  }
3975  if (nMaxFee > HIGH_MAX_TX_FEE) {
3976  warnings.push_back(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
3977  }
3978  if (CFeeRate(nMaxFee, 1000) < chain.relayMinFee()) {
3979  error = strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3980  gArgs.GetArg("-maxtxfee", ""), chain.relayMinFee().ToString());
3981  return nullptr;
3982  }
3983  walletInstance->m_default_max_tx_fee = nMaxFee;
3984  }
3985 
3986  if (chain.relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {
3987  warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
3988  _("The wallet will avoid paying less than the minimum relay fee."));
3989  }
3990 
3991  walletInstance->m_confirm_target = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3992  walletInstance->m_spend_zero_conf_change = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3993  walletInstance->m_signal_rbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
3994 
3995  walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nStart);
3996 
3997  // Try to top up keypool. No-op if the wallet is locked.
3998  walletInstance->TopUpKeyPool();
3999 
4000  LOCK(walletInstance->cs_wallet);
4001 
4002  // Register wallet with validationinterface. It's done before rescan to avoid
4003  // missing block connections between end of rescan and validation subscribing.
4004  // Because of wallet lock being hold, block connection notifications are going to
4005  // be pending on the validation-side until lock release. It's likely to have
4006  // block processing duplicata (if rescan block range overlaps with notification one)
4007  // but we guarantee at least than wallet state is correct after notifications delivery.
4008  // This is temporary until rescan and notifications delivery are unified under same
4009  // interface.
4010  walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
4011 
4012  int rescan_height = 0;
4013  if (!gArgs.GetBoolArg("-rescan", false))
4014  {
4015  WalletBatch batch(walletInstance->GetDatabase());
4016  CBlockLocator locator;
4017  if (batch.ReadBestBlock(locator)) {
4018  if (const Optional<int> fork_height = chain.findLocatorFork(locator)) {
4019  rescan_height = *fork_height;
4020  }
4021  }
4022  }
4023 
4024  const Optional<int> tip_height = chain.getHeight();
4025  if (tip_height) {
4026  walletInstance->m_last_block_processed = chain.getBlockHash(*tip_height);
4027  walletInstance->m_last_block_processed_height = *tip_height;
4028  } else {
4029  walletInstance->m_last_block_processed.SetNull();
4030  walletInstance->m_last_block_processed_height = -1;
4031  }
4032 
4033  if (tip_height && *tip_height != rescan_height)
4034  {
4035  // We can't rescan beyond non-pruned blocks, stop and throw an error.
4036  // This might happen if a user uses an old wallet within a pruned node
4037  // or if they ran -disablewallet for a longer time, then decided to re-enable
4038  if (chain.havePruned()) {
4039  // Exit early and print an error.
4040  // If a block is pruned after this check, we will load the wallet,
4041  // but fail the rescan with a generic error.
4042  int block_height = *tip_height;
4043  while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
4044  --block_height;
4045  }
4046 
4047  if (rescan_height != block_height) {
4048  error = _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)");
4049  return nullptr;
4050  }
4051  }
4052 
4053  chain.initMessage(_("Rescanning...").translated);
4054  walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
4055 
4056  // No need to read and scan block if block was created before
4057  // our wallet birthday (as adjusted for block time variability)
4058  Optional<int64_t> time_first_key;
4059  for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
4060  int64_t time = spk_man->GetTimeFirstKey();
4061  if (!time_first_key || time < *time_first_key) time_first_key = time;
4062  }
4063  if (time_first_key) {
4064  chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, FoundBlock().height(rescan_height));
4065  }
4066 
4067  {
4068  WalletRescanReserver reserver(*walletInstance);
4069  if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, {} /* max height */, reserver, true /* update */).status)) {
4070  error = _("Failed to rescan the wallet during initialization");
4071  return nullptr;
4072  }
4073  }
4074  walletInstance->chainStateFlushed(chain.getTipLocator());
4075  walletInstance->GetDatabase().IncrementUpdateCounter();
4076  }
4077 
4078  {
4079  LOCK(cs_wallets);
4080  for (auto& load_wallet : g_load_wallet_fns) {
4081  load_wallet(interfaces::MakeWallet(walletInstance));
4082  }
4083  }
4084 
4085  walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4086 
4087  {
4088  walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4089  walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4090  walletInstance->WalletLogPrintf("m_address_book.size() = %u\n", walletInstance->m_address_book.size());
4091  }
4092 
4093  return walletInstance;
4094 }
4095 
4096 const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
4097 {
4098  const auto& address_book_it = m_address_book.find(dest);
4099  if (address_book_it == m_address_book.end()) return nullptr;
4100  if ((!allow_change) && address_book_it->second.IsChange()) {
4101  return nullptr;
4102  }
4103  return &address_book_it->second;
4104 }
4105 
4107 {
4108  int prev_version = GetVersion();
4109  if (version == 0) {
4110  WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
4111  version = FEATURE_LATEST;
4112  } else {
4113  WalletLogPrintf("Allowing wallet upgrade up to %i\n", version);
4114  }
4115  if (version < prev_version) {
4116  error = strprintf(_("Cannot downgrade wallet from version %i to version %i. Wallet version unchanged."), prev_version, version);
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
4123  if (!CanSupportFeature(FEATURE_HD_SPLIT) && version >= FEATURE_HD_SPLIT && version < FEATURE_PRE_SPLIT_KEYPOOL) {
4124  error = strprintf(_("Cannot upgrade a non HD split wallet from version %i to version %i without upgrading to support pre-split keypool. Please use version %i or no version specified."), prev_version, version, FEATURE_PRE_SPLIT_KEYPOOL);
4125  return false;
4126  }
4127 
4128  // Permanently upgrade to the version
4129  SetMinVersion(GetClosestWalletFeature(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
4145  ReacceptWalletTransactions();
4146 
4147  // Update wallet transactions with current mempool transactions.
4148  chain().requestMempoolTransactions(*this);
4149 }
4150 
4151 bool CWallet::BackupWallet(const std::string& strDest) const
4152 {
4153  return GetDatabase().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);
4174  AssertLockHeld(pwallet->cs_wallet);
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 {
4367  if (IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
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.
4372  auto it = m_internal_spk_managers.find(OutputType::LEGACY);
4373  if (it == m_internal_spk_managers.end()) return nullptr;
4374  return dynamic_cast<LegacyScriptPubKeyMan*>(it->second);
4375 }
4376 
4378 {
4379  SetupLegacyScriptPubKeyMan();
4380  return GetLegacyScriptPubKeyMan();
4381 }
4382 
4384 {
4385  if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() || !m_spk_managers.empty() || IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
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 {
4423  AssertLockHeld(cs_wallet);
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(GetDatabase());
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 {
4498  if (!IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
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 }
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: wallet.cpp:2060
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:993
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:3725
CAmount nValue
Definition: transaction.h:131
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:64
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:893
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:4383
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:39
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:972
EstimatorBucket pass
Definition: fees.h:69
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:39
void Close()
Close wallet database.
Definition: wallet.cpp:490
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
Definition: wallet.cpp:1472
virtual Optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:371
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
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:3306
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:40
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:81
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:4474
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:34
std::deque< CInv >::iterator it
CAmount GetAvailableCredit(bool fUseCache=true, const isminefilter &filter=ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS
Definition: wallet.cpp:1961
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: wallet.h:339
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value)=0
Write a setting to <datadir>/settings.json.
const std::chrono::seconds now
const std::vector< UniValue > & getValues() const
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:180
static const uint32_t MAX_BIP125_RBF_SEQUENCE
Definition: rbf.h:12
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:34
EstimationResult est
Definition: fees.h:77
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:215
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:49
virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock &block={})=0
Find first block in the chain with timestamp >= the given time and height >= than the given height...
void SetNull()
Definition: uint256.h:39
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:72
assert(!tx.IsCoinBase())
bool isConfirmed() const
Definition: wallet.h:547
int returnedTarget
Definition: fees.h:80
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
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:13
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
Definition: crypter.cpp:71
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:97
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3577
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr) override
signify that a particular wallet feature is now used.
Definition: wallet.cpp:439
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
CAmount GetAvailableBalance(const CCoinControl *coinControl=nullptr) const
Definition: wallet.cpp:2159
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:139
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:2301
static void ReleaseWallet(CWallet *wallet)
Definition: wallet.cpp:162
size_t change_output_size
Definition: wallet.h:607
A UTXO entry.
Definition: coins.h:30
Bilingual messages:
Definition: translation.h:16
Definition: block.h:62
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:57
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:25
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
Encryption/decryption context with key information.
Definition: crypter.h:69
RecursiveMutex cs_KeyStore
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:490
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:232
const CTxOut & FindNonChangeParentOutput(const CTransaction &tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Find non-change parent output.
Definition: wallet.cpp:2342
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:184
CAmount m_mine_untrusted_pending
Untrusted, but in mempool (pending)
Definition: wallet.h:924
double start
Definition: fees.h:58
Optional< CMutableTransaction > tx
Definition: psbt.h:392
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1359
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:983
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:36
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: walletdb.cpp:902
std::vector< CTxIn > vin
Definition: transaction.h:346
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:909
std::map< CKeyID, CKey > keys
bool use_max_sig
Whether to use the maximum sized, 72 byte signature when calculating the size of the input spend...
Definition: wallet.h:577
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:200
SigningResult
Definition: message.h:42
void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1842
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:2174
bool SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &target_value, const CAmount &cost_of_change, std::set< CInputCoin > &out_set, CAmount &value_ret, CAmount not_input_fees)
static const uint32_t SEQUENCE_FINAL
Definition: transaction.h:75
const char * prefix
Definition: rest.cpp:670
bool SelectCoinsMinConf(const CAmount &nTargetValue, const CoinEligibilityFilter &eligibility_filter, std::vector< OutputGroup > groups, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CoinSelectionParams &coin_selection_params, bool &bnb_used) const
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
Definition: wallet.cpp:2360
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:1920
Definition: key.h:144
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key...
Definition: crypter.h:33
virtual bool isInitialBlockDownload()=0
Check if in IBD.
int64_t GetOldestKeyPoolTime() const
Definition: wallet.cpp:3361
void ListSelected(std::vector< COutPoint > &vOutpoints) const
Definition: coincontrol.h:86
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:26
bool Lock()
Definition: wallet.cpp: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:78
CAmount GetMinimumFee(const CWallet &wallet, unsigned int nTxBytes, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee considering user set parameters and the required fee.
Definition: fees.cpp:18
bool IsChange(const CTxOut &txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1315
static std::vector< std::shared_ptr< CWallet > > vpwallets GUARDED_BY(cs_wallets)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:321
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:434
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:60
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:326
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:327
CFeeRate GetDiscardRate(const CWallet &wallet)
Return the maximum feerate for discarding change.
Definition: fees.cpp:83
bool isConflicted() const
Definition: wallet.h:543
Balance GetBalance(int min_depth=0, bool avoid_reuse=true) const
Definition: wallet.cpp:2130
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
bool HasSelected() const
Definition: coincontrol.h:61
const CKeyingMaterial & GetEncryptionKey() const override
Definition: wallet.cpp:4397
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:61
bool CanGetAddresses(bool internal=false) const
Definition: wallet.cpp:1432
#define PACKAGE_NAME
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:435
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: wallet.h:923
CAmount m_watchonly_untrusted_pending
Definition: wallet.h:927
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Definition: system.h:481
static auto & nullopt
Substitute for C++17 std::nullopt DEPRECATED use std::nullopt in new code.
Definition: optional.h:18
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:928
WalletFeature GetClosestWalletFeature(int version)
Definition: walletutil.cpp:37
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
bool IsLocked() const override
Definition: wallet.cpp:4247
std::string translated
Definition: translation.h:18
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
bilingual_str TransactionErrorString(const TransactionError err)
Definition: error.cpp:11
A version of CTransaction with the PSBT format.
Definition: psbt.h:390
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:36
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:988
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:479
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:280
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:89
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
bool IsCoinBase() const
Definition: wallet.h:550
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:3741
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:12
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:86
const CWalletTx * GetWalletTx(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:340
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:212
bool ParseMoney(const std::string &money_string, CAmount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:34
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:695
void chainStateFlushed(const CBlockLocator &loc) override
Definition: wallet.cpp:433
const unsigned char * begin() const
Definition: key.h:89
bool isUnconfirmed() const
Definition: wallet.h:545
bool MarkReplaced(const uint256 &originalHash, const uint256 &newHash)
Mark a transaction as replaced by another transaction (e.g., BIP 125).
Definition: wallet.cpp:761
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:43
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:581
double withinTarget
Definition: fees.h:60
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:983
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:926
bool IsNull() const
Definition: uint256.h:31
CAmount GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.cpp:1952
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1544
OutputType
Definition: outputtype.h:17
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, Optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:107
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
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:4151
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:23
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
Definition: wallet.cpp:1477
const std::vector< CTxIn > vin
Definition: transaction.h:270
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:4349
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1116
RecursiveMutex cs_wallets
Definition: wallet.cpp:55
std::string ToString() const
Definition: wallet.cpp:335
std::map< CTxDestination, CAmount > GetAddressBalances() const
Definition: wallet.cpp:3385
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Definition: wallet.cpp:2588
int desiredTarget
Definition: fees.h:79
Access to the wallet database.
Definition: walletdb.h:176
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
Definition: script.h:543
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:306
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3208
CAmount GetImmatureWatchOnlyCredit(const bool fUseCache=true) const
Definition: wallet.cpp:1998
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:4299
bool GetNewChangeDestination(const OutputType type, CTxDestination &dest, std::string &error)
Definition: wallet.cpp:3346
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:168
size_t change_spend_size
Definition: wallet.h:608
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:998
#define AssertLockHeld(cs)
Definition: sync.h:81
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3259
bool HasEncryptionKeys() const override
Definition: wallet.cpp:4402
void MarkDirty()
Definition: wallet.cpp:752
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
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in=false)
Definition: wallet.h:586
bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3589
static void NotifyCanGetAddressesChanged(WalletModel *walletmodel)
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1453
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:3265
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:967
bool SelectCoins(const std::vector< COutput > &vAvailableCoins, const CAmount &nTargetValue, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CCoinControl &coin_control, CoinSelectionParams &coin_selection_params, bool &bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Select a set of coins such that nValueRet >= nTargetValue and at least all coins from coinControl are...
Definition: wallet.cpp:2406
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig=false) const
Definition: wallet.cpp:1509
const int DEFAULT_MAX_DEPTH
Definition: coincontrol.h:16
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:3686
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:10
void UnsetBlankWalletFlag(WalletBatch &batch) override
Unset the blank wallet flag and saves it to disk.
Definition: wallet.cpp:1467
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, const isminefilter &filter) const
Definition: wallet.cpp:1632
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:3139
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:290
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1045
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:3179
CAmount m_mine_immature
Immature coinbases in the main chain.
Definition: wallet.h:925
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 & associated output type.
Definition: wallet.cpp:4496
int nDepth
Definition: wallet.h:565
Confirmation m_confirm
Definition: wallet.h:396
std::set< ScriptPubKeyMan * > GetScriptPubKeyMans(const CScript &script, SignatureData &sigdata) const
Get all of the ScriptPubKeyMans for a script given additional information in sigdata (populated by e...
Definition: wallet.cpp:4319
DescriptorScriptPubKeyMan * GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const
Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet...
Definition: wallet.cpp:4483
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:1190
double end
Definition: fees.h:59
EstimatorBucket fail
Definition: fees.h:70
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:984
An input of a transaction.
Definition: transaction.h:65
static Mutex g_loading_wallet_mutex
Definition: wallet.cpp:155
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:2600
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:4365
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3609
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet, bool use_max_sig)
Definition: wallet.cpp:1622
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: wallet.cpp:148
void GetStrongRandBytes(unsigned char *buf, int num) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
Definition: random.cpp:586
bool IsHDEnabled() const
Definition: wallet.cpp:1422
#define LOCK(cs)
Definition: sync.h:232
const char * name
Definition: rest.cpp:41
bool InMempool() const
Definition: wallet.cpp:2016
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
static void NotifyAddressBookChanged(WalletModel *walletmodel, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)
const uint256 & GetHash() const
Definition: transaction.h:302
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
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
CTxDestination destChange
Custom change destination, if not set an address is generated.
Definition: coincontrol.h:26
bilingual_str AmountHighWarn(const std::string &optname)
Definition: error.cpp:44
Fast randomness source.
Definition: random.h:119
Removed for block.
std::set< uint256 > GetConflicts() const NO_THREAD_SAFETY_ANALYSIS
Definition: wallet.cpp:1898
void Select(const COutPoint &output)
Definition: coincontrol.h:71
An encapsulated public key.
Definition: pubkey.h:31
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:32
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1028
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:38
int GetBlocksToMaturity() const
Definition: wallet.cpp:4180
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:95
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:3583
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:271
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: walletutil.h:59
double inMempool
Definition: fees.h:62
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:142
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
uint8_t isminefilter
Definition: wallet.h:36
const int DEFAULT_MIN_DEPTH
Definition: coincontrol.h:15
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1554
Optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
Definition: coincontrol.h:40
bool IsTrusted() const
Definition: wallet.cpp:2021
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
Definition: coincontrol.h:46
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:3734
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
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:4377
isminetype
IsMine() return codes.
Definition: ismine.h:18
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:88
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:180
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:4308
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:237
An output of a transaction.
Definition: transaction.h:128
std::string ToString() const
Definition: uint256.cpp:64
bool ImportPubKeys(const std::vector< CKeyID > &ordered_pubkeys, const std::map< CKeyID, CPubKey > &pubkey_map, const std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo >> &key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1564
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:300
Descriptor with some wallet metadata.
Definition: walletutil.h:69
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:87
const uint256 & GetHash() const
Definition: wallet.h:549
OutputType TransactionChangeType(const Optional< OutputType > &change_type, const std::vector< CRecipient > &vecSend) const
Definition: wallet.cpp:2712
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:179
static const CAmount MIN_FINAL_CHANGE
final minimum change amount after paying for fees
Definition: coinselection.h:17
size_t tx_noinputs_size
Definition: wallet.h:610
std::vector< CTxOut > vout
Definition: transaction.h:347
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:308
bool IsAllFromMe(const CTransaction &tx, const isminefilter &filter) const
Returns whether all of the inputs match the filter.
Definition: wallet.cpp:1376
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:14
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
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:45
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:276
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:2670
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1284
bool HasWalletDescriptor(const WalletDescriptor &desc) const
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:270
CAmount GetCachableAmount(AmountType type, const isminefilter &filter, bool recalculate=false) const
Definition: wallet.cpp:1910
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3294
void MarkConflicted(const uint256 &hashBlock, int conflicting_height, const uint256 &hashTx)
Definition: wallet.cpp:1099
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:437
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3597
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
bool IsImmatureCoinBase() const
Definition: wallet.cpp:4189
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:3799
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:3371
int flags
Definition: bitcoin-tx.cpp:512
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: wallet.cpp:133
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1178
void SyncTransaction(const CTransactionRef &tx, CWalletTx::Confirmation confirm, bool update_tx=true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1151
const std::string & FormatOutputType(OutputType type)
Definition: outputtype.cpp:37
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
Definition: wallet.cpp:740
std::vector< OutputGroup > GroupOutputs(const std::vector< COutput > &outputs, bool single_coin, const size_t max_ancestors) const
Definition: wallet.cpp:4195
void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3571
uint256 GetHash() const
Definition: block.cpp:11
OutputGroup GetPositiveOnlyGroup()
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:85
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2116
256-bit opaque blob.
Definition: uint256.h:124
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:14
void setUnconfirmed()
Definition: wallet.h:546
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:231
std::vector< CTransactionRef > vtx
Definition: block.h:66
int m_max_depth
Maximum chain depth value for coin availability.
Definition: coincontrol.h:52
bool UpgradeWallet(int version, bilingual_str &error)
Upgrade the wallet.
Definition: wallet.cpp:4106
void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence) override
Definition: wallet.cpp:1162
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0)
bool setArray()
Definition: univalue.cpp:94
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
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
std::set< ScriptPubKeyMan * > GetActiveScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers.
Definition: wallet.cpp:4285
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
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
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:748
CAmount GetCredit(const isminefilter &filter) const
Definition: wallet.cpp:1935
int64_t GetTxTime() const
Definition: wallet.cpp:1501
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:3104
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:89
Address book data.
Definition: wallet.h:187
void ResendWalletTransactions()
Definition: wallet.cpp:2078
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:205
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
Definition: wallet.cpp:3516
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
bool IsNull() const
Definition: block.h:48
bool IsSelected(const COutPoint &output) const
Definition: coincontrol.h:66
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:3317
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::string &strPurpose)
Definition: wallet.cpp:3239
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
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
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:319
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:467
bool empty() const
Definition: prevector.h:286
int GetSpendSize(unsigned int out, bool use_max_sig=false) const
Definition: wallet.h:482
static bool IsCurrentForAntiFeeSniping(interfaces::Chain &chain, const uint256 &block_hash)
Definition: wallet.cpp:2652
CTransactionRef non_witness_utxo
Definition: psbt.h:50
CAmount effective_value
Definition: coinselection.h:79
static void NotifyTransactionChanged(WalletModel *walletmodel, const uint256 &hash, ChangeType status)
double leftMempool
Definition: fees.h:63
static const size_t OUTPUT_GROUP_MAX_ENTRIES
Definition: wallet.cpp:53
virtual void initMessage(const std::string &message)=0
Send init message.
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:21
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:354
TransactionError FillPSBT(PartiallySignedTransaction &psbtx, bool &complete, int sighash_type=1, bool sign=true, bool bip32derivs=true, size_t *n_signed=nullptr) const
Fills out a PSBT with information from the wallet.
Definition: wallet.cpp:2538
const CWalletTx * tx
Definition: wallet.h:563
int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:4171
std::string GetHex() const
Definition: uint256.cpp:20
bool GetReservedDestination(CTxDestination &pubkey, bool internal)
Reserve an address.
Definition: wallet.cpp:3531
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
bool IsCrypted() const
Definition: wallet.cpp:4242
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:1035
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:76
static Mutex g_wallet_release_mutex
Definition: wallet.cpp:156
#define AssertLockNotHeld(cs)
Definition: sync.h:82
static int count
Definition: tests.c:35
A wrapper to reserve an address from a wallet.
Definition: wallet.h:148
bool KnapsackSolver(const CAmount &nTargetValue, std::vector< OutputGroup > &groups, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet)
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:199
std::vector< unsigned char > vchSalt
Definition: crypter.h:37
Definition: wallet.h:236
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:940
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:206
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:48
Optional< int > last_scanned_height
Definition: wallet.h:910
A mutable version of CTransaction.
Definition: transaction.h:344
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:916
double totalConfirmed
Definition: fees.h:61
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:194
static std::condition_variable g_wallet_release_cv
Definition: wallet.cpp:157
static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly)
static std::vector< COutput > vCoins
Definition: coinselect