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