PIVX Core  5.6.99
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 The Bitcoin developers
3 // Copyright (c) 2014-2015 The Dash developers
4 // Copyright (c) 2015-2022 The PIVX Core developers
5 // Distributed under the MIT software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 
8 #include "optional.h"
9 #include "validation.h"
10 #if defined(HAVE_CONFIG_H)
11 #include "config/pivx-config.h"
12 #endif
13 
14 #include "wallet/wallet.h"
15 
16 #include "checkpoints.h"
17 #include "coincontrol.h"
18 #include "evo/providertx.h"
19 #include "guiinterfaceutil.h"
20 #include "policy/policy.h"
21 #include "sapling/key_io_sapling.h"
22 #include "script/sign.h"
23 #include "scheduler.h"
24 #include "shutdown.h"
25 #include "spork.h"
26 #include "util/validation.h"
27 #include "utilmoneystr.h"
28 #include "wallet/fees.h"
29 
30 #include <future>
31 #include <boost/algorithm/string/replace.hpp>
32 
33 std::vector<CWalletRef> vpwallets;
37 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
38 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
39 unsigned int nTxConfirmTarget = 1;
40 bool bdisableSystemnotifications = false; // Those bubbles can be annoying and slow down the UI when you get lots of trx
42 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
43 
50 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
51 
55 CAmount CWallet::minStakeSplitThreshold = DEFAULT_MIN_STAKE_SPLIT_THRESHOLD;
56 
57 const uint256 CWalletTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
58 
65  bool operator()(const std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> >& t1,
66  const std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> >& t2) const
67  {
68  return t1.first < t2.first;
69  }
70 };
71 
72 std::string COutput::ToString() const
73 {
74  return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
75 }
76 
77 class CAffectedKeysVisitor : public boost::static_visitor<void>
78 {
79 private:
81  std::vector<CKeyID>& vKeys;
82 
83 public:
84  CAffectedKeysVisitor(const CKeyStore& keystoreIn, std::vector<CKeyID>& vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
85 
86  void Process(const CScript& script)
87  {
88  txnouttype type;
89  std::vector<CTxDestination> vDest;
90  int nRequired;
91  if (ExtractDestinations(script, type, vDest, nRequired)) {
92  for (const CTxDestination& dest : vDest)
93  boost::apply_visitor(*this, dest);
94  }
95  }
96 
97  void operator()(const CKeyID& keyId)
98  {
99  if (keystore.HaveKey(keyId))
100  vKeys.push_back(keyId);
101  }
102 
103  void operator()(const CExchangeKeyID& keyId) {
104  if (keystore.HaveKey(keyId))
105  vKeys.push_back(keyId);
106  }
107 
108  void operator()(const CScriptID& scriptId)
109  {
110  CScript script;
111  if (keystore.GetCScript(scriptId, script))
112  Process(script);
113  }
114 
115  void operator()(const CNoDestination& none) {}
116 };
117 
118 std::vector<CKeyID> CWallet::GetAffectedKeys(const CScript& spk)
119 {
120  std::vector<CKeyID> ret;
121  std::vector<CKeyID> vAffected;
122  CAffectedKeysVisitor(*this, vAffected).Process(spk);
123  for (const CKeyID& keyid : vAffected) {
124  ret.emplace_back(keyid);
125  }
126  return ret;
127 }
128 
130 
132 
133 bool CWallet::SetupSPKM(bool newKeypool, bool memOnly)
134 {
135  if (m_spk_man->SetupGeneration(newKeypool, true, memOnly)) {
136  LogPrintf("%s : spkm setup completed\n", __func__);
137  return ActivateSaplingWallet(memOnly);
138  }
139  return false;
140 }
141 
143 {
144  if (m_sspk_man->SetupGeneration(m_spk_man->GetHDChain().GetID(), true, memOnly)) {
145  LogPrintf("%s : sapling spkm setup completed\n", __func__);
146  // Just to be triple sure, if the version isn't updated, set it.
148  LogPrintf("%s : ERROR: wallet cannot upgrade to sapling features. Try to upgrade using the 'upgradewallet' RPC command\n", __func__);
149  return false;
150  }
151  return true;
152  }
153  return false;
154 }
155 
157 {
158  return m_spk_man->IsHDEnabled();
159 }
160 
162 {
163  return m_sspk_man->IsEnabled();
164 }
165 
166 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
167 {
168  LOCK(cs_wallet);
169  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
170  if (it == mapWallet.end())
171  return nullptr;
172  return &(it->second);
173 }
174 
175 std::vector<CWalletTx> CWallet::getWalletTxs()
176 {
177  LOCK(cs_wallet);
178  std::vector<CWalletTx> result;
179  result.reserve(mapWallet.size());
180  for (const auto& entry : mapWallet) {
181  result.emplace_back(entry.second);
182  }
183  return result;
184 }
185 
187 {
189 }
190 
192 {
193  return getNewAddress(label, AddressBook::AddressBookPurpose::COLD_STAKING, CChainParams::Base58Type::STAKING_ADDRESS);
194 }
195 
196 CallResult<CTxDestination> CWallet::getNewAddress(const std::string& addressLabel, const std::string purpose,
197  const CChainParams::Base58Type addrType)
198 {
199  LOCK(cs_wallet);
200 
201  // Refill keypool if wallet is unlocked
202  if (!IsLocked())
203  TopUpKeyPool();
204 
205  uint8_t type = (addrType == CChainParams::Base58Type::STAKING_ADDRESS ? HDChain::ChangeType::STAKING : HDChain::ChangeType::EXTERNAL);
206  CPubKey newKey;
207  // Get a key
208  if (!GetKeyFromPool(newKey, type)) {
209  // inform the user to top-up the keypool or unlock the wallet
210  return CallResult<CTxDestination>(std::string(
211  _("Keypool ran out, please call keypoolrefill first, or unlock the wallet.")));
212  }
213  CKeyID keyID = newKey.GetID();
214 
215  if (!SetAddressBook(keyID, addressLabel, purpose))
216  throw std::runtime_error("CWallet::getNewAddress() : SetAddressBook failed");
217 
219 }
220 
222 {
223  auto shieldDest = Standard::GetShieldedDestination(dest);
224  auto transpDest = Standard::GetTransparentDestination(dest);
225  return shieldDest ? GetKeyCreationTime(*shieldDest) : transpDest ? GetKeyCreationTime(*transpDest) : 0;
226 }
227 
229 {
230  return mapKeyMetadata[pubkey.GetID()].nCreateTime;
231 }
232 
234 {
235  const CKeyID* keyID = boost::get<CKeyID>(&address);
236  if (keyID) {
237  CPubKey keyRet;
238  if (GetPubKey(*keyID, keyRet)) {
239  return GetKeyCreationTime(keyRet);
240  }
241  }
242  return 0;
243 }
244 
246 {
248  return GetSaplingIncomingViewingKey(address, ivk) ?
250 }
251 
252 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey)
253 {
254  AssertLockHeld(cs_wallet); // mapKeyMetadata
255  if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
256  return false;
257 
258  // TODO: Move the follow block entirely inside the spkm (including WriteKey to AddKeyPubKeyWithDB)
259  // check if we need to remove from watch-only
260  CScript script;
261  script = GetScriptForDestination(pubkey.GetID());
262  if (HaveWatchOnly(script))
263  RemoveWatchOnly(script);
264 
265  script = GetScriptForRawPubKey(pubkey);
266  if (HaveWatchOnly(script)) {
267  RemoveWatchOnly(script);
268  }
269 
270  if (!IsCrypted()) {
271  return WalletBatch(*database).WriteKey(
272  pubkey,
273  secret.GetPrivKey(),
274  mapKeyMetadata[pubkey.GetID()]);
275  }
276  return true;
277 }
278 
279 bool CWallet::AddCryptedKey(const CPubKey& vchPubKey,
280  const std::vector<unsigned char>& vchCryptedSecret)
281 {
282  if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
283  return false;
284  {
285  LOCK(cs_wallet);
286  if (encrypted_batch)
287  return encrypted_batch->WriteCryptedKey(vchPubKey,
288  vchCryptedSecret,
289  mapKeyMetadata[vchPubKey.GetID()]);
290  else
291  return WalletBatch(*database).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
292  }
293  return false;
294 }
295 
296 bool CWallet::LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& meta)
297 {
298  AssertLockHeld(cs_wallet); // mapKeyMetadata
299  if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
300  nTimeFirstKey = meta.nCreateTime;
301 
302  mapKeyMetadata[pubkey.GetID()] = meta;
303  return true;
304 }
305 
306 bool CWallet::LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret)
307 {
308  return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
309 }
310 
315 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
316 {
318  if (nCreateTime <= 1) {
319  // Cannot determine birthday information, so set the wallet birthday to
320  // the beginning of time.
321  nTimeFirstKey = 1;
322  } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
323  nTimeFirstKey = nCreateTime;
324  }
325 }
326 
327 bool CWallet::AddCScript(const CScript& redeemScript)
328 {
329  if (!CCryptoKeyStore::AddCScript(redeemScript))
330  return false;
331  return WalletBatch(*database).WriteCScript(Hash160(redeemScript), redeemScript);
332 }
333 
334 bool CWallet::LoadCScript(const CScript& redeemScript)
335 {
336  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
337  * that never can be redeemed. However, old wallets may still contain
338  * these. Do not add them to the wallet and warn. */
339  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
340  std::string strAddr = EncodeDestination(CScriptID(redeemScript));
341  LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
342  __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
343  return true;
344  }
345 
346  return CCryptoKeyStore::AddCScript(redeemScript);
347 }
348 
350 {
352  return false;
353  nTimeFirstKey = 1; // No birthday information for watch-only keys.
355  return WalletBatch(*database).WriteWatchOnly(dest);
356 }
357 
359 {
362  return false;
363  if (!HaveWatchOnly())
364  NotifyWatchonlyChanged(false);
365  if (!WalletBatch(*database).EraseWatchOnly(dest))
366  return false;
367 
368  return true;
369 }
370 
372 {
373  return CCryptoKeyStore::AddWatchOnly(dest);
374 }
375 
376 bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool stakingOnly)
377 {
378  CCrypter crypter;
380 
381  {
382  LOCK(cs_wallet);
383  for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys) {
384  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
385  return false;
386  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
387  continue; // try another master key
388  if (Unlock(vMasterKey)) {
389  fWalletUnlockStaking = stakingOnly;
390  return true;
391  }
392  }
393  }
394  return false;
395 }
396 
398 {
399  if (!SetCrypted())
400  return false;
401 
402  {
403  LOCK(cs_KeyStore);
404  vMasterKey.clear();
405  }
406 
407  NotifyStatusChanged(this);
408  return true;
409 }
410 
411 bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn)
412 {
413  {
414  LOCK(cs_KeyStore);
415  if (!SetCrypted())
416  return false;
417 
418  bool keyPass = false;
419  bool keyFail = false;
420  CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
421  for (; mi != mapCryptedKeys.end(); ++mi) {
422  const CPubKey& vchPubKey = (*mi).second.first;
423  const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second;
424  CKey key;
425  if (!DecryptKey(vMasterKeyIn, vchCryptedSecret, vchPubKey, key)) {
426  keyFail = true;
427  break;
428  }
429  keyPass = true;
431  break;
432  }
433 
434  if (keyPass && keyFail) {
435  LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
436  throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
437  }
438 
439  if (keyFail || !keyPass)
440  return false;
441 
442  // Sapling
443  if (!UnlockSaplingKeys(vMasterKeyIn, fDecryptionThoroughlyChecked)) {
444  // If Sapling key encryption fail, let's unencrypt the rest of the keys
445  LogPrintf("Sapling wallet unlock keys failed\n");
446  throw std::runtime_error("Error unlocking wallet: some Sapling keys decrypt but not all. Your wallet file may be corrupt.");
447  }
448 
449  vMasterKey = vMasterKeyIn;
451  }
452 
453  NotifyStatusChanged(this);
454  return true;
455 }
456 
457 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
458 {
459  bool fWasLocked = IsLocked();
460  SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase;
461 
462  {
463  LOCK(cs_wallet);
464  Lock();
465 
466  CCrypter crypter;
468  for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys) {
469  if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
470  return false;
471  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
472  return false;
473  if (Unlock(vMasterKey)) {
474  int64_t nStartTime = GetTimeMillis();
475  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
476  pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
477 
478  nStartTime = GetTimeMillis();
479  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
480  pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
481 
482  if (pMasterKey.second.nDeriveIterations < 25000)
483  pMasterKey.second.nDeriveIterations = 25000;
484 
485  LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
486 
487  if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
488  return false;
489  if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
490  return false;
491  WalletBatch(*database).WriteMasterKey(pMasterKey.first, pMasterKey.second);
492  if (fWasLocked)
493  Lock();
494 
495  return true;
496  }
497  }
498  }
499 
500  return false;
501 }
502 
504  const CBlock *pblock,
505  SaplingMerkleTree saplingTree)
506 {
507  IncrementNoteWitnesses(pindex, pblock, saplingTree);
508  m_sspk_man->UpdateSaplingNullifierNoteMapForBlock(pblock);
509 }
510 
512 {
513  WalletBatch batch(*database);
514  SetBestChainInternal(batch, loc);
515 }
516 
518 {
519  if (!batch.TxnBegin()) {
520  // This needs to be done atomically, so don't do it at all
521  LogPrintf("%s: Couldn't start atomic write\n", __func__);
522  return;
523  }
524 
525  // Store the best block
526  if (!batch.WriteBestBlock(loc)) {
527  LogPrintf("SetBestChain(): Failed to write best block, aborting atomic write\n");
528  batch.TxnAbort();
529  return;
530  }
531 
532  // For performance reasons, we update the witnesses data here and not when each transaction arrives
533  for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
534  auto wtx = wtxItem.second;
535  // We skip transactions for which mapSaplingNoteData is empty.
536  // This covers transactions that have no Sapling data
537  // (i.e. are purely transparent), as well as shielding and unshielding
538  // transactions in which we only have transparent addresses involved.
539  if (!wtx.mapSaplingNoteData.empty()) {
540  // Sanity check
541  if (!wtx.tx->isSaplingVersion()) {
542  LogPrintf("SetBestChain(): ERROR, Invalid tx version found with sapling data\n");
543  batch.TxnAbort();
545  _("A fatal internal error occurred, see debug.log for details"),
547  StartShutdown();
548  return;
549  }
550 
551  if (!batch.WriteTx(wtx)) {
552  LogPrintf("SetBestChain(): Failed to write CWalletTx, aborting atomic write\n");
553  batch.TxnAbort();
554  return;
555  }
556  }
557  }
558 
559  // Store sapling witness cache size
560  if (m_sspk_man->nWitnessCacheNeedsUpdate) {
561  if (!batch.WriteWitnessCacheSize(m_sspk_man->nWitnessCacheSize)) {
562  LogPrintf("%s: Failed to write nWitnessCacheSize\n", __func__);
563  batch.TxnAbort();
564  return;
565  }
566  }
567 
568  if (!batch.TxnCommit()) {
569  // Couldn't commit all to db, but in-memory state is fine
570  LogPrintf("%s: Couldn't commit atomic write\n", __func__);
571  return;
572  }
573 
574  // Reset cache if the commit succeed and is needed.
575  if (m_sspk_man->nWitnessCacheNeedsUpdate) {
576  m_sspk_man->nWitnessCacheNeedsUpdate = false;
577  }
578 }
579 
580 bool CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in, bool fExplicit)
581 {
582  LOCK(cs_wallet); // nWalletVersion
583  if (nWalletVersion >= nVersion)
584  return true;
585 
586  // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
587  if (fExplicit && nVersion > nWalletMaxVersion)
588  nVersion = FEATURE_LATEST;
589 
590  nWalletVersion = nVersion;
591 
592  if (nVersion > nWalletMaxVersion)
593  nWalletMaxVersion = nVersion;
594 
595  {
596  WalletBatch* batch = batch_in ? batch_in : new WalletBatch(*database);
597  if (nWalletVersion > 40000)
599  if (!batch_in)
600  delete batch;
601  }
602 
603  return true;
604 }
605 
606 bool CWallet::SetMaxVersion(int nVersion)
607 {
608  LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
609  // cannot downgrade below current version
610  if (nWalletVersion > nVersion)
611  return false;
612 
613  nWalletMaxVersion = nVersion;
614 
615  return true;
616 }
617 
618 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
619 {
620  std::set<uint256> result;
622 
623  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
624  if (it == mapWallet.end())
625  return result;
626  const CWalletTx& wtx = it->second;
627 
628  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
629 
630  for (const CTxIn& txin : wtx.tx->vin) {
631  if (mapTxSpends.count(txin.prevout) <= 1 || wtx.tx->HasZerocoinSpendInputs())
632  continue; // No conflict if zero or one spends
633  range = mapTxSpends.equal_range(txin.prevout);
634  for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
635  result.insert(_it->second);
636  }
637 
638  // Sapling
639  if (HasSaplingSPKM()) {
640  m_sspk_man->GetConflicts(wtx, result);
641  }
642 
643  return result;
644 }
645 
647 {
648  SyncMetaData<uint256>(range);
649 }
650 
651 template <class T>
653 {
654  // We want all the wallet transactions in range to have the same metadata as
655  // the oldest (smallest nOrderPos).
656  // So: find smallest nOrderPos:
657 
658  int nMinOrderPos = std::numeric_limits<int>::max();
659  const CWalletTx* copyFrom = nullptr;
660  for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it) {
661  const CWalletTx* wtx = &mapWallet.at(it->second);
662  int n = wtx->nOrderPos;
663  if (n < nMinOrderPos) {
664  nMinOrderPos = n;
665  copyFrom = wtx;
666  }
667  }
668 
669  if (!copyFrom) {
670  return;
671  }
672 
673  // Now copy data from copyFrom to rest:
674  for (auto it = range.first; it != range.second; ++it) {
675  const uint256& hash = it->second;
676  CWalletTx* copyTo = &mapWallet.at(hash);
677  if (copyFrom == copyTo) continue;
678  assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
679  //if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
680  copyTo->mapValue = copyFrom->mapValue;
681  copyTo->vOrderForm = copyFrom->vOrderForm;
682  // fTimeReceivedIsTxTime not copied on purpose
683  // nTimeReceived not copied on purpose
684  copyTo->nTimeSmart = copyFrom->nTimeSmart;
685  copyTo->fFromMe = copyFrom->fFromMe;
686  // nOrderPos not copied on purpose
687  // cached members not copied on purpose
688  }
689 }
690 
692 {
693  return vMasterKey;
694 }
695 
697 {
698  return !mapMasterKeys.empty();
699 }
700 
702 {
703  return m_spk_man.get();
704 }
705 
707 {
709 }
710 
712 {
713  return m_sspk_man->IsSaplingSpent(op);
714 }
715 
720 bool CWallet::IsSpent(const COutPoint& outpoint) const
721 {
723  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
724  range = mapTxSpends.equal_range(outpoint);
725  for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
726  const uint256& wtxid = it->second;
727  std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
728  if (mit != mapWallet.end()) {
729  bool fConflicted;
730  const int nDepth = mit->second.GetDepthAndMempool(fConflicted);
731  // not in mempool txes can spend coins only if not coinstakes
732  const bool fConflictedCoinstake = fConflicted && mit->second.IsCoinStake();
733  if (nDepth > 0 || (nDepth == 0 && !mit->second.isAbandoned() && !fConflictedCoinstake) )
734  return true; // Spent
735  }
736  }
737  return false;
738 }
739 
740 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
741 {
742  return IsSpent(COutPoint(hash, n));
743 }
744 
745 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
746 {
747  mapTxSpends.emplace(outpoint, wtxid);
748  setLockedCoins.erase(outpoint);
749 
750  std::pair<TxSpends::iterator, TxSpends::iterator> range;
751  range = mapTxSpends.equal_range(outpoint);
752  SyncMetaData<COutPoint>(range);
753 }
754 
755 void CWallet::AddToSpends(const uint256& wtxid)
756 {
757  auto it = mapWallet.find(wtxid);
758  assert(it != mapWallet.end());
759  CWalletTx& thisTx = it->second;
760  if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
761  return;
762 
763  for (const CTxIn& txin : thisTx.tx->vin)
764  AddToSpends(txin.prevout, wtxid);
765 
766  if (CanSupportFeature(FEATURE_SAPLING) && thisTx.tx->sapData) {
767  for (const SpendDescription &spend : thisTx.tx->sapData->vShieldedSpend) {
769  }
770  }
771 }
772 
773 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
774 {
775  if (IsCrypted())
776  return false;
777 
779 
782 
783  CMasterKey kMasterKey;
784 
785  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
787 
788  CCrypter crypter;
789  int64_t nStartTime = GetTimeMillis();
790  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
791  kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
792 
793  nStartTime = GetTimeMillis();
794  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
795  kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
796 
797  if (kMasterKey.nDeriveIterations < 25000)
798  kMasterKey.nDeriveIterations = 25000;
799 
800  LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
801 
802  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
803  return false;
804  if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
805  return false;
806 
807  {
808  LOCK(cs_wallet);
809  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
810  assert(!encrypted_batch);
812  if (!encrypted_batch->TxnBegin()) {
813  delete encrypted_batch;
814  encrypted_batch = nullptr;
815  return false;
816  }
818 
819 
820  if (!EncryptKeys(vMasterKey) || (m_sspk_man->IsEnabled() && !m_sspk_man->EncryptSaplingKeys(vMasterKey))) {
822  delete encrypted_batch;
823  // We now probably have half of our keys encrypted in memory, and half not...
824  // die and let the user reload their unencrypted wallet.
825  assert(false);
826  }
827 
828  // Encryption was introduced in version 0.4.0
830 
831  if (!encrypted_batch->TxnCommit()) {
832  delete encrypted_batch;
833  // We now have keys encrypted in memory, but not on disk...
834  // die to avoid confusion and let the user reload their unencrypted wallet.
835  assert(false);
836  }
837 
838  delete encrypted_batch;
839  encrypted_batch = nullptr;
840 
841  Lock();
842  Unlock(strWalletPassphrase);
843  // if we are using HD, replace the HD seed with a new one
844  if (m_spk_man->IsHDEnabled()) {
845  if (!m_spk_man->SetupGeneration(true, true)) {
846  return false;
847  }
848  }
849  Lock();
850 
851  // Need to completely rewrite the wallet file; if we don't, bdb might keep
852  // bits of the unencrypted private key in slack space in the database file.
853  database->Rewrite();
854 
855  // BDB seems to have a bad habit of writing old data into
856  // slack space in .dat files; that is bad if the old data is
857  // unencrypted private keys. So:
858  database->ReloadDbEnv();
859 
860  }
861  NotifyStatusChanged(this);
862 
863  return true;
864 }
865 
867 {
868  AssertLockHeld(cs_wallet); // nOrderPosNext
869  int64_t nRet = nOrderPosNext++;
870  if (batch) {
872  } else {
874  }
875  return nRet;
876 }
877 
878 bool CWallet::IsKeyUsed(const CPubKey& vchPubKey) const
879 {
880  if (vchPubKey.IsValid()) {
881  const CScript& scriptPubKey = GetScriptForDestination(vchPubKey.GetID());
882  for (const auto& entry : mapWallet) {
883  const CWalletTx& wtx = entry.second;
884  for (const CTxOut& txout : wtx.tx->vout)
885  if (txout.scriptPubKey == scriptPubKey)
886  return true;
887  }
888  }
889  return false;
890 }
891 
893 {
894  {
895  LOCK(cs_wallet);
896  for (std::pair<const uint256, CWalletTx> & item : mapWallet)
897  item.second.MarkDirty();
898  }
899 }
900 
901 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
902 {
903  LOCK(cs_wallet);
904  WalletBatch batch(*database, "r+", fFlushOnClose);
905  const uint256& hash = wtxIn.GetHash();
906 
907  // Inserts only if not already there, returns tx inserted or tx found
908  std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.emplace(hash, wtxIn);
909  CWalletTx& wtx = (*ret.first).second;
910  wtx.BindWallet(this);
911  // Sapling
912  m_sspk_man->UpdateNullifierNoteMapWithTx(wtx);
913  bool fInsertedNew = ret.second;
914  if (fInsertedNew) {
916  wtx.nOrderPos = IncOrderPosNext(&batch);
917  wtxOrdered.emplace(wtx.nOrderPos, &wtx);
918  wtx.UpdateTimeSmart();
919  AddToSpends(hash);
920  }
921 
922  bool fUpdated = false;
923  if (!fInsertedNew) {
924  if (wtxIn.m_confirm.status != wtx.m_confirm.status) {
925  wtx.m_confirm.status = wtxIn.m_confirm.status;
926  wtx.m_confirm.nIndex = wtxIn.m_confirm.nIndex;
929  wtx.UpdateTimeSmart();
930  fUpdated = true;
931  } else {
932  assert(wtx.m_confirm.nIndex == wtxIn.m_confirm.nIndex);
933  assert(wtx.m_confirm.hashBlock == wtxIn.m_confirm.hashBlock);
934  assert(wtx.m_confirm.block_height == wtxIn.m_confirm.block_height);
935  }
936  if (HasSaplingSPKM() && m_sspk_man->UpdatedNoteData(wtxIn, wtx)) {
937  fUpdated = true;
938  }
939  if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) {
940  wtx.fFromMe = wtxIn.fFromMe;
941  fUpdated = true;
942  }
943  }
944 
946  LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
947 
948  // Write to disk
949  if (fInsertedNew || fUpdated) {
950  if (!batch.WriteTx(wtx))
951  return false;
952  }
953 
954  // Break debit/credit balance caches:
955  wtx.MarkDirty();
956 
957  // Notify UI of new or updated transaction
958  NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
959 
960  // notify an external script when a wallet transaction comes in or is updated
961  std::string strCmd = gArgs.GetArg("-walletnotify", "");
962 
963  if (!strCmd.empty()) {
964  boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
965  std::thread t(runCommand, strCmd);
966  t.detach(); // thread runs free
967  }
968  return true;
969 }
970 
971 // Internal function for now, this will be part of a chain interface class in the future.
972 static Optional<int> getTipBlockHeight(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
973 {
975 
976  CBlockIndex* pindex = LookupBlockIndex(hash);
977  if (pindex && chainActive.Contains(pindex)) {
978  return Optional<int>(pindex->nHeight);
979  }
980  return nullopt;
981 }
982 
984 {
986  // If tx hasn't been reorged out of chain while wallet being shutdown
987  // change tx status to UNCONFIRMED and reset hashBlock/nIndex.
988  if (!wtxIn.m_confirm.hashBlock.IsNull()) {
989  Optional<int> block_height = getTipBlockHeight(wtxIn.m_confirm.hashBlock);
990  if (block_height) {
991  // Update cached block height variable since it not stored in the
992  // serialized transaction.
993  wtxIn.m_confirm.block_height = *block_height;
994  } else if (wtxIn.isConflicted() || wtxIn.isConfirmed()) {
995  // If tx block (or conflicting block) was reorged out of chain
996  // while the wallet was shutdown, change tx status to UNCONFIRMED
997  // and reset block height, hash, and index. ABANDONED tx don't have
998  // associated blocks and don't need to be updated. The case where a
999  // transaction was reorged out while online and then reconfirmed
1000  // while offline is covered by the rescan logic.
1001  wtxIn.setUnconfirmed();
1003  wtxIn.m_confirm.block_height = 0;
1004  wtxIn.m_confirm.nIndex = 0;
1005  }
1006  }
1007  const uint256& hash = wtxIn.GetHash();
1008  CWalletTx& wtx = mapWallet.emplace(hash, wtxIn).first->second;
1009  wtx.BindWallet(this);
1010  // Sapling
1011  m_sspk_man->UpdateNullifierNoteMapWithTx(wtx);
1012  wtxOrdered.emplace(wtx.nOrderPos, &wtx);
1013  AddToSpends(hash);
1014  for (const CTxIn& txin : wtx.tx->vin) {
1015  auto it = mapWallet.find(txin.prevout.hash);
1016  if (it != mapWallet.end()) {
1017  CWalletTx& prevtx = it->second;
1018  if (prevtx.isConflicted()) {
1020  }
1021  }
1022  }
1023  return true;
1024 }
1025 
1027 {
1028  auto saplingNoteDataAndAddressesToAdd = m_sspk_man->FindMySaplingNotes(tx);
1029  saplingNoteData = saplingNoteDataAndAddressesToAdd.first;
1030  auto addressesToAdd = saplingNoteDataAndAddressesToAdd.second;
1031  // Add my addresses
1032  for (const auto& addressToAdd : addressesToAdd) {
1033  if (!m_sspk_man->AddSaplingIncomingViewingKey(addressToAdd.second, addressToAdd.first)) {
1034  return false;
1035  }
1036  }
1037  return true;
1038 }
1039 
1041 {
1042  if (HasSaplingSPKM() && wtx.tx->IsShieldedTx()) {
1043  const uint256& txId = wtx.GetHash();
1044  // Add the external outputs.
1045  SaplingOutPoint op {txId, 0};
1046  for (unsigned int i = 0; i < wtx.tx->sapData->vShieldedOutput.size(); i++) {
1047  op.n = i;
1048  if (wtx.mapSaplingNoteData.count(op)) continue; // internal output
1049  auto recovered = GetSaplingScriptPubKeyMan()->TryToRecoverNote(wtx, op);
1050  if (recovered) {
1051  // Always true for 'IsFromMe' transactions
1052  wtx.mapSaplingNoteData[op].address = recovered->second;
1053  wtx.mapSaplingNoteData[op].amount = recovered->first.value();
1054  const auto& memo = recovered->first.memo();
1055  // don't save empty memo (starting with 0xF6)
1056  if (memo[0] < 0xF6) {
1057  wtx.mapSaplingNoteData[op].memo = memo;
1058  }
1059  }
1060  }
1061  }
1062 }
1063 
1077 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CWalletTx::Confirmation& confirm, bool fUpdate)
1078 {
1079  const CTransaction& tx = *ptx;
1080  {
1082 
1083  if (!confirm.hashBlock.IsNull() && !tx.HasZerocoinSpendInputs() && !tx.IsCoinBase()) {
1084  for (const CTxIn& txin : tx.vin) {
1085  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1086  while (range.first != range.second) {
1087  if (range.first->second != tx.GetHash()) {
1088  LogPrintf("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);
1089  MarkConflicted(confirm.hashBlock, confirm.block_height, range.first->second);
1090  }
1091  range.first++;
1092  }
1093  }
1094  }
1095 
1096  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1097  if (fExisted && !fUpdate) return false;
1098 
1099  // Check tx for Sapling notes
1100  Optional<mapSaplingNoteData_t> saplingNoteData {nullopt};
1101  if (HasSaplingSPKM()) {
1102  if (!FindNotesDataAndAddMissingIVKToKeystore(tx, saplingNoteData)) {
1103  return false; // error adding incoming viewing key.
1104  }
1105  }
1106 
1107  // If this is a ProRegTx and the wallet owns the collateral, lock the corresponding coin
1108  LockIfMyCollateral(ptx);
1109 
1110  bool isFromMe = IsFromMe(ptx);
1111  if (fExisted || IsMine(ptx) || isFromMe || (saplingNoteData && !saplingNoteData->empty())) {
1112 
1113  /* Check if any keys in the wallet keypool that were supposed to be unused
1114  * have appeared in a new transaction. If so, remove those keys from the keypool.
1115  * This can happen when restoring an old wallet backup that does not contain
1116  * the mostly recently created transactions from newer versions of the wallet.
1117  */
1118 
1119  // loop though all outputs
1120  for (const CTxOut& txout: tx.vout) {
1121  m_spk_man->MarkUnusedAddresses(txout.scriptPubKey);
1122  }
1123 
1124  CWalletTx wtx(this, MakeTransactionRef(tx));
1125  if (wtx.tx->IsShieldedTx()) {
1126  if (saplingNoteData && !saplingNoteData->empty()) {
1127  wtx.SetSaplingNoteData(*saplingNoteData);
1128  }
1129 
1130  // Add external notes info if we are sending
1131  if (isFromMe) AddExternalNotesDataToTx(wtx);
1132  }
1133 
1134  // Block disconnection override an abandoned tx as unconfirmed
1135  // which means user may have to call abandontransaction again
1136  wtx.m_confirm = confirm;
1137 
1138  return AddToWallet(wtx, false);
1139  }
1140  }
1141  return false;
1142 }
1143 
1145 {
1146  LOCK(cs_wallet);
1147 
1148  WalletBatch batch(*database, "r+");
1149 
1150  std::set<uint256> todo;
1151  std::set<uint256> done;
1152 
1153  // Can't mark abandoned if confirmed or in mempool
1154  auto it = mapWallet.find(hashTx);
1155  assert(it != mapWallet.end());
1156  CWalletTx& origtx = it->second;
1157  if (origtx.GetDepthInMainChain() != 0 || origtx.InMempool()) {
1158  return false;
1159  }
1160 
1161  todo.insert(hashTx);
1162 
1163  while (!todo.empty()) {
1164  uint256 now = *todo.begin();
1165  todo.erase(now);
1166  done.insert(now);
1167  auto it2 = mapWallet.find(now);
1168  assert(it2 != mapWallet.end());
1169  CWalletTx& wtx = it2->second;
1170  int currentconfirm = wtx.GetDepthInMainChain();
1171  // If the orig tx was not in block, none of its spends can be
1172  assert(currentconfirm <= 0);
1173  // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1174  if (currentconfirm == 0 && !wtx.isAbandoned()) {
1175  // If the orig tx was not in block/mempool, none of its spends can be in mempool
1176  assert(!wtx.InMempool());
1177  wtx.setAbandoned();
1178  wtx.MarkDirty();
1179  batch.WriteTx(wtx);
1181  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1182  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1183  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1184  if (!done.count(iter->second)) {
1185  todo.insert(iter->second);
1186  }
1187  iter++;
1188  }
1189  // If a transaction changes 'conflicted' state, that changes the balance
1190  // available of the outputs it spends. So force those to be recomputed
1191  for (const CTxIn& txin : wtx.tx->vin) {
1192  auto _it = mapWallet.find(txin.prevout.hash);
1193  if (_it != mapWallet.end()) {
1194  _it->second.MarkDirty();
1195  }
1196  }
1197  }
1198  }
1199 
1200  return true;
1201 }
1202 
1203 void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx)
1204 {
1205  LOCK(cs_wallet);
1206 
1207  int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
1208  // If number of conflict confirms cannot be determined, this means
1209  // that the block is still unknown or not yet part of the main chain,
1210  // for example when loading the wallet during a reindex. Do nothing in that
1211  // case.
1212  if (conflictconfirms >= 0)
1213  return;
1214 
1215  // Do not flush the wallet here for performance reasons
1216  WalletBatch batch(*database, "r+", false);
1217 
1218  std::set<uint256> todo;
1219  std::set<uint256> done;
1220 
1221  todo.insert(hashTx);
1222 
1223  while (!todo.empty()) {
1224  uint256 now = *todo.begin();
1225  todo.erase(now);
1226  done.insert(now);
1227  auto it = mapWallet.find(now);
1228  assert(it != mapWallet.end());
1229  CWalletTx& wtx = it->second;
1230  int currentconfirm = wtx.GetDepthInMainChain();
1231  if (conflictconfirms < currentconfirm) {
1232  // Block is 'more conflicted' than current confirm; update.
1233  // Mark transaction as conflicted with this block.
1234  wtx.m_confirm.nIndex = 0;
1235  wtx.m_confirm.hashBlock = hashBlock;
1236  wtx.m_confirm.block_height = conflicting_height;
1237  wtx.setConflicted();
1238  wtx.MarkDirty();
1239  batch.WriteTx(wtx);
1240  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1241  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1242  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1243  if (!done.count(iter->second)) {
1244  todo.insert(iter->second);
1245  }
1246  iter++;
1247  }
1248  // If a transaction changes 'conflicted' state, that changes the balance
1249  // available of the outputs it spends. So force those to be recomputed
1250  for (const CTxIn& txin : wtx.tx->vin) {
1251  auto _it = mapWallet.find(txin.prevout.hash);
1252  if (_it != mapWallet.end()) {
1253  _it->second.MarkDirty();
1254  }
1255  }
1256  }
1257  }
1258 }
1259 
1261 {
1262  if (!AddToWalletIfInvolvingMe(ptx, confirm, true)) {
1263  return; // Not one of ours
1264  }
1265 
1267 }
1268 
1270 {
1271  LOCK(cs_wallet);
1272  CWalletTx::Confirmation confirm(CWalletTx::Status::UNCONFIRMED, /* block_height */ 0, {}, /* nIndex */ 0);
1273  SyncTransaction(ptx, confirm);
1274 
1275  auto it = mapWallet.find(ptx->GetHash());
1276  if (it != mapWallet.end()) {
1277  it->second.fInMempool = true;
1278  }
1279 }
1280 
1282  LOCK(cs_wallet);
1283  auto it = mapWallet.find(ptx->GetHash());
1284  if (it != mapWallet.end()) {
1285  it->second.fInMempool = false;
1286  }
1287  // Handle transactions that were removed from the mempool because they
1288  // conflict with transactions in a newly connected block.
1289  if (reason == MemPoolRemovalReason::CONFLICT) {
1290  // Call SyncNotifications, so external -walletnotify notifications will
1291  // be triggered for these transactions. Set Status::UNCONFIRMED instead
1292  // of Status::CONFLICTED for a few reasons:
1293  //
1294  // 1. The transactionRemovedFromMempool callback does not currently
1295  // provide the conflicting block's hash and height, and for backwards
1296  // compatibility reasons it may not be not safe to store conflicted
1297  // wallet transactions with a null block hash. See
1298  // https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
1299  // 2. For most of these transactions, the wallet's internal conflict
1300  // detection in the blockConnected handler will subsequently call
1301  // MarkConflicted and update them with CONFLICTED status anyway. This
1302  // applies to any wallet transaction that has inputs spent in the
1303  // block, or that has ancestors in the wallet with inputs spent by
1304  // the block.
1305  // 3. Longstanding behavior since the sync implementation in
1306  // https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
1307  // implementation before that was to mark these transactions
1308  // unconfirmed rather than conflicted.
1309  //
1310  // Nothing described above should be seen as an unchangeable requirement
1311  // when improving this code in the future. The wallet's heuristics for
1312  // distinguishing between conflicted and unconfirmed transactions are
1313  // imperfect, and could be improved in general, see
1314  // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
1315  SyncTransaction(ptx, {CWalletTx::Status::UNCONFIRMED, /* block height */ 0, /* block hash */ {}, /* index */ 0});
1316  }
1317 }
1318 
1319 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex)
1320 {
1321  {
1323 
1324  m_last_block_processed = pindex->GetBlockHash();
1325  m_last_block_processed_time = pindex->GetBlockTime();
1326  m_last_block_processed_height = pindex->nHeight;
1327  for (size_t index = 0; index < pblock->vtx.size(); index++) {
1328  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, m_last_block_processed_height,
1329  m_last_block_processed, index);
1330  SyncTransaction(pblock->vtx[index], confirm);
1332  }
1333 
1334  // Sapling: notify about the connected block
1335  // Get prev block tree anchor
1336  CBlockIndex* pprev = pindex->pprev;
1337  SaplingMerkleTree oldSaplingTree;
1338  bool isSaplingActive = (pprev) != nullptr &&
1341  if (isSaplingActive) {
1342  assert(pcoinsTip->GetSaplingAnchorAt(pprev->hashFinalSaplingRoot, oldSaplingTree));
1343  } else {
1344  assert(pcoinsTip->GetSaplingAnchorAt(SaplingMerkleTree::empty_root(), oldSaplingTree));
1345  }
1346 
1347  // Sapling: Update cached incremental witnesses
1348  ChainTipAdded(pindex, pblock.get(), oldSaplingTree);
1349  } // cs_wallet lock end
1350 
1351  // Auto-combine functionality
1352  // If turned on Auto Combine will scan wallet for dust to combine
1353  // Outside of the cs_wallet lock because requires cs_main for now
1354  // due CreateTransaction/CommitTransaction dependency.
1355  if (fCombineDust && pindex->nHeight % frequency == 0) {
1356  AutoCombineDust(g_connman.get());
1357  }
1358 }
1359 
1360 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock, const uint256& blockHash, int nBlockHeight, int64_t blockTime)
1361 {
1362  LOCK(cs_wallet);
1363 
1364  // At block disconnection, this will change an abandoned transaction to
1365  // be unconfirmed, whether or not the transaction is added back to the mempool.
1366  // User may have to call abandontransaction again. It may be addressed in the
1367  // future with a stickier abandoned state or even removing abandontransaction call.
1368  m_last_block_processed_height = nBlockHeight - 1;
1369  m_last_block_processed_time = blockTime;
1370  m_last_block_processed = blockHash;
1371  for (const CTransactionRef& ptx : pblock->vtx) {
1372  CWalletTx::Confirmation confirm(CWalletTx::Status::UNCONFIRMED, /* block_height */ 0, {}, /* nIndex */ 0);
1373  SyncTransaction(ptx, confirm);
1374  }
1375 
1376  if (Params().GetConsensus().NetworkUpgradeActive(nBlockHeight, Consensus::UPGRADE_V5_0)) {
1377  // Update Sapling cached incremental witnesses
1378  m_sspk_man->DecrementNoteWitnesses(mapBlockIndex[blockHash]);
1379  m_sspk_man->UpdateSaplingNullifierNoteMapForBlock(pblock.get());
1380  }
1381 }
1382 
1386 
1387  {
1388  // Skip the queue-draining stuff if we know we're caught up with
1389  // chainActive.Tip()...
1390  // We could also take cs_wallet here, and call m_last_block_processed
1391  // protected by cs_wallet instead of cs_main, but as long as we need
1392  // cs_main here anyway, its easier to just call it cs_main-protected.
1393  uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
1394  LOCK(cs_main);
1395  const CBlockIndex* initialChainTip = chainActive.Tip();
1396  if (!last_block_hash.IsNull() && initialChainTip &&
1397  last_block_hash == initialChainTip->GetBlockHash()) {
1398  return;
1399  }
1400  }
1401 
1402  // ...otherwise put a callback in the validation interface queue and wait
1403  // for the queue to drain enough to execute it (indicating we are caught up
1404  // at least with the time we entered this function).
1406 }
1407 
1409 {
1410  // If a transaction changes 'conflicted' state, that changes the balance
1411  // available of the outputs it spends. So force those to be
1412  // recomputed, also:
1413  for (const CTxIn& txin : tx.vin) {
1414  if (!txin.IsZerocoinSpend()) {
1415  auto it = mapWallet.find(txin.prevout.hash);
1416  if (it != mapWallet.end()) {
1417  it->second.MarkDirty();
1418  }
1419  }
1420  }
1421 
1422  // Sapling
1423  if (HasSaplingSPKM() && tx.IsShieldedTx()) {
1424  for (const SpendDescription &spend : tx.sapData->vShieldedSpend) {
1425  const uint256& nullifier = spend.nullifier;
1426  auto nit = m_sspk_man->mapSaplingNullifiersToNotes.find(nullifier);
1427  if (nit != m_sspk_man->mapSaplingNullifiersToNotes.end()) {
1428  auto it = mapWallet.find(nit->second.hash);
1429  if (it != mapWallet.end()) {
1430  it->second.MarkDirty();
1431  }
1432  }
1433  }
1434  }
1435 }
1436 
1438 {
1439  {
1440  LOCK(cs_wallet);
1441  if (mapWallet.erase(hash))
1442  WalletBatch(*database).EraseTx(hash);
1443  LogPrintf("%s: Erased wtx %s from wallet\n", __func__, hash.GetHex());
1444  }
1445  return;
1446 }
1447 
1449 {
1450  {
1451  LOCK(cs_wallet);
1452  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1453  if (mi != mapWallet.end()) {
1454  const CWalletTx& prev = (*mi).second;
1455  if (txin.prevout.n < prev.tx->vout.size())
1456  return IsMine(prev.tx->vout[txin.prevout.n]);
1457  }
1458  }
1459  return ISMINE_NO;
1460 }
1461 
1462 bool CWallet::IsUsed(const CTxDestination address) const
1463 {
1464  LOCK(cs_wallet);
1465  CScript scriptPubKey = GetScriptForDestination(address);
1466  if (!::IsMine(*this, scriptPubKey)) {
1467  return false;
1468  }
1469 
1470  for (const auto& it : mapWallet) {
1471  const CWalletTx& wtx = it.second;
1472  if (wtx.IsCoinBase()) {
1473  continue;
1474  }
1475  for (const CTxOut& txout : wtx.tx->vout) {
1476  if (txout.scriptPubKey == scriptPubKey)
1477  return true;
1478  }
1479  }
1480  return false;
1481 }
1482 
1484 {
1485  LOCK(cs_wallet);
1486  if (!::IsMine(*this, address)) {
1487  return false;
1488  }
1489 
1490  for (const auto& it : mapWallet) {
1491  const CWalletTx& wtx = it.second;
1492  for (const auto& txout : wtx.mapSaplingNoteData) {
1493  if (txout.second.address && *txout.second.address == address)
1494  return true;
1495  }
1496  }
1497  return false;
1498 }
1499 
1500 CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const
1501 {
1502  {
1503  LOCK(cs_wallet);
1504  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1505  if (mi != mapWallet.end()) {
1506  const CWalletTx& prev = (*mi).second;
1507  if (txin.prevout.n < prev.tx->vout.size())
1508  if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1509  return prev.tx->vout[txin.prevout.n].nValue;
1510  }
1511  }
1512  return 0;
1513 }
1514 
1515 bool CWallet::IsChange(const CTxOut& txout) const
1516 {
1517  // TODO: fix handling of 'change' outputs. The assumption is that any
1518  // payment to a script that is ours, but is not in the address book
1519  // is change. That assumption is likely to break when we implement multisignature
1520  // wallets that return change back into a multi-signature-protected address;
1521  // a better way of identifying which outputs are 'the send' and which are
1522  // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1523  // which output, if any, was change).
1524  if (::IsMine(*this, txout.scriptPubKey)) {
1525  CTxDestination address;
1526  if (!ExtractDestination(txout.scriptPubKey, address))
1527  return true;
1528 
1529  return IsChange(address);
1530  }
1531  return false;
1532 }
1533 
1534 bool CWallet::IsChange(const CTxDestination& address) const
1535 {
1536  // Read the current assumptions in IsChange(const CTxOut&)
1537  // this can definitely be different in the short future.
1538  return WITH_LOCK(cs_wallet, return !HasAddressBook(address));
1539 }
1540 
1541 int64_t CWalletTx::GetTxTime() const
1542 {
1543  int64_t n = nTimeSmart;
1544  return n ? n : nTimeReceived;
1545 }
1546 
1555 {
1557  if (!m_confirm.hashBlock.IsNull()) {
1558  if (mapBlockIndex.count(m_confirm.hashBlock)) {
1559  nTimeSmart = mapBlockIndex.at(m_confirm.hashBlock)->GetBlockTime();
1560  } else
1561  LogPrintf("%s : found %s in block %s not in index\n", __func__, GetHash().ToString(), m_confirm.hashBlock.ToString());
1562  }
1563 }
1564 
1565 CAmount CWalletTx::GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate) const
1566 {
1567  auto& amount = m_amounts[type];
1568  if (recalculate || !amount.m_cached[filter]) {
1569  amount.Set(filter, type == DEBIT ? pwallet->GetDebit(tx, filter) : pwallet->GetCredit(*this, filter));
1570  }
1571  return amount.m_value[filter];
1572 }
1573 
1574 bool CWalletTx::IsAmountCached(AmountType type, const isminefilter& filter) const
1575 {
1576  return m_amounts[type].m_cached[filter];
1577 }
1578 
1581 {
1582  if (tx->vin.empty() && (tx->sapData && tx->sapData->vShieldedSpend.empty())) {
1583  return 0;
1584  }
1585 
1586  CAmount debit = 0;
1587  if (filter & ISMINE_SPENDABLE) {
1589  }
1590  if (filter & ISMINE_WATCH_ONLY) {
1592  }
1593  if (filter & ISMINE_COLD) {
1594  debit += GetCachableAmount(DEBIT, ISMINE_COLD);
1595  }
1596  if (filter & ISMINE_SPENDABLE_DELEGATED) {
1598  }
1599  if (filter & ISMINE_SPENDABLE_SHIELDED) {
1601  }
1602 
1603  return debit;
1604 }
1605 
1607 {
1608  return GetCachableAmount(DEBIT, ISMINE_COLD, !fUseCache);
1609 }
1610 
1612 {
1613  return GetCachableAmount(DEBIT, ISMINE_SPENDABLE_DELEGATED, !fUseCache);
1614 }
1615 
1616 CAmount CWalletTx::GetCredit(const isminefilter& filter, bool recalculate) const
1617 {
1618  CAmount credit = 0;
1619  if (filter & ISMINE_SPENDABLE) {
1620  // GetBalance can assume transactions in mapWallet won't change
1621  credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE, recalculate);
1622  }
1623  if (filter & ISMINE_WATCH_ONLY) {
1624  credit += GetCachableAmount(CREDIT, ISMINE_WATCH_ONLY, recalculate);
1625  }
1626  if (filter & ISMINE_COLD) {
1627  credit += GetCachableAmount(CREDIT, ISMINE_COLD, recalculate);
1628  }
1629  if (filter & ISMINE_SPENDABLE_DELEGATED) {
1630  credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE_DELEGATED, recalculate);
1631  }
1632  if (filter & ISMINE_SPENDABLE_SHIELDED) {
1633  credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE_SHIELDED, recalculate);
1634  }
1635  return credit;
1636 }
1637 
1638 CAmount CWalletTx::GetImmatureCredit(bool fUseCache, const isminefilter& filter) const
1639 {
1640  if (IsInMainChainImmature()) {
1641  return GetCachableAmount(IMMATURE_CREDIT, filter, !fUseCache);
1642  }
1643 
1644  return 0;
1645 }
1646 
1647 CAmount CWalletTx::GetAvailableCredit(bool fUseCache, const isminefilter& filter) const
1648 {
1649  if (!pwallet)
1650  return 0;
1651 
1652  // Avoid caching ismine for NO or ALL cases (could remove this check and simplify in the future).
1653  bool allow_cache = filter == ISMINE_SPENDABLE || filter == ISMINE_WATCH_ONLY ||
1655 
1656  // Must wait until coinbase/coinstake is safely deep enough in the chain before valuing it
1657  if (GetBlocksToMaturity() > 0)
1658  return 0;
1659 
1660  if (fUseCache && allow_cache && m_amounts[AVAILABLE_CREDIT].m_cached[filter]) {
1661  return m_amounts[AVAILABLE_CREDIT].m_value[filter];
1662  }
1663 
1664  CAmount nCredit = 0;
1665  // If the filter is only for shielded amounts, do not calculate the regular outputs
1666  if (filter != ISMINE_SPENDABLE_SHIELDED && filter != ISMINE_WATCH_ONLY_SHIELDED) {
1667 
1668  const uint256& hashTx = GetHash();
1669  for (unsigned int i = 0; i < tx->vout.size(); i++) {
1670  if (!pwallet->IsSpent(hashTx, i)) {
1671  const CTxOut &txout = tx->vout[i];
1672  nCredit += pwallet->GetCredit(txout, filter);
1673  if (!Params().GetConsensus().MoneyRange(nCredit))
1674  throw std::runtime_error(std::string(__func__) + " : value out of range");
1675  }
1676  }
1677 
1678  }
1679 
1680  if (pwallet->HasSaplingSPKM()) {
1681  // Can calculate the shielded available balance.
1682  if (filter & ISMINE_SPENDABLE_SHIELDED || filter & ISMINE_WATCH_ONLY_SHIELDED) {
1683  nCredit += pwallet->GetSaplingScriptPubKeyMan()->GetCredit(*this, filter, true);
1684  }
1685  }
1686 
1687  if (allow_cache) {
1688  m_amounts[AVAILABLE_CREDIT].Set(filter, nCredit);
1689  }
1690 
1691  return nCredit;
1692 }
1693 
1695 {
1696  return GetAvailableCredit(fUseCache, ISMINE_COLD);
1697 }
1698 
1700 {
1702 }
1703 
1704 // Return sum of locked coins
1706 {
1707  if (pwallet == 0)
1708  return 0;
1709 
1710  // Must wait until coinbase is safely deep enough in the chain before valuing it
1711  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1712  return 0;
1713 
1714  CAmount nCredit = 0;
1715  uint256 hashTx = GetHash();
1716  const CAmount collAmt = Params().GetConsensus().nMNCollateralAmt;
1717  for (unsigned int i = 0; i < tx->vout.size(); i++) {
1718  const CTxOut& txout = tx->vout[i];
1719 
1720  // Skip spent coins
1721  if (pwallet->IsSpent(hashTx, i)) continue;
1722 
1723  // Add locked coins
1724  if (pwallet->IsLockedCoin(hashTx, i)) {
1725  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE_ALL);
1726  }
1727 
1728  // Add masternode collaterals which are handled like locked coins
1729  else if (fMasterNode && tx->vout[i].nValue == collAmt) {
1730  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1731  }
1732 
1733  if (!Params().GetConsensus().MoneyRange(nCredit))
1734  throw std::runtime_error("CWalletTx::GetLockedCredit() : value out of range");
1735  }
1736 
1737  return nCredit;
1738 }
1739 
1741 {
1742  if (IsInMainChainImmature()) {
1744  }
1745 
1746  return 0;
1747 }
1748 
1750 {
1751  return GetAvailableCredit(fUseCache, ISMINE_WATCH_ONLY);
1752 }
1753 
1754 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1755  std::list<COutputEntry>& listSent,
1756  CAmount& nFee,
1757  const isminefilter& filter) const
1758 {
1759  nFee = 0;
1760  listReceived.clear();
1761  listSent.clear();
1762 
1763  // Compute fee:
1764  CAmount nDebit = GetDebit(filter);
1765  bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
1766 
1767  if (isFromMyTaddr) {// debit>0 means we signed/sent this transaction
1768  CAmount nValueOut = tx->GetValueOut(); // transasparent outputs plus the negative Sapling valueBalance
1769  CAmount nValueIn = tx->GetShieldedValueIn();
1770  nFee = nDebit - nValueOut + nValueIn;
1771 
1772  // If we sent utxos from this transaction, create output for value taken from (negative valueBalance)
1773  // or added (positive valueBalance) to the transparent value pool by Sapling shielding and unshielding.
1774  if (tx->sapData) {
1775  if (tx->sapData->valueBalance < 0) {
1776  COutputEntry output = {CNoDestination(), -tx->sapData->valueBalance, (int) tx->vout.size()};
1777  listSent.push_back(output);
1778  } else if (tx->sapData->valueBalance > 0) {
1779  COutputEntry output = {CNoDestination(), tx->sapData->valueBalance, (int) tx->vout.size()};
1780  listReceived.push_back(output);
1781  }
1782  }
1783  }
1784 
1785  // Sent/received.
1786  bool hasZerocoinSpends = tx->HasZerocoinSpendInputs();
1787  for (unsigned int i = 0; i < tx->vout.size(); ++i) {
1788  const CTxOut& txout = tx->vout[i];
1789  isminetype fIsMine = pwallet->IsMine(txout);
1790  // Only need to handle txouts if AT LEAST one of these is true:
1791  // 1) they debit from us (sent)
1792  // 2) the output is to us (received)
1793  if (nDebit > 0) {
1794  // Don't report 'change' txouts
1795  if (pwallet->IsChange(txout))
1796  continue;
1797  } else if (!(fIsMine & filter) && !hasZerocoinSpends)
1798  continue;
1799 
1800  // In either case, we need to get the destination address
1801  const bool fColdStake = (filter & ISMINE_COLD);
1802  CTxDestination address;
1803  if (txout.IsZerocoinMint()) {
1804  address = CNoDestination();
1805  } else if (!ExtractDestination(txout.scriptPubKey, address, fColdStake)) {
1806  if (!IsCoinStake() && !IsCoinBase()) {
1807  LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString());
1808  }
1809  address = CNoDestination();
1810  }
1811 
1812  COutputEntry output = {address, txout.nValue, (int)i};
1813 
1814  // If we are debited by the transaction, add the output as a "sent" entry
1815  if (nDebit > 0)
1816  listSent.push_back(output);
1817 
1818  // If we are receiving the output, add it as a "received" entry
1819  if (fIsMine & filter)
1820  listReceived.push_back(output);
1821  }
1822 }
1823 
1824 bool CWallet::Upgrade(std::string& error, const int prevVersion)
1825 {
1827 
1828  // Do not upgrade versions if we are already in the last one
1829  if (prevVersion >= FEATURE_SAPLING) {
1830  error = strprintf(_("Cannot upgrade to Sapling wallet (already running Sapling support). Version: %d"), prevVersion);
1831  return false;
1832  }
1833 
1834  // Check if we need to upgrade to HD
1835  if (prevVersion < FEATURE_PRE_SPLIT_KEYPOOL) {
1836  if (!m_spk_man->Upgrade(prevVersion, error)) {
1837  return false;
1838  }
1839  }
1840 
1841  // Now upgrade to Sapling manager
1842  if (prevVersion < FEATURE_SAPLING) {
1843  if (!ActivateSaplingWallet()) {
1844  return false;
1845  }
1846  }
1847 
1848  return true;
1849 }
1850 
1859 int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
1860 {
1861  // Find starting block. May be null if nCreateTime is greater than the
1862  // highest blockchain timestamp, in which case there is nothing that needs
1863  // to be scanned.
1864  CBlockIndex* startBlock = nullptr;
1865  {
1866  LOCK(cs_main);
1867  startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1868  LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1869  }
1870 
1871  if (startBlock) {
1872  const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, reserver, update);
1873  if (failedBlock) {
1874  return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1875  }
1876  }
1877  return startTime;
1878 }
1879 
1896 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, const WalletRescanReserver& reserver, bool fUpdate, bool fromStartup)
1897 {
1898  int64_t nNow = GetTime();
1899 
1900  assert(reserver.isReserved());
1901  if (pindexStop) {
1902  assert(pindexStop->nHeight >= pindexStart->nHeight);
1903  }
1904 
1905  CBlockIndex* pindex = pindexStart;
1906  CBlockIndex* ret = nullptr;
1907  {
1908  ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1909  CBlockIndex* tip = nullptr;
1910  double dProgressStart;
1911  double dProgressTip;
1912  {
1913  LOCK(cs_main);
1914  tip = chainActive.Tip();
1915  dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false);
1916  dProgressTip = Checkpoints::GuessVerificationProgress(tip, false);
1917  }
1918 
1919  std::vector<uint256> myTxHashes;
1920  while (pindex && !fAbortRescan) {
1921  double gvp = 0;
1922  if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) {
1923  gvp = WITH_LOCK(cs_main, return Checkpoints::GuessVerificationProgress(pindex, false); );
1924  ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((gvp - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1925  }
1926  if (GetTime() >= nNow + 60) {
1927  nNow = GetTime();
1928  LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, gvp);
1929  }
1930  if (fromStartup && ShutdownRequested()) {
1931  break;
1932  }
1933 
1934  CBlock block;
1935  if (ReadBlockFromDisk(block, pindex)) {
1937  if (pindex && !chainActive.Contains(pindex)) {
1938  // Abort scan if current block is no longer active, to prevent
1939  // marking transactions as coming from the wrong block.
1940  ret = pindex;
1941  break;
1942  }
1943  for (int posInBlock = 0; posInBlock < (int) block.vtx.size(); posInBlock++) {
1944  const auto& tx = block.vtx[posInBlock];
1945  CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, pindex->nHeight, pindex->GetBlockHash(), posInBlock);
1946  if (AddToWalletIfInvolvingMe(tx, confirm, fUpdate)) {
1947  myTxHashes.push_back(tx->GetHash());
1948  }
1949  }
1950 
1951  // Sapling
1952  // This should never fail: we should always be able to get the tree
1953  // state on the path to the tip of our chain
1954  if (pindex->pprev) {
1955  if (Params().GetConsensus().NetworkUpgradeActive(pindex->pprev->nHeight, Consensus::UPGRADE_V5_0)) {
1956  SaplingMerkleTree saplingTree;
1957  assert(pcoinsTip->GetSaplingAnchorAt(pindex->pprev->hashFinalSaplingRoot, saplingTree));
1958  // Increment note witness caches
1959  ChainTipAdded(pindex, &block, saplingTree);
1960  }
1961  }
1962  } else {
1963  ret = pindex;
1964  }
1965  if (pindex == pindexStop) {
1966  break;
1967  }
1968  {
1969  LOCK(cs_main);
1970  pindex = chainActive.Next(pindex);
1971  if (tip != chainActive.Tip()) {
1972  tip = chainActive.Tip();
1973  // in case the tip has changed, update progress max
1974  dProgressTip = Checkpoints::GuessVerificationProgress(tip, false);
1975  }
1976  }
1977  }
1978 
1979  // Sapling
1980  // After rescanning, persist Sapling note data that might have changed, e.g. nullifiers.
1981  // Do not flush the wallet here for performance reasons.
1982  WalletBatch batch(*database, "r+", false);
1983  for (const auto& hash : myTxHashes) {
1984  CWalletTx& wtx = mapWallet.at(hash);
1985  if (!wtx.mapSaplingNoteData.empty()) {
1986  if (!batch.WriteTx(wtx)) {
1987  LogPrintf("Rescanning... WriteToDisk failed to update Sapling note data for: %s\n", hash.ToString());
1988  }
1989  }
1990  }
1991 
1992  if (pindex && fAbortRescan) {
1993  LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex, false));
1994  }
1995  ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1996  }
1997  return ret;
1998 }
1999 
2001 {
2003  std::map<int64_t, CWalletTx*> mapSorted;
2004 
2005  // Sort pending wallet transactions based on their initial wallet insertion order
2006  for (std::pair<const uint256, CWalletTx>& item: mapWallet) {
2007  const uint256& wtxid = item.first;
2008  CWalletTx& wtx = item.second;
2009  assert(wtx.GetHash() == wtxid);
2010 
2011  int nDepth = wtx.GetDepthInMainChain();
2012  if (!wtx.IsCoinBase() && !wtx.IsCoinStake() && nDepth == 0 && !wtx.isAbandoned()) {
2013  mapSorted.emplace(wtx.nOrderPos, &wtx);
2014  }
2015  }
2016 
2017  // Try to add wallet transactions to memory pool
2018  for (std::pair<const int64_t, CWalletTx*>& item: mapSorted) {
2019  CWalletTx& wtx = *(item.second);
2020 
2021  CValidationState state;
2022  bool fSuccess = wtx.AcceptToMemoryPool(state);
2023  if (!fSuccess && fFirstLoad && GetTime() - wtx.GetTxTime() > 12*60*60) {
2024  //First load of wallet, failed to accept to mempool, and older than 12 hours... not likely to ever
2025  //make it in to mempool
2026  AbandonTransaction(wtx.GetHash());
2027  }
2028  }
2029 }
2030 
2032 {
2033  return fInMempool;
2034 }
2035 
2037 {
2038  if (!connman || IsCoinBase() || IsCoinStake()) {
2039  // Nothing to do. Return early
2040  return;
2041  }
2042  if (GetDepthInMainChain() == 0 && !isAbandoned()) {
2043  const uint256& hash = GetHash();
2044  LogPrintf("Relaying wtx %s\n", hash.ToString());
2045  CInv inv(MSG_TX, hash);
2046  connman->ForEachNode([&inv](CNode* pnode) {
2047  pnode->PushInventory(inv);
2048  });
2049  }
2050 }
2051 
2052 std::set<uint256> CWalletTx::GetConflicts() const
2053 {
2054  std::set<uint256> result;
2055  if (pwallet != nullptr) {
2056  uint256 myHash = GetHash();
2057  result = pwallet->GetConflicts(myHash);
2058  result.erase(myHash);
2059  }
2060  return result;
2061 }
2062 
2063 void CWallet::Flush(bool shutdown)
2064 {
2065  database->Flush(shutdown);
2066 }
2067 
2069 {
2070  // Do this infrequently and randomly to avoid giving away
2071  // that these are our transactions.
2072  if (GetTime() < nNextResend) {
2073  return;
2074  }
2075  bool fFirst = (nNextResend == 0);
2076  nNextResend = GetTime() + GetRand(30 * 60);
2077  if (fFirst) {
2078  return;
2079  }
2080 
2081  // Only do it if there's been a new block since last time
2083  return;
2084  }
2085  nLastResend = GetTime();
2086 
2087  // Rebroadcast any of our txes that aren't in a block yet
2088  LogPrintf("ResendWalletTransactions()\n");
2089  {
2090  LOCK(cs_wallet);
2091  // Sort them in chronological order
2092  std::multimap<unsigned int, CWalletTx*> mapSorted;
2093  for (std::pair<const uint256, CWalletTx> & item : mapWallet) {
2094  CWalletTx& wtx = item.second;
2095  // Don't rebroadcast until it's had plenty of time that
2096  // it should have gotten in already by now.
2097  if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) {
2098  mapSorted.emplace(wtx.nTimeReceived, &wtx);
2099  }
2100  }
2101  for (std::pair<const unsigned int, CWalletTx*> & item : mapSorted) {
2102  CWalletTx& wtx = *item.second;
2103  wtx.RelayWalletTransaction(connman);
2104  }
2105  }
2106 }
2107 
2108 void CWallet::UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload)
2109 {
2111 }
2112  // end of mapWallet
2114 
2115 
2121 CWallet::Balance CWallet::GetBalance(const int min_depth) const
2122 {
2123  Balance ret;
2124  {
2125  LOCK(cs_wallet);
2126  std::set<uint256> trusted_parents;
2127  for (const auto& entry : mapWallet) {
2128  const CWalletTx& wtx = entry.second;
2129  const bool is_trusted{wtx.IsTrusted()};
2130  const int tx_depth{wtx.GetDepthInMainChain()};
2131  const CAmount tx_credit_mine{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_SPENDABLE_TRANSPARENT)};
2132  const CAmount tx_credit_shield_mine{wtx.GetAvailableCredit(/* fUseCache */ true, ISMINE_SPENDABLE_SHIELDED)};
2133  if (is_trusted && tx_depth >= min_depth) {
2134  ret.m_mine_trusted += tx_credit_mine;
2135  ret.m_mine_trusted_shield += tx_credit_shield_mine;
2136  if (wtx.tx->HasP2CSOutputs()) {
2138  }
2139  }
2140  if (!is_trusted && tx_depth == 0 && wtx.InMempool()) {
2141  ret.m_mine_untrusted_pending += tx_credit_mine;
2142  ret.m_mine_untrusted_shielded_balance += tx_credit_shield_mine;
2143  }
2144  ret.m_mine_immature += wtx.GetImmatureCredit();
2145  }
2146  }
2147  return ret;
2148 }
2149 
2150 CAmount CWallet::loopTxsBalance(const std::function<void(const uint256&, const CWalletTx&, CAmount&)>& method) const
2151 {
2152  CAmount nTotal = 0;
2153  {
2154  LOCK(cs_wallet);
2155  for (const auto& it : mapWallet) {
2156  method(it.first, it.second, nTotal);
2157  }
2158  }
2159  return nTotal;
2160 }
2161 
2162 CAmount CWallet::GetAvailableBalance(bool fIncludeDelegated, bool fIncludeShielded) const
2163 {
2164  isminefilter filter;
2165  if (fIncludeDelegated && fIncludeShielded) {
2166  filter = ISMINE_SPENDABLE_ALL;
2167  } else if (fIncludeDelegated) {
2169  } else if (fIncludeShielded) {
2171  } else {
2172  filter = ISMINE_SPENDABLE;
2173  }
2174  return GetAvailableBalance(filter, true, 0);
2175 }
2176 
2177 CAmount CWallet::GetAvailableBalance(isminefilter& filter, bool useCache, int minDepth) const
2178 {
2179  return loopTxsBalance([filter, useCache, minDepth](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal){
2180  bool fConflicted;
2181  int depth;
2182  if (pcoin.IsTrusted(depth, fConflicted) && depth >= minDepth) {
2183  nTotal += pcoin.GetAvailableCredit(useCache, filter);
2184  }
2185  });
2186 }
2187 
2189 {
2190  return loopTxsBalance([](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2191  if (pcoin.tx->HasP2CSOutputs() && pcoin.IsTrusted())
2192  nTotal += pcoin.GetColdStakingCredit();
2193  });
2194 }
2195 
2196 CAmount CWallet::GetStakingBalance(const bool fIncludeColdStaking) const
2197 {
2198  return std::max(CAmount(0), loopTxsBalance(
2199  [fIncludeColdStaking](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2200  if (pcoin.IsTrusted() && pcoin.GetDepthInMainChain() >= Params().GetConsensus().nStakeMinDepth) {
2201  nTotal += pcoin.GetAvailableCredit(); // available coins
2202  nTotal -= pcoin.GetStakeDelegationCredit(); // minus delegated coins, if any
2203  nTotal -= pcoin.GetLockedCredit(); // minus locked coins, if any
2204  if (fIncludeColdStaking)
2205  nTotal += pcoin.GetColdStakingCredit(); // plus cold coins, if any and if requested
2206  }
2207  }));
2208 }
2209 
2211 {
2212  return loopTxsBalance([](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2213  if (pcoin.tx->HasP2CSOutputs() && pcoin.IsTrusted())
2214  nTotal += pcoin.GetStakeDelegationCredit();
2215  });
2216 }
2217 
2219 {
2220  LOCK(cs_wallet);
2221  if (setLockedCoins.empty()) return 0;
2222 
2223  CAmount ret = 0;
2224  for (const auto& coin : setLockedCoins) {
2225  auto it = mapWallet.find(coin.hash);
2226  if (it != mapWallet.end()) {
2227  const CWalletTx& pcoin = it->second;
2228  if (pcoin.IsTrusted() && pcoin.GetDepthInMainChain() > 0) {
2229  ret += it->second.tx->vout.at(coin.n).nValue;
2230  }
2231  }
2232  }
2233  return ret;
2234 }
2235 
2237 {
2238  LOCK(cs_wallet);
2239  if (setLockedNotes.empty()) return 0;
2240 
2241  CAmount ret = 0;
2242  for (const auto& op : setLockedNotes) {
2243  auto it = mapWallet.find(op.hash);
2244  if (it != mapWallet.end()) {
2245  const CWalletTx& pcoin = it->second;
2246  if (pcoin.IsTrusted() && pcoin.GetDepthInMainChain() > 0) {
2247  Optional<CAmount> val = pcoin.mapSaplingNoteData.at(op).amount;
2248  if (val) {
2249  ret += *val;
2250  }
2251  }
2252  }
2253  }
2254  return ret;
2255 }
2256 
2257 
2259 {
2260  return loopTxsBalance([filter](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2261  if (!pcoin.IsTrusted() && pcoin.GetDepthInMainChain() == 0 && pcoin.InMempool())
2262  nTotal += pcoin.GetCredit(filter);
2263  });
2264 }
2265 
2267 {
2268  return loopTxsBalance([](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2269  nTotal += pcoin.GetImmatureCredit(false);
2270  });
2271 }
2272 
2274 {
2275  return loopTxsBalance([](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2276  nTotal += pcoin.GetImmatureCredit(false, ISMINE_COLD);
2277  });
2278 }
2279 
2281 {
2282  return loopTxsBalance([](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2283  nTotal += pcoin.GetImmatureCredit(false, ISMINE_SPENDABLE_DELEGATED);
2284  });
2285 }
2286 
2288 {
2289  return loopTxsBalance([](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2290  if (pcoin.IsTrusted())
2291  nTotal += pcoin.GetAvailableWatchOnlyCredit();
2292  });
2293 }
2294 
2296 {
2297  return loopTxsBalance([](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2298  if (!pcoin.IsTrusted() && pcoin.GetDepthInMainChain() == 0 && pcoin.InMempool())
2299  nTotal += pcoin.GetAvailableWatchOnlyCredit();
2300  });
2301 }
2302 
2304 {
2305  return loopTxsBalance([](const uint256& id, const CWalletTx& pcoin, CAmount& nTotal) {
2306  nTotal += pcoin.GetImmatureWatchOnlyCredit();
2307  });
2308 }
2309 
2310 // Calculate total balance in a different way from GetBalance. The biggest
2311 // difference is that GetBalance sums up all unspent TxOuts paying to the
2312 // wallet, while this sums up both spent and unspent TxOuts paying to the
2313 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2314 // also has fewer restrictions on which unconfirmed transactions are considered
2315 // trusted.
2316 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth) const
2317 {
2318  LOCK(cs_wallet);
2319 
2320  CAmount balance = 0;
2321  for (const auto& entry : mapWallet) {
2322  const CWalletTx& wtx = entry.second;
2323  bool fConflicted;
2324  const int depth = wtx.GetDepthAndMempool(fConflicted);
2325  if (!IsFinalTx(wtx.tx, m_last_block_processed_height) || wtx.GetBlocksToMaturity() > 0 || depth < 0 || fConflicted) {
2326  continue;
2327  }
2328 
2329  // Loop through tx outputs and add incoming payments. For outgoing txs,
2330  // treat change outputs specially, as part of the amount debited.
2331  CAmount debit = wtx.GetDebit(filter);
2332  const bool outgoing = debit > 0;
2333  for (const CTxOut& out : wtx.tx->vout) {
2334  if (outgoing && IsChange(out)) {
2335  debit -= out.nValue;
2336  } else if (IsMine(out) & filter && depth >= minDepth) {
2337  balance += out.nValue;
2338  }
2339  }
2340 
2341  // For outgoing txs, subtract amount debited.
2342  if (outgoing) {
2343  balance -= debit;
2344  }
2345  }
2346 
2347  return balance;
2348 }
2349 
2350 // Sapling
2352 {
2354  return GetAvailableBalance(filter, fUseCache);
2355 };
2356 
2358 {
2360 };
2361 
2362 void CWallet::GetAvailableP2CSCoins(std::vector<COutput>& vCoins) const {
2363  vCoins.clear();
2364  {
2365  LOCK(cs_wallet);
2366  for (const auto& it : mapWallet) {
2367  const uint256& wtxid = it.first;
2368  const CWalletTx* pcoin = &it.second;
2369 
2370  bool fConflicted;
2371  int nDepth = pcoin->GetDepthAndMempool(fConflicted);
2372 
2373  if (fConflicted || nDepth < 0)
2374  continue;
2375 
2376  bool fSafe = pcoin->IsTrusted();
2377 
2378  if (pcoin->tx->HasP2CSOutputs()) {
2379  for (int i = 0; i < (int) pcoin->tx->vout.size(); i++) {
2380  const auto &utxo = pcoin->tx->vout[i];
2381 
2382  if (IsSpent(wtxid, i))
2383  continue;
2384 
2385  if (utxo.scriptPubKey.IsPayToColdStaking()) {
2386  isminetype mine = IsMine(utxo);
2387  bool isMineSpendable = mine & ISMINE_SPENDABLE_DELEGATED;
2388  if (mine & ISMINE_COLD || isMineSpendable)
2389  // Depth and solvability members are not used, no need waste resources and set them for now.
2390  vCoins.emplace_back(pcoin, i, 0, isMineSpendable, true, fSafe);
2391  }
2392  }
2393  }
2394  }
2395  }
2396 
2397 }
2398 
2402 static bool CheckTXAvailabilityInternal(const CWalletTx* pcoin, bool fOnlySafe, int& nDepth, bool& safeTx)
2403 {
2404  safeTx = pcoin->IsTrusted();
2405  if (fOnlySafe && !safeTx) return false;
2406  if (pcoin->GetBlocksToMaturity() > 0) return false;
2407 
2408  nDepth = pcoin->GetDepthInMainChain();
2409 
2410  // We should not consider coins which aren't at least in our mempool
2411  // It's possible for these to be conflicted via ancestors which we may never be able to detect
2412  if (nDepth == 0 && !pcoin->InMempool()) return false;
2413 
2414  return true;
2415 }
2416 
2417 // cs_main lock required
2418 static bool CheckTXAvailability(const CWalletTx* pcoin, bool fOnlySafe, int& nDepth, bool& safeTx)
2419 {
2421  if (!CheckFinalTx(pcoin->tx)) return false;
2422  return CheckTXAvailabilityInternal(pcoin, fOnlySafe, nDepth, safeTx);
2423 }
2424 
2425 // cs_main lock NOT required
2426 static bool CheckTXAvailability(const CWalletTx* pcoin,
2427  bool fOnlySafe,
2428  int& nDepth,
2429  bool& safeTx,
2430  int nBlockHeight)
2431 {
2432  // Mimic CheckFinalTx without cs_main lock
2433  if (!IsFinalTx(pcoin->tx, nBlockHeight + 1, GetAdjustedTime())) return false;
2434  return CheckTXAvailabilityInternal(pcoin, fOnlySafe, nDepth, safeTx);
2435 }
2436 
2438  CKey& keyRet,
2439  const COutPoint& collateralOut,
2440  bool fValidateCollateral,
2441  std::string& strError)
2442 {
2443  // wait for reindex and/or import to finish
2444  if (fImporting || fReindex) return false;
2445 
2446  // Find specific vin
2447  const CWalletTx* wtx = GetWalletTx(collateralOut.hash);
2448  if (!wtx) {
2449  strError = "collateral tx not found in the wallet";
2450  return error("%s: %s", __func__, strError);
2451  }
2452 
2453  // Verify index limits
2454  if (collateralOut.n < 0 || collateralOut.n >= (uint32_t) wtx->tx->vout.size()) {
2455  strError = "Invalid masternode output index";
2456  return error("%s: output index %d not found in %s", __func__, collateralOut.n, collateralOut.hash.GetHex());
2457  }
2458 
2459  CTxOut txOut = wtx->tx->vout[collateralOut.n];
2460 
2461  // Masternode collateral value
2462  const auto& consensus = Params().GetConsensus();
2463  if (txOut.nValue != consensus.nMNCollateralAmt) {
2464  strError = strprintf("Invalid collateral tx value, must be %s PIV", FormatMoney(Params().GetConsensus().nMNCollateralAmt));
2465  return error("%s: tx %s, index %d not a masternode collateral", __func__, collateralOut.hash.GetHex(), collateralOut.n);
2466  }
2467 
2468  if (fValidateCollateral) {
2469  int nDepth = 0;
2470  {
2471  LOCK(cs_wallet);
2472  // Check availability
2473  bool safeTx = false;
2474  if (!CheckTXAvailability(wtx, true, nDepth, safeTx, m_last_block_processed_height)) {
2475  strError = "Not available collateral transaction";
2476  return error("%s: tx %s not available", __func__, collateralOut.hash.GetHex());
2477  }
2478 
2479  // Skip spent coins
2480  if (IsSpent(collateralOut.hash, collateralOut.n)) {
2481  strError = "Error: collateral already spent";
2482  return error("%s: tx %s already spent", __func__, collateralOut.hash.GetHex());
2483  }
2484  }
2485 
2486  // Depth must be at least MASTERNODE_MIN_CONFIRMATIONS
2487  if (nDepth < consensus.MasternodeCollateralMinConf()) {
2488  strError = strprintf("Collateral tx must have at least %d confirmations, has %d",
2489  consensus.MasternodeCollateralMinConf(), nDepth);
2490  return error("%s: %s", __func__, strError);
2491  }
2492  }
2493 
2494  CTxDestination destCollateral;
2495  ExtractDestination(txOut.scriptPubKey, destCollateral, false);
2496  const CKeyID* keyID = boost::get<CKeyID>(&destCollateral);
2497  if (!keyID) {
2498  LogPrintf("%s: Address does not refer to a key\n", __func__);
2499  return false;
2500  }
2501 
2502  if (!GetKey(*keyID, keyRet)) {
2503  LogPrintf("%s: Private key for address is not known\n", __func__);
2504  return false;
2505  }
2506 
2507  pubKeyRet = keyRet.GetPubKey();
2508  return true;
2509 }
2510 
2512  const CTxOut& output,
2513  const unsigned int outIndex,
2514  const uint256& wtxid,
2515  const CCoinControl* coinControl,
2516  const bool fCoinsSelected,
2517  const bool fIncludeColdStaking,
2518  const bool fIncludeDelegated,
2519  const bool fIncludeLocked) const
2520 {
2522 
2523  // Check if the utxo was spent.
2524  if (IsSpent(wtxid, outIndex)) return res;
2525 
2526  isminetype mine = IsMine(output);
2527 
2528  // Check If not mine
2529  if (mine == ISMINE_NO) return res;
2530 
2531  // Skip locked utxo
2532  if (!fIncludeLocked && IsLockedCoin(wtxid, outIndex)) return res;
2533 
2534  // Check if we should include zero value utxo
2535  if (output.nValue <= 0) return res;
2536  if (fCoinsSelected && coinControl && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(wtxid, outIndex)))
2537  return res;
2538 
2539  // --Skip P2CS outputs
2540  // skip cold coins
2541  if (mine == ISMINE_COLD && (!fIncludeColdStaking || !HasDelegator(output))) return res;
2542  // skip delegated coins
2543  if (mine == ISMINE_SPENDABLE_DELEGATED && !fIncludeDelegated) return res;
2544 
2545  res.solvable = IsSolvable(*this, output.scriptPubKey, mine == ISMINE_COLD);
2546 
2547  res.spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
2548  (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && res.solvable)) ||
2549  ((mine & ((fIncludeColdStaking ? ISMINE_COLD : ISMINE_NO) |
2550  (fIncludeDelegated ? ISMINE_SPENDABLE_DELEGATED : ISMINE_NO) )) != ISMINE_NO);
2551  res.available = true;
2552  return res;
2553 }
2554 
2555 bool CWallet::AvailableCoins(std::vector<COutput>* pCoins, // --> populates when != nullptr
2556  const CCoinControl* coinControl, // Default: nullptr
2557  AvailableCoinsFilter coinsFilter) const
2558 {
2559  if (pCoins) pCoins->clear();
2560  const bool fCoinsSelected = (coinControl != nullptr) && coinControl->HasSelected();
2561  // include delegated coins when coinControl is active
2562  if (!coinsFilter.fIncludeDelegated && fCoinsSelected)
2563  coinsFilter.fIncludeDelegated = true;
2564 
2565  {
2566  LOCK(cs_wallet);
2567  CAmount nTotal = 0;
2568  for (const auto& entry : mapWallet) {
2569  const uint256& wtxid = entry.first;
2570  const CWalletTx* pcoin = &entry.second;
2571 
2572  // Check if the tx is selectable
2573  int nDepth = 0;
2574  bool safeTx = false;
2575  if (!CheckTXAvailability(pcoin, coinsFilter.fOnlySafe, nDepth, safeTx, m_last_block_processed_height))
2576  continue;
2577 
2578  // Check min depth filtering requirements
2579  if (nDepth < coinsFilter.minDepth) continue;
2580 
2581  for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2582  const auto& output = pcoin->tx->vout[i];
2583 
2584  // Filter by value if needed
2585  if (coinsFilter.nMaxOutValue > 0 && output.nValue > coinsFilter.nMaxOutValue) {
2586  continue;
2587  }
2588  if (coinsFilter.nMinOutValue > 0 && output.nValue < coinsFilter.nMinOutValue) {
2589  continue;
2590  }
2591 
2592  // Filter by specific destinations if needed
2593  if (coinsFilter.onlyFilteredDest && !coinsFilter.onlyFilteredDest->empty()) {
2594  CTxDestination address;
2595  if (!ExtractDestination(output.scriptPubKey, address) || !coinsFilter.onlyFilteredDest->count(address)) {
2596  continue;
2597  }
2598  }
2599 
2600  // Now check for chain availability
2601  auto res = CheckOutputAvailability(
2602  output,
2603  i,
2604  wtxid,
2605  coinControl,
2606  fCoinsSelected,
2607  coinsFilter.fIncludeColdStaking,
2608  coinsFilter.fIncludeDelegated,
2609  coinsFilter.fIncludeLocked);
2610 
2611  if (!res.available) continue;
2612  if (coinsFilter.fOnlySpendable && !res.spendable) continue;
2613 
2614  // found valid coin
2615  if (!pCoins) return true;
2616  pCoins->emplace_back(pcoin, (int) i, nDepth, res.spendable, res.solvable, safeTx);
2617 
2618  // Checks the sum amount of all UTXO's.
2619  if (coinsFilter.nMinimumSumAmount != 0) {
2620  nTotal += output.nValue;
2621 
2622  if (nTotal >= coinsFilter.nMinimumSumAmount) {
2623  return true;
2624  }
2625  }
2626 
2627  // Checks the maximum number of UTXO's.
2628  if (coinsFilter.nMaximumCount > 0 && pCoins->size() >= coinsFilter.nMaximumCount) {
2629  return true;
2630  }
2631  }
2632  }
2633  return (pCoins && !pCoins->empty());
2634  }
2635 }
2636 
2637 std::map<CTxDestination , std::vector<COutput> > CWallet::AvailableCoinsByAddress(bool fOnlySafe, CAmount maxCoinValue, bool fIncludeColdStaking)
2638 {
2639  CWallet::AvailableCoinsFilter coinFilter;
2640  coinFilter.fIncludeColdStaking = true;
2641  coinFilter.fOnlySafe = fOnlySafe;
2642  coinFilter.fIncludeColdStaking = fIncludeColdStaking;
2643  coinFilter.nMaxOutValue = maxCoinValue;
2644  std::vector<COutput> vCoins;
2645  AvailableCoins(&vCoins, nullptr, coinFilter);
2646 
2647  std::map<CTxDestination, std::vector<COutput> > mapCoins;
2648  for (const COutput& out : vCoins) {
2649  CTxDestination address;
2650  bool fColdStakeAddr = false;
2651  if (!ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address, fColdStakeAddr)) {
2652  bool isP2CS = out.tx->tx->vout[out.i].scriptPubKey.IsPayToColdStaking();
2653  if (isP2CS && !fIncludeColdStaking) {
2654  // It must never happen as the coin filtering process shouldn't had added the P2CS in the first place
2655  assert(false);
2656  }
2657  // if this is a P2CS we don't have the owner key - check if we have the staking key
2658  fColdStakeAddr = true;
2659  if (!isP2CS || !ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address, fColdStakeAddr) )
2660  continue;
2661  }
2662 
2663  mapCoins[address].emplace_back(out);
2664  }
2665 
2666  return mapCoins;
2667 }
2668 
2669 static void ApproximateBestSubset(const std::vector<std::pair<CAmount, std::pair<const CWalletTx*,unsigned int> > >& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2670  std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2671 {
2672  std::vector<char> vfIncluded;
2673 
2674  vfBest.assign(vValue.size(), true);
2675  nBest = nTotalLower;
2676 
2677  FastRandomContext insecure_rand;
2678 
2679  for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) {
2680  vfIncluded.assign(vValue.size(), false);
2681  CAmount nTotal = 0;
2682  bool fReachedTarget = false;
2683  for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) {
2684  for (unsigned int i = 0; i < vValue.size(); i++) {
2685  //The solver here uses a randomized algorithm,
2686  //the randomness serves no real security purpose but is just
2687  //needed to prevent degenerate behavior and it is important
2688  //that the rng is fast. We do not use a constant random sequence,
2689  //because there may be some privacy improvement by making
2690  //the selection random.
2691  if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i]) {
2692  nTotal += vValue[i].first;
2693  vfIncluded[i] = true;
2694  if (nTotal >= nTargetValue) {
2695  fReachedTarget = true;
2696  if (nTotal < nBest) {
2697  nBest = nTotal;
2698  vfBest = vfIncluded;
2699  }
2700  nTotal -= vValue[i].first;
2701  vfIncluded[i] = false;
2702  }
2703  }
2704  }
2705  }
2706  }
2707 }
2708 
2709 bool CWallet::StakeableCoins(std::vector<CStakeableOutput>* pCoins)
2710 {
2711  const bool fIncludeColdStaking = !sporkManager.IsSporkActive(SPORK_19_COLDSTAKING_MAINTENANCE) &&
2712  gArgs.GetBoolArg("-coldstaking", DEFAULT_COLDSTAKING);
2713 
2714  if (pCoins) pCoins->clear();
2715 
2717  for (const auto& it : mapWallet) {
2718  const uint256& wtxid = it.first;
2719  const CWalletTx* pcoin = &(it).second;
2720 
2721  // Check if the tx is selectable
2722  int nDepth = 0;
2723  bool safeTx = false;
2724  if (!CheckTXAvailability(pcoin, true, nDepth, safeTx))
2725  continue;
2726 
2727  // Check min depth requirement for stake inputs
2728  if (nDepth < Params().GetConsensus().nStakeMinDepth) continue;
2729 
2730  const CBlockIndex* pindex = nullptr;
2731  for (unsigned int index = 0; index < pcoin->tx->vout.size(); index++) {
2732 
2733  auto res = CheckOutputAvailability(
2734  pcoin->tx->vout[index],
2735  index,
2736  wtxid,
2737  nullptr, // coin control
2738  false, // fIncludeDelegated
2739  fIncludeColdStaking,
2740  false,
2741  false); // fIncludeLocked
2742 
2743  if (!res.available || !res.spendable) continue;
2744 
2745  // found valid coin
2746  if (!pCoins) return true;
2747  if (!pindex) pindex = mapBlockIndex.at(pcoin->m_confirm.hashBlock);
2748  pCoins->emplace_back(pcoin, (int) index, nDepth, pindex);
2749  }
2750  }
2751  return (pCoins && !pCoins->empty());
2752 }
2753 
2754 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const
2755 {
2756  setCoinsRet.clear();
2757  nValueRet = 0;
2758 
2759  // List of values less than target
2760  std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > coinLowestLarger;
2761  coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2762  coinLowestLarger.second.first = nullptr;
2763  std::vector<std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > > vValue;
2764  CAmount nTotalLower = 0;
2765 
2766  Shuffle(vCoins.begin(), vCoins.end(), FastRandomContext());
2767 
2768  for (const COutput& output : vCoins) {
2769  if (!output.fSpendable)
2770  continue;
2771 
2772  const CWalletTx* pcoin = output.tx;
2773 
2774  if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs)) {
2775  continue;
2776  }
2777 
2778  if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors)) {
2779  continue;
2780  }
2781 
2782  int i = output.i;
2783  CAmount n = pcoin->tx->vout[i].nValue;
2784 
2785  std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > coin = std::make_pair(n, std::make_pair(pcoin, i));
2786 
2787  if (n == nTargetValue) {
2788  setCoinsRet.insert(coin.second);
2789  nValueRet += coin.first;
2790  return true;
2791  } else if (n < nTargetValue + MIN_CHANGE) {
2792  vValue.push_back(coin);
2793  nTotalLower += n;
2794  } else if (n < coinLowestLarger.first) {
2795  coinLowestLarger = coin;
2796  }
2797  }
2798 
2799  if (nTotalLower == nTargetValue) {
2800  for (unsigned int i = 0; i < vValue.size(); ++i) {
2801  setCoinsRet.insert(vValue[i].second);
2802  nValueRet += vValue[i].first;
2803  }
2804  return true;
2805  }
2806 
2807  if (nTotalLower < nTargetValue) {
2808  if (coinLowestLarger.second.first == nullptr)
2809  return false;
2810  setCoinsRet.insert(coinLowestLarger.second);
2811  nValueRet += coinLowestLarger.first;
2812  return true;
2813  }
2814 
2815  // Solve subset sum by stochastic approximation
2816  std::sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
2817  std::vector<char> vfBest;
2818  CAmount nBest;
2819 
2820  ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2821  if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2822  ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2823 
2824  // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2825  // or the next bigger coin is closer), return the bigger coin
2826  if (coinLowestLarger.second.first &&
2827  ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest)) {
2828  setCoinsRet.insert(coinLowestLarger.second);
2829  nValueRet += coinLowestLarger.first;
2830  } else {
2831  std::string s = "CWallet::SelectCoinsMinConf best subset: ";
2832  for (unsigned int i = 0; i < vValue.size(); i++) {
2833  if (vfBest[i]) {
2834  setCoinsRet.insert(vValue[i].second);
2835  nValueRet += vValue[i].first;
2836  s += FormatMoney(vValue[i].first) + " ";
2837  }
2838  }
2839  LogPrintf("%s - total %s\n", s, FormatMoney(nBest));
2840  }
2841 
2842  return true;
2843 }
2844 
2845 bool CWallet::SelectCoinsToSpend(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2846 {
2847  // Note: this function should never be used for "always free" tx types like dstx
2848  std::vector<COutput> vCoins(vAvailableCoins);
2849 
2850  // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2851  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs) {
2852  for (const COutput& out : vCoins) {
2853  if (!out.fSpendable)
2854  continue;
2855 
2856  nValueRet += out.tx->tx->vout[out.i].nValue;
2857  setCoinsRet.emplace(out.tx, out.i);
2858  }
2859  return (nValueRet >= nTargetValue);
2860  }
2861 
2862  // calculate value from preset inputs and store them
2863  std::set<std::pair<const CWalletTx*, uint32_t> > setPresetCoins;
2864  CAmount nValueFromPresetInputs = 0;
2865 
2866  std::vector<OutPointWrapper> vPresetInputs;
2867  if (coinControl)
2868  coinControl->ListSelected(vPresetInputs);
2869  for (const auto& outpoint : vPresetInputs) {
2870  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.outPoint.hash);
2871  if (it != mapWallet.end()) {
2872  const CWalletTx* pcoin = &it->second;
2873  // Clearly invalid input, fail
2874  if (pcoin->tx->vout.size() <= outpoint.outPoint.n)
2875  return false;
2876  nValueFromPresetInputs += pcoin->tx->vout[outpoint.outPoint.n].nValue;
2877  setPresetCoins.emplace(pcoin, outpoint.outPoint.n);
2878  } else
2879  return false; // TODO: Allow non-wallet inputs
2880  }
2881 
2882  // remove preset inputs from vCoins
2883  for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();) {
2884  if (setPresetCoins.count(std::make_pair(it->tx, it->i)))
2885  it = vCoins.erase(it);
2886  else
2887  ++it;
2888  }
2889 
2890  size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2891 
2892  bool res = nTargetValue <= nValueFromPresetInputs ||
2893  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2894  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2895  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2896  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2897  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2898  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet));
2899 
2900  // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2901  setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2902 
2903  // add preset inputs to the total value selected
2904  nValueRet += nValueFromPresetInputs;
2905 
2906  return res;
2907 }
2908 
2909 std::map<std::pair<CTxDestination, Optional<CTxDestination>>, std::vector<COutput>> CWallet::ListCoins() const
2910 {
2911  std::map<std::pair<CTxDestination, Optional<CTxDestination>>, std::vector<COutput>> result;
2912 
2914  filter.fIncludeLocked = true;
2915  filter.fOnlySpendable = true;
2916  std::vector<COutput> availableCoins;
2917  AvailableCoins(&availableCoins, nullptr, filter);
2918 
2919  for (const COutput& coin : availableCoins) {
2920  const CScript& scriptPubKey = coin.tx->tx->vout[coin.i].scriptPubKey;
2921  txnouttype type; std::vector<CTxDestination> addresses; int nRequired;
2922  if (ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
2923  if (addresses.size() == 1) {
2924  // P2PK, P2PKH scripts
2925  const auto& addrpair = std::make_pair(addresses[0], nullopt);
2926  result[addrpair].emplace_back(std::move(coin));
2927  } else if (type == TX_COLDSTAKE) {
2928  // P2CS scripts
2929  assert(addresses.size() == 2);
2930  const auto& addrpair = std::make_pair(addresses[1], Optional<CTxDestination>(addresses[0]));
2931  result[addrpair].emplace_back(std::move(coin));
2932  }
2933  }
2934  }
2935 
2936  return result;
2937 }
2938 
2939 std::map<libzcash::SaplingPaymentAddress, std::vector<SaplingNoteEntry>> CWallet::ListNotes() const
2940 {
2941  return m_sspk_man->ListNotes();
2942 }
2943 
2945 {
2946  CScript scriptChange;
2947  scriptChange << OP_RETURN << ToByteVector(hash);
2948 
2949  CAmount nFeeRet = 0;
2950  std::string strFail = "";
2951  std::vector<CRecipient> vecSend;
2952  vecSend.emplace_back(scriptChange, fee, false);
2953 
2954  CCoinControl* coinControl = nullptr;
2955  int nChangePosInOut = -1;
2956  bool success = CreateTransaction(vecSend, tx, keyChange, nFeeRet, nChangePosInOut, strFail, coinControl, true, (CAmount)0);
2957  if (!success) {
2958  LogPrintf("%s: Error - %s\n", __func__, strFail);
2959  return false;
2960  }
2961 
2962  return true;
2963 }
2964 
2965 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, const CTxDestination& destChange)
2966 {
2967  std::vector<CRecipient> vecSend;
2968 
2969  // Turn the txout set into a CRecipient vector.
2970  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
2971  const CTxOut& txOut = tx.vout[idx];
2972  vecSend.emplace_back(txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1);
2973  }
2974 
2975  CCoinControl coinControl;
2976  coinControl.destChange = destChange;
2977  coinControl.fAllowOtherInputs = true;
2978  coinControl.fAllowWatchOnly = includeWatching;
2979  coinControl.fOverrideFeeRate = overrideEstimatedFeeRate;
2980  coinControl.nFeeRate = specificFeeRate;
2981 
2982  const int nExtraSize = tx.isSaplingVersion() ?
2984 
2985  for (const CTxIn& txin : tx.vin) {
2986  coinControl.Select(txin.prevout);
2987  }
2988 
2989  // Acquire the locks to prevent races to the new locked unspents between the
2990  // CreateTransaction call and LockCoin calls (when lockUnspents is true).
2992 
2993  CReserveKey reservekey(this);
2994  CTransactionRef wtx;
2995  if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false, 0, false, nullptr, nExtraSize)) {
2996  return false;
2997  }
2998 
2999  if (nChangePosInOut != -1) {
3000  tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx->vout[nChangePosInOut]);
3001  // We don't have the normal Create/Commit cycle, and don't want to risk
3002  // reusing change, so just remove the key from the keypool here.
3003  reservekey.KeepKey();
3004  }
3005 
3006  // Copy output sizes from new transaction; they may have had the fee
3007  // subtracted from them.
3008  for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
3009  tx.vout[idx].nValue = wtx->vout[idx].nValue;
3010  }
3011 
3012  // Add new txins while keeping original txin scriptSig/order.
3013  for (const CTxIn& txin : wtx->vin) {
3014  if (!coinControl.IsSelected(txin.prevout)) {
3015  tx.vin.emplace_back(txin);
3016  if (lockUnspents) LockCoin(txin.prevout);
3017  }
3018  }
3019 
3020  return true;
3021 }
3022 
3023 std::vector<COutput> CWallet::GetOutputsFromCoinControl(const CCoinControl* coinControl)
3024 {
3025  assert(coinControl);
3026  LOCK(cs_wallet);
3027  std::vector<COutput> vCoinsRet;
3028  std::vector<OutPointWrapper> vPresetInputs;
3029  coinControl->ListSelected(vPresetInputs);
3030  for (const auto& out : vPresetInputs) {
3031  auto it = mapWallet.find(out.outPoint.hash);
3032  if (it != mapWallet.end()) {
3033  assert(it->second.tx->vout.size() > out.outPoint.n);
3034  vCoinsRet.emplace_back(COutput(&(it->second), out.outPoint.n, 0, true, true, true));
3035  }
3036  }
3037  return vCoinsRet;
3038 }
3039 
3040 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend,
3041  CTransactionRef& txRet,
3042  CReserveKey& reservekey,
3043  CAmount& nFeeRet,
3044  int& nChangePosInOut,
3045  std::string& strFailReason,
3046  const CCoinControl* coinControl,
3047  bool sign,
3048  CAmount nFeePay,
3049  bool fIncludeDelegated,
3050  bool* fStakeDelegationVoided,
3051  int nExtraSize,
3052  int nMinDepth)
3053 {
3054  CAmount nValue = 0;
3055  int nChangePosRequest = nChangePosInOut;
3056  unsigned int nSubtractFeeFromAmount = 0;
3057  for (const CRecipient& rec : vecSend) {
3058  if (nValue < 0 || rec.nAmount < 0) {
3059  strFailReason = _("Transaction amounts must be positive");
3060  return false;
3061  }
3062  nValue += rec.nAmount;
3063  if (rec.fSubtractFeeFromAmount)
3064  nSubtractFeeFromAmount++;
3065  }
3066  if (vecSend.empty()) {
3067  strFailReason = _("Transaction must have at least one recipient");
3068  return false;
3069  }
3070 
3071  CMutableTransaction txNew;
3072  CScript scriptChange;
3073 
3074  CWallet::AvailableCoinsFilter coinFilter;
3075  coinFilter.fOnlySpendable = true;
3076  coinFilter.fIncludeDelegated = fIncludeDelegated;
3077  coinFilter.minDepth = nMinDepth;
3078 
3079  {
3080  std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
3082  {
3083  std::vector<COutput> vAvailableCoins;
3084  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs) {
3085  // Select only the outputs that the caller pre-selected.
3086  vAvailableCoins = GetOutputsFromCoinControl(coinControl);
3087  } else {
3088  // Regular selection
3089  AvailableCoins(&vAvailableCoins, coinControl, coinFilter);
3090  }
3091 
3092  nFeeRet = 0;
3093  if (nFeePay > 0) nFeeRet = nFeePay;
3094  while (true) {
3095  nChangePosInOut = nChangePosRequest;
3096  txNew.vin.clear();
3097  txNew.vout.clear();
3098  bool fFirst = true;
3099 
3100  CAmount nValueToSelect = nValue;
3101  if (nSubtractFeeFromAmount == 0)
3102  nValueToSelect += nFeeRet;
3103 
3104  // Fill outputs
3105  for (const CRecipient& rec : vecSend) {
3106  CTxOut txout(rec.nAmount, rec.scriptPubKey);
3107  if (rec.fSubtractFeeFromAmount) {
3108  assert(nSubtractFeeFromAmount != 0);
3109  txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
3110 
3111  if (fFirst) {
3112  // first receiver pays the remainder not divisible by output count
3113  fFirst = false;
3114  txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
3115  }
3116  }
3117  if (IsDust(txout, dustRelayFee)) {
3118  strFailReason = _("Transaction amount too small");
3119  return false;
3120  }
3121  txNew.vout.emplace_back(txout);
3122  }
3123 
3124  // Choose coins to use
3125  CAmount nValueIn = 0;
3126  setCoins.clear();
3127 
3128  if (!SelectCoinsToSpend(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl)) {
3129  strFailReason = _("Insufficient funds.");
3130  return false;
3131  }
3132 
3133  // Change
3134  CAmount nChange = nValueIn - nValueToSelect;
3135  if (nChange > 0) {
3136  // Fill a vout to ourself
3137  // TODO: pass in scriptChange instead of reservekey so
3138  // change transaction isn't always pay-to-pivx-address
3139  bool combineChange = false;
3140 
3141  // coin control: send change to custom address
3142  if (coinControl && IsValidDestination(coinControl->destChange)) {
3143  scriptChange = GetScriptForDestination(coinControl->destChange);
3144 
3145  std::vector<CTxOut>::iterator it = txNew.vout.begin();
3146  while (it != txNew.vout.end()) {
3147  if (scriptChange == it->scriptPubKey) {
3148  it->nValue += nChange;
3149  nChange = 0;
3150  reservekey.ReturnKey();
3151  combineChange = true;
3152  break;
3153  }
3154  ++it;
3155  }
3156  }
3157 
3158  // no coin control: send change to newly generated address
3159  else {
3160  // Note: We use a new key here to keep it from being obvious which side is the change.
3161  // The drawback is that by not reusing a previous key, the change may be lost if a
3162  // backup is restored, if the backup doesn't have the new private key for the change.
3163  // If we reused the old key, it would be possible to add code to look for and
3164  // rediscover unknown transactions that were written with keys of ours to recover
3165  // post-backup change.
3166 
3167  // Reserve a new key pair from key pool. If it fails, provide a dummy
3168  CPubKey vchPubKey;
3169  if (!reservekey.GetReservedKey(vchPubKey, true)) {
3170  strFailReason = _("Can't generate a change-address key. Please call keypoolrefill first.");
3171  scriptChange = CScript();
3172  } else {
3173  scriptChange = GetScriptForDestination(vchPubKey.GetID());
3174  }
3175  }
3176 
3177  if (!combineChange) {
3178  CTxOut newTxOut(nChange, scriptChange);
3179 
3180  // Never create dust outputs; if we would, just
3181  // add the dust to the fee.
3182  if (IsDust(newTxOut, dustRelayFee)) {
3183  nFeeRet += nChange;
3184  nChange = 0;
3185  reservekey.ReturnKey();
3186  nChangePosInOut = -1;
3187  } else {
3188  if (nChangePosInOut == -1) {
3189  // Insert change txn at random position:
3190  nChangePosInOut = GetRandInt(txNew.vout.size()+1);
3191  } else if (nChangePosInOut < 0 || (unsigned int) nChangePosInOut > txNew.vout.size()) {
3192  strFailReason = _("Change index out of range");
3193  return false;
3194  }
3195  std::vector<CTxOut>::iterator position = txNew.vout.begin() + nChangePosInOut;
3196  txNew.vout.insert(position, newTxOut);
3197  }
3198  }
3199  } else {
3200  reservekey.ReturnKey();
3201  nChangePosInOut = -1;
3202  }
3203 
3204  // Fill vin
3205  for (const std::pair<const CWalletTx*, unsigned int>& coin : setCoins) {
3206  if(fStakeDelegationVoided && coin.first->tx->vout[coin.second].scriptPubKey.IsPayToColdStaking()) {
3207  *fStakeDelegationVoided = true;
3208  }
3209  txNew.vin.emplace_back(coin.first->GetHash(), coin.second);
3210  }
3211 
3212  // Fill in dummy signatures for fee calculation.
3213  int nIn = 0;
3214  for (const auto & coin : setCoins) {
3215  const CScript& scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey;
3216  SignatureData sigdata;
3217  if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata, txNew.GetRequiredSigVersion(), false)) {
3218  strFailReason = _("Signing transaction failed");
3219  return false;
3220  } else {
3221  UpdateTransaction(txNew, nIn, sigdata);
3222  }
3223  nIn++;
3224  }
3225 
3226  // account for additional payloads in fee calculation
3227  const unsigned int nBytes = ::GetSerializeSize(txNew, PROTOCOL_VERSION) + nExtraSize;
3228  CAmount nFeeNeeded = std::max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool));
3229 
3230  // Remove scriptSigs to eliminate the fee calculation dummy signatures
3231  for (CTxIn& vin : txNew.vin) {
3232  vin.scriptSig = CScript();
3233  }
3234 
3235  if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
3236  nFeeNeeded = coinControl->nMinimumTotalFee;
3237  }
3238  if (coinControl && coinControl->fOverrideFeeRate)
3239  nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
3240 
3241  // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
3242  // because we must be at the maximum allowed fee.
3243  if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) {
3244  strFailReason = _("Transaction too large for fee policy");
3245  return false;
3246  }
3247 
3248  if (nFeeRet >= nFeeNeeded) // Done, enough fee included
3249  break;
3250 
3251  // Include more fee and try again.
3252  nFeeRet = nFeeNeeded;
3253  continue;
3254  }
3255 
3256  // Give up if change keypool ran out and we failed to find a solution without change:
3257  if (scriptChange.empty() && nChangePosInOut != -1) {
3258  return false;
3259  }
3260  }
3261 
3262  if (sign) {
3263  CTransaction txNewConst(txNew);
3264  int nIn = 0;
3265  for (const auto& coin : setCoins) {
3266  const CScript& scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey;
3267  SignatureData sigdata;
3268  bool haveKey = coin.first->GetStakeDelegationCredit() > 0;
3269 
3270  if (!ProduceSignature(
3271  TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->tx->vout[coin.second].nValue, SIGHASH_ALL),
3272  scriptPubKey,
3273  sigdata,
3274  txNewConst.GetRequiredSigVersion(),
3275  !haveKey // fColdStake
3276  )) {
3277  strFailReason = _("Signing transaction failed");
3278  return false;
3279  } else {
3280  UpdateTransaction(txNew, nIn, sigdata);
3281  }
3282  nIn++;
3283  }
3284  }
3285 
3286  // Limit size
3287  if (::GetSerializeSize(txNew, PROTOCOL_VERSION) >= MAX_STANDARD_TX_SIZE) {
3288  strFailReason = _("Transaction too large");
3289  return false;
3290  }
3291 
3292  // Embed the constructed transaction data in wtxNew.
3293  txRet = MakeTransactionRef(std::move(txNew));
3294  }
3295 
3296  // Lastly, ensure this tx will pass the mempool's chain limits
3297  CTxMemPoolEntry entry(txRet, 0, 0, 0, false, 0);
3298  CTxMemPool::setEntries setAncestors;
3299  size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
3300  size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
3301  size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
3302  size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
3303  std::string errString;
3304  if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
3305  strFailReason = _("Transaction has too long of a mempool chain");
3306  return false;
3307  }
3308 
3309  return true;
3310 }
3311 
3312 bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CTransactionRef& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, CAmount nFeePay, bool fIncludeDelegated, bool* fStakeDelegationVoided, int nExtraSize, int nMinDepth)
3313 {
3314  std::vector<CRecipient> vecSend;
3315  vecSend.emplace_back(scriptPubKey, nValue, false);
3316  int nChangePosInOut = -1;
3317  return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, true, nFeePay, fIncludeDelegated, fStakeDelegationVoided, nExtraSize, nMinDepth);
3318 }
3319 
3321 {
3322  return WITH_LOCK(cs_wallet, return m_last_block_processed_height;);
3323 }
3324 
3325 bool CWallet::CreateCoinstakeOuts(const CPivStake& stakeInput, std::vector<CTxOut>& vout, CAmount nTotal) const
3326 {
3327  std::vector<valtype> vSolutions;
3328  txnouttype whichType;
3329  CTxOut stakePrevout;
3330  if (!stakeInput.GetTxOutFrom(stakePrevout)) {
3331  return error("%s: failed to get stake input", __func__);
3332  }
3333  CScript scriptPubKeyKernel = stakePrevout.scriptPubKey;
3334  if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
3335  return error("%s: failed to parse kernel", __func__);
3336 
3337  if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH && whichType != TX_COLDSTAKE)
3338  return error("%s: type=%d (%s) not supported for scriptPubKeyKernel", __func__, whichType, GetTxnOutputType(whichType));
3339 
3340  CKey key;
3341  if (whichType == TX_PUBKEYHASH || whichType == TX_COLDSTAKE) {
3342  // if P2PKH or P2CS check that we have the input private key
3343  if (!GetKey(CKeyID(uint160(vSolutions[0])), key))
3344  return error("%s: Unable to get staking private key", __func__);
3345  }
3346 
3347  vout.emplace_back(0, scriptPubKeyKernel);
3348 
3349  // Calculate if we need to split the output
3350  if (nStakeSplitThreshold > 0) {
3351  int nSplit = static_cast<int>(nTotal / nStakeSplitThreshold);
3352  if (nSplit > 1) {
3353  // if nTotal is twice or more of the threshold; create more outputs
3354  int txSizeMax = MAX_STANDARD_TX_SIZE >> 11; // limit splits to <10% of the max TX size (/2048)
3355  if (nSplit > txSizeMax)
3356  nSplit = txSizeMax;
3357  for (int i = nSplit; i > 1; i--) {
3358  LogPrintf("%s: StakeSplit: nTotal = %d; adding output %d of %d\n", __func__, nTotal, (nSplit-i)+2, nSplit);
3359  vout.emplace_back(0, scriptPubKeyKernel);
3360  }
3361  }
3362  }
3363 
3364  return true;
3365 }
3366 
3368  const CBlockIndex* pindexPrev,
3369  unsigned int nBits,
3370  CMutableTransaction& txNew,
3371  int64_t& nTxNewTime,
3372  std::vector<CStakeableOutput>* availableCoins,
3373  bool stopOnNewBlock) const
3374 {
3375  // shuffle coins
3376  if (availableCoins && Params().IsRegTestNet()) {
3377  Shuffle(availableCoins->begin(), availableCoins->end(), FastRandomContext());
3378  }
3379 
3380  // Mark coin stake transaction
3381  txNew.vin.clear();
3382  txNew.vout.clear();
3383  txNew.vout.emplace_back(0, CScript());
3384 
3385  // update staker status (hash)
3386  pStakerStatus->SetLastTip(pindexPrev);
3387  pStakerStatus->SetLastCoins((int) availableCoins->size());
3388 
3389  // Kernel Search
3390  CAmount nCredit;
3391  CAmount nMasternodePayment;
3392  CScript scriptPubKeyKernel;
3393  bool fKernelFound = false;
3394  int nAttempts = 0;
3395  for (auto it = availableCoins->begin(); it != availableCoins->end();) {
3396  COutPoint outPoint = COutPoint(it->tx->GetHash(), it->i);
3397  CPivStake stakeInput(it->tx->tx->vout[it->i],
3398  outPoint,
3399  it->pindex);
3400 
3401  // New block came in, move on
3402  if (stopOnNewBlock && GetLastBlockHeightLockWallet() != pindexPrev->nHeight) return false;
3403 
3404  // Make sure the wallet is unlocked and shutdown hasn't been requested
3405  if (IsLocked() || ShutdownRequested()) return false;
3406 
3407  // Make sure the stake input hasn't been spent since last check
3408  if (WITH_LOCK(cs_wallet, return IsSpent(outPoint))) {
3409  // remove it from the available coins
3410  it = availableCoins->erase(it);
3411  continue;
3412  }
3413 
3414  nCredit = 0;
3415 
3416  nAttempts++;
3417  fKernelFound = Stake(pindexPrev, &stakeInput, nBits, nTxNewTime);
3418 
3419  // update staker status (time, attempts)
3420  pStakerStatus->SetLastTime(nTxNewTime);
3421  pStakerStatus->SetLastTries(nAttempts);
3422 
3423  if (!fKernelFound) {
3424  it++;
3425  continue;
3426  }
3427 
3428  // Found a kernel
3429  LogPrintf("CreateCoinStake : kernel found\n");
3430  nCredit += stakeInput.GetValue();
3431 
3432  // Add block reward to the credit
3433  nCredit += GetBlockValue(pindexPrev->nHeight + 1);
3434  nMasternodePayment = GetMasternodePayment(pindexPrev->nHeight + 1);
3435 
3436  // Create the output transaction(s)
3437  std::vector<CTxOut> vout;
3438  if (!CreateCoinstakeOuts(stakeInput, vout, nCredit - nMasternodePayment)) {
3439  LogPrintf("%s : failed to create output\n", __func__);
3440  it++;
3441  continue;
3442  }
3443  txNew.vout.insert(txNew.vout.end(), vout.begin(), vout.end());
3444 
3445  // Set output amount
3446  int outputs = (int) txNew.vout.size() - 1;
3447  CAmount nRemaining = nCredit;
3448  if (outputs > 1) {
3449  // Split the stake across the outputs
3450  CAmount nShare = nRemaining / outputs;
3451  for (int i = 1; i < outputs; i++) {
3452  // loop through all but the last one.
3453  txNew.vout[i].nValue = nShare;
3454  nRemaining -= nShare;
3455  }
3456  }
3457  // put the remaining on the last output (which all into the first if only one output)
3458  txNew.vout[outputs].nValue += nRemaining;
3459 
3460  // Set coinstake input
3461  txNew.vin.emplace_back(stakeInput.GetTxIn());
3462 
3463  // Limit size
3464  unsigned int nBytes = ::GetSerializeSize(txNew, PROTOCOL_VERSION);
3465  if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5)
3466  return error("%s : exceeded coinstake size limit", __func__);
3467 
3468  break;
3469  }
3470  LogPrint(BCLog::STAKING, "%s: attempted staking %d times\n", __func__, nAttempts);
3471 
3472  return fKernelFound;
3473 }
3474 
3476 {
3477  // Sign it
3478  int nIn = 0;
3479  for (const CTxIn& txIn : txNew.vin) {
3480  const CWalletTx* wtx = GetWalletTx(txIn.prevout.hash);
3481  if (!wtx || !SignSignature(*this, *(wtx->tx), txNew, nIn++, SIGHASH_ALL, true))
3482  return error("%s : failed to sign coinstake", __func__);
3483  }
3484 
3485  // Successfully signed coinstake
3486  return true;
3487 }
3488 
3490 {
3491  std::string strErrRet = strprintf(_("Failed to accept tx in the memory pool (reason: %s)\n"), FormatStateMessage(state));
3492 
3493  switch (status) {
3495  return _("No error");
3496  case CWallet::CommitStatus::Abandoned:
3497  strErrRet += _("Transaction canceled.");
3498  break;
3499  case CWallet::CommitStatus::NotAccepted:
3500  strErrRet += strprintf(_("WARNING: The transaction has been signed and recorded, so the wallet will try to re-send it. "
3501  "Use 'abandontransaction' to cancel it. (txid: %s)"), hashTx.ToString());
3502  break;
3503  default:
3504  return _("Invalid status error.");
3505  }
3506 
3507  return strErrRet;
3508 }
3509 
3511 {
3512  return CommitTransaction(std::move(tx), &opReservekey, connman);
3513 }
3514 
3519 {
3520  CommitResult res;
3521 
3522  CWalletTx wtxNew(this, std::move(tx));
3523  wtxNew.fTimeReceivedIsTxTime = true;
3524  wtxNew.BindWallet(this);
3525  wtxNew.fFromMe = true;
3526  wtxNew.fStakeDelegationVoided = wtxNew.tx->HasP2CSOutputs();
3527  if (extras) wtxNew.mapValue.insert(extras->begin(), extras->end());
3528 
3529  {
3531  LogPrintf("%s: %s\n", __func__, wtxNew.tx->ToString());
3532  {
3533  // Take key pair from key pool so it won't be used again
3534  if (opReservekey) opReservekey->KeepKey();
3535 
3536  // Add tx to wallet, because if it has change it's also ours,
3537  // otherwise just for transaction history.
3538  AddToWallet(wtxNew);
3539 
3540  // Notify that old coins are spent
3541  if (!wtxNew.tx->HasZerocoinSpendInputs()) {
3542  std::set<uint256> updated_hashes;
3543  for (const CTxIn& txin : wtxNew.tx->vin) {
3544  // notify only once
3545  if (updated_hashes.find(txin.prevout.hash) != updated_hashes.end()) continue;
3546 
3547  CWalletTx& coin = mapWallet.at(txin.prevout.hash);
3548  coin.BindWallet(this);
3550  updated_hashes.insert(txin.prevout.hash);
3551  }
3552  }
3553  }
3554 
3555  res.hashTx = wtxNew.GetHash();
3556 
3557  // Get the inserted-CWalletTx from mapWallet so that the
3558  // fInMempool flag is cached properly
3559  CWalletTx& wtx = mapWallet.at(wtxNew.GetHash());
3560 
3561  // Try ATMP. This must not fail. The transaction has already been signed and recorded.
3562  CValidationState state;
3563  if (!wtx.AcceptToMemoryPool(state)) {
3564  res.state = state;
3565  // Abandon the transaction
3566  if (AbandonTransaction(res.hashTx)) {
3567  res.status = CWallet::CommitStatus::Abandoned;
3568  // Return the change key
3569  if (opReservekey) opReservekey->ReturnKey();
3570  }
3571 
3572  LogPrintf("%s: ERROR: %s\n", __func__, res.ToString());
3573  return res;
3574  }
3575 
3577 
3578  // Broadcast
3579  wtx.RelayWalletTransaction(connman);
3580  }
3581  return res;
3582 }
3583 
3584 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3585 {
3587 
3588  DBErrors nLoadWalletRet = WalletBatch(*database, "cr+").LoadWallet(this);
3589  if (nLoadWalletRet == DB_NEED_REWRITE) {
3590  if (database->Rewrite( "\x04pool")) {
3591  // TODO: Implement spk_man->RewriteDB().
3592  m_spk_man->set_pre_split_keypool.clear();
3593  // Note: can't top-up keypool here, because wallet is locked.
3594  // User will be prompted to unlock wallet the next operation
3595  // the requires a new key.
3596  }
3597  }
3598 
3599  // This wallet is in its first run if all of these are empty
3600  fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapMasterKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3601 
3602  if (nLoadWalletRet != DB_LOAD_OK)
3603  return nLoadWalletRet;
3604 
3605  uiInterface.LoadWallet(this);
3606 
3607  return DB_LOAD_OK;
3608 }
3609 
3610 
3611 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3612 {
3613  DBErrors nZapWalletTxRet = WalletBatch(*database, "cr+").ZapWalletTx(this, vWtx);
3614  if (nZapWalletTxRet == DB_NEED_REWRITE) {
3615  if (database->Rewrite("\x04pool")) {
3616  LOCK(cs_wallet);
3617  m_spk_man->set_pre_split_keypool.clear();
3618  // Note: can't top-up keypool here, because wallet is locked.
3619  // User will be prompted to unlock wallet the next operation
3620  // that requires a new key.
3621  }
3622  }
3623 
3624  if (nZapWalletTxRet != DB_LOAD_OK)
3625  return nZapWalletTxRet;
3626 
3627  return DB_LOAD_OK;
3628 }
3629 
3630 std::string CWallet::ParseIntoAddress(const CWDestination& dest, const std::string& purpose) {
3631  CChainParams::Base58Type addrType;
3632  if (AddressBook::IsColdStakingPurpose(purpose)) {
3633  addrType = CChainParams::STAKING_ADDRESS;
3634  } else if (AddressBook::IsExchangePurpose(purpose)) {
3635  addrType = CChainParams::EXCHANGE_ADDRESS;
3636  } else {
3637  addrType = CChainParams::PUBKEY_ADDRESS;
3638  }
3639  return Standard::EncodeDestination(dest, addrType);
3640 }
3641 
3642 bool CWallet::SetAddressBook(const CWDestination& address, const std::string& strName, const std::string& strPurpose)
3643 {
3644  bool fUpdated = HasAddressBook(address);
3645  {
3646  LOCK(cs_wallet); // mapAddressBook
3647  mapAddressBook[address].name = strName;
3648  if (!strPurpose.empty()) /* update purpose only if requested */
3649  mapAddressBook[address].purpose = strPurpose;
3650  }
3651  NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3652  mapAddressBook.at(address).purpose, (fUpdated ? CT_UPDATED : CT_NEW));
3653  std::string addressStr = ParseIntoAddress(address, mapAddressBook.at(address).purpose);
3654  if (!strPurpose.empty() && !WalletBatch(*database).WritePurpose(addressStr, strPurpose))
3655  return false;
3656  return WalletBatch(*database).WriteName(addressStr, strName);
3657 }
3658 
3660 {
3661  std::string strAddress = Standard::EncodeDestination(address, addrType);
3662  std::string purpose = GetPurposeForAddressBookEntry(address);
3663  {
3664  LOCK(cs_wallet); // mapAddressBook
3665 
3666  // Delete destdata tuples associated with address
3667  for (const std::pair<std::string, std::string> & item : mapAddressBook[address].destdata) {
3668  WalletBatch(*database).EraseDestData(strAddress, item.first);
3669  }
3670  mapAddressBook.erase(address);
3671  }
3672 
3673  NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, purpose, CT_DELETED);
3674 
3675  WalletBatch(*database).ErasePurpose(strAddress);
3676  return WalletBatch(*database).EraseName(strAddress);
3677 }
3678 
3680 {
3681  LOCK(cs_wallet);
3682  auto it = mapAddressBook.find(address);
3683  return it != mapAddressBook.end() ? it->second.purpose : "";
3684 }
3685 
3686 std::string CWallet::GetNameForAddressBookEntry(const CWDestination& address) const
3687 {
3688  LOCK(cs_wallet);
3689  auto it = mapAddressBook.find(address);
3690  return it != mapAddressBook.end() ? it->second.name : "";
3691 }
3692 
3694 {
3695  LOCK(cs_wallet);
3696  auto it = mapAddressBook.find(dest);
3697  return it != mapAddressBook.end() ? Optional<AddressBook::CAddressBookData>(it->second) : nullopt;
3698 }
3699 
3700 void CWallet::LoadAddressBookName(const CWDestination& dest, const std::string& strName)
3701 {
3702  mapAddressBook[dest].name = strName;
3703 }
3704 
3705 void CWallet::LoadAddressBookPurpose(const CWDestination& dest, const std::string& strPurpose)
3706 {
3707  mapAddressBook[dest].purpose = strPurpose;
3708 }
3709 
3710 bool CWallet::HasAddressBook(const CWDestination& address) const
3711 {
3712  return WITH_LOCK(cs_wallet, return mapAddressBook.count(address));
3713 }
3714 
3715 bool CWallet::HasDelegator(const CTxOut& out) const
3716 {
3717  CTxDestination delegator;
3718  if (!ExtractDestination(out.scriptPubKey, delegator, false))
3719  return false;
3720  {
3721  LOCK(cs_wallet); // mapAddressBook
3722  const auto mi = mapAddressBook.find(delegator);
3723  if (mi == mapAddressBook.end())
3724  return false;
3725  return (*mi).second.purpose == AddressBook::AddressBookPurpose::DELEGATOR;
3726  }
3727 }
3728 
3730 {
3731  return m_spk_man->KeypoolCountExternalKeys();
3732 }
3733 
3734 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3735 {
3736  return m_spk_man->TopUp(kpSize);
3737 }
3738 
3739 void CWallet::KeepKey(int64_t nIndex)
3740 {
3741  m_spk_man->KeepDestination(nIndex);
3742 }
3743 
3744 void CWallet::ReturnKey(int64_t nIndex, const bool internal, const bool staking)
3745 {
3746  // Return to key pool
3747  CTxDestination address; // This is not needed for now.
3748  uint8_t changeType = staking ? HDChain::ChangeType::STAKING : (internal ? HDChain::ChangeType::INTERNAL : HDChain::ChangeType::EXTERNAL);
3749  m_spk_man->ReturnDestination(nIndex, changeType, address);
3750 }
3751 
3752 bool CWallet::GetKeyFromPool(CPubKey& result, const uint8_t& type)
3753 {
3754  return m_spk_man->GetKeyFromPool(result, type);
3755 }
3756 
3758 {
3759  return WITH_LOCK(cs_wallet, return std::min(std::numeric_limits<int64_t>::max(), m_spk_man->GetOldestKeyPoolTime()));
3760 }
3761 
3762 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3763 {
3764  std::map<CTxDestination, CAmount> balances;
3765 
3766  {
3767  LOCK(cs_wallet);
3768  for (const auto& walletEntry : mapWallet) {
3769  const CWalletTx* pcoin = &walletEntry.second;
3770 
3771  if (!IsFinalTx(pcoin->tx, m_last_block_processed_height) || !pcoin->IsTrusted())
3772  continue;
3773 
3774  if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3775  continue;
3776 
3777  bool fConflicted;
3778  int nDepth = pcoin->GetDepthAndMempool(fConflicted);
3779  if (fConflicted)
3780  continue;
3781  if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3782  continue;
3783 
3784  for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
3785  CTxDestination addr;
3786  if (!IsMine(pcoin->tx->vout[i]))
3787  continue;
3788  if ( !ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr) &&
3789  !ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr, true) )
3790  continue;
3791 
3792  CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3793 
3794  if (!balances.count(addr))
3795  balances[addr] = 0;
3796  balances[addr] += n;
3797  }
3798  }
3799  }
3800 
3801  return balances;
3802 }
3803 
3804 std::set<std::set<CTxDestination> > CWallet::GetAddressGroupings()
3805 {
3806  AssertLockHeld(cs_wallet); // mapWallet
3807  std::set<std::set<CTxDestination> > groupings;
3808  std::set<CTxDestination> grouping;
3809 
3810  for (const auto& walletEntry : mapWallet) {
3811  const CWalletTx* pcoin = &walletEntry.second;
3812 
3813  if (pcoin->tx->vin.size() > 0) {
3814  bool any_mine = false;
3815  // group all input addresses with each other
3816  for (CTxIn txin : pcoin->tx->vin) {
3817  CTxDestination address;
3818  if (!IsMine(txin)) /* If this input isn't mine, ignore it */
3819  continue;
3820  if (!ExtractDestination(mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
3821  continue;
3822  grouping.insert(address);
3823  any_mine = true;
3824  }
3825 
3826  // group change with input addresses
3827  if (any_mine) {
3828  for (CTxOut txout : pcoin->tx->vout)
3829  if (IsChange(txout)) {
3830  CTxDestination txoutAddr;
3831  if (!ExtractDestination(txout.scriptPubKey, txoutAddr))
3832  continue;
3833  grouping.insert(txoutAddr);
3834  }
3835  }
3836  if (grouping.size() > 0) {
3837  groupings.insert(grouping);
3838  grouping.clear();
3839  }
3840  }
3841 
3842  // group lone addrs by themselves
3843  for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3844  if (IsMine(pcoin->tx->vout[i])) {
3845  CTxDestination address;
3846  if (!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, address))
3847  continue;
3848  grouping.insert(address);
3849  groupings.insert(grouping);
3850  grouping.clear();
3851  }
3852  }
3853 
3854  std::set<std::set<CTxDestination>*> uniqueGroupings; // a set of pointers to groups of addresses
3855  std::map<CTxDestination, std::set<CTxDestination>*> setmap; // map addresses to the unique group containing it
3856  for (std::set<CTxDestination> grouping : groupings) {
3857  // make a set of all the groups hit by this new group
3858  std::set<std::set<CTxDestination>*> hits;
3859  std::map<CTxDestination, std::set<CTxDestination>*>::iterator it;
3860  for (CTxDestination address : grouping)
3861  if ((it = setmap.find(address)) != setmap.end())
3862  hits.insert((*it).second);
3863 
3864  // merge all hit groups into a new single group and delete old groups
3865  std::set<CTxDestination>* merged = new std::set<CTxDestination>(grouping);
3866  for (std::set<CTxDestination>* hit : hits) {
3867  merged->insert(hit->begin(), hit->end());
3868  uniqueGroupings.erase(hit);
3869  delete hit;
3870  }
3871  uniqueGroupings.insert(merged);
3872 
3873  // update setmap
3874  for (CTxDestination element : *merged)
3875  setmap[element] = merged;
3876  }
3877 
3878  std::set<std::set<CTxDestination> > ret;
3879  for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings) {
3880  ret.insert(*uniqueGrouping);
3881  delete uniqueGrouping;
3882  }
3883 
3884  return ret;
3885 }
3886 
3887 std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
3888 {
3889  LOCK(cs_wallet);
3890  std::set<CTxDestination> result;
3891  for (const auto& item : mapAddressBook) {
3892  if (item.second.isShielded()) continue;
3893  const auto& address = boost::get<CTxDestination>(item.first);
3894  const std::string& strName = item.second.name;
3895  if (strName == label)
3896  result.insert(address);
3897  }
3898  return result;
3899 }
3900 
3901 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool _internal)
3902 {
3903 
3904  ScriptPubKeyMan* m_spk_man = pwallet->GetScriptPubKeyMan();
3905  if (!m_spk_man) {
3906  return false;
3907  }
3908 
3909  if (nIndex == -1) {
3910 
3911  // Fill the pool if needed
3912  m_spk_man->TopUp();
3913  internal = _internal;
3914 
3915  // Modify this for Staking addresses support if needed.
3916  uint8_t changeType = internal ? HDChain::ChangeType::INTERNAL : HDChain::ChangeType::EXTERNAL;
3917  CKeyPool keypool;
3918  if (!m_spk_man->GetReservedKey(changeType, nIndex, keypool))
3919  return false;
3920 
3921  if (nIndex != -1)
3922  vchPubKey = keypool.vchPubKey;
3923  else {
3924  return false;
3925  }
3926  }
3927  assert(vchPubKey.IsValid());
3928  pubkey = vchPubKey;
3929  return true;
3930 }
3931 
3933 {
3934  if (nIndex != -1)
3935  pwallet->KeepKey(nIndex);
3936  nIndex = -1;
3937  vchPubKey = CPubKey();
3938 }
3939 
3941 {
3942  if (nIndex != -1)
3943  pwallet->ReturnKey(nIndex, internal);
3944  nIndex = -1;
3945  vchPubKey = CPubKey();
3946 }
3947 
3948 void CWallet::LockCoin(const COutPoint& output)
3949 {
3950  AssertLockHeld(cs_wallet); // setLockedCoins
3951  setLockedCoins.insert(output);
3952 }
3953 
3955 {
3956  AssertLockHeld(cs_wallet); // setLockedNotes
3957  setLockedNotes.insert(op);
3958 }
3959 
3960 void CWallet::UnlockCoin(const COutPoint& output)
3961 {
3962  AssertLockHeld(cs_wallet); // setLockedCoins
3963  setLockedCoins.erase(output);
3964 }
3965 
3967 {
3968  AssertLockHeld(cs_wallet); // setLockedNotes
3969  setLockedNotes.erase(op);
3970 }
3971 
3973 {
3974  AssertLockHeld(cs_wallet); // setLockedCoins
3975  setLockedCoins.clear();
3976 }
3977 
3979 {
3980  AssertLockHeld(cs_wallet); // setLockedNotes
3981  setLockedNotes.clear();
3982 }
3983 
3984 bool CWallet::IsLockedCoin(const uint256& hash, unsigned int n) const
3985 {
3986  AssertLockHeld(cs_wallet); // setLockedCoins
3987  const COutPoint outpt(hash, n);
3988 
3989  return (setLockedCoins.count(outpt) > 0);
3990 }
3991 
3993 {
3994  AssertLockHeld(cs_wallet); // setLockedNotes
3995  return (setLockedNotes.count(op) > 0);
3996 }
3997 
3998 std::set<COutPoint> CWallet::ListLockedCoins()
3999 {
4000  AssertLockHeld(cs_wallet); // setLockedCoins
4001  return setLockedCoins;
4002 }
4003 
4004 std::set<SaplingOutPoint> CWallet::ListLockedNotes()
4005 {
4006  AssertLockHeld(cs_wallet); // setLockedNotes
4007  return setLockedNotes;
4008 }
4009 
4011 {
4012  LOCK(cs_wallet);
4013  if (nStakeSplitThreshold != sst) {
4014  nStakeSplitThreshold = sst;
4015  if (!WalletBatch(*database).WriteStakeSplitThreshold(sst)) {
4016  return false;
4017  }
4018  NotifySSTChanged(sst);
4019  }
4020  return true;
4021 }
4022  // end of Actions
4024 
4025 
4026 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const
4027 {
4028  AssertLockHeld(cs_wallet); // mapKeyMetadata
4029  mapKeyBirth.clear();
4030 
4031  // get birth times for keys with metadata
4032  for (const auto& entry : mapKeyMetadata) {
4033  if (entry.second.nCreateTime) mapKeyBirth[entry.first] = entry.second.nCreateTime;
4034  }
4035 
4036  // map in which we'll infer heights of other keys
4037  CBlockIndex* pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
4038  std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
4039  for (const CKeyID& keyid : GetKeys()) {
4040  if (mapKeyBirth.count(keyid) == 0)
4041  mapKeyFirstBlock[keyid] = pindexMax;
4042  }
4043 
4044  // if there are no such keys, we're done
4045  if (mapKeyFirstBlock.empty())
4046  return;
4047 
4048  // find first block that affects those keys, if there are any left
4049  std::vector<CKeyID> vAffected;
4050  for (const auto& entry : mapWallet) {
4051  // iterate over all wallet transactions...
4052  const CWalletTx& wtx = entry.second;
4054  if (pindex && chainActive.Contains(pindex)) {
4055  // ... which are already in a block
4056  int nHeight = pindex->nHeight;
4057  for (const CTxOut& txout : wtx.tx->vout) {
4058  // iterate over all their outputs
4059  CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
4060  for (const CKeyID& keyid : vAffected) {
4061  // ... and all their affected keys
4062  std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
4063  if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
4064  rit->second = pindex;
4065  }
4066  vAffected.clear();
4067  }
4068  }
4069  }
4070 
4071  // Extract block timestamps for those keys
4072  for (const auto& entry : mapKeyFirstBlock)
4073  mapKeyBirth[entry.first] = entry.second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
4074 }
4075 
4076 bool CWallet::AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value)
4077 {
4078  if (!IsValidDestination(dest))
4079  return false;
4080 
4081  mapAddressBook[dest].destdata.emplace(key, value);
4082  return WalletBatch(*database).WriteDestData(EncodeDestination(dest), key, value);
4083 }
4084 
4085 bool CWallet::EraseDestData(const CTxDestination& dest, const std::string& key)
4086 {
4087  if (!mapAddressBook[dest].destdata.erase(key))
4088  return false;
4089  return WalletBatch(*database).EraseDestData(EncodeDestination(dest), key);
4090 }
4091 
4092 bool CWallet::LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value)
4093 {
4094  mapAddressBook[dest].destdata.emplace(key, value);
4095  return true;
4096 }
4097 
4098 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
4099 {
4100  LOCK(cs_wallet);
4101  std::vector<std::string> values;
4102  for (const auto& address : mapAddressBook) {
4103  for (const auto& data : address.second.destdata) {
4104  if (!data.first.compare(0, prefix.size(), prefix)) {
4105  values.emplace_back(data.second);
4106  }
4107  }
4108  }
4109  return values;
4110 }
4111 
4113 {
4114  {
4115  LOCK(cs_wallet);
4116  if (m_last_block_processed.IsNull() ||
4117  m_last_block_processed_time < (GetAdjustedTime() - 300) ||
4118  IsLocked()) {
4119  return;
4120  }
4121  }
4122 
4123  std::map<CTxDestination, std::vector<COutput> > mapCoinsByAddress =
4125 
4126  //coins are sectioned by address. This combination code only wants to combine inputs that belong to the same address
4127  for (const auto& entry : mapCoinsByAddress) {
4128  std::vector<COutput> vCoins, vRewardCoins;
4129  bool maxSize = false;
4130  vCoins = entry.second;
4131 
4132  // We don't want the tx to be refused for being too large
4133  // we use 50 bytes as a base tx size (2 output: 2*34 + overhead: 10 -> 90 to be certain)
4134  unsigned int txSizeEstimate = 90;
4135 
4136  //find masternode rewards that need to be combined
4137  CCoinControl* coinControl = new CCoinControl();
4138  CAmount nTotalRewardsValue = 0;
4139  for (const COutput& out : vCoins) {
4140  if (!out.fSpendable)
4141  continue;
4142 
4143  COutPoint outpt(out.tx->GetHash(), out.i);
4144  coinControl->Select(outpt);
4145  vRewardCoins.push_back(out);
4146  nTotalRewardsValue += out.Value();
4147 
4148  // Combine to the threshold and not way above considering the safety margin.
4149  if ((nTotalRewardsValue - (nTotalRewardsValue / 10)) > nAutoCombineThreshold)
4150  break;
4151 
4152  // Around 180 bytes per input. We use 190 to be certain
4153  txSizeEstimate += 190;
4154  if (txSizeEstimate >= MAX_STANDARD_TX_SIZE - 200) {
4155  maxSize = true;
4156  break;
4157  }
4158  }
4159 
4160  //if no inputs found then return
4161  if (!coinControl->HasSelected())
4162  continue;
4163 
4164  //we cannot combine one coin with itself
4165  if (vRewardCoins.size() <= 1)
4166  continue;
4167 
4168  std::vector<CRecipient> vecSend;
4169  const CScript& scriptPubKey = GetScriptForDestination(entry.first);
4170  vecSend.emplace_back(scriptPubKey, nTotalRewardsValue, false);
4171 
4172  //Send change to same address
4173  CTxDestination destMyAddress;
4174  if (!ExtractDestination(scriptPubKey, destMyAddress)) {
4175  LogPrintf("AutoCombineDust: failed to extract destination\n");
4176  continue;
4177  }
4178  coinControl->destChange = destMyAddress;
4179 
4180  // Create the transaction and commit it to the network
4181  CTransactionRef wtx;
4182  CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch
4183  std::string strErr;
4184  CAmount nFeeRet = 0;
4185  int nChangePosInOut = -1;
4186 
4187  // 10% safety margin to avoid "Insufficient funds" errors
4188  vecSend[0].nAmount = nTotalRewardsValue - (nTotalRewardsValue / 10);
4189 
4190  {
4191  // For now, CreateTransaction requires cs_main lock.
4193  if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, nChangePosInOut, strErr, coinControl,
4194  true, false, CAmount(0))) {
4195  LogPrintf("AutoCombineDust createtransaction failed, reason: %s\n", strErr);
4196  continue;
4197  }
4198  }
4199 
4200  //we don't combine below the threshold unless the fees are 0 to avoid paying fees over fees over fees
4201  if (!maxSize && vecSend[0].nAmount < nAutoCombineThreshold && nFeeRet > 0)
4202  continue;
4203 
4204  const CWallet::CommitResult& res = CommitTransaction(wtx, keyChange, connman);
4205  if (res.status != CWallet::CommitStatus::OK) {
4206  LogPrintf("AutoCombineDust transaction commit failed\n");
4207  continue;
4208  }
4209 
4210  LogPrintf("AutoCombineDust sent transaction. Fee=%d, Total value=%d, Sending=%d\n", nFeeRet, nTotalRewardsValue, vecSend[0].nAmount);
4211 
4212  delete coinControl;
4213  }
4214 }
4215 
4217 {
4219 }
4220 
4222 {
4224  CTxOut txout;
4225  if (ptx && c.hash == ptx->GetHash() && c.n < ptx->vout.size()) {
4226  // the collateral is an output of this tx
4227  txout = ptx->vout[c.n];
4228  } else {
4229  // the collateral is a reference to an utxo inside this wallet
4230  const auto& it = mapWallet.find(c.hash);
4231  if (it != mapWallet.end()) {
4232  txout = it->second.tx->vout[c.n];
4233  }
4234  }
4235  if (!txout.IsNull() && IsMine(txout) != ISMINE_NO && !IsSpent(c)) {
4236  LockCoin(c);
4237  }
4238 }
4239 
4240 // Called from AddToWalletIfInvolvingMe
4242 {
4244 
4245  COutPoint o;
4246  if (GetProRegCollateral(ptx, o)) {
4247  LockOutpointIfMine(ptx, o);
4248  }
4249 }
4250 
4251 CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path& path)
4252 {
4253  const std::string& walletFile = name;
4254 
4255  // needed to restore wallet transaction meta data after -zapwallettxes
4256  std::vector<CWalletTx> vWtx;
4257 
4258  if (gArgs.GetBoolArg("-zapwallettxes", false)) {
4259  uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
4260 
4261  std::unique_ptr<CWallet> tempWallet = std::make_unique<CWallet>(name, WalletDatabase::Create(path));
4262  DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
4263  if (nZapWalletRet != DB_LOAD_OK) {
4264  UIError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
4265  return nullptr;
4266  }
4267  }
4268 
4269  uiInterface.InitMessage(_("Loading wallet..."));
4270 
4271  int64_t nStart = GetTimeMillis();
4272  bool fFirstRun = true;
4273  CWallet *walletInstance = new CWallet(name, WalletDatabase::Create(path));
4274  DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
4275  if (nLoadWalletRet != DB_LOAD_OK) {
4276  if (nLoadWalletRet == DB_CORRUPT) {
4277  UIError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
4278  return nullptr;
4279  } else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) {
4280  UIWarning(strprintf(_("Warning: error reading %s! All keys read correctly, but transaction data"
4281  " or address book entries might be missing or incorrect."), walletFile));
4282  } else if (nLoadWalletRet == DB_TOO_NEW) {
4283  UIError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, PACKAGE_NAME));
4284  return nullptr;
4285  } else if (nLoadWalletRet == DB_NEED_REWRITE) {
4286  UIError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME));
4287  return nullptr;
4288  } else {
4289  UIError(strprintf(_("Error loading %s\n"), walletFile));
4290  return nullptr;
4291  }
4292  }
4293 
4294  // check minimum stake split threshold
4295  if (walletInstance->nStakeSplitThreshold && walletInstance->nStakeSplitThreshold < CWallet::minStakeSplitThreshold) {
4296  LogPrintf("WARNING: stake split threshold value %s too low. Restoring to minimum value %s.\n",
4299  }
4300 
4301  int prev_version = walletInstance->GetVersion();
4302 
4303  // Forced upgrade
4304  const bool fLegacyWallet = gArgs.GetBoolArg("-legacywallet", false);
4305  if (gArgs.GetBoolArg("-upgradewallet", fFirstRun && !fLegacyWallet) ||
4306  (!walletInstance->IsLocked() && prev_version == FEATURE_PRE_SPLIT_KEYPOOL)) {
4307  if (prev_version <= FEATURE_PRE_PIVX && walletInstance->IsLocked()) {
4308  // Cannot upgrade a locked wallet
4309  UIError(_("Cannot upgrade a locked wallet."));
4310  return nullptr;
4311  }
4312 
4313  int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
4314  if (nMaxVersion == 0) // the -upgradewallet without argument case
4315  {
4316  LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
4317  nMaxVersion = FEATURE_LATEST;
4318  walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
4319  } else {
4320  LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
4321  }
4322  if (nMaxVersion < walletInstance->GetVersion()) {
4323  UIError(_("Cannot downgrade wallet."));
4324  return nullptr;
4325  }
4326  walletInstance->SetMaxVersion(nMaxVersion);
4327  }
4328 
4329  // Upgrade to HD only if explicit upgrade was requested
4330  // or if we are running an HD wallet and need to upgrade to Sapling.
4331  if (gArgs.GetBoolArg("-upgradewallet", false) ||
4332  (!walletInstance->IsLocked() && prev_version == FEATURE_PRE_SPLIT_KEYPOOL)) {
4333  std::string upgradeError;
4334  if (!walletInstance->Upgrade(upgradeError, prev_version)) {
4335  UIError(upgradeError);
4336  return nullptr;
4337  }
4338  }
4339 
4340  if (fFirstRun) {
4341  if (!fLegacyWallet) {
4342  // Create new HD Wallet
4343  LogPrintf("Creating HD Wallet\n");
4344  // Ensure this wallet can only be opened by clients supporting HD.
4345  walletInstance->SetMinVersion(FEATURE_LATEST);
4346  walletInstance->SetupSPKM();
4347  } else {
4348  if (!Params().IsRegTestNet()) {
4349  UIError("Legacy wallets can only be created on RegTest.");
4350  return nullptr;
4351  }
4352  // Create legacy wallet
4353  LogPrintf("Creating Pre-HD Wallet\n");
4354  walletInstance->SetMaxVersion(FEATURE_PRE_PIVX);
4355  }
4356 
4357  // Top up the keypool
4358  if (!walletInstance->TopUpKeyPool()) {
4359  // Error generating keys
4360  UIError(_("Unable to generate initial key!"));
4361  return nullptr;
4362  }
4363 
4364  walletInstance->SetBestChain(WITH_LOCK(cs_main, return chainActive.GetLocator()));
4365  }
4366 
4367  LogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nStart);
4368 
4369  LOCK(cs_main);
4370  CBlockIndex* pindexRescan = chainActive.Genesis();
4371 
4372  if (gArgs.GetBoolArg("-rescan", false)) {
4373  // clear note witness cache before a full rescan
4374  walletInstance->ClearNoteWitnessCache();
4375  } else {
4376  WalletBatch batch(*walletInstance->database);
4377  CBlockLocator locator;
4378  if (batch.ReadBestBlock(locator))
4379  pindexRescan = FindForkInGlobalIndex(chainActive, locator);
4380  }
4381 
4382  {
4383  LOCK(walletInstance->cs_wallet);
4384  const CBlockIndex* tip = chainActive.Tip();
4385  if (tip) {
4386  walletInstance->m_last_block_processed = tip->GetBlockHash();
4387  walletInstance->m_last_block_processed_height = tip->nHeight;
4388  walletInstance->m_last_block_processed_time = tip->GetBlockTime();
4389  }
4390  }
4391  RegisterValidationInterface(walletInstance);
4392 
4393  if (chainActive.Tip() && chainActive.Tip() != pindexRescan) {
4394  uiInterface.InitMessage(_("Rescanning..."));
4395  LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
4396 
4397  // no need to read and scan block, if block was created before
4398  // our wallet birthday (as adjusted for block time variability)
4399  while (pindexRescan && walletInstance->nTimeFirstKey &&
4400  pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW)) {
4401  pindexRescan = chainActive.Next(pindexRescan);
4402  }
4403  const int64_t nWalletRescanTime = GetTimeMillis();
4404  {
4405  WalletRescanReserver reserver(walletInstance);
4406  if (!reserver.reserve()) {
4407  UIError(_("Failed to rescan the wallet during initialization"));
4408  return nullptr;
4409  }
4410  if (walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, reserver, true, true) != nullptr) {
4411  UIError(_("Shutdown requested over the txs scan. Exiting."));
4412  return nullptr;
4413  }
4414  }
4415  LogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - nWalletRescanTime);
4416  walletInstance->SetBestChain(chainActive.GetLocator());
4417  walletInstance->database->IncrementUpdateCounter();
4418 
4419  // Restore wallet transaction metadata after -zapwallettxes=1
4420  if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2") {
4421  WalletBatch batch(*walletInstance->database);
4422  for (const CWalletTx& wtxOld : vWtx) {
4423  uint256 hash = wtxOld.GetHash();
4424  std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4425  if (mi != walletInstance->mapWallet.end()) {
4426  const CWalletTx* copyFrom = &wtxOld;
4427  CWalletTx* copyTo = &mi->second;
4428  copyTo->mapValue = copyFrom->mapValue;
4429  copyTo->vOrderForm = copyFrom->vOrderForm;
4430  copyTo->nTimeReceived = copyFrom->nTimeReceived;
4431  copyTo->nTimeSmart = copyFrom->nTimeSmart;
4432  copyTo->fFromMe = copyFrom->fFromMe;
4433  copyTo->nOrderPos = copyFrom->nOrderPos;
4434  batch.WriteTx(*copyTo);
4435  }
4436  }
4437  }
4438  }
4439 
4440  return walletInstance;
4441 }
4442 
4443 
4444 std::atomic<bool> CWallet::fFlushScheduled(false);
4445 
4447 {
4448  // Add wallet transactions that aren't already in a block to mapTransactions
4449  ReacceptWalletTransactions(/*fFirstLoad*/true);
4450 
4451  // Run a thread to flush wallet periodically
4452  if (!CWallet::fFlushScheduled.exchange(true)) {
4454  }
4455 }
4456 
4457 bool CWallet::BackupWallet(const std::string& strDest)
4458 {
4459  return database->Backup(strDest);
4460 }
4461 
4463 {
4464  nTime = GetTime();
4465  type = HDChain::ChangeType::EXTERNAL;
4466  m_pre_split = false;
4467 }
4468 
4469 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, const uint8_t& _type)
4470 {
4471  nTime = GetTime();
4472  vchPubKey = vchPubKeyIn;
4473  type = _type;
4474  m_pre_split = false;
4475 }
4476 
4478 {
4479  assert(pwallet != nullptr);
4480  AssertLockHeld(pwallet->cs_wallet);
4481  if (isUnconfirmed() || isAbandoned()) return 0;
4482 
4483  return (pwallet->GetLastBlockHeight() - m_confirm.block_height + 1) * (isConflicted() ? -1 : 1);
4484 }
4485 
4487 {
4488  if (!(IsCoinBase() || IsCoinStake()))
4489  return 0;
4490  return std::max(0, (Params().GetConsensus().nCoinbaseMaturity + 1) - GetDepthInMainChain());
4491 }
4492 
4494 {
4495  if (!IsCoinBase() && !IsCoinStake()) return false;
4496  const int depth = GetDepthInMainChain();
4497  return (depth > 0 && depth <= Params().GetConsensus().nCoinbaseMaturity);
4498 }
4499 
4500 
4502 {
4504 
4505  // Quick check to avoid re-setting fInMempool to false
4506  if (mempool.exists(tx->GetHash())) {
4507  return false;
4508  }
4509 
4510  // We must set fInMempool here - while it will be re-set to true by the
4511  // entered-mempool callback, if we did not there would be a race where a
4512  // user could call sendmoney in a loop and hit spurious out of funds errors
4513  // because we think that the transaction they just generated's change is
4514  // unavailable as we're not yet aware its in mempool.
4515  bool fMissingInputs;
4516  bool fAccepted = ::AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs, false, true, false);
4517  fInMempool = fAccepted;
4518  if (!fAccepted) {
4519  if (fMissingInputs) {
4520  // For now, "missing inputs" error is not returning the proper state, so need to set it manually here.
4521  // TODO: clean this setting the proper invalid state inside AcceptToMemoryPool (btc#15921).
4522  state.Invalid(false, REJECT_INVALID, "Missing inputs");
4523  }
4524  LogPrintf("%s : %s\n", __func__, state.GetRejectReason());
4525  }
4526  return fAccepted;
4527 }
4528 
4530 {
4531  std::string name = !m_name.empty() ? SanitizeString(m_name, SAFE_CHARS_FILENAME) : "wallet_backup";
4533 }
4534 
4535 CWallet::CWallet(std::string name, std::unique_ptr<WalletDatabase> database) : m_name(std::move(name)), database(std::move(database))
4536 {
4537  SetNull();
4538 }
4539 
4541 {
4542  delete encrypted_batch;
4543  delete pStakerStatus;
4544 }
4545 
4547 {
4550  nMasterKeyMaxID = 0;
4551  encrypted_batch = nullptr;
4552  nOrderPosNext = 0;
4553  nNextResend = 0;
4554  nLastResend = 0;
4555  nTimeFirstKey = 0;
4556  nRelockTime = 0;
4557  fAbortRescan = false;
4558  fScanningWallet = false;
4559  fWalletUnlockStaking = false;
4560 
4561  // Staker status (last hashed block and time)
4562  if (pStakerStatus) {
4564  } else {
4565  pStakerStatus = new CStakerStatus();
4566  }
4567  // Stake split threshold
4569 
4570  // User-defined fee PIV/kb
4571  fUseCustomFee = false;
4573 
4574  //Auto Combine Dust
4575  fCombineDust = false;
4577  frequency = 30;
4578 
4579  // Sapling.
4580  m_sspk_man->nWitnessCacheSize = 0;
4581  m_sspk_man->nWitnessCacheNeedsUpdate = true;
4582 }
4583 
4585 {
4587  return nWalletMaxVersion >= wf;
4588 }
4589 
4590 bool CWallet::LoadMinVersion(int nVersion)
4591 {
4593  nWalletVersion = nVersion;
4594  nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion);
4595  return true;
4596 }
4597 
4598 isminetype CWallet::IsMine(const CTxOut& txout) const
4599 {
4600  return ::IsMine(*this, txout.scriptPubKey);
4601 }
4602 
4603 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
4604 {
4605  if (!Params().GetConsensus().MoneyRange(txout.nValue))
4606  throw std::runtime_error("CWallet::GetCredit() : value out of range");
4607  return ((IsMine(txout) & filter) ? txout.nValue : 0);
4608 }
4609 
4610 CAmount CWallet::GetChange(const CTxOut& txout) const
4611 {
4612  if (!Params().GetConsensus().MoneyRange(txout.nValue))
4613  throw std::runtime_error("CWallet::GetChange() : value out of range");
4614  return (IsChange(txout) ? txout.nValue : 0);
4615 }
4616 
4617 bool CWallet::IsMine(const CTransactionRef& tx) const
4618 {
4619  for (const CTxOut& txout : tx->vout)
4620  if (IsMine(txout))
4621  return true;
4622  return false;
4623 }
4624 
4625 bool CWallet::IsFromMe(const CTransactionRef& tx) const
4626 {
4627  if (GetDebit(tx, ISMINE_ALL) > 0) {
4628  return true;
4629  }
4630 
4631  if (tx->IsShieldedTx()) {
4632  for (const SpendDescription& spend : tx->sapData->vShieldedSpend) {
4633  if (m_sspk_man->IsSaplingNullifierFromMe(spend.nullifier)) {
4634  return true;
4635  }
4636  }
4637  }
4638 
4639  return false;
4640 }
4641 
4643 {
4644  CAmount nDebit = 0;
4645  for (const CTxIn& txin : tx->vin) {
4646  nDebit += GetDebit(txin, filter);
4647  if (!Params().GetConsensus().MoneyRange(nDebit))
4648  throw std::runtime_error("CWallet::GetDebit() : value out of range");
4649  }
4650 
4651  // Shielded debit
4652  if (filter & ISMINE_SPENDABLE_SHIELDED || filter & ISMINE_WATCH_ONLY_SHIELDED) {
4653  if (tx->hasSaplingData()) {
4654  nDebit += m_sspk_man->GetDebit(*tx, filter);
4655  }
4656  }
4657 
4658  return nDebit;
4659 }
4660 
4661 CAmount CWallet::GetCredit(const CWalletTx& tx, const isminefilter& filter) const
4662 {
4663  CAmount nCredit = 0;
4664  for (unsigned int i = 0; i < tx.tx->vout.size(); i++) {
4665  nCredit += GetCredit(tx.tx->vout[i], filter);
4666  }
4667 
4668  // Shielded credit
4669  if (filter & ISMINE_SPENDABLE_SHIELDED || filter & ISMINE_WATCH_ONLY_SHIELDED) {
4670  if (tx.tx->hasSaplingData()) {
4671  nCredit += m_sspk_man->GetCredit(tx, filter, false);
4672  }
4673  }
4674 
4675  if (!Params().GetConsensus().MoneyRange(nCredit))
4676  throw std::runtime_error("CWallet::GetCredit() : value out of range");
4677  return nCredit;
4678 }
4679 
4681 {
4682  CAmount nChange = 0;
4683  for (const CTxOut& txout : tx->vout) {
4684  nChange += GetChange(txout);
4685  if (!Params().GetConsensus().MoneyRange(nChange))
4686  throw std::runtime_error("CWallet::GetChange() : value out of range");
4687  }
4688  return nChange;
4689 }
4690 
4692 {
4693  return m_spk_man->GetKeyPoolSize();
4694 }
4695 
4697 {
4698  return m_spk_man->GetStakingKeyPoolSize();
4699 }
4700 
4702 {
4703  LOCK(cs_wallet);
4704  return nWalletVersion;
4705 }
4706 
4709 
4711  if (!m_sspk_man->IsEnabled()) {
4712  throw std::runtime_error("Cannot generate shielded addresses. Start with -upgradewallet in order to upgrade a non-HD wallet to HD and Sapling features");
4713  }
4714 
4715  auto address = m_sspk_man->GenerateNewSaplingZKey();
4717  return address;
4718 }
4719 
4721  const CBlock* pblock,
4722  SaplingMerkleTree& saplingTree) { m_sspk_man->IncrementNoteWitnesses(pindex, pblock, saplingTree); }
4723 
4724 void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex) { m_sspk_man->DecrementNoteWitnesses(pindex); }
4725 
4726 void CWallet::ClearNoteWitnessCache() { m_sspk_man->ClearNoteWitnessCache(); }
4727 
4728 bool CWallet::AddSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key) { return m_sspk_man->AddSaplingZKey(key); }
4729 
4732  const libzcash::SaplingPaymentAddress &addr) { return m_sspk_man->AddSaplingIncomingViewingKey(ivk, addr); }
4733 
4736  const std::vector<unsigned char> &vchCryptedSecret) { return m_sspk_man->AddCryptedSaplingSpendingKeyDB(extfvk, vchCryptedSecret); }
4737 
4738 bool CWallet::HaveSpendingKeyForPaymentAddress(const libzcash::SaplingPaymentAddress &zaddr) const { return m_sspk_man->HaveSpendingKeyForPaymentAddress(zaddr); }
4739 bool CWallet::LoadSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key) { return m_sspk_man->LoadSaplingZKey(key); }
4740 bool CWallet::LoadSaplingZKeyMetadata(const libzcash::SaplingIncomingViewingKey &ivk, const CKeyMetadata &meta) { return m_sspk_man->LoadSaplingZKeyMetadata(ivk, meta); }
4742  const std::vector<unsigned char> &vchCryptedSecret) { return m_sspk_man->LoadCryptedSaplingZKey(extfvk, vchCryptedSecret); }
4743 
4745  const libzcash::SaplingPaymentAddress &addr,
4746  const libzcash::SaplingIncomingViewingKey &ivk) { return m_sspk_man->LoadSaplingPaymentAddress(addr, ivk); }
4747 
4750 
4752  : tx(std::move(arg))
4753 {
4754  Init(pwalletIn);
4755 }
4756 
4757 void CWalletTx::Init(const CWallet* pwalletIn)
4758 {
4759  pwallet = pwalletIn;
4760  mapValue.clear();
4761  mapSaplingNoteData.clear();
4762  vOrderForm.clear();
4763  fTimeReceivedIsTxTime = false;
4764  nTimeReceived = 0;
4765  nTimeSmart = 0;
4766  fFromMe = false;
4767  fChangeCached = false;
4768  fInMempool = false;
4769  nChangeCached = 0;
4770  fStakeDelegationVoided = false;
4771  fShieldedChangeCached = false;
4773  nOrderPos = -1;
4774  m_confirm = Confirmation{};
4775 }
4776 
4778 {
4779  bool fConflicted = false;
4780  int nDepth = 0;
4781  return IsTrusted(nDepth, fConflicted);
4782 }
4783 
4784 bool CWalletTx::IsTrusted(int& nDepth, bool& fConflicted) const
4785 {
4786  {
4787  LOCK(pwallet->cs_wallet); // future: receive block height instead of locking here.
4788  // Quick answer in most cases
4790  return false;
4791  }
4792 
4793  nDepth = GetDepthAndMempool(fConflicted);
4794 
4795  if (fConflicted) // Don't trust unconfirmed transactions from us unless they are in the mempool.
4796  return false;
4797  if (nDepth >= 1)
4798  return true;
4799  if (nDepth < 0)
4800  return false;
4801  if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
4802  return false;
4803 
4804  // Trusted if all inputs are from us and are in the mempool:
4805  for (const CTxIn& txin : tx->vin) {
4806  // Transactions not sent by us: not trusted
4807  const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
4808  if (parent == nullptr)
4809  return false;
4810  const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
4811  if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
4812  return false;
4813  }
4814  return true;
4815 }
4816 
4817 int CWalletTx::GetDepthAndMempool(bool& fConflicted) const
4818 {
4819  int ret = GetDepthInMainChain();
4820  fConflicted = (ret == 0 && !InMempool()); // not in chain nor in mempool
4821  return ret;
4822 }
4823 
4824 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
4825 {
4826  CMutableTransaction tx1 {*tx};
4827  CMutableTransaction tx2 {*_tx.tx};
4828  for (auto& txin : tx1.vin) txin.scriptSig = CScript();
4829  for (auto& txin : tx2.vin) txin.scriptSig = CScript();
4830  return CTransaction(tx1) == CTransaction(tx2);
4831 }
4832 
4834 {
4835  m_amounts[DEBIT].Reset();
4836  m_amounts[CREDIT].Reset();
4839  nChangeCached = 0;
4840  fChangeCached = false;
4842  fShieldedChangeCached = false;
4843  fStakeDelegationVoided = false;
4844 }
4845 
4847 {
4848  pwallet = pwalletIn;
4849  MarkDirty();
4850 }
4851 
4853 {
4854  mapSaplingNoteData.clear();
4855  for (const std::pair<SaplingOutPoint, SaplingNoteData> nd : noteData) {
4856  if (nd.first.n < tx->sapData->vShieldedOutput.size()) {
4857  mapSaplingNoteData[nd.first] = nd.second;
4858  } else {
4859  throw std::logic_error("CWalletTx::SetSaplingNoteData(): Invalid note");
4860  }
4861  }
4862 }
4863 
4864 Optional<std::pair<
4867 {
4868  // Check whether we can decrypt this SaplingOutPoint with the ivk
4869  auto it = this->mapSaplingNoteData.find(op);
4870  if (it == this->mapSaplingNoteData.end() || !it->second.IsMyNote()) {
4871  return nullopt;
4872  }
4873 
4874  auto output = this->tx->sapData->vShieldedOutput[op.n];
4875  auto nd = this->mapSaplingNoteData.at(op);
4876 
4878  output.encCiphertext,
4879  *(nd.ivk),
4880  output.ephemeralKey,
4881  output.cmu);
4882  assert(static_cast<bool>(maybe_pt));
4883  auto notePt = maybe_pt.get();
4884 
4885  auto maybe_pa = nd.ivk->address(notePt.d);
4886  assert(static_cast<bool>(maybe_pa));
4887  auto pa = maybe_pa.get();
4888 
4889  return std::make_pair(notePt, pa);
4890 }
4891 
4892 Optional<std::pair<
4894  libzcash::SaplingPaymentAddress>> CWalletTx::RecoverSaplingNote(const SaplingOutPoint& op, const std::set<uint256>& ovks) const
4895 {
4896  auto output = this->tx->sapData->vShieldedOutput[op.n];
4897 
4898  for (const auto& ovk : ovks) {
4900  output.outCiphertext,
4901  ovk,
4902  output.cv,
4903  output.cmu,
4904  output.ephemeralKey);
4905  if (!outPt) {
4906  continue;
4907  }
4908 
4910  output.encCiphertext,
4911  output.ephemeralKey,
4912  outPt->esk,
4913  outPt->pk_d,
4914  output.cmu);
4915  assert(static_cast<bool>(maybe_pt));
4916  auto notePt = maybe_pt.get();
4917 
4918  return std::make_pair(notePt, libzcash::SaplingPaymentAddress(notePt.d, outPt->pk_d));
4919  }
4920 
4921  // Couldn't recover with any of the provided OutgoingViewingKeys
4922  return nullopt;
4923 }
4924 
4926 {
4927  return GetStakeDelegationDebit(true) > 0 || GetColdStakingDebit(true) > 0;
4928 }
4929 
4931 {
4932  if (fChangeCached)
4933  return nChangeCached;
4935  fChangeCached = true;
4936  return nChangeCached;
4937 }
4938 
4940 {
4941  if (fShieldedChangeCached) {
4942  return nShieldedChangeCached;
4943  }
4945  fShieldedChangeCached = true;
4946  return nShieldedChangeCached;
4947 }
4948 
4949 bool CWalletTx::IsFromMe(const isminefilter& filter) const
4950 {
4951  return (GetDebit(filter) > 0);
4952 }
4953 
4955 {
4956  return GetAvailableCredit(fUseCache, ISMINE_SPENDABLE_SHIELDED);
4957 }
4958 
4960 {
4961  return boost::get<CTxDestination>(&it->first);
4962 }
4963 
4965 {
4966  return boost::get<libzcash::SaplingPaymentAddress>(&it->first);
4967 }
4968 
4970 {
4971  return &it->first;
4972 }
4973 
4975  int iIn,
4976  int nDepthIn,
4977  const CBlockIndex*& _pindex) :
4978  COutput(txIn, iIn, nDepthIn, true /*fSpendable*/, true/*fSolvable*/, true/*fSafe*/),
4979  pindex(_pindex)
4980 {}
int64_t CAmount
Amount in PIV (Can be negative)
Definition: amount.h:13
true
Definition: bls_dkg.cpp:153
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:449
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:465
uint256 hash
Definition: transaction.h:35
uint32_t n
Definition: transaction.h:36
static std::unique_ptr< BerkeleyDatabase > Create(const fs::path &path)
Return object for accessing database at specified path.
Definition: db.h:126
std::map< CWDestination, AddressBook::CAddressBookData >::iterator it
Definition: wallet.h:265
const libzcash::SaplingPaymentAddress * GetShieldedDestKey()
Definition: wallet.cpp:4964
const CWDestination * GetDestKey()
Definition: wallet.cpp:4969
const CTxDestination * GetCTxDestKey()
Definition: wallet.cpp:4959
void operator()(const CScriptID &scriptId)
Definition: wallet.cpp:108
void Process(const CScript &script)
Definition: wallet.cpp:86
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector< CKeyID > &vKeysIn)
Definition: wallet.cpp:84
std::vector< CKeyID > & vKeys
Definition: wallet.cpp:81
const CKeyStore & keystore
Definition: wallet.cpp:80
void operator()(const CKeyID &keyId)
Definition: wallet.cpp:97
void operator()(const CNoDestination &none)
Definition: wallet.cpp:115
void operator()(const CExchangeKeyID &keyId)
Definition: wallet.cpp:103
virtual bool RemoveWatchOnly(const CScript &dest)
Definition: keystore.cpp:94
virtual bool AddWatchOnly(const CScript &dest)
Support for Watch-only addresses.
Definition: keystore.cpp:84
virtual bool AddCScript(const CScript &redeemScript)
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:41
ScriptMap mapScripts
Definition: keystore.h:103
virtual bool HaveWatchOnly() const
Definition: keystore.cpp:110
virtual bool GetSaplingIncomingViewingKey(const libzcash::SaplingPaymentAddress &addr, libzcash::SaplingIncomingViewingKey &ivkOut) const
Definition: keystore.cpp:228
WatchOnlySet setWatchOnly
Definition: keystore.h:104
KeyMap mapKeys
Definition: keystore.h:101
Definition: block.h:80
std::vector< CTransactionRef > vtx
Definition: block.h:83
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:139
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:145
uint256 GetBlockHash() const
Definition: chain.h:215
int64_t GetBlockTime() const
Definition: chain.h:216
int64_t GetBlockTimeMax() const
Definition: chain.h:217
uint256 hashFinalSaplingRoot
Definition: chain.h:195
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:151
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:399
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:441
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:405
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:27
int Height() const
Return the maximal height in the chain.
Definition: chain.h:450
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:435
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
Definition: chain.cpp:67
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:72
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: guiinterface.h:87
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: guiinterface.h:84
boost::signals2::signal< void(CWallet *wallet)> LoadWallet
A wallet has been loaded.
Definition: guiinterface.h:99
Coin Control Features.
Definition: coincontrol.h:34
bool IsSelected(const BaseOutPoint &output) const
Definition: coincontrol.h:71
bool HasSelected() const
Definition: coincontrol.h:66
CFeeRate nFeeRate
Feerate to use if overrideFeeRate is true.
Definition: coincontrol.h:48
void Select(const BaseOutPoint &output, CAmount value=0, bool isP2CS=false)
Definition: coincontrol.h:76
void ListSelected(std::vector< OutPointWrapper > &vOutpoints) const
Definition: coincontrol.h:91
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:42
bool fOverrideFeeRate
Override estimated feerate.
Definition: coincontrol.h:46
CTxDestination destChange
Definition: coincontrol.h:38
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:40
CAmount nMinimumTotalFee
Minimum absolute fee (not per kilobyte)
Definition: coincontrol.h:44
Definition: net.h:145
void ForEachNode(Callable &&func)
Definition: net.h:257
Encryption/decryption context with key information.
Definition: crypter.h:84
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
Definition: crypter.cpp:71
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:40
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:88
bool GetKey(const CKeyID &address, CKey &keyOut) const override
Definition: crypter.cpp:199
static bool DecryptKey(const CKeyingMaterial &vMasterKey, const std::vector< unsigned char > &vchCryptedSecret, const CPubKey &vchPubKey, CKey &key)
Definition: crypter.cpp:124
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Add a key to the store.
Definition: crypter.cpp:156
bool IsLocked() const
Definition: crypter.cpp:148
bool UnlockSaplingKeys(const CKeyingMaterial &vMasterKeyIn, bool fDecryptionThoroughlyChecked)
bool EncryptKeys(CKeyingMaterial &vMasterKeyIn)
will encrypt previously unencrypted keys
Definition: crypter.cpp:244
virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Definition: crypter.cpp:188
CKeyingMaterial vMasterKey
Definition: crypter.h:135
bool IsCrypted() const
Definition: crypter.h:154
CryptedKeyMap mapCryptedKeys
Definition: crypter.h:144
std::set< CKeyID > GetKeys() const override
Definition: crypter.cpp:231
boost::signals2::signal< void(CCryptoKeyStore *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: crypter.h:175
bool SetCrypted()
Definition: crypter.cpp:137
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Definition: crypter.cpp:215
A reference to a CKey: the Hash160 of its serialized public key, special case for exchange key.
Definition: pubkey.h:30
Fee rate in PIV per kilobyte: CAmount / kB.
Definition: feerate.h:20
CAmount GetFee(size_t size) const
Definition: feerate.cpp:21
CAmount GetFeePerK() const
Definition: feerate.h:29
inv message data
Definition: protocol.h:466
An encapsulated private key.
Definition: key.h:30
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized secp256k1 private key data).
Definition: key.cpp:173
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:186
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:21
int64_t nCreateTime
Definition: walletdb.h:69
A key pool entry.
Definition: wallet.h:125
CPubKey vchPubKey
The public key.
Definition: wallet.h:130
CKeyPool()
Definition: wallet.cpp:4462
A virtual base class for key stores.
Definition: keystore.h:23
RecursiveMutex cs_KeyStore
Definition: keystore.h:26
virtual bool HaveKey(const CKeyID &address) const =0
Check whether a key corresponding to a given address is present in the store.
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const =0
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
Definition: crypter.h:39
std::vector< unsigned char > vchSalt
Definition: crypter.h:42
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:45
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:41
unsigned int nDeriveIterations
Definition: crypter.h:46
Information about a peer.
Definition: net.h:669
void PushInventory(const CInv &inv)
Definition: net.h:914
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:72
int nDepth
Definition: wallet.h:1289
const CWalletTx * tx
Definition: wallet.h:1287
int i
Definition: wallet.h:1288
bool GetTxOutFrom(CTxOut &out) const override
Definition: stakeinput.cpp:66
CAmount GetValue() const override
Definition: stakeinput.cpp:77
CTxIn GetTxIn() const
Definition: stakeinput.cpp:72
An encapsulated public key.
Definition: pubkey.h:44
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:167
bool IsValid() const
Definition: pubkey.h:183
A key allocated from the key pool.
Definition: wallet.h:1256
void scheduleEvery(Function f, int64_t deltaMilliSeconds)
Definition: scheduler.cpp:105
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:381
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:24
bool IsSporkActive(SporkId nSporkID)
Definition: spork.cpp:220
CStakeableOutput(const CWalletTx *txIn, int iIn, int nDepthIn, const CBlockIndex *&pindex)
Definition: wallet.cpp:4974
Record info about last stake attempt:
Definition: wallet.h:185
void SetLastTime(const uint64_t lastTime)
Definition: wallet.h:204
void SetNull()
Definition: wallet.h:205
void SetLastTries(const int tries)
Definition: wallet.h:202
void SetLastCoins(const int coins)
Definition: wallet.h:201
void SetLastTip(const CBlockIndex *lastTip)
Definition: wallet.h:203
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:244
bool HasZerocoinSpendInputs() const
std::vector< CTxIn > vin
Definition: transaction.h:270
bool IsShieldedTx() const
Definition: transaction.h:319
SigVersion GetRequiredSigVersion() const
Definition: transaction.h:347
const uint256 & GetHash() const
Definition: transaction.h:301
bool IsCoinBase() const
Definition: transaction.h:376
Optional< SaplingTxData > sapData
Definition: transaction.h:275
std::vector< CTxOut > vout
Definition: transaction.h:271
An input of a transaction.
Definition: transaction.h:94
bool IsZerocoinSpend() const
Definition: transaction.cpp:43
CScript scriptSig
Definition: transaction.h:97
COutPoint prevout
Definition: transaction.h:96
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:55
bool TransactionWithinChainLimit(const uint256 &txid, size_t chainLimit) const
Returns false if the transaction is in the mempool and not within the chain limit specified.
Definition: txmempool.cpp:1490
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:149
bool exists(uint256 hash) const
Definition: txmempool.h:640
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:481
An output of a transaction.
Definition: transaction.h:137
CScript scriptPubKey
Definition: transaction.h:140
bool IsZerocoinMint() const
Definition: transaction.cpp:83
CAmount nValue
Definition: transaction.h:139
bool IsNull() const
Definition: transaction.h:159
Capture information about block/transaction validation.
Definition: validation.h:24
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
Definition: validation.h:55
std::string GetRejectReason() const
Definition: validation.h:94
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,...
Definition: wallet.h:577
WalletBatch * encrypted_batch
Definition: wallet.h:724
std::map< CWDestination, AddressBook::CAddressBookData > mapAddressBook
Destination --> label/purpose mapping.
Definition: wallet.h:675
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:766
bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
Adds a destination data tuple to the store, without saving it to disk.
Definition: wallet.cpp:4092
int nWalletMaxVersion
the maximum wallet format version: memory-only variable that specifies to what version this wallet ma...
Definition: wallet.h:597
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: wallet.cpp:4026
static CWallet * CreateWalletFromFile(const std::string &name, const fs::path &path)
Definition: wallet.cpp:4251
void IncrementNoteWitnesses(const CBlockIndex *pindex, const CBlock *pblock, SaplingMerkleTree &saplingTree)
pindex is the new tip being connected.
Definition: wallet.cpp:4720
bool LoadCryptedSaplingZKey(const libzcash::SaplingExtendedFullViewingKey &extfvk, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted spending key to the store, without saving it to disk (used by LoadWallet)
Definition: wallet.cpp:4741
MasterKeyMap mapMasterKeys
Definition: wallet.h:729
boost::signals2::signal< void(const CAmount stakeSplitThreshold)> NotifySSTChanged
notify stake-split threshold changed
Definition: wallet.h:1251
std::string m_name
Wallet filename from wallet=<path> command line or config option.
Definition: wallet.h:604
TxItems wtxOrdered
Definition: wallet.h:769
void DecrementNoteWitnesses(const CBlockIndex *pindex)
pindex is the old tip being disconnected.
Definition: wallet.cpp:4724
bool LoadSaplingZKeyMetadata(const libzcash::SaplingIncomingViewingKey &ivk, const CKeyMetadata &meta)
Load spending key metadata (used by LoadWallet)
Definition: wallet.cpp:4740
CStakerStatus * pStakerStatus
Definition: wallet.h:737
void LockOutpointIfMine(const CTransactionRef &ptx, const COutPoint &c)
Definition: wallet.cpp:4221
RecursiveMutex cs_wallet
Definition: wallet.h:720
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
Definition: wallet.h:587
void AutoCombineDust(CConnman *connman)
Definition: wallet.cpp:4112
bool fCombineDust
Definition: wallet.h:744
std::unique_ptr< ScriptPubKeyMan > m_spk_man
Key manager //.
Definition: wallet.h:590
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.cpp:4701
bool AddSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key)
Adds Sapling spending key to the store, and saves it to disk.
Definition: wallet.cpp:4728
CWallet(std::string name, std::unique_ptr< WalletDatabase > dbw_in)
Construct wallet with specified name and database implementation.
Definition: wallet.cpp:4535
int64_t nRelockTime
Lock Wallet Holds a timestamp at which point the wallet is scheduled (externally) to be relocked.
Definition: wallet.h:1009
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:1239
void LockOutpointIfMineWithMutex(const CTransactionRef &ptx, const COutPoint &c)
Definition: wallet.cpp:4216
std::unique_ptr< SaplingScriptPubKeyMan > m_sspk_man
Definition: wallet.h:591
CAmount nStakeSplitThreshold
Definition: wallet.h:733
std::atomic< bool > fAbortRescan
Definition: wallet.h:580
std::set< COutPoint > setLockedCoins
Definition: wallet.h:773
static CAmount minStakeSplitThreshold
minimum accpeted value for stake split threshold
Definition: wallet.h:735
void postInitProcess(CScheduler &scheduler)
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:4446
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:689
bool BackupWallet(const std::string &strDest)
Creates a wallet backup in strDest path.
Definition: wallet.cpp:4457
int64_t nTimeFirstKey
Definition: wallet.h:776
bool CanSupportFeature(enum WalletFeature wf)
check whether we are allowed to upgrade (or already support) to the named feature
Definition: wallet.cpp:4584
bool LoadMinVersion(int nVersion)
Definition: wallet.cpp:4590
CAmount nAutoCombineThreshold
Definition: wallet.h:745
TxSpends mapTxSpends
Definition: wallet.h:639
bool LoadSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key)
Adds spending key to the store, without saving it to disk (used by LoadWallet)
Definition: wallet.cpp:4739
void LockIfMyCollateral(const CTransactionRef &ptx)
Definition: wallet.cpp:4241
int64_t nLastResend
Definition: wallet.h:630
int64_t nNextResend
Definition: wallet.h:629
std::vector< std::string > GetDestValues(const std::string &prefix) const
Get all destination values matching a prefix.
Definition: wallet.cpp:4098
bool fUseCustomFee
Definition: wallet.h:740
bool HaveSpendingKeyForPaymentAddress(const libzcash::SaplingPaymentAddress &zaddr) const
Returns true if the wallet contains the spending key.
Definition: wallet.cpp:4738
bool EraseDestData(const CTxDestination &dest, const std::string &key)
Erases a destination data tuple in the store and on disk.
Definition: wallet.cpp:4085
unsigned int GetKeyPoolSize()
Definition: wallet.cpp:4691
std::set< SaplingOutPoint > setLockedNotes
Definition: wallet.h:774
CAmount GetCredit(const CTxOut &txout, const isminefilter &filter) const
Definition: wallet.cpp:4603
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:607
static CFeeRate minTxFee
Fees smaller than this (in upiv) are considered zero fee (for transaction creation) We are ~100 times...
Definition: wallet.h:1129
void SetNull()
Definition: wallet.cpp:4546
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:1245
std::atomic< int64_t > nTimeBestReceived
Definition: wallet.h:631
bool fWalletUnlockStaking
Definition: wallet.h:722
CAmount nCustomFee
Definition: wallet.h:741
bool IsFromMe(const CTransactionRef &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:4625
CAmount GetChange(const CTxOut &txout) const
Definition: wallet.cpp:4610
~CWallet()
Definition: wallet.cpp:4540
SaplingScriptPubKeyMan * GetSaplingScriptPubKeyMan() const
Definition: wallet.h:712
std::string GetUniqueWalletBackupName() const
Definition: wallet.cpp:4529
bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
Adds a destination data tuple to the store, and saves it to disk.
Definition: wallet.cpp:4076
std::map< CKeyID, CKeyMetadata > mapKeyMetadata
Definition: wallet.h:726
int nWalletVersion
the current wallet version: clients below this version are not able to load the wallet
Definition: wallet.h:594
unsigned int GetStakingKeyPoolSize()
Definition: wallet.cpp:4696
libzcash::SaplingPaymentAddress GenerateNewSaplingZKey(std::string label="")
Generates new Sapling key.
Definition: wallet.cpp:4710
static const CAmount DEFAULT_STAKE_SPLIT_THRESHOLD
Definition: wallet.h:679
bool LoadSaplingPaymentAddress(const libzcash::SaplingPaymentAddress &addr, const libzcash::SaplingIncomingViewingKey &ivk)
Adds a Sapling payment address -> incoming viewing key map entry, without saving it to disk (used by ...
Definition: wallet.cpp:4744
void ClearNoteWitnessCache()
clear note witness cache
Definition: wallet.cpp:4726
bool AddSaplingIncomingViewingKeyW(const libzcash::SaplingIncomingViewingKey &ivk, const libzcash::SaplingPaymentAddress &addr)
Definition: wallet.cpp:4730
std::atomic< bool > fScanningWallet
Definition: wallet.h:581
int frequency
Definition: wallet.h:746
unsigned int nMasterKeyMaxID
Definition: wallet.h:730
boost::signals2::signal< void(CWallet *wallet, const CWDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:1233
int64_t nOrderPosNext
Definition: wallet.h:771
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1242
bool AddCryptedSaplingSpendingKeyW(const libzcash::SaplingExtendedFullViewingKey &extfvk, const std::vector< unsigned char > &vchCryptedSecret)
Definition: wallet.cpp:4734
static std::atomic< bool > fFlushScheduled
Definition: wallet.h:579
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:325
char fFromMe
Definition: wallet.h:345
bool isAbandoned() const
Definition: wallet.h:546
mapValue_t mapValue
Definition: wallet.h:335
CTransactionRef tx
Definition: wallet.h:364
const CWallet * pwallet
Definition: wallet.h:327
Optional< std::pair< libzcash::SaplingNotePlaintext, libzcash::SaplingPaymentAddress > > RecoverSaplingNote(const SaplingOutPoint &op, const std::set< uint256 > &ovks) const
Definition: wallet.cpp:4894
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:4477
void setConflicted()
Definition: wallet.h:555
int GetDepthAndMempool(bool &fConflicted) const
Definition: wallet.cpp:4817
bool AcceptToMemoryPool(CValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Pass this transaction to the mempool.
Definition: wallet.cpp:4501
unsigned int nTimeSmart
time received by this node
Definition: wallet.h:344
bool HasP2CSInputs() const
checks whether a tx has P2CS inputs or not
Definition: wallet.cpp:4925
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.cpp:4949
CAmount nShieldedChangeCached
Definition: wallet.h:359
bool IsCoinStake() const
Definition: wallet.h:563
CAmount GetShieldedChange() const
Definition: wallet.cpp:4939
int GetBlocksToMaturity() const
Definition: wallet.cpp:4486
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: wallet.cpp:4824
CAmount GetChange() const
Definition: wallet.cpp:4930
bool IsTrusted() const
Definition: wallet.cpp:4777
bool isConflicted() const
Definition: wallet.h:554
Confirmation m_confirm
Definition: wallet.h:394
AmountType
position in ordered transaction list
Definition: wallet.h:349
@ CREDIT
Definition: wallet.h:349
@ AVAILABLE_CREDIT
Definition: wallet.h:349
@ DEBIT
Definition: wallet.h:349
@ IMMATURE_CREDIT
Definition: wallet.h:349
void SetSaplingNoteData(mapSaplingNoteData_t &noteData)
Definition: wallet.cpp:4852
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned, only used at serialization/deserializat...
Definition: wallet.h:332
bool fStakeDelegationVoided
Definition: wallet.h:354
Optional< std::pair< libzcash::SaplingNotePlaintext, libzcash::SaplingPaymentAddress > > DecryptSaplingNote(const SaplingOutPoint &op) const
Definition: wallet.cpp:4866
bool fShieldedChangeCached
Definition: wallet.h:358
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:337
mapSaplingNoteData_t mapSaplingNoteData
Definition: wallet.h:336
void setAbandoned()
Definition: wallet.h:547
bool IsInMainChainImmature() const
Definition: wallet.cpp:4493
CAmount GetShieldedAvailableCredit(bool fUseCache=true) const
Definition: wallet.cpp:4954
void setUnconfirmed()
Definition: wallet.h:557
void BindWallet(CWallet *pwalletIn)
Definition: wallet.cpp:4846
const uint256 & GetHash() const
Definition: wallet.h:561
bool fChangeCached
Definition: wallet.h:355
bool fInMempool
Definition: wallet.h:356
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:338
bool isConfirmed() const
Definition: wallet.h:558
CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS]
Definition: wallet.h:352
void MarkDirty()
make sure balances are recalculated
Definition: wallet.cpp:4833
void Init(const CWallet *pwalletIn)
Definition: wallet.cpp:4757
CWalletTx(const CWallet *pwalletIn, CTransactionRef arg)
Definition: wallet.cpp:4751
bool IsCoinBase() const
Definition: wallet.h:562
CAmount nChangeCached
Definition: wallet.h:357
unsigned int nTimeReceived
Definition: wallet.h:339
int64_t nOrderPos
Definition: wallet.h:346
A signature creator that just produces 72-byte empty signatyres.
Definition: sign.h:94
Fast randomness source.
Definition: random.h:107
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:197
An outpoint - a combination of a transaction hash and an index n into its sapling output description ...
Definition: transaction.h:82
int64_t GetKeyCreationTime(const libzcash::SaplingIncomingViewingKey &ivk)
void AddToSaplingSpends(const uint256 &nullifier, const uint256 &wtxid)
Keep track of the used nullifier.
CAmount GetCredit(const CWalletTx &tx, const isminefilter &filter, const bool fUnspent=false) const
Return the shielded credit of the tx.
Optional< std::pair< libzcash::SaplingNotePlaintext, libzcash::SaplingPaymentAddress > > TryToRecoverNote(const CWalletTx &tx, const SaplingOutPoint &op)
Try to recover the note using the wallet's ovks (mostly used when the outpoint is a debit)
CAmount GetShieldedChange(const CWalletTx &wtx) const
Return the shielded change of the tx.
A shielded input to a transaction.
uint256 nullifier
The nullifier of the input note.
A signature creator for transactions.
Definition: sign.h:73
Access to the wallet database.
Definition: walletdb.h:112
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:974
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:191
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:70
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:270
DBErrors ZapWalletTx(CWallet *pwallet, std::vector< CWalletTx > &vWtx)
Definition: walletdb.cpp:795
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:87
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:196
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:206
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:117
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:102
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:964
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:217
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:225
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:92
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:969
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:979
bool WriteWitnessCacheSize(int64_t nWitnessCacheSize)
Definition: walletdb.cpp:186
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:211
bool WriteWatchOnly(const CScript &script)
Definition: walletdb.cpp:201
bool EraseTx(uint256 hash)
Definition: walletdb.cpp:97
bool WriteStakeSplitThreshold(const CAmount &nStakeSplitThreshold)
Definition: walletdb.cpp:230
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:82
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:959
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:75
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:635
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1324
bool isReserved() const
Definition: wallet.h:1343
std::string ToString() const
Definition: uint256.cpp:65
bool IsNull() const
Definition: uint256.h:36
std::string GetHex() const
Definition: uint256.cpp:21
unsigned char * begin()
Definition: uint256.h:63
static Optional< SaplingNotePlaintext > decrypt(const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk, const uint256 &cmu)
Definition: note.cpp:115
static Optional< SaplingOutgoingPlaintext > decrypt(const SaplingOutCiphertext &ciphertext, const uint256 &ovk, const uint256 &cv, const uint256 &cm, const uint256 &epk)
Definition: note.cpp:90
Sapling functions.
Definition: address.h:30
bool empty() const
Definition: prevector.h:281
size_type size() const
Definition: prevector.h:277
160-bit opaque blob.
Definition: uint256.h:127
256-bit opaque blob.
Definition: uint256.h:138
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:63
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:19
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:18
boost::variant< CTxDestination, libzcash::SaplingPaymentAddress > CWDestination
void UnlockCoin(const COutPoint &output)
Definition: wallet.cpp:3960
CAmount GetImmatureDelegatedBalance() const
Definition: wallet.cpp:2280
void GetAvailableP2CSCoins(std::vector< COutput > &vCoins) const
Available coins (P2CS)
Definition: wallet.cpp:2362
CAmount GetImmatureWatchOnlyBalance() const
Definition: wallet.cpp:2303
bool SelectCoinsToSpend(const std::vector< COutput > &vAvailableCoins, const CAmount &nTargetValue, std::set< std::pair< const CWalletTx *, unsigned int > > &setCoinsRet, CAmount &nValueRet, const CCoinControl *coinControl=nullptr) const
Available coins (spending)
Definition: wallet.cpp:2845
CAmount loopTxsBalance(const std::function< void(const uint256 &, const CWalletTx &, CAmount &)> &method) const
Definition: wallet.cpp:2150
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:3757
CAmount GetUnconfirmedShieldedBalance() const
Definition: wallet.cpp:2357
static std::string ParseIntoAddress(const CWDestination &dest, const std::string &purpose)
Definition: wallet.cpp:3630
bool DelAddressBook(const CWDestination &address, const CChainParams::Base58Type addrType=CChainParams::PUBKEY_ADDRESS)
Definition: wallet.cpp:3659
CAmount GetDelegatedBalance() const
Definition: wallet.cpp:2210
void UnlockAllNotes()
Definition: wallet.cpp:3978
CAmount GetLegacyBalance(const isminefilter &filter, int minDepth) const
Definition: wallet.cpp:2316
std::map< std::pair< CTxDestination, Optional< CTxDestination > >, std::vector< COutput > > ListCoins() const
Return list of available coins and locked coins grouped by non-change output address.
Definition: wallet.cpp:2909
std::string GetPurposeForAddressBookEntry(const CWDestination &address) const
Definition: wallet.cpp:3679
void LockNote(const SaplingOutPoint &op)
Definition: wallet.cpp:3954
void KeepKey()
Definition: wallet.cpp:3932
CWallet::CommitResult CommitTransaction(CTransactionRef tx, CReserveKey &opReservekey, CConnman *connman)
Definition: wallet.cpp:3510
bool GetKeyFromPool(CPubKey &key, const uint8_t &type=HDChain::ChangeType::EXTERNAL)
Definition: wallet.cpp:3752
void LoadAddressBookPurpose(const CWDestination &dest, const std::string &strPurpose)
Definition: wallet.cpp:3705
size_t KeypoolCountExternalKeys()
Definition: wallet.cpp:3729
CAmount GetImmatureColdStakingBalance() const
Definition: wallet.cpp:2273
CAmount GetColdStakingBalance() const
Definition: wallet.cpp:2188
bool CreateTransaction(const std::vector< CRecipient > &vecSend, CTransactionRef &txRet, CReserveKey &reservekey, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, const CCoinControl *coinControl=nullptr, bool sign=true, CAmount nFeePay=0, bool fIncludeDelegated=false, bool *fStakeDelegationVoided=nullptr, int nExtraSize=0, int nMinDepth=0)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: wallet.cpp:3040
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:3584
Balance GetBalance(int min_depth=0) const
Definition: wallet.cpp:2121
std::set< std::set< CTxDestination > > GetAddressGroupings()
Definition: wallet.cpp:3804
int GetLastBlockHeightLockWallet() const
Get last block processed height locking the wallet.
Definition: wallet.cpp:3320
bool SelectCoinsMinConf(const CAmount &nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector< COutput > vCoins, std::set< std::pair< const CWalletTx *, unsigned int > > &setCoinsRet, CAmount &nValueRet) const
Select coins until nTargetValue is reached.
Definition: wallet.cpp:2754
CAmount GetLockedShieldCoins() const
Definition: wallet.cpp:2236
bool GetMasternodeVinAndKeys(CPubKey &pubKeyRet, CKey &keyRet, const COutPoint &collateralOut, bool fValidateCollateral, std::string &strError)
Get 10000 PIV output and keys which can be used for the Masternode.
Definition: wallet.cpp:2437
CAmount GetImmatureBalance() const
Definition: wallet.cpp:2266
bool IsLockedNote(const SaplingOutPoint &op) const
Definition: wallet.cpp:3992
CAmount GetLockedCoins() const
Definition: wallet.cpp:2218
std::set< SaplingOutPoint > ListLockedNotes()
Definition: wallet.cpp:4004
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:3611
CAmount GetStakingBalance(const bool fIncludeColdStaking=true) const
Definition: wallet.cpp:2196
bool FundTransaction(CMutableTransaction &tx, CAmount &nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate &specificFeeRate, int &nChangePosInOut, std::string &strFailReason, bool includeWatching, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, const CTxDestination &destChange=CNoDestination())
Definition: wallet.cpp:2965
void LoadAddressBookName(const CWDestination &dest, const std::string &strName)
Definition: wallet.cpp:3700
bool AvailableCoins(std::vector< COutput > *pCoins, const CCoinControl *coinControl=nullptr, AvailableCoinsFilter coinsFilter=AvailableCoinsFilter()) const
populate vCoins with vector of available COutputs.
Definition: wallet.cpp:2555
bool SetStakeSplitThreshold(const CAmount sst)
Definition: wallet.cpp:4010
bool CreateCoinStake(const CBlockIndex *pindexPrev, unsigned int nBits, CMutableTransaction &txNew, int64_t &nTxNewTime, std::vector< CStakeableOutput > *availableCoins, bool stopOnNewBlock=true) const
Definition: wallet.cpp:3367
CAmount GetWatchOnlyBalance() const
Definition: wallet.cpp:2287
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:3734
bool CreateBudgetFeeTX(CTransactionRef &tx, const uint256 &hash, CReserveKey &keyChange, CAmount fee)
Definition: wallet.cpp:2944
std::vector< COutput > GetOutputsFromCoinControl(const CCoinControl *coinControl)
Return the selected known outputs.
Definition: wallet.cpp:3023
std::string GetNameForAddressBookEntry(const CWDestination &address) const
Definition: wallet.cpp:3686
CAmount GetUnconfirmedWatchOnlyBalance() const
Definition: wallet.cpp:2295
void UnlockAllCoins()
Definition: wallet.cpp:3972
bool HasDelegator(const CTxOut &out) const
Definition: wallet.cpp:3715
std::map< libzcash::SaplingPaymentAddress, std::vector< SaplingNoteEntry > > ListNotes() const
Return list of available shield notes and locked shield notes grouped by sapling address.
Definition: wallet.cpp:2939
bool HasAddressBook(const CWDestination &address) const
Definition: wallet.cpp:3710
CAmount GetAvailableBalance(bool fIncludeDelegated=true, bool fIncludeShielded=true) const
Definition: wallet.cpp:2162
OutputAvailabilityResult CheckOutputAvailability(const CTxOut &output, const unsigned int outIndex, const uint256 &wtxid, const CCoinControl *coinControl, const bool fCoinsSelected, const bool fIncludeColdStaking, const bool fIncludeDelegated, const bool fIncludeLocked) const
Definition: wallet.cpp:2511
std::set< COutPoint > ListLockedCoins()
Definition: wallet.cpp:3998
bool SetAddressBook(const CWDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3642
bool IsLockedCoin(const uint256 &hash, unsigned int n) const
Definition: wallet.cpp:3984
bool GetReservedKey(CPubKey &pubkey, bool internal=false)
Definition: wallet.cpp:3901
CAmount GetUnconfirmedBalance(isminetype filter=ISMINE_SPENDABLE_ALL) const
Definition: wallet.cpp:2258
std::string ToString() const
Definition: wallet.cpp:3489
CAmount GetAvailableShieldedBalance(bool fUseCache=true) const
Definition: wallet.cpp:2351
void LockCoin(const COutPoint &output)
Definition: wallet.cpp:3948
std::map< CTxDestination, CAmount > GetAddressBalances()
Definition: wallet.cpp:3762
bool StakeableCoins(std::vector< CStakeableOutput > *pCoins=nullptr)
Available coins (staking)
Definition: wallet.cpp:2709
void KeepKey(int64_t nIndex)
Definition: wallet.cpp:3739
void ReturnKey(int64_t nIndex, const bool internal=false, const bool staking=false)
Definition: wallet.cpp:3744
Optional< AddressBook::CAddressBookData > GetAddressBookEntry(const CWDestination &address) const
Definition: wallet.cpp:3693
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
Definition: wallet.cpp:3887
void ReturnKey()
Definition: wallet.cpp:3940
bool CreateCoinstakeOuts(const CPivStake &stakeInput, std::vector< CTxOut > &vout, CAmount nTotal) const
Definition: wallet.cpp:3325
bool SignCoinStake(CMutableTransaction &txNew) const
Definition: wallet.cpp:3475
std::map< CTxDestination, std::vector< COutput > > AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue, bool fIncludeColdStaking)
Definition: wallet.cpp:2637
void UnlockNote(const SaplingOutPoint &op)
Definition: wallet.cpp:3966
CAmount GetImmatureCredit(bool fUseCache=true, const isminefilter &filter=ISMINE_SPENDABLE_ALL) const
Definition: wallet.cpp:1638
std::vector< CWalletTx > getWalletTxs()
Definition: wallet.cpp:175
CAmount GetImmatureWatchOnlyCredit(const bool fUseCache=true) const
Definition: wallet.cpp:1740
bool IsSaplingSpent(const SaplingOutPoint &op) const
Definition: wallet.cpp:711
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
Definition: wallet.cpp:306
bool Lock()
Definition: wallet.cpp:397
CallResult< CTxDestination > getNewAddress(const std::string &addressLabel, const std::string purpose, const CChainParams::Base58Type addrType=CChainParams::PUBKEY_ADDRESS)
Definition: wallet.cpp:196
void SyncTransaction(const CTransactionRef &tx, const CWalletTx::Confirmation &confirm)
Definition: wallet.cpp:1260
std::vector< CKeyID > GetAffectedKeys(const CScript &spk)
Definition: wallet.cpp:118
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: wallet.cpp:327
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
Definition: wallet.cpp:2063
CAmount GetAvailableWatchOnlyCredit(const bool fUseCache=true) const
Definition: wallet.cpp:1749
bool SetMaxVersion(int nVersion)
change which version we're allowed to upgrade to (note that this does not immediately imply upgrading...
Definition: wallet.cpp:606
bool IsAmountCached(AmountType type, const isminefilter &filter) const
Definition: wallet.cpp:1574
bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
Definition: wallet.cpp:296
ScriptPubKeyMan * GetScriptPubKeyMan() const
Get spkm.
Definition: wallet.cpp:701
void MarkDirty()
Definition: wallet.cpp:892
bool AddWatchOnly(const CScript &dest) override
Adds a watch-only address to the store, and saves it to disk.
Definition: wallet.cpp:349
bool RemoveWatchOnly(const CScript &dest) override
Definition: wallet.cpp:358
bool Upgrade(std::string &error, const int prevVersion)
Upgrade wallet to HD and Sapling if needed.
Definition: wallet.cpp:1824
const CKeyingMaterial & GetEncryptionKey() const
Definition: wallet.cpp:691
CAmount GetColdStakingCredit(bool fUseCache=true) const
Definition: wallet.cpp:1694
void EraseFromWallet(const uint256 &hash)
Definition: wallet.cpp:1437
std::set< uint256 > GetConflicts(const uint256 &txid) const
Get wallet transactions that conflict with given transaction (spend same outputs)
Definition: wallet.cpp:618
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:457
CBlockIndex * ScanForWalletTransactions(CBlockIndex *pindexStart, CBlockIndex *pindexStop, const WalletRescanReserver &reserver, bool fUpdate=false, bool fromStartup=false)
Scan the block chain (starting in pindexStart) for transactions from or to us.
Definition: wallet.cpp:1896
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1448
bool SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr, bool fExplicit=false)
signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVe...
Definition: wallet.cpp:580
bool LoadToWallet(CWalletTx &wtxIn)
Definition: wallet.cpp:983
void RelayWalletTransaction(CConnman *connman)
Definition: wallet.cpp:2036
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Definition: wallet.cpp:1500
bool Unlock(const SecureString &strWalletPassphrase, bool anonimizeOnly=false)
Definition: wallet.cpp:376
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
Definition: wallet.cpp:901
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid)
Definition: wallet.cpp:745
CAmount GetCachableAmount(AmountType type, const isminefilter &filter, bool recalculate=false) const
Definition: wallet.cpp:1565
bool IsKeyUsed(const CPubKey &vchPubKey) const
Definition: wallet.cpp:878
void UpdateTimeSmart()
Update smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:1554
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:1580
void BlockUntilSyncedToCurrentChain()
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
Definition: wallet.cpp:1383
void SetBestChain(const CBlockLocator &loc) override
Notifies listeners of the new active block chain on-disk.
Definition: wallet.cpp:511
void UpdateTimeFirstKey(int64_t nCreateTime)
Update wallet first key creation time.
Definition: wallet.cpp:315
CallResult< CTxDestination > getNewStakingAddress(const std::string &label)
Definition: wallet.cpp:191
CAmount GetLockedCredit() const
Definition: wallet.cpp:1705
int64_t IncOrderPosNext(WalletBatch *batch=nullptr)
Increment the next transaction order id.
Definition: wallet.cpp:866
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1144
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret) override
Adds an encrypted key to the store, and saves it to disk.
Definition: wallet.cpp:279
void ReacceptWalletTransactions(bool fFirstLoad=false)
Definition: wallet.cpp:2000
bool FindNotesDataAndAddMissingIVKToKeystore(const CTransaction &tx, Optional< mapSaplingNoteData_t > &saplingNoteData)
Definition: wallet.cpp:1026
bool IsHDEnabled() const
Whether the wallet is hd or not //.
Definition: wallet.cpp:156
void ResendWalletTransactions(CConnman *connman) override
Tells listeners to broadcast their data.
Definition: wallet.cpp:2068
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, const isminefilter &filter) const
Definition: wallet.cpp:1754
void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override
Notifies listeners when the block chain tip advances.
Definition: wallet.cpp:2108
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:773
int64_t GetTxTime() const
Definition: wallet.cpp:1541
bool HasSaplingSPKM() const
Definition: wallet.cpp:706
bool IsChange(const CTxOut &txout) const
Definition: wallet.cpp:1515
int64_t GetKeyCreationTime(const CWDestination &dest)
Definition: wallet.cpp:221
bool ActivateSaplingWallet(bool memOnly=false)
Definition: wallet.cpp:142
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, const CWalletTx::Confirmation &confirm, bool fUpdate)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1077
const CWalletTx * GetWalletTx(const uint256 &hash) const
Definition: wallet.cpp:166
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
Definition: wallet.cpp:252
CAmount GetCredit(const isminefilter &filter, bool recalculate=false) const
Definition: wallet.cpp:1616
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1859
CAmount GetColdStakingDebit(bool fUseCache=true) const
Definition: wallet.cpp:1606
void SyncMetaData(std::pair< typename TxSpendMap< T >::iterator, typename TxSpendMap< T >::iterator > range)
Definition: wallet.cpp:652
void SyncMetaDataN(std::pair< TxSpendMap< uint256 >::iterator, TxSpendMap< uint256 >::iterator > range)
Definition: wallet.cpp:646
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
Definition: wallet.cpp:371
void SetBestChainInternal(WalletBatch &batch, const CBlockLocator &loc)
Definition: wallet.cpp:517
std::string ToString() const
Definition: wallet.cpp:72
bool LoadCScript(const CScript &redeemScript)
Definition: wallet.cpp:334
bool SetupSPKM(bool newKeypool=true, bool memOnly=false)
Generates hd wallet //.
Definition: wallet.cpp:133
CAmount GetStakeDelegationDebit(bool fUseCache=true) const
Definition: wallet.cpp:1611
std::set< uint256 > GetConflicts() const
Definition: wallet.cpp:2052
bool IsUsed(const CTxDestination address) const
Definition: wallet.cpp:1462
void TransactionAddedToMempool(const CTransactionRef &tx) override
Notifies listeners of a transaction having been added to mempool.
Definition: wallet.cpp:1269
bool InMempool() const
Definition: wallet.cpp:2031
CAmount GetAvailableCredit(bool fUseCache=true, const isminefilter &filter=ISMINE_SPENDABLE) const
Definition: wallet.cpp:1647
bool HasEncryptionKeys() const
Definition: wallet.cpp:696
void BlockConnected(const std::shared_ptr< const CBlock > &pblock, const CBlockIndex *pindex) override
Notifies listeners of a block being connected.
Definition: wallet.cpp:1319
void MarkAffectedTransactionsDirty(const CTransaction &tx)
Definition: wallet.cpp:1408
void ChainTipAdded(const CBlockIndex *pindex, const CBlock *pblock, SaplingMerkleTree saplingTree)
Definition: wallet.cpp:503
CAmount GetStakeDelegationCredit(bool fUseCache=true) const
Definition: wallet.cpp:1699
void AddExternalNotesDataToTx(CWalletTx &wtx) const
Definition: wallet.cpp:1040
void MarkConflicted(const uint256 &hashBlock, int conflicting_height, const uint256 &hashTx)
Definition: wallet.cpp:1203
void TransactionRemovedFromMempool(const CTransactionRef &ptx, MemPoolRemovalReason reason) override
Notifies listeners of a transaction leaving mempool.
Definition: wallet.cpp:1281
bool IsSaplingUpgradeEnabled() const
Whether the wallet supports Sapling or not //.
Definition: wallet.cpp:161
bool IsSpent(const COutPoint &outpoint) const
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:720
void BlockDisconnected(const std::shared_ptr< const CBlock > &pblock, const uint256 &blockHash, int nBlockHeight, int64_t blockTime) override
Notifies listeners of a block being disconnected.
Definition: wallet.cpp:1360
@ CT_UPDATED
Definition: guiinterface.h:26
@ CT_DELETED
Definition: guiinterface.h:27
@ CT_NEW
Definition: guiinterface.h:25
CClientUIInterface uiInterface
Definition: init.cpp:109
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:193
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:90
@ SIGHASH_ALL
Definition: interpreter.h:24
isminetype IsMine(const CKeyStore &keystore, const CTxDestination &dest)
Definition: ismine.cpp:29
isminetype
IsMine() return codes.
Definition: ismine.h:19
@ ISMINE_SPENDABLE_NO_DELEGATED
Definition: ismine.h:32
@ ISMINE_ALL
Definition: ismine.h:35
@ ISMINE_SPENDABLE_ALL
Definition: ismine.h:33
@ ISMINE_COLD
Indicates that we have the staking key of a P2CS.
Definition: ismine.h:24
@ ISMINE_SPENDABLE_SHIELDED
Indicates that we have the spending key of a shielded spend/output.
Definition: ismine.h:30
@ ISMINE_WATCH_ONLY_SHIELDED
Indicates that we don't have the spending key of a shielded spend/output.
Definition: ismine.h:28
@ ISMINE_SPENDABLE
Definition: ismine.h:22
@ ISMINE_NO
Definition: ismine.h:20
@ ISMINE_WATCH_ONLY
Definition: ismine.h:21
@ ISMINE_SPENDABLE_TRANSPARENT
Definition: ismine.h:31
@ ISMINE_SPENDABLE_DELEGATED
Indicates that we have the spending key of a P2CS.
Definition: ismine.h:26
uint8_t isminefilter
used for bitflags of isminetype
Definition: ismine.h:39
bool Stake(const CBlockIndex *pindexPrev, CStakeInput *stakeInput, unsigned int nBits, int64_t &nTimeTx)
Definition: kernel.cpp:115
@ LOCK
Definition: lockunlock.h:16
#define LogPrint(category,...)
Definition: logging.h:163
const std::string SHIELDED_RECEIVE
Definition: addressbook.cpp:17
const std::string COLD_STAKING
Definition: addressbook.cpp:15
bool IsExchangePurpose(const std::string &purpose)
Definition: addressbook.cpp:32
bool IsColdStakingPurpose(const std::string &purpose)
Definition: addressbook.cpp:22
@ STAKING
Definition: logging.h:58
double GuessVerificationProgress(const CBlockIndex *pindex, bool fSigchecks)
Guess how far we are in the verification process at the given block index.
Definition: checkpoints.cpp:43
@ UPGRADE_V5_0
Definition: params.h:36
const CTxDestination * GetTransparentDestination(const CWDestination &dest)
bool IsValidDestination(const CWDestination &address)
std::string EncodeDestination(const CWDestination &address, const CChainParams::Base58Type addrType)
const libzcash::SaplingPaymentAddress * GetShieldedDestination(const CWDestination &dest)
Definition: uint256.h:212
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:80
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:12
#define PACKAGE_NAME
Definition: pivx-config.h:366
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:45
CFeeRate dustRelayFee
Definition: policy.cpp:19
@ MSG_TX
Definition: protocol.h:436
bool GetProRegCollateral(const CTransactionRef &tx, COutPoint &outRet)
Definition: providertx.cpp:210
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:580
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:586
int GetRandInt(int nMax) noexcept
Definition: random.cpp:591
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:217
const char * prefix
Definition: rest.cpp:564
const char * name
Definition: rest.cpp:37
std::map< SaplingOutPoint, SaplingNoteData > mapSaplingNoteData_t
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:43
@ OP_RETURN
Definition: script.h:87
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:61
unsigned int GetSerializeSize(const std::array< T, N > &item)
array
Definition: serialize.h:847
bool ShutdownRequested()
Definition: shutdown.cpp:22
void StartShutdown()
Definition: shutdown.cpp:14
void UpdateTransaction(CMutableTransaction &tx, unsigned int nIn, const SignatureData &data)
Definition: sign.cpp:186
bool IsSolvable(const CKeyStore &store, const CScript &script, bool fColdStaking)
Definition: sign.cpp:394
bool SignSignature(const CKeyStore &keystore, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType, bool fColdStake)
Produce a script signature for a transaction.
Definition: sign.cpp:192
bool ProduceSignature(const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata, SigVersion sigversion, bool fColdStake, ScriptError *serror)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:153
CSporkManager sporkManager
Definition: spork.cpp:29
@ SPORK_19_COLDSTAKING_MAINTENANCE
Definition: sporkid.h:26
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Parse a standard scriptPubKey with one or more destination addresses.
Definition: standard.cpp:195
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:90
const char * GetTxnOutputType(txnouttype t)
Definition: standard.cpp:18
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:286
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a PIVX scriptPubKey for the given CTxDestination.
Definition: standard.cpp:278
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet, bool fColdStake)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:162
boost::variant< CNoDestination, CKeyID, CScriptID, CExchangeKeyID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:72
txnouttype
Definition: standard.h:46
@ TX_PUBKEYHASH
Definition: standard.h:50
@ TX_PUBKEY
Definition: standard.h:49
@ TX_COLDSTAKE
Definition: standard.h:54
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:154
A mutable version of CTransaction.
Definition: transaction.h:409
Optional< std::vector< uint8_t > > extraPayload
Definition: transaction.h:416
Optional< SaplingTxData > sapData
Definition: transaction.h:415
SigVersion GetRequiredSigVersion() const
Definition: transaction.h:450
std::vector< CTxOut > vout
Definition: transaction.h:411
std::vector< CTxIn > vin
Definition: transaction.h:410
bool isSaplingVersion() const
Definition: transaction.h:436
Definition: wallet.h:292
std::set< CTxDestination > * onlyFilteredDest
Definition: wallet.h:813
unsigned int nMaximumCount
Definition: wallet.h:820
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: wallet.h:1049
CAmount m_mine_trusted_shield
Trusted shield, at depth=GetBalance.min_depth or more.
Definition: wallet.h:1052
CAmount m_mine_untrusted_pending
Untrusted, but in mempool (pending)
Definition: wallet.h:1050
CAmount m_mine_immature
Immature coinbases/coinstakes in the main chain.
Definition: wallet.h:1051
CAmount m_mine_untrusted_shielded_balance
Untrusted shield, but in mempool (pending)
Definition: wallet.h:1053
CAmount m_mine_cs_delegated_trusted
Trusted, at depth=GetBalance.min_depth or more. Part of m_mine_trusted as well.
Definition: wallet.h:1054
CWallet::CommitStatus status
Definition: wallet.h:1106
CValidationState state
Definition: wallet.h:1107
void Set(isminefilter filter, CAmount value)
Definition: ismine.h:57
CAmount m_value[ISMINE_ENUM_ELEMENTS]
Definition: ismine.h:52
std::bitset< ISMINE_ENUM_ELEMENTS > m_cached
Definition: ismine.h:51
void Reset()
Definition: ismine.h:53
bool operator()(const std::pair< CAmount, std::pair< const CWalletTx *, unsigned int > > &t1, const std::pair< CAmount, std::pair< const CWalletTx *, unsigned int > > &t2) const
Definition: wallet.cpp:65
CAmount nMNCollateralAmt
Definition: params.h:184
int nStakeMinDepth
Definition: params.h:190
bool NetworkUpgradeActive(int nHeight, Consensus::UpgradeIndex idx) const
Returns true if the given network upgrade is active as of the given block height.
Definition: params.cpp:12
#define AssertLockNotHeld(cs)
Definition: sync.h:76
#define LOCK2(cs1, cs2)
Definition: sync.h:221
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:247
#define AssertLockHeld(cs)
Definition: sync.h:75
ArgsManager gArgs
Definition: system.cpp:89
std::atomic< bool > fMasterNode
Definition: system.cpp:87
void runCommand(std::string strCommand)
Definition: system.cpp:1031
bool error(const char *fmt, const Args &... args)
Definition: system.h:77
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a Optional result.
Definition: system.h:65
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:50
int64_t GetAdjustedTime()
Definition: timedata.cpp:36
#define strprintf
Definition: tinyformat.h:1056
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:456
bool IsFinalTx(const CTransactionRef &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: tx_verify.cpp:12
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:295
@ BLOCK
Removed for reorganization.
@ CONFLICT
Removed for block.
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:175
uint256 uint256S(const char *str)
Definition: uint256.h:157
bool NetworkUpgradeActive(int nHeight, const Consensus::Params &params, Consensus::UpgradeIndex idx)
Returns true if the given network upgrade is active as of the given block height.
Definition: upgrades.cpp:107
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:13
std::string FormatMoney(const CAmount &n, bool fPlus)
Money parsing/formatting utilities.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
@ SAFE_CHARS_FILENAME
Chars allowed in filenames.
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: utiltime.cpp:61
std::string FormatISO8601DateTimeForBackup(int64_t nTime)
Definition: utiltime.cpp:115
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: utiltime.cpp:27
bool CheckFinalTx(const CTransactionRef &tx, int flags)
Check if transaction will be final in the next block to be created.
Definition: validation.cpp:224
CTxMemPool mempool(::minRelayTxFee)
CFeeRate minRelayTxFee
Fees smaller than this (in upiv) are considered zero fee (for relaying, mining and transaction creati...
Definition: validation.cpp:108
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:206
int64_t GetMasternodePayment(int nHeight)
Definition: validation.cpp:852
CAmount GetBlockValue(int nHeight)
Definition: validation.cpp:816
std::atomic< bool > fImporting
Definition: validation.cpp:94
BlockMap mapBlockIndex
Definition: validation.cpp:82
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectInsaneFee, bool ignoreFees)
(try to) add transaction to memory pool
Definition: validation.cpp:649
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos)
Definition: validation.cpp:758
std::atomic< bool > fReindex
Definition: validation.cpp:95
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:84
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:181
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:345
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool &pool)
Estimate the minimum fee considering user set parameters and the required fee.
Definition: fees.cpp:20
std::vector< CWalletRef > vpwallets
Definition: wallet.cpp:33
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
Settings.
bool bSpendZeroConfChange
Definition: wallet.cpp:42
CAmount maxTxFee
Definition: wallet.cpp:38
bool fPayAtLeastCustomFee
Definition: wallet.cpp:41
unsigned int nTxConfirmTarget
Definition: wallet.cpp:39
bool bdisableSystemnotifications
Definition: wallet.cpp:40
WalletFeature
(client) version numbers for particular wallet features
Definition: wallet.h:104
@ FEATURE_SAPLING
Definition: wallet.h:118
@ FEATURE_WALLETCRYPT
Definition: wallet.h:107
@ FEATURE_PRE_SPLIT_KEYPOOL
Definition: wallet.h:116
@ FEATURE_BASE
Definition: wallet.h:105
@ FEATURE_PRE_PIVX
Definition: wallet.h:110
@ FEATURE_LATEST
Definition: wallet.h:120
std::multimap< T, uint256 > TxSpendMap
Definition: wallet.h:270
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:273
void MaybeCompactWalletDB()
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
Definition: walletdb.cpp:812
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:50
@ DB_TOO_NEW
Definition: walletdb.h:54
@ DB_CORRUPT
Definition: walletdb.h:52
@ DB_LOAD_OK
Definition: walletdb.h:51
@ DB_NONCRITICAL_ERROR
Definition: walletdb.h:53
@ DB_NEED_REWRITE
Definition: walletdb.h:56
CScheduler scheduler