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