Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Copyright (c) 2014-2020 The Dash Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include <wallet/wallet.h>
8 
9 #include <base58.h>
10 #include <checkpoints.h>
11 #include <chain.h>
12 #include <wallet/coincontrol.h>
13 #include <consensus/consensus.h>
14 #include <consensus/validation.h>
15 #include <fs.h>
16 #include <key.h>
17 #include <keystore.h>
18 #include <validation.h>
19 #include <net.h>
20 #include <policy/fees.h>
21 #include <policy/policy.h>
22 #include <primitives/block.h>
23 #include <primitives/transaction.h>
24 #include <script/script.h>
25 #include <script/sign.h>
26 #include <timedata.h>
27 #include <txmempool.h>
28 #include <util.h>
29 #include <utilmoneystr.h>
30 #include <wallet/fees.h>
31 #include <wallet/walletutil.h>
32 
33 #include <governance/governance.h>
34 #include <keepass.h>
36 #include <spork.h>
37 
38 #include <evo/providertx.h>
39 
42 
43 #include <algorithm>
44 #include <assert.h>
45 #include <future>
46 
47 #include <boost/algorithm/string/replace.hpp>
48 #include <boost/thread.hpp>
49 
51 static std::vector<CWallet*> vpwallets GUARDED_BY(cs_wallets);
52 
53 bool AddWallet(CWallet* wallet)
54 {
56  assert(wallet);
57  std::vector<CWallet*>::const_iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
58  if (i != vpwallets.end()) return false;
59  vpwallets.push_back(wallet);
60  return true;
61 }
62 
63 bool RemoveWallet(CWallet* wallet)
64 {
66  assert(wallet);
67  std::vector<CWallet*>::iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
68  if (i == vpwallets.end()) return false;
69  vpwallets.erase(i);
70  return true;
71 }
72 
73 bool HasWallets()
74 {
76  return !vpwallets.empty();
77 }
78 
79 std::vector<CWallet*> GetWallets()
80 {
82  return vpwallets;
83 }
84 
85 CWallet* GetWallet(const std::string& name)
86 {
88  for (CWallet* wallet : vpwallets) {
89  if (wallet->GetName() == name) return wallet;
90  }
91  return nullptr;
92 }
93 
98 
110 
112 
113 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
114 
121 {
122  bool operator()(const CInputCoin& t1,
123  const CInputCoin& t2) const
124  {
125  return t1.txout.nValue < t2.txout.nValue;
126  }
127 };
128 
129 std::string COutput::ToString() const
130 {
131  return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
132 }
133 
134 class CAffectedKeysVisitor : public boost::static_visitor<void> {
135 private:
137  std::vector<CKeyID> &vKeys;
138 
139 public:
140  CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
141 
142  void Process(const CScript &script) {
143  txnouttype type;
144  std::vector<CTxDestination> vDest;
145  int nRequired;
146  if (ExtractDestinations(script, type, vDest, nRequired)) {
147  for (const CTxDestination &dest : vDest)
148  boost::apply_visitor(*this, dest);
149  }
150  }
151 
152  void operator()(const CKeyID &keyId) {
153  if (keystore.HaveKey(keyId))
154  vKeys.push_back(keyId);
155  }
156 
157  void operator()(const CScriptID &scriptId) {
158  CScript script;
159  if (keystore.GetCScript(scriptId, script))
160  Process(script);
161  }
162 
163  void operator()(const CNoDestination &none) {}
164 };
165 
166 int COutput::Priority() const
167 {
168  for (const auto& d : CPrivateSend::GetStandardDenominations()) {
169  // large denoms have lower value
170  if(tx->tx->vout[i].nValue == d) return (float)COIN / d * 10000;
171  }
172  if(tx->tx->vout[i].nValue < 1*COIN) return 20000;
173 
174  //nondenom return largest first
175  return -(tx->tx->vout[i].nValue/COIN);
176 }
177 
178 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
179 {
180  LOCK(cs_wallet);
181  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
182  if (it == mapWallet.end())
183  return nullptr;
184  return &(it->second);
185 }
186 
187 CPubKey CWallet::GenerateNewKey(WalletBatch &batch, uint32_t nAccountIndex, bool fInternal)
188 {
189  AssertLockHeld(cs_wallet); // mapKeyMetadata
190  bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
191 
192  CKey secret;
193 
194  // Create new metadata
195  int64_t nCreationTime = GetTime();
196  CKeyMetadata metadata(nCreationTime);
197 
198  CPubKey pubkey;
199  // use HD key derivation if HD was enabled during wallet creation
200  if (IsHDEnabled()) {
201  DeriveNewChildKey(batch, metadata, secret, nAccountIndex, fInternal);
202  pubkey = secret.GetPubKey();
203  } else {
204  secret.MakeNewKey(fCompressed);
205 
206  // Compressed public keys were introduced in version 0.6.0
207  if (fCompressed) {
209  }
210 
211  pubkey = secret.GetPubKey();
212  assert(secret.VerifyPubKey(pubkey));
213 
214  // Create new metadata
215  mapKeyMetadata[pubkey.GetID()] = metadata;
216  UpdateTimeFirstKey(nCreationTime);
217 
218  if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
219  throw std::runtime_error(std::string(__func__) + ": AddKey failed");
220  }
221  }
222  return pubkey;
223 }
224 
225 void CWallet::DeriveNewChildKey(WalletBatch &batch, const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal)
226 {
227  CHDChain hdChainTmp;
228  if (!GetHDChain(hdChainTmp)) {
229  throw std::runtime_error(std::string(__func__) + ": GetHDChain failed");
230  }
231 
232  if (!DecryptHDChain(hdChainTmp))
233  throw std::runtime_error(std::string(__func__) + ": DecryptHDChainSeed failed");
234  // make sure seed matches this chain
235  if (hdChainTmp.GetID() != hdChainTmp.GetSeedHash())
236  throw std::runtime_error(std::string(__func__) + ": Wrong HD chain!");
237 
238  CHDAccount acc;
239  if (!hdChainTmp.GetAccount(nAccountIndex, acc))
240  throw std::runtime_error(std::string(__func__) + ": Wrong HD account!");
241 
242  // derive child key at next index, skip keys already known to the wallet
243  CExtKey childKey;
244  uint32_t nChildIndex = fInternal ? acc.nInternalChainCounter : acc.nExternalChainCounter;
245  do {
246  hdChainTmp.DeriveChildExtKey(nAccountIndex, fInternal, nChildIndex, childKey);
247  // increment childkey index
248  nChildIndex++;
249  } while (HaveKey(childKey.key.GetPubKey().GetID()));
250  secretRet = childKey.key;
251 
252  CPubKey pubkey = secretRet.GetPubKey();
253  assert(secretRet.VerifyPubKey(pubkey));
254 
255  // store metadata
256  mapKeyMetadata[pubkey.GetID()] = metadata;
258 
259  // update the chain model in the database
260  CHDChain hdChainCurrent;
261  GetHDChain(hdChainCurrent);
262 
263  if (fInternal) {
264  acc.nInternalChainCounter = nChildIndex;
265  }
266  else {
267  acc.nExternalChainCounter = nChildIndex;
268  }
269 
270  if (!hdChainCurrent.SetAccount(nAccountIndex, acc))
271  throw std::runtime_error(std::string(__func__) + ": SetAccount failed");
272 
273  if (IsCrypted()) {
274  if (!SetCryptedHDChain(batch, hdChainCurrent, false))
275  throw std::runtime_error(std::string(__func__) + ": SetCryptedHDChain failed");
276  }
277  else {
278  if (!SetHDChain(batch, hdChainCurrent, false))
279  throw std::runtime_error(std::string(__func__) + ": SetHDChain failed");
280  }
281 
282  if (!AddHDPubKey(batch, childKey.Neuter(), fInternal))
283  throw std::runtime_error(std::string(__func__) + ": AddHDPubKey failed");
284 }
285 
286 bool CWallet::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
287 {
288  LOCK(cs_wallet);
289  std::map<CKeyID, CHDPubKey>::const_iterator mi = mapHdPubKeys.find(address);
290  if (mi != mapHdPubKeys.end())
291  {
292  const CHDPubKey &hdPubKey = (*mi).second;
293  vchPubKeyOut = hdPubKey.extPubKey.pubkey;
294  return true;
295  }
296  else
297  return CCryptoKeyStore::GetPubKey(address, vchPubKeyOut);
298 }
299 
300 bool CWallet::GetKey(const CKeyID &address, CKey& keyOut) const
301 {
302  LOCK(cs_wallet);
303  std::map<CKeyID, CHDPubKey>::const_iterator mi = mapHdPubKeys.find(address);
304  if (mi != mapHdPubKeys.end())
305  {
306  // if the key has been found in mapHdPubKeys, derive it on the fly
307  const CHDPubKey &hdPubKey = (*mi).second;
308  CHDChain hdChainCurrent;
309  if (!GetHDChain(hdChainCurrent))
310  throw std::runtime_error(std::string(__func__) + ": GetHDChain failed");
311  if (!DecryptHDChain(hdChainCurrent))
312  throw std::runtime_error(std::string(__func__) + ": DecryptHDChainSeed failed");
313  // make sure seed matches this chain
314  if (hdChainCurrent.GetID() != hdChainCurrent.GetSeedHash())
315  throw std::runtime_error(std::string(__func__) + ": Wrong HD chain!");
316 
317  CExtKey extkey;
318  hdChainCurrent.DeriveChildExtKey(hdPubKey.nAccountIndex, hdPubKey.nChangeIndex != 0, hdPubKey.extPubKey.nChild, extkey);
319  keyOut = extkey.key;
320 
321  return true;
322  }
323  else {
324  return CCryptoKeyStore::GetKey(address, keyOut);
325  }
326 }
327 
328 bool CWallet::HaveKey(const CKeyID &address) const
329 {
330  LOCK(cs_wallet);
331  if (mapHdPubKeys.count(address) > 0)
332  return true;
333  return CCryptoKeyStore::HaveKey(address);
334 }
335 
336 bool CWallet::LoadHDPubKey(const CHDPubKey &hdPubKey)
337 {
339 
340  mapHdPubKeys[hdPubKey.extPubKey.pubkey.GetID()] = hdPubKey;
341  return true;
342 }
343 
344 bool CWallet::AddHDPubKey(WalletBatch &batch, const CExtPubKey &extPubKey, bool fInternal)
345 {
347 
348  CHDChain hdChainCurrent;
349  GetHDChain(hdChainCurrent);
350 
351  CHDPubKey hdPubKey;
352  hdPubKey.extPubKey = extPubKey;
353  hdPubKey.hdchainID = hdChainCurrent.GetID();
354  hdPubKey.nChangeIndex = fInternal ? 1 : 0;
355  mapHdPubKeys[extPubKey.pubkey.GetID()] = hdPubKey;
356 
357  // check if we need to remove from watch-only
358  CScript script;
359  script = GetScriptForDestination(extPubKey.pubkey.GetID());
360  if (HaveWatchOnly(script))
361  RemoveWatchOnly(script);
362  script = GetScriptForRawPubKey(extPubKey.pubkey);
363  if (HaveWatchOnly(script))
364  RemoveWatchOnly(script);
365 
366  return batch.WriteHDPubKey(hdPubKey, mapKeyMetadata[extPubKey.pubkey.GetID()]);
367 }
368 
369 bool CWallet::AddKeyPubKeyWithDB(WalletBatch &batch, const CKey& secret, const CPubKey &pubkey)
370 {
371  AssertLockHeld(cs_wallet); // mapKeyMetadata
372 
373  // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
374  // which is overridden below. To avoid flushes, the database handle is
375  // tunneled through to it.
376  bool needsDB = !encrypted_batch;
377  if (needsDB) {
378  encrypted_batch = &batch;
379  }
380  if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
381  if (needsDB) encrypted_batch = nullptr;
382  return false;
383  }
384  if (needsDB) encrypted_batch = nullptr;
385  // check if we need to remove from watch-only
386  CScript script;
387  script = GetScriptForDestination(pubkey.GetID());
388  if (HaveWatchOnly(script)) {
389  RemoveWatchOnly(script);
390  }
391  script = GetScriptForRawPubKey(pubkey);
392  if (HaveWatchOnly(script)) {
393  RemoveWatchOnly(script);
394  }
395 
396  if (!IsCrypted()) {
397  return batch.WriteKey(pubkey,
398  secret.GetPrivKey(),
399  mapKeyMetadata[pubkey.GetID()]);
400  }
401  return true;
402 }
403 
404 
405 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
406 {
407  WalletBatch batch(*database);
408 
409  return CWallet::AddKeyPubKeyWithDB(batch, secret, pubkey);
410 }
411 
412 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
413  const std::vector<unsigned char> &vchCryptedSecret)
414 {
415  if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
416  return false;
417  {
418  LOCK(cs_wallet);
419  if (encrypted_batch)
420  return encrypted_batch->WriteCryptedKey(vchPubKey,
421  vchCryptedSecret,
422  mapKeyMetadata[vchPubKey.GetID()]);
423  else
424  return WalletBatch(*database).WriteCryptedKey(vchPubKey,
425  vchCryptedSecret,
426  mapKeyMetadata[vchPubKey.GetID()]);
427  }
428 }
429 
430 bool CWallet::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &meta)
431 {
432  AssertLockHeld(cs_wallet); // mapKeyMetadata
434  mapKeyMetadata[keyID] = meta;
435  return true;
436 }
437 
438 bool CWallet::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &meta)
439 {
440  AssertLockHeld(cs_wallet); // m_script_metadata
442  m_script_metadata[script_id] = meta;
443  return true;
444 }
445 
446 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
447 {
448  return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
449 }
450 
455 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
456 {
458  if (nCreateTime <= 1) {
459  // Cannot determine birthday information, so set the wallet birthday to
460  // the beginning of time.
461  nTimeFirstKey = 1;
462  } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
463  nTimeFirstKey = nCreateTime;
464  }
465 }
466 
467 bool CWallet::AddCScript(const CScript& redeemScript)
468 {
469  if (!CCryptoKeyStore::AddCScript(redeemScript))
470  return false;
471  return WalletBatch(*database).WriteCScript(Hash160(redeemScript), redeemScript);
472 }
473 
474 bool CWallet::LoadCScript(const CScript& redeemScript)
475 {
476  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
477  * that never can be redeemed. However, old wallets may still contain
478  * these. Do not add them to the wallet and warn. */
479  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
480  {
481  std::string strAddr = EncodeDestination(CScriptID(redeemScript));
482  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",
483  __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
484  return true;
485  }
486 
487  return CCryptoKeyStore::AddCScript(redeemScript);
488 }
489 
491 {
493  return false;
494  const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
497  return WalletBatch(*database).WriteWatchOnly(dest, meta);
498 }
499 
500 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
501 {
502  m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
503  return AddWatchOnly(dest);
504 }
505 
507 {
510  return false;
511  if (!HaveWatchOnly())
512  NotifyWatchonlyChanged(false);
513  if (!WalletBatch(*database).EraseWatchOnly(dest))
514  return false;
515 
516  return true;
517 }
518 
520 {
521  return CCryptoKeyStore::AddWatchOnly(dest);
522 }
523 
524 bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly)
525 {
526  SecureString strWalletPassphraseFinal;
527 
528  if (!IsLocked()) // was already fully unlocked, not only for mixing
529  return true;
530 
531  // Verify KeePassIntegration
532  if (strWalletPassphrase == "keepass" && gArgs.GetBoolArg("-keepass", false)) {
533  try {
534  strWalletPassphraseFinal = keePassInt.retrievePassphrase();
535  } catch (std::exception& e) {
536  LogPrintf("CWallet::Unlock could not retrieve passphrase from KeePass: Error: %s\n", e.what());
537  return false;
538  }
539  } else {
540  strWalletPassphraseFinal = strWalletPassphrase;
541  }
542 
543  CCrypter crypter;
544  CKeyingMaterial _vMasterKey;
545 
546  {
547  LOCK(cs_wallet);
548  for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
549  {
550  if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
551  return false;
552  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
553  continue; // try another master key
554  if (CCryptoKeyStore::Unlock(_vMasterKey, fForMixingOnly)) {
555  if(nWalletBackups == -2) {
556  TopUpKeyPool();
557  LogPrintf("Keypool replenished, re-initializing automatic backups.\n");
558  nWalletBackups = gArgs.GetArg("-createwalletbackups", 10);
559  }
560  return true;
561  }
562  }
563  }
564  return false;
565 }
566 
567 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
568 {
569  bool fWasLocked = IsLocked(true);
570  bool bUseKeePass = false;
571 
572  SecureString strOldWalletPassphraseFinal;
573 
574  // Verify KeePassIntegration
575  if(strOldWalletPassphrase == "keepass" && gArgs.GetBoolArg("-keepass", false)) {
576  bUseKeePass = true;
577  try {
578  strOldWalletPassphraseFinal = keePassInt.retrievePassphrase();
579  } catch (std::exception& e) {
580  LogPrintf("CWallet::ChangeWalletPassphrase -- could not retrieve passphrase from KeePass: Error: %s\n", e.what());
581  return false;
582  }
583  } else {
584  strOldWalletPassphraseFinal = strOldWalletPassphrase;
585  }
586 
587  {
588  LOCK(cs_wallet);
589  Lock();
590 
591  CCrypter crypter;
592  CKeyingMaterial _vMasterKey;
593  for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
594  {
595  if(!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
596  return false;
597  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
598  return false;
599  if (CCryptoKeyStore::Unlock(_vMasterKey))
600  {
601  int64_t nStartTime = GetTimeMillis();
602  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
603  pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
604 
605  nStartTime = GetTimeMillis();
606  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
607  pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
608 
609  if (pMasterKey.second.nDeriveIterations < 25000)
610  pMasterKey.second.nDeriveIterations = 25000;
611 
612  LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
613 
614  if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
615  return false;
616  if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
617  return false;
618  WalletBatch(*database).WriteMasterKey(pMasterKey.first, pMasterKey.second);
619  if (fWasLocked)
620  Lock();
621 
622  // Update KeePass if necessary
623  if(bUseKeePass) {
624  LogPrintf("CWallet::ChangeWalletPassphrase -- Updating KeePass with new passphrase\n");
625  try {
626  keePassInt.updatePassphrase(strNewWalletPassphrase);
627  } catch (std::exception& e) {
628  LogPrintf("CWallet::ChangeWalletPassphrase -- could not update passphrase in KeePass: Error: %s\n", e.what());
629  return false;
630  }
631  }
632 
633  return true;
634  }
635  }
636  }
637 
638  return false;
639 }
640 
642 {
643  WalletBatch batch(*database);
644  batch.WriteBestBlock(loc);
645 }
646 
647 bool CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in, bool fExplicit)
648 {
649  LOCK(cs_wallet); // nWalletVersion
650  if (nWalletVersion >= nVersion)
651  return true;
652 
653  // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
654  if (fExplicit && nVersion > nWalletMaxVersion)
655  nVersion = FEATURE_LATEST;
656 
657  nWalletVersion = nVersion;
658 
659  if (nVersion > nWalletMaxVersion)
660  nWalletMaxVersion = nVersion;
661 
662  {
663  WalletBatch* batch = batch_in ? batch_in : new WalletBatch(*database);
664  if (nWalletVersion > 40000)
666  if (!batch_in)
667  delete batch;
668  }
669 
670  return true;
671 }
672 
673 bool CWallet::SetMaxVersion(int nVersion)
674 {
675  LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
676  // cannot downgrade below current version
677  if (nWalletVersion > nVersion)
678  return false;
679 
680  nWalletMaxVersion = nVersion;
681 
682  return true;
683 }
684 
685 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
686 {
687  std::set<uint256> result;
689 
690  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
691  if (it == mapWallet.end())
692  return result;
693  const CWalletTx& wtx = it->second;
694 
695  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
696 
697  for (const CTxIn& txin : wtx.tx->vin)
698  {
699  if (mapTxSpends.count(txin.prevout) <= 1)
700  continue; // No conflict if zero or one spends
701  range = mapTxSpends.equal_range(txin.prevout);
702  for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
703  result.insert(_it->second);
704  }
705  return result;
706 }
707 
708 void CWallet::Flush(bool shutdown)
709 {
710  database->Flush(shutdown);
711 }
712 
713 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
714 {
715  // We want all the wallet transactions in range to have the same metadata as
716  // the oldest (smallest nOrderPos).
717  // So: find smallest nOrderPos:
718 
719  int nMinOrderPos = std::numeric_limits<int>::max();
720  const CWalletTx* copyFrom = nullptr;
721  for (TxSpends::iterator it = range.first; it != range.second; ++it) {
722  const CWalletTx* wtx = &mapWallet[it->second];
723  if (wtx->nOrderPos < nMinOrderPos) {
724  nMinOrderPos = wtx->nOrderPos;;
725  copyFrom = wtx;
726  }
727  }
728 
729  assert(copyFrom);
730 
731  // Now copy data from copyFrom to rest:
732  for (TxSpends::iterator it = range.first; it != range.second; ++it)
733  {
734  const uint256& hash = it->second;
735  CWalletTx* copyTo = &mapWallet[hash];
736  if (copyFrom == copyTo) continue;
737  assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
738  if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
739  copyTo->mapValue = copyFrom->mapValue;
740  copyTo->vOrderForm = copyFrom->vOrderForm;
741  // fTimeReceivedIsTxTime not copied on purpose
742  // nTimeReceived not copied on purpose
743  copyTo->nTimeSmart = copyFrom->nTimeSmart;
744  copyTo->fFromMe = copyFrom->fFromMe;
745  copyTo->strFromAccount = copyFrom->strFromAccount;
746  // nOrderPos not copied on purpose
747  // cached members not copied on purpose
748  }
749 }
750 
755 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
756 {
757  const COutPoint outpoint(hash, n);
758  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
759  range = mapTxSpends.equal_range(outpoint);
760 
761  for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
762  {
763  const uint256& wtxid = it->second;
764  std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
765  if (mit != mapWallet.end()) {
766  int depth = mit->second.GetDepthInMainChain();
767  if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
768  return true; // Spent
769  }
770  }
771  return false;
772 }
773 
774 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
775 {
776  mapTxSpends.insert(std::make_pair(outpoint, wtxid));
777  setWalletUTXO.erase(outpoint);
778 
779  std::pair<TxSpends::iterator, TxSpends::iterator> range;
780  range = mapTxSpends.equal_range(outpoint);
781  SyncMetaData(range);
782 }
783 
784 
785 void CWallet::AddToSpends(const uint256& wtxid)
786 {
787  auto it = mapWallet.find(wtxid);
788  assert(it != mapWallet.end());
789  CWalletTx& thisTx = it->second;
790  if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
791  return;
792 
793  for (const CTxIn& txin : thisTx.tx->vin)
794  AddToSpends(txin.prevout, wtxid);
795 }
796 
797 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
798 {
799  if (IsCrypted())
800  return false;
801 
802  CKeyingMaterial _vMasterKey;
803 
804  _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
805  GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
806 
807  CMasterKey kMasterKey;
808 
809  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
811 
812  CCrypter crypter;
813  int64_t nStartTime = GetTimeMillis();
814  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
815  kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
816 
817  nStartTime = GetTimeMillis();
818  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
819  kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
820 
821  if (kMasterKey.nDeriveIterations < 25000)
822  kMasterKey.nDeriveIterations = 25000;
823 
824  LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
825 
826  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
827  return false;
828  if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
829  return false;
830 
831  {
832  LOCK(cs_wallet);
833  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
834  assert(!encrypted_batch);
836  if (!encrypted_batch->TxnBegin()) {
837  delete encrypted_batch;
838  encrypted_batch = nullptr;
839  return false;
840  }
842 
843  // must get current HD chain before EncryptKeys
844  CHDChain hdChainCurrent;
845  GetHDChain(hdChainCurrent);
846 
847  if (!EncryptKeys(_vMasterKey))
848  {
850  delete encrypted_batch;
851  // We now probably have half of our keys encrypted in memory, and half not...
852  // die and let the user reload the unencrypted wallet.
853  assert(false);
854  }
855 
856  if (!hdChainCurrent.IsNull()) {
857  assert(EncryptHDChain(_vMasterKey));
858 
859  CHDChain hdChainCrypted;
860  assert(GetHDChain(hdChainCrypted));
861 
862  DBG(
863  printf("EncryptWallet -- current seed: '%s'\n", HexStr(hdChainCurrent.GetSeed()).c_str());
864  printf("EncryptWallet -- crypted seed: '%s'\n", HexStr(hdChainCrypted.GetSeed()).c_str());
865  );
866 
867  // ids should match, seed hashes should not
868  assert(hdChainCurrent.GetID() == hdChainCrypted.GetID());
869  assert(hdChainCurrent.GetSeedHash() != hdChainCrypted.GetSeedHash());
870 
871  assert(SetCryptedHDChain(*encrypted_batch, hdChainCrypted, false));
872  }
873 
874  // Encryption was introduced in version 0.4.0
876 
877  if (!encrypted_batch->TxnCommit()) {
878  delete encrypted_batch;
879  // We now have keys encrypted in memory, but not on disk...
880  // die to avoid confusion and let the user reload the unencrypted wallet.
881  assert(false);
882  }
883 
884  delete encrypted_batch;
885  encrypted_batch = nullptr;
886 
887  Lock();
888  Unlock(strWalletPassphrase);
889 
890  // if we are not using HD, generate new keypool
891  if(IsHDEnabled()) {
892  TopUpKeyPool();
893  }
894  else {
895  NewKeyPool();
896  }
897 
898  Lock();
899 
900  // Need to completely rewrite the wallet file; if we don't, bdb might keep
901  // bits of the unencrypted private key in slack space in the database file.
902  database->Rewrite();
903 
904  // Update KeePass if necessary
905  if(gArgs.GetBoolArg("-keepass", false)) {
906  LogPrintf("CWallet::EncryptWallet -- Updating KeePass with new passphrase\n");
907  try {
908  keePassInt.updatePassphrase(strWalletPassphrase);
909  } catch (std::exception& e) {
910  LogPrintf("CWallet::EncryptWallet -- could not update passphrase in KeePass: Error: %s\n", e.what());
911  }
912  }
913 
914  }
915  NotifyStatusChanged(this);
916 
917  return true;
918 }
919 
921 {
922  LOCK(cs_wallet);
923  WalletBatch batch(*database);
924 
925  // Old wallets didn't have any defined order for transactions
926  // Probably a bad idea to change the output of this
927 
928  // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
929  typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
930  typedef std::multimap<int64_t, TxPair > TxItems;
931  TxItems txByTime;
932 
933  for (auto& entry : mapWallet)
934  {
935  CWalletTx* wtx = &entry.second;
936  txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
937  }
938  std::list<CAccountingEntry> acentries;
939  batch.ListAccountCreditDebit("", acentries);
940  for (CAccountingEntry& entry : acentries)
941  {
942  txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
943  }
944 
945  nOrderPosNext = 0;
946  std::vector<int64_t> nOrderPosOffsets;
947  for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
948  {
949  CWalletTx *const pwtx = (*it).second.first;
950  CAccountingEntry *const pacentry = (*it).second.second;
951  int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
952 
953  if (nOrderPos == -1)
954  {
955  nOrderPos = nOrderPosNext++;
956  nOrderPosOffsets.push_back(nOrderPos);
957 
958  if (pwtx)
959  {
960  if (!batch.WriteTx(*pwtx))
961  return DB_LOAD_FAIL;
962  }
963  else
964  if (!batch.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
965  return DB_LOAD_FAIL;
966  }
967  else
968  {
969  int64_t nOrderPosOff = 0;
970  for (const int64_t& nOffsetStart : nOrderPosOffsets)
971  {
972  if (nOrderPos >= nOffsetStart)
973  ++nOrderPosOff;
974  }
975  nOrderPos += nOrderPosOff;
976  nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
977 
978  if (!nOrderPosOff)
979  continue;
980 
981  // Since we're changing the order, write it back
982  if (pwtx)
983  {
984  if (!batch.WriteTx(*pwtx))
985  return DB_LOAD_FAIL;
986  }
987  else
988  if (!batch.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
989  return DB_LOAD_FAIL;
990  }
991  }
993 
994  return DB_LOAD_OK;
995 }
996 
998 {
999  AssertLockHeld(cs_wallet); // nOrderPosNext
1000  int64_t nRet = nOrderPosNext++;
1001  if (batch) {
1003  } else {
1005  }
1006  return nRet;
1007 }
1008 
1009 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
1010 {
1011  WalletBatch batch(*database);
1012  if (!batch.TxnBegin())
1013  return false;
1014 
1015  int64_t nNow = GetAdjustedTime();
1016 
1017  // Debit
1018  CAccountingEntry debit;
1019  debit.nOrderPos = IncOrderPosNext(&batch);
1020  debit.strAccount = strFrom;
1021  debit.nCreditDebit = -nAmount;
1022  debit.nTime = nNow;
1023  debit.strOtherAccount = strTo;
1024  debit.strComment = strComment;
1025  AddAccountingEntry(debit, &batch);
1026 
1027  // Credit
1028  CAccountingEntry credit;
1029  credit.nOrderPos = IncOrderPosNext(&batch);
1030  credit.strAccount = strTo;
1031  credit.nCreditDebit = nAmount;
1032  credit.nTime = nNow;
1033  credit.strOtherAccount = strFrom;
1034  credit.strComment = strComment;
1035  AddAccountingEntry(credit, &batch);
1036 
1037  if (!batch.TxnCommit())
1038  return false;
1039 
1040  return true;
1041 }
1042 
1043 bool CWallet::GetAccountDestination(CTxDestination &dest, std::string strAccount, bool bForceNew)
1044 {
1045  WalletBatch batch(*database);
1046 
1047  CAccount account;
1048  batch.ReadAccount(strAccount, account);
1049 
1050  if (!bForceNew) {
1051  if (!account.vchPubKey.IsValid())
1052  bForceNew = true;
1053  else {
1054  // Check if the current key has been used
1055  CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
1056  for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
1057  it != mapWallet.end() && account.vchPubKey.IsValid();
1058  ++it)
1059  for (const CTxOut& txout : (*it).second.tx->vout)
1060  if (txout.scriptPubKey == scriptPubKey) {
1061  bForceNew = true;
1062  break;
1063  }
1064  }
1065  }
1066 
1067  // Generate a new key
1068  if (bForceNew) {
1069  if (!GetKeyFromPool(account.vchPubKey, false))
1070  return false;
1071 
1072  dest = account.vchPubKey.GetID();
1073  SetAddressBook(dest, strAccount, "receive");
1074  batch.WriteAccount(strAccount, account);
1075  } else {
1076  dest = account.vchPubKey.GetID();
1077  }
1078 
1079  return true;
1080 }
1081 
1083 {
1084  {
1085  LOCK(cs_wallet);
1086  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1087  item.second.MarkDirty();
1088  }
1089 
1090  fAnonymizableTallyCached = false;
1092 }
1093 
1094 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
1095 {
1096  LOCK(cs_wallet);
1097 
1098  WalletBatch batch(*database, "r+", fFlushOnClose);
1099 
1100  uint256 hash = wtxIn.GetHash();
1101 
1102  // Inserts only if not already there, returns tx inserted or tx found
1103  std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
1104  CWalletTx& wtx = (*ret.first).second;
1105  wtx.BindWallet(this);
1106  bool fInsertedNew = ret.second;
1107  if (fInsertedNew) {
1109  wtx.nOrderPos = IncOrderPosNext(&batch);
1110  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
1111  wtx.nTimeSmart = ComputeTimeSmart(wtx);
1112  AddToSpends(hash);
1113 
1114  auto mnList = deterministicMNManager->GetListAtChainTip();
1115  for(unsigned int i = 0; i < wtx.tx->vout.size(); ++i) {
1116  if (IsMine(wtx.tx->vout[i]) && !IsSpent(hash, i)) {
1117  setWalletUTXO.insert(COutPoint(hash, i));
1118  if (deterministicMNManager->IsProTxWithCollateral(wtx.tx, i) || mnList.HasMNByCollateral(COutPoint(hash, i))) {
1119  LockCoin(COutPoint(hash, i));
1120  }
1121  }
1122  }
1123  }
1124 
1125  bool fUpdated = false;
1126  if (!fInsertedNew)
1127  {
1128  // Merge
1129  if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
1130  {
1131  wtx.hashBlock = wtxIn.hashBlock;
1132  fUpdated = true;
1133  }
1134  // If no longer abandoned, update
1135  if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
1136  {
1137  wtx.hashBlock = wtxIn.hashBlock;
1138  fUpdated = true;
1139  }
1140  if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
1141  {
1142  wtx.nIndex = wtxIn.nIndex;
1143  fUpdated = true;
1144  }
1145  if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1146  {
1147  wtx.fFromMe = wtxIn.fFromMe;
1148  fUpdated = true;
1149  }
1150  }
1151 
1153  LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1154 
1155  // Write to disk
1156  if (fInsertedNew || fUpdated)
1157  if (!batch.WriteTx(wtx))
1158  return false;
1159 
1160  // Break debit/credit balance caches:
1161  wtx.MarkDirty();
1162 
1163  // Notify UI of new or updated transaction
1164  NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1165 
1166  // notify an external script when a wallet transaction comes in or is updated
1167  std::string strCmd = gArgs.GetArg("-walletnotify", "");
1168 
1169  if (!strCmd.empty())
1170  {
1171  boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1172  boost::thread t(runCommand, strCmd); // thread runs free
1173  }
1174 
1175  fAnonymizableTallyCached = false;
1177 
1178  return true;
1179 }
1180 
1182 {
1183  uint256 hash = wtxIn.GetHash();
1184  const auto& ins = mapWallet.emplace(hash, wtxIn);
1185  CWalletTx& wtx = ins.first->second;
1186  wtx.BindWallet(this);
1187  if (/* insertion took place */ ins.second) {
1188  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
1189  }
1190  AddToSpends(hash);
1191  for (const CTxIn& txin : wtx.tx->vin) {
1192  auto it = mapWallet.find(txin.prevout.hash);
1193  if (it != mapWallet.end()) {
1194  CWalletTx& prevtx = it->second;
1195  if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
1196  MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1197  }
1198  }
1199  }
1200 
1201  return true;
1202 }
1203 
1217 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1218 {
1219  const CTransaction& tx = *ptx;
1220  {
1222 
1223  if (pIndex != nullptr) {
1224  for (const CTxIn& txin : tx.vin) {
1225  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1226  while (range.first != range.second) {
1227  if (range.first->second != tx.GetHash()) {
1228  LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pIndex->GetBlockHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1229  MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1230  }
1231  range.first++;
1232  }
1233  }
1234  }
1235 
1236  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1237  if (fExisted && !fUpdate) return false;
1238  if (fExisted || IsMine(tx) || IsFromMe(tx))
1239  {
1240  /* Check if any keys in the wallet keypool that were supposed to be unused
1241  * have appeared in a new transaction. If so, remove those keys from the keypool.
1242  * This can happen when restoring an old wallet backup that does not contain
1243  * the mostly recently created transactions from newer versions of the wallet.
1244  */
1245 
1246  // loop though all outputs
1247  for (const CTxOut& txout: tx.vout) {
1248  // extract addresses and check if they match with an unused keypool key
1249  std::vector<CKeyID> vAffected;
1250  CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1251  for (const CKeyID &keyid : vAffected) {
1252  std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1253  if (mi != m_pool_key_to_index.end()) {
1254  LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1255  MarkReserveKeysAsUsed(mi->second);
1256 
1257  if (!TopUpKeyPool()) {
1258  LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1259  }
1260  }
1261  }
1262  }
1263 
1264  CWalletTx wtx(this, ptx);
1265 
1266  // Get merkle branch if transaction was found in a block
1267  if (pIndex != nullptr)
1268  wtx.SetMerkleBranch(pIndex, posInBlock);
1269 
1270  return AddToWallet(wtx, false);
1271  }
1272  }
1273  return false;
1274 }
1275 
1277 {
1279  const CWalletTx* wtx = GetWalletTx(hashTx);
1280  return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1281 }
1282 
1284 {
1286 
1287  WalletBatch batch(*database, "r+");
1288 
1289  std::set<uint256> todo;
1290  std::set<uint256> done;
1291 
1292  // Can't mark abandoned if confirmed or in mempool
1293  auto it = mapWallet.find(hashTx);
1294  assert(it != mapWallet.end());
1295  CWalletTx& origtx = it->second;
1296  if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool() || origtx.IsLockedByInstantSend()) {
1297  return false;
1298  }
1299 
1300  todo.insert(hashTx);
1301 
1302  while (!todo.empty()) {
1303  uint256 now = *todo.begin();
1304  todo.erase(now);
1305  done.insert(now);
1306  auto it = mapWallet.find(now);
1307  assert(it != mapWallet.end());
1308  CWalletTx& wtx = it->second;
1309  int currentconfirm = wtx.GetDepthInMainChain();
1310  // If the orig tx was not in block, none of its spends can be
1311  assert(currentconfirm <= 0);
1312  // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1313  if (currentconfirm == 0 && !wtx.isAbandoned()) {
1314  // If the orig tx was not in block/mempool, none of its spends can be in mempool
1315  assert(!wtx.InMempool());
1316  wtx.nIndex = -1;
1317  wtx.setAbandoned();
1318  wtx.MarkDirty();
1319  batch.WriteTx(wtx);
1320  NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1321  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1322  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1323  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1324  if (!done.count(iter->second)) {
1325  todo.insert(iter->second);
1326  }
1327  iter++;
1328  }
1329  // If a transaction changes 'conflicted' state, that changes the balance
1330  // available of the outputs it spends. So force those to be recomputed
1331  for (const CTxIn& txin : wtx.tx->vin)
1332  {
1333  auto it = mapWallet.find(txin.prevout.hash);
1334  if (it != mapWallet.end()) {
1335  it->second.MarkDirty();
1336  }
1337  }
1338  }
1339  }
1340 
1341  fAnonymizableTallyCached = false;
1343 
1344  return true;
1345 }
1346 
1347 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1348 {
1349  LOCK2(cs_main, cs_wallet); // check "LOCK2(cs_main, pwallet->cs_wallet);" in WalletBatch::LoadWallet()
1350 
1351  int conflictconfirms = 0;
1352  if (mapBlockIndex.count(hashBlock)) {
1353  CBlockIndex* pindex = mapBlockIndex[hashBlock];
1354  if (chainActive.Contains(pindex)) {
1355  conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1356  }
1357  }
1358  // If number of conflict confirms cannot be determined, this means
1359  // that the block is still unknown or not yet part of the main chain,
1360  // for example when loading the wallet during a reindex. Do nothing in that
1361  // case.
1362  if (conflictconfirms >= 0)
1363  return;
1364 
1365  // Do not flush the wallet here for performance reasons
1366  WalletBatch batch(*database, "r+", false);
1367 
1368  std::set<uint256> todo;
1369  std::set<uint256> done;
1370 
1371  todo.insert(hashTx);
1372 
1373  while (!todo.empty()) {
1374  uint256 now = *todo.begin();
1375  todo.erase(now);
1376  done.insert(now);
1377  auto it = mapWallet.find(now);
1378  assert(it != mapWallet.end());
1379  CWalletTx& wtx = it->second;
1380  int currentconfirm = wtx.GetDepthInMainChain();
1381  if (conflictconfirms < currentconfirm) {
1382  // Block is 'more conflicted' than current confirm; update.
1383  // Mark transaction as conflicted with this block.
1384  wtx.nIndex = -1;
1385  wtx.hashBlock = hashBlock;
1386  wtx.MarkDirty();
1387  batch.WriteTx(wtx);
1388  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1389  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1390  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1391  if (!done.count(iter->second)) {
1392  todo.insert(iter->second);
1393  }
1394  iter++;
1395  }
1396  // If a transaction changes 'conflicted' state, that changes the balance
1397  // available of the outputs it spends. So force those to be recomputed
1398  for (const CTxIn& txin : wtx.tx->vin) {
1399  auto it = mapWallet.find(txin.prevout.hash);
1400  if (it != mapWallet.end()) {
1401  it->second.MarkDirty();
1402  }
1403  }
1404  }
1405  }
1406 
1407  fAnonymizableTallyCached = false;
1409 }
1410 
1411 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1412  const CTransaction& tx = *ptx;
1413 
1414  if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1415  return; // Not one of ours
1416 
1417  // If a transaction changes 'conflicted' state, that changes the balance
1418  // available of the outputs it spends. So force those to be
1419  // recomputed, also:
1420  for (const CTxIn& txin : tx.vin) {
1421  auto it = mapWallet.find(txin.prevout.hash);
1422  if (it != mapWallet.end()) {
1423  it->second.MarkDirty();
1424  }
1425  }
1426 
1427  fAnonymizableTallyCached = false;
1429 }
1430 
1431 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx, int64_t nAcceptTime) {
1433  SyncTransaction(ptx);
1434 
1435  auto it = mapWallet.find(ptx->GetHash());
1436  if (it != mapWallet.end()) {
1437  it->second.fInMempool = true;
1438  }
1439 }
1440 
1442  LOCK(cs_wallet);
1443  auto it = mapWallet.find(ptx->GetHash());
1444  if (it != mapWallet.end()) {
1445  it->second.fInMempool = false;
1446  }
1447 }
1448 
1449 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1451  // TODO: Temporarily ensure that mempool removals are notified before
1452  // connected transactions. This shouldn't matter, but the abandoned
1453  // state of transactions in our wallet is currently cleared when we
1454  // receive another notification and there is a race condition where
1455  // notification of a connected conflict might cause an outside process
1456  // to abandon a transaction and then have it inadvertently cleared by
1457  // the notification that the conflicted transaction was evicted.
1458 
1459  for (const CTransactionRef& ptx : vtxConflicted) {
1460  SyncTransaction(ptx);
1462  }
1463  for (size_t i = 0; i < pblock->vtx.size(); i++) {
1464  SyncTransaction(pblock->vtx[i], pindex, i);
1465  TransactionRemovedFromMempool(pblock->vtx[i]);
1466  }
1467 
1468  m_last_block_processed = pindex;
1469 
1470  // The GUI expects a NotifyTransactionChanged when a coinbase tx
1471  // which is in our wallet moves from in-the-best-block to
1472  // 2-confirmations (as it only displays them at that time).
1473  // We do that here.
1474  if (hashPrevBestCoinbase.IsNull()) {
1475  // Immediately after restart we have no idea what the coinbase
1476  // transaction from the previous block is.
1477  // For correctness we scan over the entire wallet, looking for
1478  // the previous block's coinbase, just in case it is ours, so
1479  // that we can notify the UI that it should now be displayed.
1480  if (pindex->pprev) {
1481  for (const std::pair<uint256, CWalletTx>& p : mapWallet) {
1482  if (p.second.IsCoinBase() && p.second.hashBlock == pindex->pprev->GetBlockHash()) {
1483  NotifyTransactionChanged(this, p.first, CT_UPDATED);
1484  break;
1485  }
1486  }
1487  }
1488  } else {
1489  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashPrevBestCoinbase);
1490  if (mi != mapWallet.end()) {
1492  }
1493  }
1494 
1495  hashPrevBestCoinbase = pblock->vtx[0]->GetHash();
1496 
1497  // reset cache to make sure no longer immature coins are included
1498  fAnonymizableTallyCached = false;
1500 }
1501 
1502 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexDisconnected) {
1504 
1505  for (const CTransactionRef& ptx : pblock->vtx) {
1506  // NOTE: do NOT pass pindex here
1507  SyncTransaction(ptx);
1508  }
1509 
1510  // reset cache to make sure no longer mature coins are excluded
1511  fAnonymizableTallyCached = false;
1513 }
1514 
1515 
1516 
1520 
1521  {
1522  // Skip the queue-draining stuff if we know we're caught up with
1523  // chainActive.Tip()...
1524  // We could also take cs_wallet here, and call m_last_block_processed
1525  // protected by cs_wallet instead of cs_main, but as long as we need
1526  // cs_main here anyway, its easier to just call it cs_main-protected.
1527  LOCK(cs_main);
1528  const CBlockIndex* initialChainTip = chainActive.Tip();
1529 
1530  if (m_last_block_processed->GetAncestor(initialChainTip->nHeight) == initialChainTip) {
1531  return;
1532  }
1533  }
1534 
1535  // ...otherwise put a callback in the validation interface queue and wait
1536  // for the queue to drain enough to execute it (indicating we are caught up
1537  // at least with the time we entered this function).
1539 }
1540 
1541 
1543 {
1544  {
1545  LOCK(cs_wallet);
1546  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1547  if (mi != mapWallet.end())
1548  {
1549  const CWalletTx& prev = (*mi).second;
1550  if (txin.prevout.n < prev.tx->vout.size())
1551  return IsMine(prev.tx->vout[txin.prevout.n]);
1552  }
1553  }
1554  return ISMINE_NO;
1555 }
1556 
1557 // Note that this function doesn't distinguish between a 0-valued input,
1558 // and a not-"is mine" (according to the filter) input.
1559 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1560 {
1561  {
1562  LOCK(cs_wallet);
1563  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1564  if (mi != mapWallet.end())
1565  {
1566  const CWalletTx& prev = (*mi).second;
1567  if (txin.prevout.n < prev.tx->vout.size())
1568  if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1569  return prev.tx->vout[txin.prevout.n].nValue;
1570  }
1571  }
1572  return 0;
1573 }
1574 
1575 // Recursively determine the rounds of a given input (How deep is the PrivateSend chain for a given input)
1576 int CWallet::GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds) const
1577 {
1578  LOCK(cs_wallet);
1579 
1581 
1582  if (nRounds >= nRoundsMax) {
1583  // there can only be nRoundsMax rounds max
1584  return nRoundsMax - 1;
1585  }
1586 
1587  auto pair = mapOutpointRoundsCache.emplace(outpoint, -10);
1588  auto nRoundsRef = &pair.first->second;
1589  if (!pair.second) {
1590  // we already processed it, just return what we have
1591  return *nRoundsRef;
1592  }
1593 
1594  // TODO wtx should refer to a CWalletTx object, not a pointer, based on surrounding code
1595  const CWalletTx* wtx = GetWalletTx(outpoint.hash);
1596 
1597  if (wtx == nullptr || wtx->tx == nullptr) {
1598  // no such tx in this wallet
1599  *nRoundsRef = -1;
1600  LogPrint(BCLog::PRIVATESEND, "%s FAILED %-70s %3d\n", __func__, outpoint.ToStringShort(), -1);
1601  return *nRoundsRef;
1602  }
1603 
1604  // bounds check
1605  if (outpoint.n >= wtx->tx->vout.size()) {
1606  // should never actually hit this
1607  *nRoundsRef = -4;
1608  LogPrint(BCLog::PRIVATESEND, "%s FAILED %-70s %3d\n", __func__, outpoint.ToStringShort(), -4);
1609  return *nRoundsRef;
1610  }
1611 
1612  auto txOutRef = &wtx->tx->vout[outpoint.n];
1613 
1614  if (CPrivateSend::IsCollateralAmount(txOutRef->nValue)) {
1615  *nRoundsRef = -3;
1616  LogPrint(BCLog::PRIVATESEND, "%s UPDATED %-70s %3d\n", __func__, outpoint.ToStringShort(), *nRoundsRef);
1617  return *nRoundsRef;
1618  }
1619 
1620  // make sure the final output is non-denominate
1621  if (!CPrivateSend::IsDenominatedAmount(txOutRef->nValue)) { //NOT DENOM
1622  *nRoundsRef = -2;
1623  LogPrint(BCLog::PRIVATESEND, "%s UPDATED %-70s %3d\n", __func__, outpoint.ToStringShort(), *nRoundsRef);
1624  return *nRoundsRef;
1625  }
1626 
1627  for (const auto& out : wtx->tx->vout) {
1628  if (!CPrivateSend::IsDenominatedAmount(out.nValue)) {
1629  // this one is denominated but there is another non-denominated output found in the same tx
1630  *nRoundsRef = 0;
1631  LogPrint(BCLog::PRIVATESEND, "%s UPDATED %-70s %3d\n", __func__, outpoint.ToStringShort(), *nRoundsRef);
1632  return *nRoundsRef;
1633  }
1634  }
1635 
1636  int nShortest = -10; // an initial value, should be no way to get this by calculations
1637  bool fDenomFound = false;
1638  // only denoms here so let's look up
1639  for (const auto& txinNext : wtx->tx->vin) {
1640  if (IsMine(txinNext)) {
1641  int n = GetRealOutpointPrivateSendRounds(txinNext.prevout, nRounds + 1);
1642  // denom found, find the shortest chain or initially assign nShortest with the first found value
1643  if(n >= 0 && (n < nShortest || nShortest == -10)) {
1644  nShortest = n;
1645  fDenomFound = true;
1646  }
1647  }
1648  }
1649  *nRoundsRef = fDenomFound
1650  ? (nShortest >= nRoundsMax - 1 ? nRoundsMax : nShortest + 1) // good, we a +1 to the shortest one but only nRoundsMax rounds max allowed
1651  : 0; // too bad, we are the fist one in that chain
1652  LogPrint(BCLog::PRIVATESEND, "%s UPDATED %-70s %3d\n", __func__, outpoint.ToStringShort(), *nRoundsRef);
1653  return *nRoundsRef;
1654 }
1655 
1656 // respect current settings
1658 {
1659  LOCK(cs_wallet);
1660  int realPrivateSendRounds = GetRealOutpointPrivateSendRounds(outpoint);
1661  return realPrivateSendRounds > privateSendClient.nPrivateSendRounds ? privateSendClient.nPrivateSendRounds : realPrivateSendRounds;
1662 }
1663 
1664 bool CWallet::IsDenominated(const COutPoint& outpoint) const
1665 {
1666  LOCK(cs_wallet);
1667 
1668  const auto it = mapWallet.find(outpoint.hash);
1669  if (it == mapWallet.end()) {
1670  return false;
1671  }
1672 
1673  if (outpoint.n >= it->second.tx->vout.size()) {
1674  return false;
1675  }
1676 
1677  return CPrivateSend::IsDenominatedAmount(it->second.tx->vout[outpoint.n].nValue);
1678 }
1679 
1680 bool CWallet::IsFullyMixed(const COutPoint& outpoint) const
1681 {
1682  int nRounds = GetRealOutpointPrivateSendRounds(outpoint);
1683  // Mix again if we don't have N rounds yet
1684  if (nRounds < privateSendClient.nPrivateSendRounds) return false;
1685 
1686  // Try to mix a "random" number of rounds more than minimum.
1687  // If we have already mixed N + MaxOffset rounds, don't mix again.
1688  // Otherwise, we should mix again 50% of the time, this results in an exponential decay
1689  // N rounds 50% N+1 25% N+2 12.5%... until we reach N + GetRandomRounds() rounds where we stop.
1692  ss << outpoint << nPrivateSendSalt;
1693  uint256 nHash;
1694  CSHA256().Write((const unsigned char*)ss.data(), ss.size()).Finalize(nHash.begin());
1695  if (nHash.GetCheapHash() % 2 == 0) {
1696  return false;
1697  }
1698  }
1699 
1700  return true;
1701 }
1702 
1703 isminetype CWallet::IsMine(const CTxOut& txout) const
1704 {
1705  return ::IsMine(*this, txout.scriptPubKey);
1706 }
1707 
1708 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1709 {
1710  if (!MoneyRange(txout.nValue))
1711  throw std::runtime_error(std::string(__func__) + ": value out of range");
1712  return ((IsMine(txout) & filter) ? txout.nValue : 0);
1713 }
1714 
1715 bool CWallet::IsChange(const CTxOut& txout) const
1716 {
1717  // TODO: fix handling of 'change' outputs. The assumption is that any
1718  // payment to a script that is ours, but is not in the address book
1719  // is change. That assumption is likely to break when we implement multisignature
1720  // wallets that return change back into a multi-signature-protected address;
1721  // a better way of identifying which outputs are 'the send' and which are
1722  // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1723  // which output, if any, was change).
1724  if (::IsMine(*this, txout.scriptPubKey))
1725  {
1726  CTxDestination address;
1727  if (!ExtractDestination(txout.scriptPubKey, address))
1728  return true;
1729 
1730  LOCK(cs_wallet);
1731  if (!mapAddressBook.count(address))
1732  return true;
1733  }
1734  return false;
1735 }
1736 
1737 CAmount CWallet::GetChange(const CTxOut& txout) const
1738 {
1739  if (!MoneyRange(txout.nValue))
1740  throw std::runtime_error(std::string(__func__) + ": value out of range");
1741  return (IsChange(txout) ? txout.nValue : 0);
1742 }
1743 
1745 {
1746  CHDChain newHdChain;
1747 
1748  std::string strSeed = gArgs.GetArg("-hdseed", "not hex");
1749 
1750  if(gArgs.IsArgSet("-hdseed") && IsHex(strSeed)) {
1751  std::vector<unsigned char> vchSeed = ParseHex(strSeed);
1752  if (!newHdChain.SetSeed(SecureVector(vchSeed.begin(), vchSeed.end()), true))
1753  throw std::runtime_error(std::string(__func__) + ": SetSeed failed");
1754  }
1755  else {
1756  if (gArgs.IsArgSet("-hdseed") && !IsHex(strSeed))
1757  LogPrintf("CWallet::GenerateNewHDChain -- Incorrect seed, generating random one instead\n");
1758 
1759  // NOTE: empty mnemonic means "generate a new one for me"
1760  std::string strMnemonic = gArgs.GetArg("-mnemonic", "");
1761  // NOTE: default mnemonic passphrase is an empty string
1762  std::string strMnemonicPassphrase = gArgs.GetArg("-mnemonicpassphrase", "");
1763 
1764  SecureVector vchMnemonic(strMnemonic.begin(), strMnemonic.end());
1765  SecureVector vchMnemonicPassphrase(strMnemonicPassphrase.begin(), strMnemonicPassphrase.end());
1766 
1767  if (!newHdChain.SetMnemonic(vchMnemonic, vchMnemonicPassphrase, true))
1768  throw std::runtime_error(std::string(__func__) + ": SetMnemonic failed");
1769  }
1770  newHdChain.Debug(__func__);
1771 
1772  if (!SetHDChainSingle(newHdChain, false))
1773  throw std::runtime_error(std::string(__func__) + ": SetHDChainSingle failed");
1774 
1775  // clean up
1776  gArgs.ForceRemoveArg("-hdseed");
1777  gArgs.ForceRemoveArg("-mnemonic");
1778  gArgs.ForceRemoveArg("-mnemonicpassphrase");
1779 }
1780 
1781 bool CWallet::SetHDChain(WalletBatch &batch, const CHDChain& chain, bool memonly)
1782 {
1783  LOCK(cs_wallet);
1784 
1785  if (!CCryptoKeyStore::SetHDChain(chain))
1786  return false;
1787 
1788  if (!memonly && !batch.WriteHDChain(chain))
1789  throw std::runtime_error(std::string(__func__) + ": WriteHDChain failed");
1790 
1791  return true;
1792 }
1793 
1794 bool CWallet::SetCryptedHDChain(WalletBatch &batch, const CHDChain& chain, bool memonly)
1795 {
1796  LOCK(cs_wallet);
1797 
1799  return false;
1800 
1801  if (!memonly) {
1802  if (encrypted_batch) {
1803  if (!encrypted_batch->WriteCryptedHDChain(chain))
1804  throw std::runtime_error(std::string(__func__) + ": WriteCryptedHDChain failed");
1805  } else {
1806  if (!batch.WriteCryptedHDChain(chain))
1807  throw std::runtime_error(std::string(__func__) + ": WriteCryptedHDChain failed");
1808  }
1809  }
1810 
1811  return true;
1812 }
1813 
1814 bool CWallet::SetHDChainSingle(const CHDChain& chain, bool memonly)
1815 {
1816  WalletBatch batch(*database);
1817  return SetHDChain(batch, chain, memonly);
1818 }
1819 
1820 bool CWallet::SetCryptedHDChainSingle(const CHDChain& chain, bool memonly)
1821 {
1822  WalletBatch batch(*database);
1823  return SetCryptedHDChain(batch, chain, memonly);
1824 }
1825 
1827 {
1828  LOCK(cs_wallet);
1829 
1830  CHDChain hdChainTmp;
1831  if (!GetHDChain(hdChainTmp)) {
1832  return false;
1833  }
1834 
1835  if (!DecryptHDChain(hdChainTmp))
1836  return false;
1837 
1838  // make sure seed matches this chain
1839  if (hdChainTmp.GetID() != hdChainTmp.GetSeedHash())
1840  return false;
1841 
1842  hdChainRet = hdChainTmp;
1843 
1844  return true;
1845 }
1846 
1848 {
1849  CHDChain hdChainCurrent;
1850  return GetHDChain(hdChainCurrent);
1851 }
1852 
1853 bool CWallet::IsMine(const CTransaction& tx) const
1854 {
1855  for (const CTxOut& txout : tx.vout)
1856  if (IsMine(txout))
1857  return true;
1858  return false;
1859 }
1860 
1861 bool CWallet::IsFromMe(const CTransaction& tx) const
1862 {
1863  return (GetDebit(tx, ISMINE_ALL) > 0);
1864 }
1865 
1866 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1867 {
1868  CAmount nDebit = 0;
1869  for (const CTxIn& txin : tx.vin)
1870  {
1871  nDebit += GetDebit(txin, filter);
1872  if (!MoneyRange(nDebit))
1873  throw std::runtime_error(std::string(__func__) + ": value out of range");
1874  }
1875  return nDebit;
1876 }
1877 
1878 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1879 {
1880  LOCK(cs_wallet);
1881 
1882  for (const CTxIn& txin : tx.vin)
1883  {
1884  auto mi = mapWallet.find(txin.prevout.hash);
1885  if (mi == mapWallet.end())
1886  return false; // any unknown inputs can't be from us
1887 
1888  const CWalletTx& prev = (*mi).second;
1889 
1890  if (txin.prevout.n >= prev.tx->vout.size())
1891  return false; // invalid input!
1892 
1893  if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1894  return false;
1895  }
1896  return true;
1897 }
1898 
1899 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1900 {
1901  CAmount nCredit = 0;
1902  for (const CTxOut& txout : tx.vout)
1903  {
1904  nCredit += GetCredit(txout, filter);
1905  if (!MoneyRange(nCredit))
1906  throw std::runtime_error(std::string(__func__) + ": value out of range");
1907  }
1908  return nCredit;
1909 }
1910 
1912 {
1913  CAmount nChange = 0;
1914  for (const CTxOut& txout : tx.vout)
1915  {
1916  nChange += GetChange(txout);
1917  if (!MoneyRange(nChange))
1918  throw std::runtime_error(std::string(__func__) + ": value out of range");
1919  }
1920  return nChange;
1921 }
1922 
1923 int64_t CWalletTx::GetTxTime() const
1924 {
1925  int64_t n = nTimeSmart;
1926  return n ? n : nTimeReceived;
1927 }
1928 
1929 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1930  std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1931 {
1932  nFee = 0;
1933  listReceived.clear();
1934  listSent.clear();
1935  strSentAccount = strFromAccount;
1936 
1937  // Compute fee:
1938  CAmount nDebit = GetDebit(filter);
1939  if (nDebit > 0) // debit>0 means we signed/sent this transaction
1940  {
1941  CAmount nValueOut = tx->GetValueOut();
1942  nFee = nDebit - nValueOut;
1943  }
1944 
1945  // Sent/received.
1946  for (unsigned int i = 0; i < tx->vout.size(); ++i)
1947  {
1948  const CTxOut& txout = tx->vout[i];
1949  isminetype fIsMine = pwallet->IsMine(txout);
1950  // Only need to handle txouts if AT LEAST one of these is true:
1951  // 1) they debit from us (sent)
1952  // 2) the output is to us (received)
1953  if (nDebit > 0)
1954  {
1955  // Don't report 'change' txouts
1956  if (pwallet->IsChange(txout))
1957  continue;
1958  }
1959  else if (!(fIsMine & filter))
1960  continue;
1961 
1962  // In either case, we need to get the destination address
1963  CTxDestination address;
1964 
1965  if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1966  {
1967  LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1968  this->GetHash().ToString());
1969  address = CNoDestination();
1970  }
1971 
1972  COutputEntry output = {address, txout.nValue, (int)i};
1973 
1974  // If we are debited by the transaction, add the output as a "sent" entry
1975  if (nDebit > 0)
1976  listSent.push_back(output);
1977 
1978  // If we are receiving the output, add it as a "received" entry
1979  if (fIsMine & filter)
1980  listReceived.push_back(output);
1981  }
1982 
1983 }
1984 
1993 int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
1994 {
1995  // Find starting block. May be null if nCreateTime is greater than the
1996  // highest blockchain timestamp, in which case there is nothing that needs
1997  // to be scanned.
1998  CBlockIndex* startBlock = nullptr;
1999  {
2000  LOCK(cs_main);
2001  startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
2002  LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
2003  }
2004 
2005  if (startBlock) {
2006  const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, reserver, update);
2007  if (failedBlock) {
2008  return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
2009  }
2010  }
2011  return startTime;
2012 }
2013 
2030 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, const WalletRescanReserver &reserver, bool fUpdate)
2031 {
2032  int64_t nNow = GetTime();
2033  const CChainParams& chainParams = Params();
2034 
2035  assert(reserver.isReserved());
2036  if (pindexStop) {
2037  assert(pindexStop->nHeight >= pindexStart->nHeight);
2038  }
2039 
2040  CBlockIndex* pindex = pindexStart;
2041  CBlockIndex* ret = nullptr;
2042  {
2043  fAbortRescan = false;
2044  ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
2045  CBlockIndex* tip = nullptr;
2046  double dProgressStart;
2047  double dProgressTip;
2048  {
2049  LOCK(cs_main);
2050  tip = chainActive.Tip();
2051  dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
2052  dProgressTip = GuessVerificationProgress(chainParams.TxData(), tip);
2053  }
2054  while (pindex && !fAbortRescan)
2055  {
2056  if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) {
2057  double gvp = 0;
2058  {
2059  LOCK(cs_main);
2060  gvp = GuessVerificationProgress(chainParams.TxData(), pindex);
2061  }
2062  ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((gvp - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
2063  }
2064  if (GetTime() >= nNow + 60) {
2065  nNow = GetTime();
2066  LOCK(cs_main);
2067  LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
2068  }
2069 
2070  CBlock block;
2071  if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
2073  if (pindex && !chainActive.Contains(pindex)) {
2074  // Abort scan if current block is no longer active, to prevent
2075  // marking transactions as coming from the wrong block.
2076  ret = pindex;
2077  break;
2078  }
2079  for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
2080  AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
2081  }
2082  } else {
2083  ret = pindex;
2084  }
2085  if (pindex == pindexStop) {
2086  break;
2087  }
2088  {
2089  LOCK(cs_main);
2090  pindex = chainActive.Next(pindex);
2091  if (tip != chainActive.Tip()) {
2092  tip = chainActive.Tip();
2093  // in case the tip has changed, update progress max
2094  dProgressTip = GuessVerificationProgress(chainParams.TxData(), tip);
2095  }
2096  }
2097  }
2098  if (pindex && fAbortRescan) {
2099  LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
2100  }
2101  ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
2102  }
2103  return ret;
2104 }
2105 
2107 {
2108  // If transactions aren't being broadcasted, don't let them into local mempool either
2110  return;
2111  LOCK2(cs_main, mempool.cs);
2112  LOCK(cs_wallet);
2113  std::map<int64_t, CWalletTx*> mapSorted;
2114 
2115  // Sort pending wallet transactions based on their initial wallet insertion order
2116  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
2117  {
2118  const uint256& wtxid = item.first;
2119  CWalletTx& wtx = item.second;
2120  assert(wtx.GetHash() == wtxid);
2121 
2122  int nDepth = wtx.GetDepthInMainChain();
2123 
2124  if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.IsLockedByInstantSend() && !wtx.isAbandoned())) {
2125  mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
2126  }
2127  }
2128 
2129  // Try to add wallet transactions to memory pool
2130  for (std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
2131  CWalletTx& wtx = *(item.second);
2132  CValidationState state;
2133  wtx.AcceptToMemoryPool(maxTxFee, state);
2134  }
2135 }
2136 
2138 {
2139  assert(pwallet->GetBroadcastTransactions());
2140  if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
2141  {
2142  CValidationState state;
2143  /* GetDepthInMainChain already catches known conflicts. */
2144  if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
2145  uint256 hash = GetHash();
2146  LogPrintf("Relaying wtx %s\n", hash.ToString());
2147 
2148  if (connman) {
2149  connman->RelayTransaction(*tx);
2150  return true;
2151  }
2152  }
2153  }
2154  return false;
2155 }
2156 
2157 std::set<uint256> CWalletTx::GetConflicts() const
2158 {
2159  std::set<uint256> result;
2160  if (pwallet != nullptr)
2161  {
2162  uint256 myHash = GetHash();
2163  result = pwallet->GetConflicts(myHash);
2164  result.erase(myHash);
2165  }
2166  return result;
2167 }
2168 
2170 {
2171  if (tx->vin.empty())
2172  return 0;
2173 
2174  CAmount debit = 0;
2175  if(filter & ISMINE_SPENDABLE)
2176  {
2177  if (fDebitCached)
2178  debit += nDebitCached;
2179  else
2180  {
2182  fDebitCached = true;
2183  debit += nDebitCached;
2184  }
2185  }
2186  if(filter & ISMINE_WATCH_ONLY)
2187  {
2188  if(fWatchDebitCached)
2189  debit += nWatchDebitCached;
2190  else
2191  {
2193  fWatchDebitCached = true;
2194  debit += nWatchDebitCached;
2195  }
2196  }
2197  return debit;
2198 }
2199 
2201 {
2202  // Must wait until coinbase is safely deep enough in the chain before valuing it
2203  if (IsCoinBase() && GetBlocksToMaturity() > 0)
2204  return 0;
2205 
2206  CAmount credit = 0;
2207  if (filter & ISMINE_SPENDABLE)
2208  {
2209  // GetBalance can assume transactions in mapWallet won't change
2210  if (fCreditCached)
2211  credit += nCreditCached;
2212  else
2213  {
2215  fCreditCached = true;
2216  credit += nCreditCached;
2217  }
2218  }
2219  if (filter & ISMINE_WATCH_ONLY)
2220  {
2221  if (fWatchCreditCached)
2222  credit += nWatchCreditCached;
2223  else
2224  {
2226  fWatchCreditCached = true;
2227  credit += nWatchCreditCached;
2228  }
2229  }
2230  return credit;
2231 }
2232 
2234 {
2235  if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2236  {
2237  if (fUseCache && fImmatureCreditCached)
2238  return nImmatureCreditCached;
2240  fImmatureCreditCached = true;
2241  return nImmatureCreditCached;
2242  }
2243 
2244  return 0;
2245 }
2246 
2248 {
2249  if (pwallet == nullptr)
2250  return 0;
2251 
2252  // Must wait until coinbase is safely deep enough in the chain before valuing it
2253  if (IsCoinBase() && GetBlocksToMaturity() > 0)
2254  return 0;
2255 
2256  if (fUseCache && fAvailableCreditCached)
2257  return nAvailableCreditCached;
2258 
2259  CAmount nCredit = 0;
2260  uint256 hashTx = GetHash();
2261  for (unsigned int i = 0; i < tx->vout.size(); i++)
2262  {
2263  if (!pwallet->IsSpent(hashTx, i))
2264  {
2265  const CTxOut &txout = tx->vout[i];
2266  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
2267  if (!MoneyRange(nCredit))
2268  throw std::runtime_error(std::string(__func__) + ": value out of range");
2269  }
2270  }
2271 
2272  nAvailableCreditCached = nCredit;
2273  fAvailableCreditCached = true;
2274  return nCredit;
2275 }
2276 
2278 {
2279  if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2280  {
2281  if (fUseCache && fImmatureWatchCreditCached)
2286  }
2287 
2288  return 0;
2289 }
2290 
2292 {
2293  if (pwallet == nullptr)
2294  return 0;
2295 
2296  // Must wait until coinbase is safely deep enough in the chain before valuing it
2297  if (IsCoinBase() && GetBlocksToMaturity() > 0)
2298  return 0;
2299 
2300  if (fUseCache && fAvailableWatchCreditCached)
2302 
2303  CAmount nCredit = 0;
2304  for (unsigned int i = 0; i < tx->vout.size(); i++)
2305  {
2306  if (!pwallet->IsSpent(GetHash(), i))
2307  {
2308  const CTxOut &txout = tx->vout[i];
2309  nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2310  if (!MoneyRange(nCredit))
2311  throw std::runtime_error(std::string(__func__) + ": value out of range");
2312  }
2313  }
2314 
2315  nAvailableWatchCreditCached = nCredit;
2317  return nCredit;
2318 }
2319 
2321 {
2322  if (pwallet == 0)
2323  return 0;
2324 
2325  // Exclude coinbase and conflicted txes
2326  if (IsCoinBase() || GetDepthInMainChain() < 0)
2327  return 0;
2328 
2329  if (coinControl == nullptr && fAnonymizedCreditCached)
2330  return nAnonymizedCreditCached;
2331 
2332  CAmount nCredit = 0;
2333  uint256 hashTx = GetHash();
2334  for (unsigned int i = 0; i < tx->vout.size(); i++)
2335  {
2336  const CTxOut &txout = tx->vout[i];
2337  const COutPoint outpoint = COutPoint(hashTx, i);
2338 
2339  if (coinControl != nullptr && coinControl->HasSelected() && !coinControl->IsSelected(outpoint)) {
2340  continue;
2341  }
2342 
2343  if (pwallet->IsSpent(hashTx, i) || !CPrivateSend::IsDenominatedAmount(txout.nValue)) continue;
2344 
2345  if (pwallet->IsFullyMixed(outpoint)) {
2346  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
2347  if (!MoneyRange(nCredit))
2348  throw std::runtime_error(std::string(__func__) + ": value out of range");
2349  }
2350  }
2351 
2352  if (coinControl == nullptr) {
2353  nAnonymizedCreditCached = nCredit;
2354  fAnonymizedCreditCached = true;
2355  }
2356 
2357  return nCredit;
2358 }
2359 
2360 CAmount CWalletTx::GetDenominatedCredit(bool unconfirmed, bool fUseCache) const
2361 {
2362  if (pwallet == 0)
2363  return 0;
2364 
2365  // Must wait until coinbase is safely deep enough in the chain before valuing it
2366  if (IsCoinBase() && GetBlocksToMaturity() > 0)
2367  return 0;
2368 
2369  int nDepth = GetDepthInMainChain();
2370  if (nDepth < 0) return 0;
2371 
2372  bool isUnconfirmed = IsTrusted() && nDepth == 0;
2373  if (unconfirmed != isUnconfirmed) return 0;
2374 
2375  if (fUseCache) {
2376  if(unconfirmed && fDenomUnconfCreditCached)
2377  return nDenomUnconfCreditCached;
2378  else if (!unconfirmed && fDenomConfCreditCached)
2379  return nDenomConfCreditCached;
2380  }
2381 
2382  CAmount nCredit = 0;
2383  uint256 hashTx = GetHash();
2384  for (unsigned int i = 0; i < tx->vout.size(); i++)
2385  {
2386  const CTxOut &txout = tx->vout[i];
2387 
2388  if (pwallet->IsSpent(hashTx, i) || !CPrivateSend::IsDenominatedAmount(txout.nValue)) continue;
2389 
2390  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
2391  if (!MoneyRange(nCredit))
2392  throw std::runtime_error(std::string(__func__) + ": value out of range");
2393  }
2394 
2395  if (unconfirmed) {
2396  nDenomUnconfCreditCached = nCredit;
2397  fDenomUnconfCreditCached = true;
2398  } else {
2399  nDenomConfCreditCached = nCredit;
2400  fDenomConfCreditCached = true;
2401  }
2402  return nCredit;
2403 }
2404 
2406 {
2407  if (fChangeCached)
2408  return nChangeCached;
2410  fChangeCached = true;
2411  return nChangeCached;
2412 }
2413 
2415 {
2416  return fInMempool;
2417 }
2418 
2420 {
2421  // Quick answer in most cases
2422  if (!CheckFinalTx(*tx))
2423  return false;
2424  int nDepth = GetDepthInMainChain();
2425  if (nDepth >= 1)
2426  return true;
2427  if (nDepth < 0)
2428  return false;
2429  if (IsLockedByInstantSend())
2430  return true;
2431  if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2432  return false;
2433 
2434  // Don't trust unconfirmed transactions from us unless they are in the mempool.
2435  if (!InMempool())
2436  return false;
2437 
2438  // Trusted if all inputs are from us and are in the mempool:
2439  for (const CTxIn& txin : tx->vin)
2440  {
2441  // Transactions not sent by us: not trusted
2442  const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2443  if (parent == nullptr)
2444  return false;
2445  const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
2446  if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2447  return false;
2448  }
2449  return true;
2450 }
2451 
2452 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
2453 {
2454  CMutableTransaction tx1 = *this->tx;
2455  CMutableTransaction tx2 = *_tx.tx;
2456  for (auto& txin : tx1.vin) txin.scriptSig = CScript();
2457  for (auto& txin : tx2.vin) txin.scriptSig = CScript();
2458  return CTransaction(tx1) == CTransaction(tx2);
2459 }
2460 
2461 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
2462 {
2463  std::vector<uint256> result;
2464 
2466 
2467  // Sort them in chronological order
2468  std::multimap<unsigned int, CWalletTx*> mapSorted;
2469  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
2470  {
2471  CWalletTx& wtx = item.second;
2472  // Don't rebroadcast if newer than nTime:
2473  if (wtx.nTimeReceived > nTime)
2474  continue;
2475  mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
2476  }
2477  for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
2478  {
2479  CWalletTx& wtx = *item.second;
2480  if (wtx.RelayWalletTransaction(connman))
2481  result.push_back(wtx.GetHash());
2482  }
2483  return result;
2484 }
2485 
2486 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
2487 {
2488  // Do this infrequently and randomly to avoid giving away
2489  // that these are our transactions.
2491  return;
2492  bool fFirst = (nNextResend == 0);
2493  nNextResend = GetTime() + GetRand(30 * 60);
2494  if (fFirst)
2495  return;
2496 
2497  // Only do it if there's been a new block since last time
2498  if (nBestBlockTime < nLastResend)
2499  return;
2500  nLastResend = GetTime();
2501 
2502  // Rebroadcast unconfirmed txes older than 5 minutes before the last
2503  // block was found:
2504  std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
2505  if (!relayed.empty())
2506  LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2507 }
2508  // end of mapWallet
2510 
2511 
2512 
2513 
2520 std::unordered_set<const CWalletTx*, WalletTxHasher> CWallet::GetSpendableTXs() const
2521 {
2523 
2524  std::unordered_set<const CWalletTx*, WalletTxHasher> ret;
2525  for (auto it = setWalletUTXO.begin(); it != setWalletUTXO.end(); ) {
2526  const auto& outpoint = *it;
2527  const auto jt = mapWallet.find(outpoint.hash);
2528  if (jt != mapWallet.end()) {
2529  ret.emplace(&jt->second);
2530  }
2531 
2532  // setWalletUTXO is sorted by COutPoint, which means that all UTXOs for the same TX are neighbors
2533  // skip entries until we encounter a new TX
2534  while (it != setWalletUTXO.end() && it->hash == outpoint.hash) {
2535  ++it;
2536  }
2537  }
2538  return ret;
2539 }
2540 
2542 {
2543  CAmount nTotal = 0;
2544  {
2546  for (auto pcoin : GetSpendableTXs()) {
2547  if (pcoin->IsTrusted())
2548  nTotal += pcoin->GetAvailableCredit();
2549  }
2550  }
2551 
2552  return nTotal;
2553 }
2554 
2555 CAmount CWallet::GetAnonymizableBalance(bool fSkipDenominated, bool fSkipUnconfirmed) const
2556 {
2557  if(!privateSendClient.fEnablePrivateSend) return 0;
2558 
2559  std::vector<CompactTallyItem> vecTally;
2560  if(!SelectCoinsGroupedByAddresses(vecTally, fSkipDenominated, true, fSkipUnconfirmed)) return 0;
2561 
2562  CAmount nTotal = 0;
2563 
2564  const CAmount nSmallestDenom = CPrivateSend::GetSmallestDenomination();
2565  const CAmount nMixingCollateral = CPrivateSend::GetCollateralAmount();
2566  for (const auto& item : vecTally) {
2567  bool fIsDenominated = CPrivateSend::IsDenominatedAmount(item.nAmount);
2568  if(fSkipDenominated && fIsDenominated) continue;
2569  // assume that the fee to create denoms should be mixing collateral at max
2570  if(item.nAmount >= nSmallestDenom + (fIsDenominated ? 0 : nMixingCollateral))
2571  nTotal += item.nAmount;
2572  }
2573 
2574  return nTotal;
2575 }
2576 
2578 {
2579  if(!privateSendClient.fEnablePrivateSend) return 0;
2580 
2581  CAmount nTotal = 0;
2582 
2584 
2585  for (auto pcoin : GetSpendableTXs()) {
2586  nTotal += pcoin->GetAnonymizedCredit(coinControl);
2587  }
2588 
2589  return nTotal;
2590 }
2591 
2592 // Note: calculated including unconfirmed,
2593 // that's ok as long as we use it for informational purposes only
2595 {
2596  if(!privateSendClient.fEnablePrivateSend) return 0;
2597 
2598  int nTotal = 0;
2599  int nCount = 0;
2600 
2602  for (const auto& outpoint : setWalletUTXO) {
2603  if(!IsDenominated(outpoint)) continue;
2604 
2605  nTotal += GetCappedOutpointPrivateSendRounds(outpoint);
2606  nCount++;
2607  }
2608 
2609  if(nCount == 0) return 0;
2610 
2611  return (float)nTotal/nCount;
2612 }
2613 
2614 // Note: calculated including unconfirmed,
2615 // that's ok as long as we use it for informational purposes only
2617 {
2618  if(!privateSendClient.fEnablePrivateSend) return 0;
2619 
2620  CAmount nTotal = 0;
2621 
2623  for (const auto& outpoint : setWalletUTXO) {
2624  const auto it = mapWallet.find(outpoint.hash);
2625  if (it == mapWallet.end()) continue;
2626 
2627  CAmount nValue = it->second.tx->vout[outpoint.n].nValue;
2628  if (!CPrivateSend::IsDenominatedAmount(nValue)) continue;
2629  if (it->second.GetDepthInMainChain() < 0) continue;
2630 
2631  int nRounds = GetCappedOutpointPrivateSendRounds(outpoint);
2632  nTotal += nValue * nRounds / privateSendClient.nPrivateSendRounds;
2633  }
2634 
2635  return nTotal;
2636 }
2637 
2639 {
2640  if(!privateSendClient.fEnablePrivateSend) return 0;
2641 
2642  CAmount nTotal = 0;
2643 
2645 
2646  for (auto pcoin : GetSpendableTXs()) {
2647  nTotal += pcoin->GetDenominatedCredit(unconfirmed);
2648  }
2649 
2650  return nTotal;
2651 }
2652 
2654 {
2655  CAmount nTotal = 0;
2656  {
2658  for (auto pcoin : GetSpendableTXs()) {
2659  if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && !pcoin->IsLockedByInstantSend() && pcoin->InMempool())
2660  nTotal += pcoin->GetAvailableCredit();
2661  }
2662  }
2663  return nTotal;
2664 }
2665 
2667 {
2668  CAmount nTotal = 0;
2669  {
2671  for (auto pcoin : GetSpendableTXs()) {
2672  nTotal += pcoin->GetImmatureCredit();
2673  }
2674  }
2675  return nTotal;
2676 }
2677 
2679 {
2680  CAmount nTotal = 0;
2681  {
2683  for (auto pcoin : GetSpendableTXs()) {
2684  if (pcoin->IsTrusted())
2685  nTotal += pcoin->GetAvailableWatchOnlyCredit();
2686  }
2687  }
2688 
2689  return nTotal;
2690 }
2691 
2693 {
2694  CAmount nTotal = 0;
2695  {
2697  for (auto pcoin : GetSpendableTXs()) {
2698  if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && !pcoin->IsLockedByInstantSend() && pcoin->InMempool())
2699  nTotal += pcoin->GetAvailableWatchOnlyCredit();
2700  }
2701  }
2702  return nTotal;
2703 }
2704 
2706 {
2707  CAmount nTotal = 0;
2708  {
2710  for (auto pcoin : GetSpendableTXs()) {
2711  nTotal += pcoin->GetImmatureWatchOnlyCredit();
2712  }
2713  }
2714  return nTotal;
2715 }
2716 
2717 // Calculate total balance in a different way from GetBalance. The biggest
2718 // difference is that GetBalance sums up all unspent TxOuts paying to the
2719 // wallet, while this sums up both spent and unspent TxOuts paying to the
2720 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2721 // also has fewer restrictions on which unconfirmed transactions are considered
2722 // trusted.
2723 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account, const bool fAddLocked) const
2724 {
2726 
2727  CAmount balance = 0;
2728  for (const auto& entry : mapWallet) {
2729  const CWalletTx& wtx = entry.second;
2730  const int depth = wtx.GetDepthInMainChain();
2731  if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2732  continue;
2733  }
2734 
2735  // Loop through tx outputs and add incoming payments. For outgoing txs,
2736  // treat change outputs specially, as part of the amount debited.
2737  CAmount debit = wtx.GetDebit(filter);
2738  const bool outgoing = debit > 0;
2739  for (const CTxOut& out : wtx.tx->vout) {
2740  if (outgoing && IsChange(out)) {
2741  debit -= out.nValue;
2742  } else if (IsMine(out) & filter && (depth >= minDepth || (fAddLocked && wtx.IsLockedByInstantSend())) && (!account || *account == GetAccountName(out.scriptPubKey))) {
2743  balance += out.nValue;
2744  }
2745  }
2746 
2747  // For outgoing txs, subtract amount debited.
2748  if (outgoing && (!account || *account == wtx.strFromAccount)) {
2749  balance -= debit;
2750  }
2751  }
2752 
2753  if (account) {
2754  balance += WalletBatch(*database).GetAccountCreditDebit(*account);
2755  }
2756 
2757  return balance;
2758 }
2759 
2761 {
2763 
2764  CAmount balance = 0;
2765  std::vector<COutput> vCoins;
2766  AvailableCoins(vCoins, true, coinControl);
2767  for (const COutput& out : vCoins) {
2768  if (out.fSpendable) {
2769  balance += out.tx->tx->vout[out.i].nValue;
2770  }
2771  }
2772  return balance;
2773 }
2774 
2775 void CWallet::AvailableCoins(std::vector<COutput> &vCoins, bool fOnlySafe, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount, const int nMinDepth, const int nMaxDepth) const
2776 {
2777  vCoins.clear();
2778  CoinType nCoinType = coinControl ? coinControl->nCoinType : CoinType::ALL_COINS;
2779 
2780  {
2782 
2783  CAmount nTotal = 0;
2784 
2785  for (auto pcoin : GetSpendableTXs()) {
2786  const uint256& wtxid = pcoin->GetHash();
2787 
2788  if (!CheckFinalTx(*pcoin->tx))
2789  continue;
2790 
2791  if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2792  continue;
2793 
2794  int nDepth = pcoin->GetDepthInMainChain();
2795 
2796  // We should not consider coins which aren't at least in our mempool
2797  // It's possible for these to be conflicted via ancestors which we may never be able to detect
2798  if (nDepth == 0 && !pcoin->InMempool())
2799  continue;
2800 
2801  bool safeTx = pcoin->IsTrusted();
2802 
2803  if (fOnlySafe && !safeTx) {
2804  continue;
2805  }
2806 
2807  if (nDepth < nMinDepth || nDepth > nMaxDepth)
2808  continue;
2809 
2810  for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2811  bool found = false;
2812  if (nCoinType == CoinType::ONLY_FULLY_MIXED) {
2813  if (!CPrivateSend::IsDenominatedAmount(pcoin->tx->vout[i].nValue)) continue;
2814  found = IsFullyMixed(COutPoint(wtxid, i));
2815  } else if(nCoinType == CoinType::ONLY_READY_TO_MIX) {
2816  if (!CPrivateSend::IsDenominatedAmount(pcoin->tx->vout[i].nValue)) continue;
2817  found = !IsFullyMixed(COutPoint(wtxid, i));
2818  } else if(nCoinType == CoinType::ONLY_NONDENOMINATED) {
2819  if (CPrivateSend::IsCollateralAmount(pcoin->tx->vout[i].nValue)) continue; // do not use collateral amounts
2820  found = !CPrivateSend::IsDenominatedAmount(pcoin->tx->vout[i].nValue);
2821  } else if(nCoinType == CoinType::ONLY_MASTERNODE_COLLATERAL) {
2822  found = pcoin->tx->vout[i].nValue == 1000*COIN;
2823  } else if(nCoinType == CoinType::ONLY_PRIVATESEND_COLLATERAL) {
2824  found = CPrivateSend::IsCollateralAmount(pcoin->tx->vout[i].nValue);
2825  } else {
2826  found = true;
2827  }
2828  if(!found) continue;
2829 
2830  if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2831  continue;
2832 
2833  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(wtxid, i)))
2834  continue;
2835 
2836  if (IsLockedCoin(wtxid, i) && nCoinType != CoinType::ONLY_MASTERNODE_COLLATERAL)
2837  continue;
2838 
2839  if (IsSpent(wtxid, i))
2840  continue;
2841 
2842  isminetype mine = IsMine(pcoin->tx->vout[i]);
2843 
2844  if (mine == ISMINE_NO) {
2845  continue;
2846  }
2847 
2848  bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2849  bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2850 
2851  vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2852 
2853  // Checks the sum amount of all UTXO's.
2854  if (nMinimumSumAmount != MAX_MONEY) {
2855  nTotal += pcoin->tx->vout[i].nValue;
2856 
2857  if (nTotal >= nMinimumSumAmount) {
2858  return;
2859  }
2860  }
2861 
2862  // Checks the maximum number of UTXO's.
2863  if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2864  return;
2865  }
2866  }
2867  }
2868  }
2869 }
2870 
2871 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2872 {
2873  // TODO: Add AssertLockHeld(cs_wallet) here.
2874  //
2875  // Because the return value from this function contains pointers to
2876  // CWalletTx objects, callers to this function really should acquire the
2877  // cs_wallet lock before calling it. However, the current caller doesn't
2878  // acquire this lock yet. There was an attempt to add the missing lock in
2879  // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2880  // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2881  // avoid adding some extra complexity to the Qt code.
2882 
2883  std::map<CTxDestination, std::vector<COutput>> result;
2884 
2885  std::vector<COutput> availableCoins;
2886  AvailableCoins(availableCoins);
2887 
2889  for (auto& coin : availableCoins) {
2890  CTxDestination address;
2891  if (coin.fSpendable &&
2892  ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2893  result[address].emplace_back(std::move(coin));
2894  }
2895  }
2896 
2897  std::vector<COutPoint> lockedCoins;
2898  ListLockedCoins(lockedCoins);
2899  for (const auto& output : lockedCoins) {
2900  auto it = mapWallet.find(output.hash);
2901  if (it != mapWallet.end()) {
2902  int depth = it->second.GetDepthInMainChain();
2903  if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2904  IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2905  CTxDestination address;
2906  if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2907  result[address].emplace_back(
2908  &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2909  }
2910  }
2911  }
2912  }
2913 
2914  return result;
2915 }
2916 
2917 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2918 {
2919  const CTransaction* ptx = &tx;
2920  int n = output;
2921  while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2922  const COutPoint& prevout = ptx->vin[0].prevout;
2923  auto it = mapWallet.find(prevout.hash);
2924  if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2925  !IsMine(it->second.tx->vout[prevout.n])) {
2926  break;
2927  }
2928  ptx = it->second.tx.get();
2929  n = prevout.n;
2930  }
2931  return ptx->vout[n];
2932 }
2933 
2935 {
2936  // Avoid fetching it multiple times
2937  assert(nPrivateSendSalt.IsNull());
2938 
2939  WalletBatch batch(*database);
2940  batch.ReadPrivateSendSalt(nPrivateSendSalt);
2941 
2942  while (nPrivateSendSalt.IsNull()) {
2943  // We never generated/saved it
2945  batch.WritePrivateSendSalt(nPrivateSendSalt);
2946  }
2947 }
2948 
2949 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2950  std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2951 {
2952  std::vector<char> vfIncluded;
2953 
2954  vfBest.assign(vValue.size(), true);
2955  nBest = nTotalLower;
2956  int nBestInputCount = 0;
2957 
2958  FastRandomContext insecure_rand;
2959 
2960  for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2961  {
2962  vfIncluded.assign(vValue.size(), false);
2963  CAmount nTotal = 0;
2964  int nTotalInputCount = 0;
2965  bool fReachedTarget = false;
2966  for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2967  {
2968  for (unsigned int i = 0; i < vValue.size(); i++)
2969  {
2970  //The solver here uses a randomized algorithm,
2971  //the randomness serves no real security purpose but is just
2972  //needed to prevent degenerate behavior and it is important
2973  //that the rng is fast. We do not use a constant random sequence,
2974  //because there may be some privacy improvement by making
2975  //the selection random.
2976  if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2977  {
2978  nTotal += vValue[i].txout.nValue;
2979  ++nTotalInputCount;
2980  vfIncluded[i] = true;
2981  if (nTotal >= nTargetValue)
2982  {
2983  fReachedTarget = true;
2984  if (nTotal < nBest || (nTotal == nBest && nTotalInputCount < nBestInputCount))
2985  {
2986  nBest = nTotal;
2987  nBestInputCount = nTotalInputCount;
2988  vfBest = vfIncluded;
2989  }
2990  nTotal -= vValue[i].txout.nValue;
2991  --nTotalInputCount;
2992  vfIncluded[i] = false;
2993  }
2994  }
2995  }
2996  }
2997  }
2998 }
2999 
3001 {
3002  bool operator()(const COutput& t1,
3003  const COutput& t2) const
3004  {
3005  return t1.Priority() > t2.Priority();
3006  }
3007 };
3008 
3009 // move denoms down
3010 bool less_then_denom (const COutput& out1, const COutput& out2)
3011 {
3012  const CWalletTx *pcoin1 = out1.tx;
3013  const CWalletTx *pcoin2 = out2.tx;
3014 
3015  bool found1 = false;
3016  bool found2 = false;
3017  for (const auto& d : CPrivateSend::GetStandardDenominations()) // loop through predefined denoms
3018  {
3019  if(pcoin1->tx->vout[out1.i].nValue == d) found1 = true;
3020  if(pcoin2->tx->vout[out2.i].nValue == d) found2 = true;
3021  }
3022  return (!found1 && found2);
3023 }
3024 
3025 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
3026  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, CoinType nCoinType) const
3027 {
3028  setCoinsRet.clear();
3029  nValueRet = 0;
3030 
3031  // List of values less than target
3032  boost::optional<CInputCoin> coinLowestLarger;
3033  std::vector<CInputCoin> vValue;
3034  CAmount nTotalLower = 0;
3035 
3036  random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3037 
3038  int tryDenomStart = 0;
3039  CAmount nMinChange = MIN_CHANGE;
3040 
3041  if (nCoinType == CoinType::ONLY_FULLY_MIXED) {
3042  // larger denoms first
3043  std::sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority());
3044  // we actually want denoms only, so let's skip "non-denom only" step
3045  tryDenomStart = 1;
3046  // no change is allowed
3047  nMinChange = 0;
3048  } else {
3049  // move denoms down on the list
3050  // try not to use denominated coins when not needed, save denoms for privatesend
3051  std::sort(vCoins.begin(), vCoins.end(), less_then_denom);
3052  }
3053 
3054  // try to find nondenom first to prevent unneeded spending of mixed coins
3055  for (unsigned int tryDenom = tryDenomStart; tryDenom < 2; tryDenom++)
3056  {
3057  LogPrint(BCLog::SELECTCOINS, "tryDenom: %d\n", tryDenom);
3058  vValue.clear();
3059  nTotalLower = 0;
3060  for (const COutput &output : vCoins)
3061  {
3062  if (!output.fSpendable)
3063  continue;
3064 
3065  const CWalletTx *pcoin = output.tx;
3066 
3067  bool fLockedByIS = pcoin->IsLockedByInstantSend();
3068 
3069  // if (logCategories != BCLog::NONE) LogPrint(BCLog::SELECTCOINS, "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth);
3070  if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs) && !fLockedByIS)
3071  continue;
3072 
3073  if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
3074  continue;
3075 
3076  int i = output.i;
3077 
3078  CInputCoin coin = CInputCoin(pcoin, i);
3079 
3080  if (tryDenom == 0 && CPrivateSend::IsDenominatedAmount(coin.txout.nValue)) continue; // we don't want denom values on first run
3081 
3082  if (coin.txout.nValue == nTargetValue)
3083  {
3084  setCoinsRet.insert(coin);
3085  nValueRet += coin.txout.nValue;
3086  return true;
3087  }
3088  else if (coin.txout.nValue < nTargetValue + nMinChange)
3089  {
3090  vValue.push_back(coin);
3091  nTotalLower += coin.txout.nValue;
3092  }
3093  else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
3094  {
3095  coinLowestLarger = coin;
3096  }
3097  }
3098 
3099  if (nTotalLower == nTargetValue)
3100  {
3101  for (const auto& input : vValue)
3102  {
3103  setCoinsRet.insert(input);
3104  nValueRet += input.txout.nValue;
3105  }
3106  return true;
3107  }
3108 
3109  if (nTotalLower < nTargetValue)
3110  {
3111  if (!coinLowestLarger) // there is no input larger than nTargetValue
3112  {
3113  if (tryDenom == 0)
3114  // we didn't look at denom yet, let's do it
3115  continue;
3116  else
3117  // we looked at everything possible and didn't find anything, no luck
3118  return false;
3119  }
3120  setCoinsRet.insert(coinLowestLarger.get());
3121  nValueRet += coinLowestLarger->txout.nValue;
3122  // There is no change in PS, so we know the fee beforehand,
3123  // can see if we exceeded the max fee and thus fail quickly.
3124  return (nCoinType == CoinType::ONLY_FULLY_MIXED) ? (nValueRet - nTargetValue <= maxTxFee) : true;
3125  }
3126 
3127  // nTotalLower > nTargetValue
3128  break;
3129  }
3130 
3131  // Solve subset sum by stochastic approximation
3132  std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
3133  std::reverse(vValue.begin(), vValue.end());
3134  std::vector<char> vfBest;
3135  CAmount nBest;
3136 
3137  ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
3138  if (nBest != nTargetValue && nMinChange != 0 && nTotalLower >= nTargetValue + nMinChange)
3139  ApproximateBestSubset(vValue, nTotalLower, nTargetValue + nMinChange, vfBest, nBest);
3140 
3141  // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
3142  // or the next bigger coin is closer), return the bigger coin
3143  if (coinLowestLarger &&
3144  ((nBest != nTargetValue && nBest < nTargetValue + nMinChange) || coinLowestLarger->txout.nValue <= nBest))
3145  {
3146  setCoinsRet.insert(coinLowestLarger.get());
3147  nValueRet += coinLowestLarger->txout.nValue;
3148  }
3149  else {
3150  std::string s = "CWallet::SelectCoinsMinConf best subset: ";
3151  for (unsigned int i = 0; i < vValue.size(); i++)
3152  {
3153  if (vfBest[i])
3154  {
3155  setCoinsRet.insert(vValue[i]);
3156  nValueRet += vValue[i].txout.nValue;
3157  s += FormatMoney(vValue[i].txout.nValue) + " ";
3158  }
3159  }
3160  LogPrint(BCLog::SELECTCOINS, "%s - total %s\n", s, FormatMoney(nBest));
3161  }
3162 
3163  // There is no change in PS, so we know the fee beforehand,
3164  // can see if we exceeded the max fee and thus fail quickly.
3165  return (nCoinType == CoinType::ONLY_FULLY_MIXED) ? (nValueRet - nTargetValue <= maxTxFee) : true;
3166 }
3167 
3168 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
3169 {
3170  // Note: this function should never be used for "always free" tx types like dstx
3171 
3172  std::vector<COutput> vCoins(vAvailableCoins);
3173  CoinType nCoinType = coinControl ? coinControl->nCoinType : CoinType::ALL_COINS;
3174 
3175  // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
3176  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
3177  {
3178  for (const COutput& out : vCoins)
3179  {
3180  if(!out.fSpendable)
3181  continue;
3182 
3183  nValueRet += out.tx->tx->vout[out.i].nValue;
3184  setCoinsRet.insert(CInputCoin(out.tx, out.i));
3185 
3186  if (!coinControl->fRequireAllInputs && nValueRet >= nTargetValue) {
3187  // stop when we added at least one input and enough inputs to have at least nTargetValue funds
3188  return true;
3189  }
3190  }
3191 
3192  return (nValueRet >= nTargetValue);
3193  }
3194 
3195  // calculate value from preset inputs and store them
3196  std::set<CInputCoin> setPresetCoins;
3197  CAmount nValueFromPresetInputs = 0;
3198 
3199  std::vector<COutPoint> vPresetInputs;
3200  if (coinControl)
3201  coinControl->ListSelected(vPresetInputs);
3202  for (const COutPoint& outpoint : vPresetInputs)
3203  {
3204  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
3205  if (it != mapWallet.end())
3206  {
3207  const CWalletTx* pcoin = &it->second;
3208  // Clearly invalid input, fail
3209  if (pcoin->tx->vout.size() <= outpoint.n)
3210  return false;
3211  if (nCoinType == CoinType::ONLY_FULLY_MIXED) {
3212  // Make sure to include mixed preset inputs only,
3213  // even if some non-mixed inputs were manually selected via CoinControl
3214  if (!IsFullyMixed(outpoint)) continue;
3215  }
3216  nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
3217  setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
3218  } else
3219  return false; // TODO: Allow non-wallet inputs
3220  }
3221 
3222  // remove preset inputs from vCoins
3223  for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
3224  {
3225  if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
3226  it = vCoins.erase(it);
3227  else
3228  ++it;
3229  }
3230 
3231  size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
3232  bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
3233 
3234  bool res = nTargetValue <= nValueFromPresetInputs ||
3235  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet, nCoinType) ||
3236  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet, nCoinType) ||
3237  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet, nCoinType)) ||
3238  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet, nCoinType)) ||
3239  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet, nCoinType)) ||
3240  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet, nCoinType)) ||
3241  (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet, nCoinType));
3242 
3243  // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
3244  setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
3245 
3246  // add preset inputs to the total value selected
3247  nValueRet += nValueFromPresetInputs;
3248 
3249  return res;
3250 }
3251 
3252 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
3253 {
3254  std::vector<CRecipient> vecSend;
3255 
3256  // Turn the txout set into a CRecipient vector.
3257  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
3258  const CTxOut& txOut = tx.vout[idx];
3259  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
3260  vecSend.push_back(recipient);
3261  }
3262 
3263  coinControl.fAllowOtherInputs = true;
3264 
3265  for (const CTxIn& txin : tx.vin) {
3266  coinControl.Select(txin.prevout);
3267  }
3268 
3269  // Acquire the locks to prevent races to the new locked unspents between the
3270  // CreateTransaction call and LockCoin calls (when lockUnspents is true).
3271  LOCK2(cs_main, mempool.cs);
3272  LOCK(cs_wallet);
3273 
3274  int nExtraPayloadSize = 0;
3275  if (tx.nVersion == 3 && tx.nType != TRANSACTION_NORMAL)
3276  nExtraPayloadSize = (int)tx.vExtraPayload.size();
3277 
3278  CReserveKey reservekey(this);
3279  CWalletTx wtx;
3280  if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false, nExtraPayloadSize)) {
3281  return false;
3282  }
3283 
3284  if (nChangePosInOut != -1) {
3285  tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
3286  // We don't have the normal Create/Commit cycle, and don't want to risk
3287  // reusing change, so just remove the key from the keypool here.
3288  reservekey.KeepKey();
3289  }
3290 
3291  // Copy output sizes from new transaction; they may have had the fee
3292  // subtracted from them.
3293  for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
3294  tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
3295  }
3296 
3297  // Add new txins while keeping original txin scriptSig/order.
3298  for (const CTxIn& txin : wtx.tx->vin) {
3299  if (!coinControl.IsSelected(txin.prevout)) {
3300  tx.vin.push_back(txin);
3301 
3302  if (lockUnspents) {
3303  LockCoin(txin.prevout);
3304  }
3305  }
3306  }
3307 
3308  return true;
3309 }
3310 
3311 bool CWallet::SelectPSInOutPairsByDenominations(int nDenom, CAmount nValueMax, std::vector< std::pair<CTxDSIn, CTxOut> >& vecPSInOutPairsRet)
3312 {
3313  CAmount nValueTotal{0};
3314 
3315  std::set<uint256> setRecentTxIds;
3316  std::vector<COutput> vCoins;
3317 
3318  vecPSInOutPairsRet.clear();
3319 
3320  if (!CPrivateSend::IsValidDenomination(nDenom)) {
3321  return false;
3322  }
3323  CAmount nDenomAmount = CPrivateSend::DenominationToAmount(nDenom);
3324 
3325  CCoinControl coin_control;
3326  coin_control.nCoinType = CoinType::ONLY_READY_TO_MIX;
3327  AvailableCoins(vCoins, true, &coin_control);
3328  LogPrint(BCLog::PRIVATESEND, "CWallet::%s -- vCoins.size(): %d\n", __func__, vCoins.size());
3329 
3330  std::random_shuffle(vCoins.rbegin(), vCoins.rend(), GetRandInt);
3331 
3332  for (const auto& out : vCoins) {
3333  uint256 txHash = out.tx->GetHash();
3334  CAmount nValue = out.tx->tx->vout[out.i].nValue;
3335  if (setRecentTxIds.find(txHash) != setRecentTxIds.end()) continue; // no duplicate txids
3336  if (nValueTotal + nValue > nValueMax) continue;
3337 
3338  CTxIn txin = CTxIn(txHash, out.i);
3339  CScript scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
3340  int nRounds = GetRealOutpointPrivateSendRounds(txin.prevout);
3341 
3342  if (nValue != nDenomAmount) continue;
3343  nValueTotal += nValue;
3344  vecPSInOutPairsRet.emplace_back(CTxDSIn(txin, scriptPubKey), CTxOut(nValue, scriptPubKey, nRounds));
3345  setRecentTxIds.emplace(txHash);
3346  LogPrint(BCLog::PRIVATESEND, "CWallet::%s -- hash: %s, nValue: %d.%08d, nRounds: %d\n",
3347  __func__, txHash.ToString(), nValue / COIN, nValue % COIN, nRounds);
3348  }
3349 
3350  LogPrint(BCLog::PRIVATESEND, "CWallet::%s -- setRecentTxIds.size(): %d\n", __func__, setRecentTxIds.size());
3351 
3352  return nValueTotal > 0;
3353 }
3354 
3355 bool CWallet::SelectCoinsGroupedByAddresses(std::vector<CompactTallyItem>& vecTallyRet, bool fSkipDenominated, bool fAnonymizable, bool fSkipUnconfirmed, int nMaxOupointsPerAddress) const
3356 {
3358 
3359  isminefilter filter = ISMINE_SPENDABLE;
3360 
3361  // Try using the cache for already confirmed mixable inputs.
3362  // This should only be used if nMaxOupointsPerAddress was NOT specified.
3363  if(nMaxOupointsPerAddress == -1 && fAnonymizable && fSkipUnconfirmed) {
3364  if(fSkipDenominated && fAnonymizableTallyCachedNonDenom) {
3365  vecTallyRet = vecAnonymizableTallyCachedNonDenom;
3366  LogPrint(BCLog::SELECTCOINS, "SelectCoinsGroupedByAddresses - using cache for non-denom inputs %d\n", vecTallyRet.size());
3367  return vecTallyRet.size() > 0;
3368  }
3369  if(!fSkipDenominated && fAnonymizableTallyCached) {
3370  vecTallyRet = vecAnonymizableTallyCached;
3371  LogPrint(BCLog::SELECTCOINS, "SelectCoinsGroupedByAddresses - using cache for all inputs %d\n", vecTallyRet.size());
3372  return vecTallyRet.size() > 0;
3373  }
3374  }
3375 
3377 
3378  // Tally
3379  std::map<CTxDestination, CompactTallyItem> mapTally;
3380  std::set<uint256> setWalletTxesCounted;
3381  for (const auto& outpoint : setWalletUTXO) {
3382 
3383  if (!setWalletTxesCounted.emplace(outpoint.hash).second) continue;
3384 
3385  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
3386  if (it == mapWallet.end()) continue;
3387 
3388  const CWalletTx& wtx = (*it).second;
3389 
3390  if(wtx.IsCoinBase() && wtx.GetBlocksToMaturity() > 0) continue;
3391  if(fSkipUnconfirmed && !wtx.IsTrusted()) continue;
3392 
3393  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
3394  CTxDestination txdest;
3395  if (!ExtractDestination(wtx.tx->vout[i].scriptPubKey, txdest)) continue;
3396 
3397  isminefilter mine = ::IsMine(*this, txdest);
3398  if(!(mine & filter)) continue;
3399 
3400  auto itTallyItem = mapTally.find(txdest);
3401  if (nMaxOupointsPerAddress != -1 && itTallyItem != mapTally.end() && itTallyItem->second.vecOutPoints.size() >= nMaxOupointsPerAddress) continue;
3402 
3403  if(IsSpent(outpoint.hash, i) || IsLockedCoin(outpoint.hash, i)) continue;
3404 
3405  if(fSkipDenominated && CPrivateSend::IsDenominatedAmount(wtx.tx->vout[i].nValue)) continue;
3406 
3407  if(fAnonymizable) {
3408  // ignore collaterals
3409  if(CPrivateSend::IsCollateralAmount(wtx.tx->vout[i].nValue)) continue;
3410  if(fMasternodeMode && wtx.tx->vout[i].nValue == 1000*COIN) continue;
3411  // ignore outputs that are 10 times smaller then the smallest denomination
3412  // otherwise they will just lead to higher fee / lower priority
3413  if(wtx.tx->vout[i].nValue <= nSmallestDenom/10) continue;
3414  // ignore mixed
3415  if (IsFullyMixed(COutPoint(outpoint.hash, i))) continue;
3416  }
3417 
3418  if (itTallyItem == mapTally.end()) {
3419  itTallyItem = mapTally.emplace(txdest, CompactTallyItem()).first;
3420  itTallyItem->second.txdest = txdest;
3421  }
3422  itTallyItem->second.nAmount += wtx.tx->vout[i].nValue;
3423  itTallyItem->second.vecOutPoints.emplace_back(outpoint.hash, i);
3424  }
3425  }
3426 
3427  // construct resulting vector
3428  // NOTE: vecTallyRet is "sorted" by txdest (i.e. address), just like mapTally
3429  vecTallyRet.clear();
3430  for (const auto& item : mapTally) {
3431  if(fAnonymizable && item.second.nAmount < nSmallestDenom) continue;
3432  vecTallyRet.push_back(item.second);
3433  }
3434 
3435  // Cache already confirmed mixable entries for later use.
3436  // This should only be used if nMaxOupointsPerAddress was NOT specified.
3437  if(nMaxOupointsPerAddress == -1 && fAnonymizable && fSkipUnconfirmed) {
3438  if(fSkipDenominated) {
3439  vecAnonymizableTallyCachedNonDenom = vecTallyRet;
3441  } else {
3442  vecAnonymizableTallyCached = vecTallyRet;
3443  fAnonymizableTallyCached = true;
3444  }
3445  }
3446 
3447  // debug
3449  std::string strMessage = "SelectCoinsGroupedByAddresses - vecTallyRet:\n";
3450  for (const auto& item : vecTallyRet)
3451  strMessage += strprintf(" %s %f\n", EncodeDestination(item.txdest).c_str(), float(item.nAmount)/COIN);
3452  LogPrint(BCLog::SELECTCOINS, "%s", strMessage);
3453  }
3454 
3455  return vecTallyRet.size() > 0;
3456 }
3457 
3458 bool CWallet::SelectDenominatedAmounts(CAmount nValueMax, std::set<CAmount>& setAmountsRet) const
3459 {
3460  CAmount nValueTotal{0};
3461  setAmountsRet.clear();
3462 
3463  std::vector<COutput> vCoins;
3464  CCoinControl coin_control;
3465  coin_control.nCoinType = CoinType::ONLY_READY_TO_MIX;
3466  AvailableCoins(vCoins, true, &coin_control);
3467  // larger denoms first
3468  std::sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority());
3469 
3470  for (const auto& out : vCoins) {
3471  CAmount nValue = out.tx->tx->vout[out.i].nValue;
3472  if (nValueTotal + nValue <= nValueMax) {
3473  nValueTotal += nValue;
3474  setAmountsRet.emplace(nValue);
3475  }
3476  }
3477 
3478  return nValueTotal >= CPrivateSend::GetSmallestDenomination();
3479 }
3480 
3481 bool CWallet::GetCollateralTxDSIn(CTxDSIn& txdsinRet, CAmount& nValueRet) const
3482 {
3484 
3485  std::vector<COutput> vCoins;
3486 
3487  CCoinControl coin_control;
3489  AvailableCoins(vCoins, true, &coin_control);
3490 
3491  if (vCoins.empty()) {
3492  return false;
3493  }
3494 
3495  const auto& out = vCoins.at((int)GetRandInt(vCoins.size()));
3496  txdsinRet = CTxDSIn(CTxIn(out.tx->tx->GetHash(), out.i), out.tx->tx->vout[out.i].scriptPubKey);
3497  nValueRet = out.tx->tx->vout[out.i].nValue;
3498  return true;
3499 }
3500 
3501 bool CWallet::GetMasternodeOutpointAndKeys(COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet, const std::string& strTxHash, const std::string& strOutputIndex)
3502 {
3503  // wait for reindex and/or import to finish
3504  if (fImporting || fReindex) return false;
3505 
3506  // Find possible candidates
3507  std::vector<COutput> vPossibleCoins;
3508  CCoinControl coin_control;
3510  AvailableCoins(vPossibleCoins, true, &coin_control);
3511  if(vPossibleCoins.empty()) {
3512  LogPrintf("CWallet::GetMasternodeOutpointAndKeys -- Could not locate any valid masternode vin\n");
3513  return false;
3514  }
3515 
3516  if(strTxHash.empty()) // No output specified, select the first one
3517  return GetOutpointAndKeysFromOutput(vPossibleCoins[0], outpointRet, pubKeyRet, keyRet);
3518 
3519  // Find specific outpoint
3520  uint256 txHash = uint256S(strTxHash);
3521  int nOutputIndex = atoi(strOutputIndex);
3522 
3523  for (const auto& out : vPossibleCoins)
3524  if(out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it!
3525  return GetOutpointAndKeysFromOutput(out, outpointRet, pubKeyRet, keyRet);
3526 
3527  LogPrintf("CWallet::GetMasternodeOutpointAndKeys -- Could not locate specified masternode vin\n");
3528  return false;
3529 }
3530 
3531 bool CWallet::GetOutpointAndKeysFromOutput(const COutput& out, COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet)
3532 {
3533  // wait for reindex and/or import to finish
3534  if (fImporting || fReindex) return false;
3535 
3536  CScript pubScript;
3537 
3538  outpointRet = COutPoint(out.tx->GetHash(), out.i);
3539  pubScript = out.tx->tx->vout[out.i].scriptPubKey; // the inputs PubKey
3540 
3541  CTxDestination dest;
3542  ExtractDestination(pubScript, dest);
3543 
3544  const CKeyID *keyID = boost::get<CKeyID>(&dest);
3545  if (!keyID) {
3546  LogPrintf("CWallet::GetOutpointAndKeysFromOutput -- Address does not refer to a key\n");
3547  return false;
3548  }
3549 
3550  if (!GetKey(*keyID, keyRet)) {
3551  LogPrintf ("CWallet::GetOutpointAndKeysFromOutput -- Private key for address is not known\n");
3552  return false;
3553  }
3554 
3555  pubKeyRet = keyRet.GetPubKey();
3556  return true;
3557 }
3558 
3560 {
3561  CAmount nTotal = 0;
3562 
3564 
3565  for (const auto& outpoint : setWalletUTXO) {
3566  const auto it = mapWallet.find(outpoint.hash);
3567  if (it == mapWallet.end()) continue;
3568  if (it->second.tx->vout[outpoint.n].nValue != nInputAmount) continue;
3569  if (it->second.GetDepthInMainChain() < 0) continue;
3570 
3571  nTotal++;
3572  }
3573 
3574  return nTotal;
3575 }
3576 
3577 bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const
3578 {
3579  std::vector<COutput> vCoins;
3580  CCoinControl coin_control;
3582  AvailableCoins(vCoins, fOnlyConfirmed, &coin_control);
3583 
3584  return !vCoins.empty();
3585 }
3586 
3587 bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason)
3588 {
3590 
3591  txCollateral.vin.clear();
3592  txCollateral.vout.clear();
3593 
3594  CReserveKey reservekey(this);
3595  CAmount nValue = 0;
3596  CTxDSIn txdsinCollateral;
3597 
3598  if (!GetCollateralTxDSIn(txdsinCollateral, nValue)) {
3599  strReason = "PrivateSend requires a collateral transaction and could not locate an acceptable input!";
3600  return false;
3601  }
3602 
3603  txCollateral.vin.push_back(txdsinCollateral);
3604 
3605  // pay collateral charge in fees
3606  // NOTE: no need for protobump patch here,
3607  // CPrivateSend::IsCollateralAmount in GetCollateralTxDSIn should already take care of this
3608  if (nValue >= CPrivateSend::GetCollateralAmount() * 2) {
3609  // make our change address
3610  CScript scriptChange;
3611  CPubKey vchPubKey;
3612  bool success = reservekey.GetReservedKey(vchPubKey, true);
3613  assert(success); // should never fail, as we just unlocked
3614  scriptChange = GetScriptForDestination(vchPubKey.GetID());
3615  reservekey.KeepKey();
3616  // return change
3617  txCollateral.vout.push_back(CTxOut(nValue - CPrivateSend::GetCollateralAmount(), scriptChange));
3618  } else { // nValue < CPrivateSend::GetCollateralAmount() * 2
3619  // create dummy data output only and pay everything as a fee
3620  txCollateral.vout.push_back(CTxOut(0, CScript() << OP_RETURN));
3621  }
3622 
3623  if (!SignSignature(*this, txdsinCollateral.prevPubKey, txCollateral, 0, nValue, SIGHASH_ALL)) {
3624  strReason = "Unable to sign collateral transaction!";
3625  return false;
3626  }
3627 
3628  return true;
3629 }
3630 
3632 {
3633  // make our change address
3634  CReserveKey reservekey(this);
3635 
3636  CScript scriptChange;
3637  scriptChange << OP_RETURN << ToByteVector(hash);
3638 
3639  CAmount nFeeRet = 0;
3640  int nChangePosRet = -1;
3641  std::string strFail = "";
3642  std::vector< CRecipient > vecSend;
3643  vecSend.push_back((CRecipient){scriptChange, amount, false});
3644 
3645  CCoinControl coinControl;
3646  if (!outpoint.IsNull()) {
3647  coinControl.Select(outpoint);
3648  }
3649  bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, nChangePosRet, strFail, coinControl);
3650  if(!success){
3651  LogPrintf("CWallet::GetBudgetSystemCollateralTX -- Error: %s\n", strFail);
3652  return false;
3653  }
3654 
3655  return true;
3656 }
3657 
3658 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
3659  int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign, int nExtraPayloadSize)
3660 {
3661  CAmount nValue = 0;
3662  int nChangePosRequest = nChangePosInOut;
3663  unsigned int nSubtractFeeFromAmount = 0;
3664  for (const auto& recipient : vecSend)
3665  {
3666  if (nValue < 0 || recipient.nAmount < 0)
3667  {
3668  strFailReason = _("Transaction amounts must not be negative");
3669  return false;
3670  }
3671  nValue += recipient.nAmount;
3672 
3673  if (recipient.fSubtractFeeFromAmount)
3674  nSubtractFeeFromAmount++;
3675  }
3676  if (vecSend.empty())
3677  {
3678  strFailReason = _("Transaction must have at least one recipient");
3679  return false;
3680  }
3681 
3682  wtxNew.fTimeReceivedIsTxTime = true;
3683  wtxNew.BindWallet(this);
3684  if (coin_control.nCoinType == CoinType::ONLY_FULLY_MIXED) {
3685  wtxNew.mapValue["DS"] = "1";
3686  }
3687 
3688  CMutableTransaction txNew;
3689 
3690  // Discourage fee sniping.
3691  //
3692  // For a large miner the value of the transactions in the best block and
3693  // the mempool can exceed the cost of deliberately attempting to mine two
3694  // blocks to orphan the current best block. By setting nLockTime such that
3695  // only the next block can include the transaction, we discourage this
3696  // practice as the height restricted and limited blocksize gives miners
3697  // considering fee sniping fewer options for pulling off this attack.
3698  //
3699  // A simple way to think about this is from the wallet's point of view we
3700  // always want the blockchain to move forward. By setting nLockTime this
3701  // way we're basically making the statement that we only want this
3702  // transaction to appear in the next block; we don't want to potentially
3703  // encourage reorgs by allowing transactions to appear at lower heights
3704  // than the next block in forks of the best chain.
3705  //
3706  // Of course, the subsidy is high enough, and transaction volume low
3707  // enough, that fee sniping isn't a problem yet, but by implementing a fix
3708  // now we ensure code won't be written that makes assumptions about
3709  // nLockTime that preclude a fix later.
3710 
3711  txNew.nLockTime = chainActive.Height();
3712 
3713  // Secondly occasionally randomly pick a nLockTime even further back, so
3714  // that transactions that are delayed after signing for whatever reason,
3715  // e.g. high-latency mix networks and some CoinJoin implementations, have
3716  // better privacy.
3717  if (GetRandInt(10) == 0)
3718  txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
3719 
3720  assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
3721  assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
3722  FeeCalculation feeCalc;
3723  CFeeRate discard_rate = coin_control.m_discard_feerate ? *coin_control.m_discard_feerate : GetDiscardRate(::feeEstimator);
3724  unsigned int nBytes;
3725  {
3726  std::vector<CInputCoin> vecCoins;
3727  LOCK2(cs_main, mempool.cs);
3728  LOCK(cs_wallet);
3729  {
3730  CAmount nAmountAvailable{0};
3731  std::vector<COutput> vAvailableCoins;
3732  AvailableCoins(vAvailableCoins, true, &coin_control);
3733 
3734  for (auto out : vAvailableCoins) {
3735  if (out.fSpendable) {
3736  nAmountAvailable += out.tx->tx->vout[out.i].nValue;
3737  }
3738  }
3739 
3740  // Create change script that will be used if we need change
3741  // TODO: pass in scriptChange instead of reservekey so
3742  // change transaction isn't always pay-to-bitcoin-address
3743  CScript scriptChange;
3744 
3745  // coin control: send change to custom address
3746  if (!boost::get<CNoDestination>(&coin_control.destChange)) {
3747  scriptChange = GetScriptForDestination(coin_control.destChange);
3748  } else { // no coin control: send change to newly generated address
3749  // Note: We use a new key here to keep it from being obvious which side is the change.
3750  // The drawback is that by not reusing a previous key, the change may be lost if a
3751  // backup is restored, if the backup doesn't have the new private key for the change.
3752  // If we reused the old key, it would be possible to add code to look for and
3753  // rediscover unknown transactions that were written with keys of ours to recover
3754  // post-backup change.
3755 
3756  // Reserve a new key pair from key pool
3757  CPubKey vchPubKey;
3758  bool ret;
3759  ret = reservekey.GetReservedKey(vchPubKey, true);
3760  if (!ret)
3761  {
3762  strFailReason = _("Keypool ran out, please call keypoolrefill first");
3763  return false;
3764  }
3765 
3766  scriptChange = GetScriptForDestination(vchPubKey.GetID());
3767  }
3768 
3769  nFeeRet = 0;
3770  bool pick_new_inputs = true;
3771  CAmount nValueIn = 0;
3772  CAmount nAmountToSelectAdditional{0};
3773  // Start with nAmountToSelectAdditional=0 and loop until there is enough to cover the request + fees, try it 500 times.
3774  int nMaxTries = 500;
3775  while (--nMaxTries > 0)
3776  {
3777  nChangePosInOut = std::numeric_limits<int>::max();
3778  txNew.vin.clear();
3779  txNew.vout.clear();
3780  wtxNew.fFromMe = true;
3781  bool fFirst = true;
3782 
3783  CAmount nValueToSelect = nValue;
3784  if (nSubtractFeeFromAmount == 0) {
3785  assert(nAmountToSelectAdditional >= 0);
3786  nValueToSelect += nAmountToSelectAdditional;
3787  }
3788  // vouts to the payees
3789  for (const auto& recipient : vecSend)
3790  {
3791  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
3792 
3793  if (recipient.fSubtractFeeFromAmount)
3794  {
3795  assert(nSubtractFeeFromAmount != 0);
3796  txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
3797 
3798  if (fFirst) // first receiver pays the remainder not divisible by output count
3799  {
3800  fFirst = false;
3801  txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
3802  }
3803  }
3804 
3805  if (IsDust(txout, ::dustRelayFee))
3806  {
3807  if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
3808  {
3809  if (txout.nValue < 0)
3810  strFailReason = _("The transaction amount is too small to pay the fee");
3811  else
3812  strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3813  }
3814  else
3815  strFailReason = _("Transaction amount too small");
3816  return false;
3817  }
3818  txNew.vout.push_back(txout);
3819  }
3820 
3821  // Choose coins to use
3822  if (pick_new_inputs) {
3823  nValueIn = 0;
3824  std::set<CInputCoin> setCoinsTmp;
3825  if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoinsTmp, nValueIn, &coin_control)) {
3826  if (coin_control.nCoinType == CoinType::ONLY_NONDENOMINATED) {
3827  strFailReason = _("Unable to locate enough PrivateSend non-denominated funds for this transaction.");
3828  } else if (coin_control.nCoinType == CoinType::ONLY_FULLY_MIXED) {
3829  strFailReason = _("Unable to locate enough PrivateSend denominated funds for this transaction.");
3830  strFailReason += " " + _("PrivateSend uses exact denominated amounts to send funds, you might simply need to mix some more coins.");
3831  } else if (nValueIn < nValueToSelect) {
3832  strFailReason = _("Insufficient funds.");
3833  }
3834  return false;
3835  }
3836  vecCoins.assign(setCoinsTmp.begin(), setCoinsTmp.end());
3837  }
3838 
3839  // Fill vin
3840  //
3841  // Note how the sequence number is set to max()-1 so that the
3842  // nLockTime set above actually works.
3843  txNew.vin.clear();
3844  for (const auto& coin : vecCoins) {
3845  txNew.vin.emplace_back(coin.outpoint, CScript(), CTxIn::SEQUENCE_FINAL - 1);
3846  }
3847 
3848  auto calculateFee = [&](CAmount& nFee) -> bool {
3849  // Fill in dummy signatures for fee calculation.
3850  int nIn = 0;
3851  for (const auto& coin : vecCoins) {
3852  const CScript& scriptPubKey = coin.txout.scriptPubKey;
3853  SignatureData sigdata;
3854  if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata)) {
3855  strFailReason = _("Signing transaction failed");
3856  return false;
3857  } else {
3858  UpdateTransaction(txNew, nIn, sigdata);
3859  }
3860 
3861  nIn++;
3862  }
3863 
3865 
3866  if (nExtraPayloadSize != 0) {
3867  // account for extra payload in fee calculation
3868  nBytes += GetSizeOfCompactSize(nExtraPayloadSize) + nExtraPayloadSize;
3869  }
3870 
3871  if (nBytes > MAX_STANDARD_TX_SIZE) {
3872  // Do not create oversized transactions (bad-txns-oversize).
3873  strFailReason = _("Transaction too large");
3874  return false;
3875  }
3876 
3877  // Remove scriptSigs to eliminate the fee calculation dummy signatures
3878  for (auto& txin : txNew.vin) {
3879  txin.scriptSig = CScript();
3880  }
3881 
3882  nFee = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
3883 
3884  // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
3885  // because we must be at the maximum allowed fee.
3886  if (nFee < ::minRelayTxFee.GetFee(nBytes)) {
3887  strFailReason = _("Transaction too large for fee policy");
3888  return false;
3889  }
3890 
3891  return true;
3892  };
3893 
3894  if (!calculateFee(nFeeRet)) {
3895  return false;
3896  }
3897 
3898  CTxOut newTxOut;
3899  const CAmount nAmountLeft = nValueIn - nValue;
3900  auto getChange = [&]() {
3901  if (nSubtractFeeFromAmount > 0) {
3902  return nAmountLeft;
3903  } else {
3904  return nAmountLeft - nFeeRet;
3905  }
3906  };
3907 
3908  if (getChange() > 0)
3909  {
3910  //over pay for denominated transactions
3911  if (coin_control.nCoinType == CoinType::ONLY_FULLY_MIXED) {
3912  nChangePosInOut = -1;
3913  nFeeRet += getChange();
3914  } else {
3915  // Fill a vout to ourself with zero amount until we know the correct change
3916  newTxOut = CTxOut(0, scriptChange);
3917  txNew.vout.push_back(newTxOut);
3918 
3919  // Calculate the fee with the change output added, store the
3920  // current fee to reset it in case the remainder is dust and we
3921  // don't need to fee with change output added.
3922  CAmount nFeePrev = nFeeRet;
3923  if (!calculateFee(nFeeRet)) {
3924  return false;
3925  }
3926 
3927  // Remove the change output again, it will be added later again if required
3928  txNew.vout.pop_back();
3929 
3930  // Set the change amount properly
3931  newTxOut.nValue = getChange();
3932 
3933  // Never create dust outputs; if we would, just
3934  // add the dust to the fee.
3935  if (IsDust(newTxOut, discard_rate))
3936  {
3937  nFeeRet = nFeePrev;
3938  nChangePosInOut = -1;
3939  nFeeRet += getChange();
3940  }
3941  else
3942  {
3943  if (nChangePosRequest == -1)
3944  {
3945  // Insert change txn at random position:
3946  nChangePosInOut = GetRandInt(txNew.vout.size()+1);
3947  }
3948  else if ((unsigned int)nChangePosRequest > txNew.vout.size())
3949  {
3950  strFailReason = _("Change index out of range");
3951  return false;
3952  } else {
3953  nChangePosInOut = nChangePosRequest;
3954  }
3955 
3956  std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
3957  txNew.vout.insert(position, newTxOut);
3958  }
3959  }
3960  } else {
3961  nChangePosInOut = -1;
3962  }
3963 
3964  if (getChange() < 0) {
3965  if (nSubtractFeeFromAmount == 0) {
3966  // nValueIn is not enough to cover nValue + nFeeRet. Add the missing amount abs(nChange) to the fee
3967  // and try to select other inputs in the next loop step to cover the full required amount.
3968  nAmountToSelectAdditional += abs(getChange());
3969  } else if (nAmountToSelectAdditional > 0 && nValueToSelect == nAmountAvailable) {
3970  // We tried selecting more and failed. We have no extra funds left,
3971  // so just add 1 duff to fail in the next loop step with a correct reason
3972  nAmountToSelectAdditional += 1;
3973  }
3974  continue;
3975  }
3976 
3977  // If no specific change position was requested, apply BIP69
3978  if (nChangePosRequest == -1) {
3979  std::sort(vecCoins.begin(), vecCoins.end(), CompareInputCoinBIP69());
3980  std::sort(txNew.vin.begin(), txNew.vin.end(), CompareInputBIP69());
3981  std::sort(txNew.vout.begin(), txNew.vout.end(), CompareOutputBIP69());
3982 
3983  // If there was a change output added before, we must update its position now
3984  if (nChangePosInOut != -1) {
3985  int i = 0;
3986  for (const CTxOut& txOut : txNew.vout)
3987  {
3988  if (txOut == newTxOut)
3989  {
3990  nChangePosInOut = i;
3991  break;
3992  }
3993  i++;
3994  }
3995  }
3996  }
3997 
3998  if (nAmountLeft == nFeeRet) {
3999  // We either added the change amount to nFeeRet because the change amount was considered
4000  // to be dust or the input exactly matches output + fee.
4001  // Either way, we used the total amount of the inputs we picked and the transaction is ready.
4002  break;
4003  }
4004 
4005  // We have a change output and we don't need to subtruct fees, which means the transaction is ready.
4006  if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
4007  break;
4008  }
4009 
4010  // If subtracting fee from recipients, we now know what fee we
4011  // need to subtract, we have no reason to reselect inputs
4012  if (nSubtractFeeFromAmount > 0) {
4013  // If we are in here the second time it means we already subtracted the fee from the
4014  // output(s) and there weren't any issues while doing that. So the transaction is ready now
4015  // and we can break.
4016  if (!pick_new_inputs) {
4017  break;
4018  }
4019  pick_new_inputs = false;
4020  }
4021  }
4022 
4023  if (nMaxTries == 0) {
4024  strFailReason = _("Exceeded max tries.");
4025  return false;
4026  }
4027  }
4028 
4029  // Make sure change position was updated one way or another
4030  assert(nChangePosInOut != std::numeric_limits<int>::max());
4031 
4032  if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
4033 
4034  if (sign)
4035  {
4036  CTransaction txNewConst(txNew);
4037  int nIn = 0;
4038  for(const auto& coin : vecCoins)
4039  {
4040  const CScript& scriptPubKey = coin.txout.scriptPubKey;
4041  SignatureData sigdata;
4042 
4043  if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, SIGHASH_ALL), scriptPubKey, sigdata))
4044  {
4045  strFailReason = _("Signing transaction failed");
4046  return false;
4047  } else {
4048  UpdateTransaction(txNew, nIn, sigdata);
4049  }
4050 
4051  nIn++;
4052  }
4053  }
4054 
4055  // Embed the constructed transaction data in wtxNew.
4056  wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
4057  }
4058 
4059  if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
4060  // Lastly, ensure this tx will pass the mempool's chain limits
4061  LockPoints lp;
4062  CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
4063  CTxMemPool::setEntries setAncestors;
4064  size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
4065  size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
4066  size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
4067  size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
4068  std::string errString;
4069  if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
4070  strFailReason = _("Transaction has too long of a mempool chain");
4071  return false;
4072  }
4073  }
4074 
4075  LogPrintf("Fee Calculation: Fee:%d Bytes:%u Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
4076  nFeeRet, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
4077  feeCalc.est.pass.start, feeCalc.est.pass.end,
4078  100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
4079  feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
4080  feeCalc.est.fail.start, feeCalc.est.fail.end,
4081  100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
4082  feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
4083  return true;
4084 }
4085 
4089 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
4090 {
4091  {
4092  LOCK2(cs_main, mempool.cs);
4093  LOCK(cs_wallet);
4094  LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
4095  {
4096  // Take key pair from key pool so it won't be used again
4097  reservekey.KeepKey();
4098 
4099  // Add tx to wallet, because if it has change it's also ours,
4100  // otherwise just for transaction history.
4101  AddToWallet(wtxNew);
4102 
4103  // Notify that old coins are spent
4104  std::set<uint256> updated_hahes;
4105  for (const CTxIn& txin : wtxNew.tx->vin)
4106  {
4107  // notify only once
4108  if(updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue;
4109 
4110  CWalletTx &coin = mapWallet[txin.prevout.hash];
4111  coin.BindWallet(this);
4113  updated_hahes.insert(txin.prevout.hash);
4114  }
4115  }
4116 
4117  // Get the inserted-CWalletTx from mapWallet so that the
4118  // fInMempool flag is cached properly
4119  CWalletTx& wtx = mapWallet[wtxNew.GetHash()];
4120 
4122  {
4123  // Broadcast
4124  if (!wtx.AcceptToMemoryPool(maxTxFee, state)) {
4125  LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
4126  // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
4127  } else {
4128  wtx.RelayWalletTransaction(connman);
4129  }
4130  }
4131  }
4132  return true;
4133 }
4134 
4135 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
4136  WalletBatch batch(*database);
4137  return batch.ListAccountCreditDebit(strAccount, entries);
4138 }
4139 
4141 {
4142  WalletBatch batch(*database);
4143 
4144  return AddAccountingEntry(acentry, &batch);
4145 }
4146 
4148 {
4149  if (!batch->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
4150  return false;
4151  }
4152 
4153  laccentries.push_back(acentry);
4154  CAccountingEntry & entry = laccentries.back();
4155  wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
4156 
4157  return true;
4158 }
4159 
4160 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
4161 {
4163 
4164  fFirstRunRet = false;
4165  DBErrors nLoadWalletRet = WalletBatch(*database,"cr+").LoadWallet(this);
4166  if (nLoadWalletRet == DB_NEED_REWRITE)
4167  {
4168  if (database->Rewrite("\x04pool"))
4169  {
4170  setInternalKeyPool.clear();
4171  setExternalKeyPool.clear();
4173  m_pool_key_to_index.clear();
4174  // Note: can't top-up keypool here, because wallet is locked.
4175  // User will be prompted to unlock wallet the next operation
4176  // that requires a new key.
4177  }
4178  }
4179 
4180  // This wallet is in its first run if all of these are empty
4181  fFirstRunRet = mapKeys.empty() && mapHdPubKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
4182 
4183  {
4185  for (auto& pair : mapWallet) {
4186  for(unsigned int i = 0; i < pair.second.tx->vout.size(); ++i) {
4187  if (IsMine(pair.second.tx->vout[i]) && !IsSpent(pair.first, i)) {
4188  setWalletUTXO.insert(COutPoint(pair.first, i));
4189  }
4190  }
4191  }
4192  }
4193 
4195 
4196  if (nLoadWalletRet != DB_LOAD_OK)
4197  return nLoadWalletRet;
4198 
4199  return DB_LOAD_OK;
4200 }
4201 
4202 // Goes through all wallet transactions and checks if they are masternode collaterals, in which case these are locked
4203 // This avoids accidential spending of collaterals. They can still be unlocked manually if a spend is really intended.
4205 {
4206  auto mnList = deterministicMNManager->GetListAtChainTip();
4207 
4209  for (const auto& pair : mapWallet) {
4210  for (unsigned int i = 0; i < pair.second.tx->vout.size(); ++i) {
4211  if (IsMine(pair.second.tx->vout[i]) && !IsSpent(pair.first, i)) {
4212  if (deterministicMNManager->IsProTxWithCollateral(pair.second.tx, i) || mnList.HasMNByCollateral(COutPoint(pair.first, i))) {
4213  LockCoin(COutPoint(pair.first, i));
4214  }
4215  }
4216  }
4217  }
4218 }
4219 
4220 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
4221 {
4222  AssertLockHeld(cs_wallet); // mapWallet
4223  DBErrors nZapSelectTxRet = WalletBatch(*database,"cr+").ZapSelectTx(vHashIn, vHashOut);
4224  for (uint256 hash : vHashOut) {
4225  const auto& it = mapWallet.find(hash);
4226  wtxOrdered.erase(it->second.m_it_wtxOrdered);
4227  mapWallet.erase(it);
4228  }
4229 
4230  if (nZapSelectTxRet == DB_NEED_REWRITE)
4231  {
4232  if (database->Rewrite("\x04pool"))
4233  {
4234  setInternalKeyPool.clear();
4235  setExternalKeyPool.clear();
4236  m_pool_key_to_index.clear();
4237  // Note: can't top-up keypool here, because wallet is locked.
4238  // User will be prompted to unlock wallet the next operation
4239  // that requires a new key.
4240  }
4241  }
4242 
4243  if (nZapSelectTxRet != DB_LOAD_OK)
4244  return nZapSelectTxRet;
4245 
4246  MarkDirty();
4247 
4248  return DB_LOAD_OK;
4249 
4250 }
4251 
4252 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
4253 {
4254  DBErrors nZapWalletTxRet = WalletBatch(*database,"cr+").ZapWalletTx(vWtx);
4255  if (nZapWalletTxRet == DB_NEED_REWRITE)
4256  {
4257  if (database->Rewrite("\x04pool"))
4258  {
4259  LOCK(cs_wallet);
4260  setInternalKeyPool.clear();
4261  setExternalKeyPool.clear();
4263  m_pool_key_to_index.clear();
4264  // Note: can't top-up keypool here, because wallet is locked.
4265  // User will be prompted to unlock wallet the next operation
4266  // that requires a new key.
4267  }
4268  }
4269 
4270  if (nZapWalletTxRet != DB_LOAD_OK)
4271  return nZapWalletTxRet;
4272 
4273  return DB_LOAD_OK;
4274 }
4275 
4276 
4277 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
4278 {
4279  bool fUpdated = false;
4280  {
4281  LOCK(cs_wallet); // mapAddressBook
4282  std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
4283  fUpdated = mi != mapAddressBook.end();
4284  mapAddressBook[address].name = strName;
4285  if (!strPurpose.empty()) /* update purpose only if requested */
4286  mapAddressBook[address].purpose = strPurpose;
4287  }
4288  NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
4289  strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
4290  if (!strPurpose.empty() && !WalletBatch(*database).WritePurpose(EncodeDestination(address), strPurpose))
4291  return false;
4292  return WalletBatch(*database).WriteName(EncodeDestination(address), strName);
4293 }
4294 
4296 {
4297  {
4298  LOCK(cs_wallet); // mapAddressBook
4299 
4300  // Delete destdata tuples associated with address
4301  std::string strAddress = EncodeDestination(address);
4302  for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
4303  {
4304  WalletBatch(*database).EraseDestData(strAddress, item.first);
4305  }
4306  mapAddressBook.erase(address);
4307  }
4308 
4309  NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
4310 
4311  WalletBatch(*database).ErasePurpose(EncodeDestination(address));
4312  return WalletBatch(*database).EraseName(EncodeDestination(address));
4313 }
4314 
4315 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
4316 {
4317  CTxDestination address;
4318  if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
4319  auto mi = mapAddressBook.find(address);
4320  if (mi != mapAddressBook.end()) {
4321  return mi->second.name;
4322  }
4323  }
4324  // A scriptPubKey that doesn't have an entry in the address book is
4325  // associated with the default account ("").
4326  const static std::string DEFAULT_ACCOUNT_NAME;
4327  return DEFAULT_ACCOUNT_NAME;
4328 }
4329 
4335 {
4336  {
4337  LOCK(cs_wallet);
4338  WalletBatch batch(*database);
4339  for (int64_t nIndex : setInternalKeyPool) {
4340  batch.ErasePool(nIndex);
4341  }
4342  setInternalKeyPool.clear();
4343  for (int64_t nIndex : setExternalKeyPool) {
4344  batch.ErasePool(nIndex);
4345  }
4346  setExternalKeyPool.clear();
4349 
4350  m_pool_key_to_index.clear();
4351 
4352  if (!TopUpKeyPool())
4353  return false;
4354 
4355  LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
4356  }
4357  return true;
4358 }
4359 
4361 {
4362  AssertLockHeld(cs_wallet); // setExternalKeyPool
4363  return setExternalKeyPool.size();
4364 }
4365 
4366 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
4367 {
4369  if (keypool.fInternal) {
4370  setInternalKeyPool.insert(nIndex);
4371  } else {
4372  setExternalKeyPool.insert(nIndex);
4373  }
4374  m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
4375  m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
4376 
4377  // If no metadata exists yet, create a default with the pool key's
4378  // creation time. Note that this may be overwritten by actually
4379  // stored metadata for that key later, which is fine.
4380  CKeyID keyid = keypool.vchPubKey.GetID();
4381  if (mapKeyMetadata.count(keyid) == 0)
4382  mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
4383 }
4384 
4386 {
4387  AssertLockHeld(cs_wallet); // setInternalKeyPool
4388  return setInternalKeyPool.size();
4389 }
4390 
4391 bool CWallet::TopUpKeyPool(unsigned int kpSize)
4392 {
4393  {
4394  LOCK(cs_wallet);
4395 
4396  if (IsLocked(true))
4397  return false;
4398 
4399  // Top up key pool
4400  unsigned int nTargetSize;
4401  if (kpSize > 0)
4402  nTargetSize = kpSize;
4403  else
4404  nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
4405 
4406  // count amount of available keys (internal, external)
4407  // make sure the keypool of external and internal keys fits the user selected target (-keypool)
4408  int64_t amountExternal = setExternalKeyPool.size();
4409  int64_t amountInternal = setInternalKeyPool.size();
4410  int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountExternal, (int64_t) 0);
4411  int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountInternal, (int64_t) 0);
4412 
4413  if (!IsHDEnabled())
4414  {
4415  // don't create extra internal keys
4416  missingInternal = 0;
4417  } else {
4418  nTargetSize *= 2;
4419  }
4420  bool fInternal = false;
4421  WalletBatch batch(*database);
4422  for (int64_t i = missingInternal + missingExternal; i--;)
4423  {
4424  if (i < missingInternal) {
4425  fInternal = true;
4426  }
4427 
4428  assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
4429  int64_t index = ++m_max_keypool_index;
4430 
4431  // TODO: implement keypools for all accounts?
4432  CPubKey pubkey(GenerateNewKey(batch, 0, fInternal));
4433  if (!batch.WritePool(index, CKeyPool(pubkey, fInternal))) {
4434  throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
4435  }
4436 
4437  if (fInternal) {
4438  setInternalKeyPool.insert(index);
4439  } else {
4440  setExternalKeyPool.insert(index);
4441  }
4442 
4443  m_pool_key_to_index[pubkey.GetID()] = index;
4444  if (missingInternal + missingExternal > 0) {
4445  LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n",
4446  missingInternal + missingExternal, missingInternal,
4447  setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
4448  }
4449 
4450  double dProgress = 100.f * index / (nTargetSize + 1);
4451  std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress);
4452  uiInterface.InitMessage(strMsg);
4453  }
4454  }
4455  return true;
4456 }
4457 
4458 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fInternal)
4459 {
4460  nIndex = -1;
4461  keypool.vchPubKey = CPubKey();
4462  {
4463  LOCK(cs_wallet);
4464 
4465  if (!IsLocked(true))
4466  TopUpKeyPool();
4467 
4468  fInternal = fInternal && IsHDEnabled();
4469  std::set<int64_t>& setKeyPool = fInternal ? setInternalKeyPool : setExternalKeyPool;
4470 
4471  // Get the oldest key
4472  if(setKeyPool.empty())
4473  return;
4474 
4475  WalletBatch batch(*database);
4476 
4477  nIndex = *setKeyPool.begin();
4478  setKeyPool.erase(nIndex);
4479  if (!batch.ReadPool(nIndex, keypool)) {
4480  throw std::runtime_error(std::string(__func__) + ": read failed");
4481  }
4482  if (!HaveKey(keypool.vchPubKey.GetID())) {
4483  throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
4484  }
4485  if (keypool.fInternal != fInternal) {
4486  throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
4487  }
4488 
4489  assert(keypool.vchPubKey.IsValid());
4490  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
4491  LogPrintf("keypool reserve %d\n", nIndex);
4492  }
4493 }
4494 
4495 void CWallet::KeepKey(int64_t nIndex)
4496 {
4497  // Remove from key pool
4498  WalletBatch batch(*database);
4499  if (batch.ErasePool(nIndex))
4501  if (!nWalletBackups)
4503  LogPrintf("keypool keep %d\n", nIndex);
4504 }
4505 
4506 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
4507 {
4508  // Return to key pool
4509  {
4510  LOCK(cs_wallet);
4511  if (fInternal) {
4512  setInternalKeyPool.insert(nIndex);
4513  } else {
4514  setExternalKeyPool.insert(nIndex);
4515  }
4516  m_pool_key_to_index[pubkey.GetID()] = nIndex;
4517  }
4518  LogPrintf("keypool return %d\n", nIndex);
4519 }
4520 
4521 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
4522 {
4523  CKeyPool keypool;
4524  {
4525  LOCK(cs_wallet);
4526  int64_t nIndex = 0;
4527  ReserveKeyFromKeyPool(nIndex, keypool, internal);
4528  if (nIndex == -1)
4529  {
4530  if (IsLocked(true)) return false;
4531  // TODO: implement keypool for all accouts?
4532 
4533  WalletBatch batch(*database);
4534  result = GenerateNewKey(batch, 0, internal);
4535  return true;
4536  }
4537  KeepKey(nIndex);
4538  result = keypool.vchPubKey;
4539  }
4540  return true;
4541 }
4542 
4543 static int64_t GetOldestKeyInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
4544  CKeyPool keypool;
4545  int64_t nIndex = *(setKeyPool.begin());
4546  if (!batch.ReadPool(nIndex, keypool)) {
4547  throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
4548  }
4549  assert(keypool.vchPubKey.IsValid());
4550  return keypool.nTime;
4551 }
4552 
4554 {
4555  LOCK(cs_wallet);
4556 
4557  // if the keypool is empty, return <NOW>
4558  if (setExternalKeyPool.empty() && setInternalKeyPool.empty())
4559  return GetTime();
4560 
4561  WalletBatch batch(*database);
4562  int64_t oldestKey = -1;
4563 
4564  // load oldest key from keypool, get time and return
4565  if (!setInternalKeyPool.empty()) {
4566  oldestKey = std::max(GetOldestKeyInPool(setInternalKeyPool, batch), oldestKey);
4567  }
4568  if (!setExternalKeyPool.empty()) {
4569  oldestKey = std::max(GetOldestKeyInPool(setExternalKeyPool, batch), oldestKey);
4570  }
4571  return oldestKey;
4572 }
4573 
4574 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
4575 {
4576  std::map<CTxDestination, CAmount> balances;
4577 
4578  {
4579  LOCK(cs_wallet);
4580  for (const auto& walletEntry : mapWallet)
4581  {
4582  const CWalletTx *pcoin = &walletEntry.second;
4583 
4584  if (!pcoin->IsTrusted())
4585  continue;
4586 
4587  if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
4588  continue;
4589 
4590  int nDepth = pcoin->GetDepthInMainChain();
4591  if ((nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) && !pcoin->IsLockedByInstantSend())
4592  continue;
4593 
4594  for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
4595  {
4596  CTxDestination addr;
4597  if (!IsMine(pcoin->tx->vout[i]))
4598  continue;
4599  if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
4600  continue;
4601 
4602  CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
4603 
4604  if (!balances.count(addr))
4605  balances[addr] = 0;
4606  balances[addr] += n;
4607  }
4608  }
4609  }
4610 
4611  return balances;
4612 }
4613 
4614 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
4615 {
4616  AssertLockHeld(cs_wallet); // mapWallet
4617  std::set< std::set<CTxDestination> > groupings;
4618  std::set<CTxDestination> grouping;
4619 
4620  for (const auto& walletEntry : mapWallet)
4621  {
4622  const CWalletTx *pcoin = &walletEntry.second;
4623 
4624  if (pcoin->tx->vin.size() > 0)
4625  {
4626  bool any_mine = false;
4627  // group all input addresses with each other
4628  for (CTxIn txin : pcoin->tx->vin)
4629  {
4630  CTxDestination address;
4631  if(!IsMine(txin)) /* If this input isn't mine, ignore it */
4632  continue;
4633  if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
4634  continue;
4635  grouping.insert(address);
4636  any_mine = true;
4637  }
4638 
4639  // group change with input addresses
4640  if (any_mine)
4641  {
4642  for (CTxOut txout : pcoin->tx->vout)
4643  if (IsChange(txout))
4644  {
4645  CTxDestination txoutAddr;
4646  if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
4647  continue;
4648  grouping.insert(txoutAddr);
4649  }
4650  }
4651  if (grouping.size() > 0)
4652  {
4653  groupings.insert(grouping);
4654  grouping.clear();
4655  }
4656  }
4657 
4658  // group lone addrs by themselves
4659  for (const auto& txout : pcoin->tx->vout)
4660  if (IsMine(txout))
4661  {
4662  CTxDestination address;
4663  if(!ExtractDestination(txout.scriptPubKey, address))
4664  continue;
4665  grouping.insert(address);
4666  groupings.insert(grouping);
4667  grouping.clear();
4668  }
4669  }
4670 
4671  std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
4672  std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
4673  for (std::set<CTxDestination> _grouping : groupings)
4674  {
4675  // make a set of all the groups hit by this new group
4676  std::set< std::set<CTxDestination>* > hits;
4677  std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
4678  for (CTxDestination address : _grouping)
4679  if ((it = setmap.find(address)) != setmap.end())
4680  hits.insert((*it).second);
4681 
4682  // merge all hit groups into a new single group and delete old groups
4683  std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
4684  for (std::set<CTxDestination>* hit : hits)
4685  {
4686  merged->insert(hit->begin(), hit->end());
4687  uniqueGroupings.erase(hit);
4688  delete hit;
4689  }
4690  uniqueGroupings.insert(merged);
4691 
4692  // update setmap
4693  for (CTxDestination element : *merged)
4694  setmap[element] = merged;
4695  }
4696 
4697  std::set< std::set<CTxDestination> > ret;
4698  for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
4699  {
4700  ret.insert(*uniqueGrouping);
4701  delete uniqueGrouping;
4702  }
4703 
4704  return ret;
4705 }
4706 
4707 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
4708 {
4709  LOCK(cs_wallet);
4710  std::set<CTxDestination> result;
4711  for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
4712  {
4713  const CTxDestination& address = item.first;
4714  const std::string& strName = item.second.name;
4715  if (strName == strAccount)
4716  result.insert(address);
4717  }
4718  return result;
4719 }
4720 
4721 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool fInternalIn)
4722 {
4723  if (nIndex == -1)
4724  {
4725  CKeyPool keypool;
4726  pwallet->ReserveKeyFromKeyPool(nIndex, keypool, fInternalIn);
4727  if (nIndex != -1) {
4728  vchPubKey = keypool.vchPubKey;
4729  }
4730  else {
4731  return false;
4732  }
4733  fInternal = keypool.fInternal;
4734  }
4735  assert(vchPubKey.IsValid());
4736  pubkey = vchPubKey;
4737  return true;
4738 }
4739 
4741 {
4742  if (nIndex != -1) {
4744  }
4745  nIndex = -1;
4746  vchPubKey = CPubKey();
4747 }
4748 
4750 {
4751  if (nIndex != -1) {
4753  }
4754  nIndex = -1;
4755  vchPubKey = CPubKey();
4756 }
4757 
4758 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
4759 {
4761  bool internal = setInternalKeyPool.count(keypool_id);
4762  if (!internal) assert(setExternalKeyPool.count(keypool_id));
4763  std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
4764  auto it = setKeyPool->begin();
4765 
4766  WalletBatch batch(*database);
4767  while (it != std::end(*setKeyPool)) {
4768  const int64_t& index = *(it);
4769  if (index > keypool_id) break; // set*KeyPool is ordered
4770 
4771  CKeyPool keypool;
4772  if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
4773  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
4774  }
4775  batch.ErasePool(index);
4776  LogPrintf("keypool index %d removed\n", index);
4777  it = setKeyPool->erase(it);
4778  }
4779 }
4780 
4781 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
4782 {
4783  std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
4784  CPubKey pubkey;
4785  if (!rKey->GetReservedKey(pubkey, false))
4786  return;
4787 
4788  script = rKey;
4789  script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
4790 }
4791 
4792 void CWallet::LockCoin(const COutPoint& output)
4793 {
4794  AssertLockHeld(cs_wallet); // setLockedCoins
4795  setLockedCoins.insert(output);
4796  std::map<uint256, CWalletTx>::iterator it = mapWallet.find(output.hash);
4797  if (it != mapWallet.end()) it->second.MarkDirty(); // recalculate all credits for this tx
4798 
4799  fAnonymizableTallyCached = false;
4801 }
4802 
4803 void CWallet::UnlockCoin(const COutPoint& output)
4804 {
4805  AssertLockHeld(cs_wallet); // setLockedCoins
4806  setLockedCoins.erase(output);
4807  std::map<uint256, CWalletTx>::iterator it = mapWallet.find(output.hash);
4808  if (it != mapWallet.end()) it->second.MarkDirty(); // recalculate all credits for this tx
4809 
4810  fAnonymizableTallyCached = false;
4812 }
4813 
4815 {
4816  AssertLockHeld(cs_wallet); // setLockedCoins
4817  setLockedCoins.clear();
4818 }
4819 
4820 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
4821 {
4822  AssertLockHeld(cs_wallet); // setLockedCoins
4823  COutPoint outpt(hash, n);
4824 
4825  return (setLockedCoins.count(outpt) > 0);
4826 }
4827 
4828 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
4829 {
4830  AssertLockHeld(cs_wallet); // setLockedCoins
4831  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
4832  it != setLockedCoins.end(); it++) {
4833  COutPoint outpt = (*it);
4834  vOutpts.push_back(outpt);
4835  }
4836 }
4837 
4838 void CWallet::ListProTxCoins(std::vector<COutPoint>& vOutpts)
4839 {
4840  auto mnList = deterministicMNManager->GetListAtChainTip();
4841 
4843  for (const auto &o : setWalletUTXO) {
4844  auto it = mapWallet.find(o.hash);
4845  if (it != mapWallet.end()) {
4846  const auto &p = it->second;
4847  if (deterministicMNManager->IsProTxWithCollateral(p.tx, o.n) || mnList.HasMNByCollateral(o)) {
4848  vOutpts.emplace_back(o);
4849  }
4850  }
4851  }
4852 }
4853  // end of Actions
4855 
4856 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
4857  AssertLockHeld(cs_wallet); // mapKeyMetadata
4858  mapKeyBirth.clear();
4859 
4860  // get birth times for keys with metadata
4861  for (const auto& entry : mapKeyMetadata) {
4862  if (entry.second.nCreateTime) {
4863  mapKeyBirth[entry.first] = entry.second.nCreateTime;
4864  }
4865  }
4866 
4867  // map in which we'll infer heights of other keys
4868  CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
4869  std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
4870  for (const CKeyID &keyid : GetKeys()) {
4871  if (mapKeyBirth.count(keyid) == 0)
4872  mapKeyFirstBlock[keyid] = pindexMax;
4873  }
4874 
4875  // if there are no such keys, we're done
4876  if (mapKeyFirstBlock.empty())
4877  return;
4878 
4879  // find first block that affects those keys, if there are any left
4880  std::vector<CKeyID> vAffected;
4881  for (const auto& entry : mapWallet) {
4882  // iterate over all wallet transactions...
4883  const CWalletTx &wtx = entry.second;
4884  BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
4885  if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
4886  // ... which are already in a block
4887  int nHeight = blit->second->nHeight;
4888  for (const CTxOut &txout : wtx.tx->vout) {
4889  // iterate over all their outputs
4890  CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
4891  for (const CKeyID &keyid : vAffected) {
4892  // ... and all their affected keys
4893  std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
4894  if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
4895  rit->second = blit->second;
4896  }
4897  vAffected.clear();
4898  }
4899  }
4900  }
4901 
4902  // Extract block timestamps for those keys
4903  for (const auto& entry : mapKeyFirstBlock)
4904  mapKeyBirth[entry.first] = entry.second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
4905 }
4906 
4928 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
4929 {
4930  unsigned int nTimeSmart = wtx.nTimeReceived;
4931  if (!wtx.hashUnset()) {
4932  if (mapBlockIndex.count(wtx.hashBlock)) {
4933  int64_t latestNow = wtx.nTimeReceived;
4934  int64_t latestEntry = 0;
4935 
4936  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
4937  int64_t latestTolerated = latestNow + 300;
4938  const TxItems& txOrdered = wtxOrdered;
4939  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
4940  CWalletTx* const pwtx = it->second.first;
4941  if (pwtx == &wtx) {
4942  continue;
4943  }
4944  CAccountingEntry* const pacentry = it->second.second;
4945  int64_t nSmartTime;
4946  if (pwtx) {
4947  nSmartTime = pwtx->nTimeSmart;
4948  if (!nSmartTime) {
4949  nSmartTime = pwtx->nTimeReceived;
4950  }
4951  } else {
4952  nSmartTime = pacentry->nTime;
4953  }
4954  if (nSmartTime <= latestTolerated) {
4955  latestEntry = nSmartTime;
4956  if (nSmartTime > latestNow) {
4957  latestNow = nSmartTime;
4958  }
4959  break;
4960  }
4961  }
4962 
4963  int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
4964  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
4965  } else {
4966  LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
4967  }
4968  }
4969  return nTimeSmart;
4970 }
4971 
4972 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
4973 {
4974  if (boost::get<CNoDestination>(&dest))
4975  return false;
4976 
4977  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
4978  return WalletBatch(*database).WriteDestData(EncodeDestination(dest), key, value);
4979 }
4980 
4981 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
4982 {
4983  if (!mapAddressBook[dest].destdata.erase(key))
4984  return false;
4985  return WalletBatch(*database).EraseDestData(EncodeDestination(dest), key);
4986 }
4987 
4988 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
4989 {
4990  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
4991  return true;
4992 }
4993 
4994 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
4995 {
4996  std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
4997  if(i != mapAddressBook.end())
4998  {
4999  CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
5000  if(j != i->second.destdata.end())
5001  {
5002  if(value)
5003  *value = j->second;
5004  return true;
5005  }
5006  }
5007  return false;
5008 }
5009 
5010 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
5011 {
5012  LOCK(cs_wallet);
5013  std::vector<std::string> values;
5014  for (const auto& address : mapAddressBook) {
5015  for (const auto& data : address.second.destdata) {
5016  if (!data.first.compare(0, prefix.size(), prefix)) {
5017  values.emplace_back(data.second);
5018  }
5019  }
5020  }
5021  return values;
5022 }
5023 
5024 bool CWallet::Verify(std::string wallet_file, bool salvage_wallet, std::string& error_string, std::string& warning_string)
5025 {
5026  // Do some checking on wallet path. It should be either a:
5027  //
5028  // 1. Path where a directory can be created.
5029  // 2. Path to an existing directory.
5030  // 3. Path to a symlink to a directory.
5031  // 4. For backwards compatibility, the name of a data file in -walletdir.
5032  LOCK(cs_wallets);
5033  fs::path wallet_path = fs::absolute(wallet_file, GetWalletDir());
5034  fs::file_type path_type = fs::symlink_status(wallet_path).type();
5035  if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
5036  (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
5037  (path_type == fs::regular_file && fs::path(wallet_file).filename() == wallet_file))) {
5038  error_string =strprintf(
5039  "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
5040  "database/log.?????????? files can be stored, a location where such a directory could be created, "
5041  "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
5042  wallet_file, GetWalletDir());
5043  return false;
5044  }
5045 
5046  // Make sure that the wallet path doesn't clash with an existing wallet path
5047  for (auto wallet : GetWallets()) {
5048  if (fs::absolute(wallet->GetName(), GetWalletDir()) == wallet_path) {
5049  error_string = strprintf("Error loading wallet %s. Duplicate -wallet filename specified.", wallet_file);
5050  return false;
5051  }
5052  }
5053 
5054  if (!WalletBatch::VerifyEnvironment(wallet_path, error_string)) {
5055  return false;
5056  }
5057 
5058  std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(wallet_file, WalletDatabase::Create(wallet_path));
5059  if (!tempWallet->AutoBackupWallet(wallet_path, warning_string, error_string) && !error_string.empty()) {
5060  return false;
5061  }
5062 
5063  if (salvage_wallet) {
5064  // Recover readable keypairs:
5065  CWallet dummyWallet("dummy", WalletDatabase::CreateDummy());
5066  std::string backup_filename;
5067  if (!WalletBatch::Recover(wallet_path, (void *)&dummyWallet, WalletBatch::RecoverKeysOnlyFilter, backup_filename)) {
5068  return false;
5069  }
5070  }
5071 
5072  return WalletBatch::VerifyDatabaseFile(wallet_path, warning_string, error_string);
5073 }
5074 
5075 CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path& path)
5076 {
5077  const std::string& walletFile = name;
5078 
5079  // needed to restore wallet transaction meta data after -zapwallettxes
5080  std::vector<CWalletTx> vWtx;
5081 
5082  if (gArgs.GetBoolArg("-zapwallettxes", false)) {
5083  uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
5084 
5085  std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(name, WalletDatabase::Create(path));
5086  DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
5087  if (nZapWalletRet != DB_LOAD_OK) {
5088  InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
5089  return nullptr;
5090  }
5091  }
5092 
5093  uiInterface.InitMessage(_("Loading wallet..."));
5094 
5095  int64_t nStart = GetTimeMillis();
5096  bool fFirstRun = true;
5097  // Make a temporary wallet unique pointer so memory doesn't get leaked if
5098  // wallet creation fails.
5099  auto temp_wallet = MakeUnique<CWallet>(name, WalletDatabase::Create(path));
5100  CWallet *walletInstance = temp_wallet.get();
5101  DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
5102  if (nLoadWalletRet != DB_LOAD_OK)
5103  {
5104  if (nLoadWalletRet == DB_CORRUPT) {
5105  InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
5106  return nullptr;
5107  }
5108  else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
5109  {
5110  InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
5111  " or address book entries might be missing or incorrect."),
5112  walletFile));
5113  }
5114  else if (nLoadWalletRet == DB_TOO_NEW) {
5115  InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
5116  return nullptr;
5117  }
5118  else if (nLoadWalletRet == DB_NEED_REWRITE)
5119  {
5120  InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
5121  return nullptr;
5122  }
5123  else {
5124  InitError(strprintf(_("Error loading %s"), walletFile));
5125  return nullptr;
5126  }
5127  }
5128 
5129  if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
5130  {
5131  int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
5132  if (nMaxVersion == 0) // the -upgradewallet without argument case
5133  {
5134  LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
5135  nMaxVersion = CLIENT_VERSION;
5136  walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
5137  }
5138  else
5139  LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
5140  if (nMaxVersion < walletInstance->GetVersion())
5141  {
5142  InitError(_("Cannot downgrade wallet"));
5143  return nullptr;
5144  }
5145  walletInstance->SetMaxVersion(nMaxVersion);
5146  }
5147 
5148  if (fFirstRun)
5149  {
5150  // Create new keyUser and set as default key
5151  if (gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
5152  if (gArgs.GetArg("-mnemonicpassphrase", "").size() > 256) {
5153  InitError(_("Mnemonic passphrase is too long, must be at most 256 characters"));
5154  return nullptr;
5155  }
5156  // generate a new master key
5157  walletInstance->GenerateNewHDChain();
5158 
5159  // ensure this wallet.dat can only be opened by clients supporting HD
5160  walletInstance->SetMinVersion(FEATURE_HD);
5161  }
5162 
5163  // Top up the keypool
5164  if (!walletInstance->TopUpKeyPool()) {
5165  InitError(_("Unable to generate initial keys") += "\n");
5166  return nullptr;
5167  }
5168 
5169  walletInstance->SetBestChain(chainActive.GetLocator());
5170 
5171  // Try to create wallet backup right after new wallet was created
5172  std::string strBackupWarning;
5173  std::string strBackupError;
5174  if(!walletInstance->AutoBackupWallet("", strBackupWarning, strBackupError)) {
5175  if (!strBackupWarning.empty()) {
5176  InitWarning(strBackupWarning);
5177  }
5178  if (!strBackupError.empty()) {
5179  InitError(strBackupError);
5180  return nullptr;
5181  }
5182  }
5183 
5184  }
5185  else if (gArgs.IsArgSet("-usehd")) {
5186  bool useHD = gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
5187  if (walletInstance->IsHDEnabled() && !useHD) {
5188  InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"),
5189  walletInstance->GetName()));
5190  return nullptr;
5191  }
5192  if (!walletInstance->IsHDEnabled() && useHD) {
5193  InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"),
5194  walletInstance->GetName()));
5195  return nullptr;
5196  }
5197  }
5198 
5199  // Warn user every time he starts non-encrypted HD wallet
5200  if (gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsLocked()) {
5201  InitWarning(_("Make sure to encrypt your wallet and delete all non-encrypted backups after you have verified that the wallet works!"));
5202  }
5203 
5204  LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
5205 
5206  // Try to top up keypool. No-op if the wallet is locked.
5207  walletInstance->TopUpKeyPool();
5208 
5209  CBlockIndex *pindexRescan = chainActive.Genesis();
5210  if (!gArgs.GetBoolArg("-rescan", false))
5211  {
5212  WalletBatch batch(*walletInstance->database);
5213  CBlockLocator locator;
5214  if (batch.ReadBestBlock(locator))
5215  pindexRescan = FindForkInGlobalIndex(chainActive, locator);
5216  }
5217 
5218  walletInstance->m_last_block_processed = chainActive.Tip();
5219 
5220  if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
5221  {
5222  //We can't rescan beyond non-pruned blocks, stop and throw an error
5223  //this might happen if a user uses an old wallet within a pruned node
5224  // or if he ran -disablewallet for a longer time, then decided to re-enable
5225  if (fPruneMode)
5226  {
5227  CBlockIndex *block = chainActive.Tip();
5228  while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
5229  block = block->pprev;
5230 
5231  if (pindexRescan != block) {
5232  InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
5233  return nullptr;
5234  }
5235  }
5236 
5237  uiInterface.InitMessage(_("Rescanning..."));
5238  LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
5239 
5240  // No need to read and scan block if block was created before
5241  // our wallet birthday (as adjusted for block time variability)
5242  while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
5243  pindexRescan = chainActive.Next(pindexRescan);
5244  }
5245 
5246  nStart = GetTimeMillis();
5247  {
5248  WalletRescanReserver reserver(walletInstance);
5249  if (!reserver.reserve()) {
5250  InitError(_("Failed to rescan the wallet during initialization"));
5251  return nullptr;
5252  }
5253  uiInterface.LoadWallet(walletInstance); // TODO: move it up when backporting 13063
5254  walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, reserver, true);
5255  }
5256  LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
5257  walletInstance->SetBestChain(chainActive.GetLocator());
5258  walletInstance->database->IncrementUpdateCounter();
5259 
5260  // Restore wallet transaction metadata after -zapwallettxes=1
5261  if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
5262  {
5263  WalletBatch batch(*walletInstance->database);
5264 
5265  for (const CWalletTx& wtxOld : vWtx)
5266  {
5267  uint256 hash = wtxOld.GetHash();
5268  std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
5269  if (mi != walletInstance->mapWallet.end())
5270  {
5271  const CWalletTx* copyFrom = &wtxOld;
5272  CWalletTx* copyTo = &mi->second;
5273  copyTo->mapValue = copyFrom->mapValue;
5274  copyTo->vOrderForm = copyFrom->vOrderForm;
5275  copyTo->nTimeReceived = copyFrom->nTimeReceived;
5276  copyTo->nTimeSmart = copyFrom->nTimeSmart;
5277  copyTo->fFromMe = copyFrom->fFromMe;
5278  copyTo->strFromAccount = copyFrom->strFromAccount;
5279  copyTo->nOrderPos = copyFrom->nOrderPos;
5280  batch.WriteTx(*copyTo);
5281  }
5282  }
5283  }
5284  }
5285 
5286  // Register with the validation interface. It's ok to do this after rescan since we're still holding cs_main.
5287  RegisterValidationInterface(temp_wallet.release());
5288 
5289  walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
5290 
5291  {
5292  LOCK(walletInstance->cs_wallet);
5293  LogPrintf("setExternalKeyPool.size() = %u\n", walletInstance->KeypoolCountExternalKeys());
5294  LogPrintf("setInternalKeyPool.size() = %u\n", walletInstance->KeypoolCountInternalKeys());
5295  LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
5296  LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
5297  }
5298 
5299  return walletInstance;
5300 }
5301 
5303 {
5304  // Add wallet transactions that aren't already in a block to mempool
5305  // Do this here as mempool requires genesis block to be loaded
5307 }
5308 
5310 {
5311  if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
5312  return true;
5313 
5314  nWalletBackups = gArgs.GetArg("-createwalletbackups", 10);
5315  nWalletBackups = std::max(0, std::min(10, nWalletBackups));
5316 
5317  return true;
5318 }
5319 
5320 bool CWallet::BackupWallet(const std::string& strDest)
5321 {
5322  return database->Backup(strDest);
5323 }
5324 
5325 // This should be called carefully:
5326 // either supply the actual wallet_path to make a raw copy of wallet.dat or "" to backup current instance via BackupWallet()
5327 bool CWallet::AutoBackupWallet(const fs::path& wallet_path, std::string& strBackupWarningRet, std::string& strBackupErrorRet)
5328 {
5329  strBackupWarningRet = strBackupErrorRet = "";
5330  std::string strWalletName = m_name.empty() ? "wallet.dat" : m_name;
5331 
5332  if (nWalletBackups <= 0) {
5333  LogPrintf("Automatic wallet backups are disabled!\n");
5334  return false;
5335  }
5336 
5337  fs::path backupsDir = GetBackupsDir();
5338  backupsDir.make_preferred();
5339 
5340  if (!fs::exists(backupsDir))
5341  {
5342  // Always create backup folder to not confuse the operating system's file browser
5343  LogPrintf("Creating backup folder %s\n", backupsDir.string());
5344  if(!fs::create_directories(backupsDir)) {
5345  // something is wrong, we shouldn't continue until it's resolved
5346  strBackupErrorRet = strprintf(_("Wasn't able to create wallet backup folder %s!"), backupsDir.string());
5347  LogPrintf("%s\n", strBackupErrorRet);
5348  nWalletBackups = -1;
5349  return false;
5350  }
5351  } else if (!fs::is_directory(backupsDir)) {
5352  // something is wrong, we shouldn't continue until it's resolved
5353  strBackupErrorRet = strprintf(_("%s is not a valid backup folder!"), backupsDir.string());
5354  LogPrintf("%s\n", strBackupErrorRet);
5355  nWalletBackups = -1;
5356  return false;
5357  }
5358 
5359  // Create backup of the ...
5360  std::string dateTimeStr = DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime());
5361  if (wallet_path.empty()) {
5362  // ... opened wallet
5364  fs::path backupFile = backupsDir / (strWalletName + dateTimeStr);
5365  backupFile.make_preferred();
5366  if (!BackupWallet(backupFile.string())) {
5367  strBackupWarningRet = strprintf(_("Failed to create backup %s!"), backupFile.string());
5368  LogPrintf("%s\n", strBackupWarningRet);
5369  nWalletBackups = -1;
5370  return false;
5371  }
5372 
5373  // Update nKeysLeftSinceAutoBackup using current external keypool size
5375  LogPrintf("nKeysLeftSinceAutoBackup: %d\n", nKeysLeftSinceAutoBackup);
5376  if (IsLocked(true)) {
5377  strBackupWarningRet = _("Wallet is locked, can't replenish keypool! Automatic backups and mixing are disabled, please unlock your wallet to replenish keypool.");
5378  LogPrintf("%s\n", strBackupWarningRet);
5379  nWalletBackups = -2;
5380  return false;
5381  }
5382  } else {
5383  // ... strWalletName file
5384  std::string strSourceFile;
5385  BerkeleyEnvironment* env = GetWalletEnv(wallet_path, strSourceFile);
5386  fs::path sourceFile = env->Directory() / strSourceFile;
5387  fs::path backupFile = backupsDir / (strWalletName + dateTimeStr);
5388  sourceFile.make_preferred();
5389  backupFile.make_preferred();
5390  if (fs::exists(backupFile))
5391  {
5392  strBackupWarningRet = _("Failed to create backup, file already exists! This could happen if you restarted wallet in less than 60 seconds. You can continue if you are ok with this.");
5393  LogPrintf("%s\n", strBackupWarningRet);
5394  return false;
5395  }
5396  if(fs::exists(sourceFile)) {
5397  try {
5398  fs::copy_file(sourceFile, backupFile);
5399  LogPrintf("Creating backup of %s -> %s\n", sourceFile.string(), backupFile.string());
5400  } catch(fs::filesystem_error &error) {
5401  strBackupWarningRet = strprintf(_("Failed to create backup, error: %s"), error.what());
5402  LogPrintf("%s\n", strBackupWarningRet);
5403  nWalletBackups = -1;
5404  return false;
5405  }
5406  }
5407  }
5408 
5409  // Keep only the last 10 backups, including the new one of course
5410  typedef std::multimap<std::time_t, fs::path> folder_set_t;
5411  folder_set_t folder_set;
5412  fs::directory_iterator end_iter;
5413  // Build map of backup files for current(!) wallet sorted by last write time
5414  fs::path currentFile;
5415  for (fs::directory_iterator dir_iter(backupsDir); dir_iter != end_iter; ++dir_iter)
5416  {
5417  // Only check regular files
5418  if ( fs::is_regular_file(dir_iter->status()))
5419  {
5420  currentFile = dir_iter->path().filename();
5421  // Only add the backups for the current wallet, e.g. wallet.dat.*
5422  if (dir_iter->path().stem().string() == strWalletName) {
5423  folder_set.insert(folder_set_t::value_type(fs::last_write_time(dir_iter->path()), *dir_iter));
5424  }
5425  }
5426  }
5427 
5428  // Loop backward through backup files and keep the N newest ones (1 <= N <= 10)
5429  int counter = 0;
5430  for(auto it = folder_set.rbegin(); it != folder_set.rend(); ++it) {
5431  std::pair<const std::time_t, fs::path> file = *it;
5432  counter++;
5433  if (counter > nWalletBackups)
5434  {
5435  // More than nWalletBackups backups: delete oldest one(s)
5436  try {
5437  fs::remove(file.second);
5438  LogPrintf("Old backup deleted: %s\n", file.second);
5439  } catch(fs::filesystem_error &error) {
5440  strBackupWarningRet = strprintf(_("Failed to delete backup, error: %s"), error.what());
5441  LogPrintf("%s\n", strBackupWarningRet);
5442  return false;
5443  }
5444  }
5445  }
5446 
5447  return true;
5448 }
5449 
5451 {
5452  LOCK(cs_wallet);
5453  // Only notify UI if this transaction is in this wallet
5454  uint256 txHash = tx.GetHash();
5455  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txHash);
5456  if (mi != mapWallet.end()){
5457  NotifyTransactionChanged(this, txHash, CT_UPDATED);
5459  // notify an external script
5460  std::string strCmd = gArgs.GetArg("-instantsendnotify", "");
5461  if (!strCmd.empty()) {
5462  boost::replace_all(strCmd, "%s", txHash.GetHex());
5463  boost::thread t(runCommand, strCmd); // thread runs free
5464  }
5465  }
5466 }
5467 
5468 void CWallet::NotifyChainLock(const CBlockIndex* pindexChainLock, const llmq::CChainLockSig& clsig)
5469 {
5470  NotifyChainLockReceived(pindexChainLock->nHeight);
5471 }
5472 
5474 {
5475  nTime = GetTime();
5476  fInternal = false;
5477 }
5478 
5479 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool fInternalIn)
5480 {
5481  nTime = GetTime();
5482  vchPubKey = vchPubKeyIn;
5483  fInternal = fInternalIn;
5484 }
5485 
5486 CWalletKey::CWalletKey(int64_t nExpires)
5487 {
5488  nTimeCreated = (nExpires ? GetTime() : 0);
5489  nTimeExpires = nExpires;
5490 }
5491 
5492 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
5493 {
5494  // Update the tx's hashBlock
5495  hashBlock = pindex->GetBlockHash();
5496 
5497  // set the position of the transaction in the block
5498  nIndex = posInBlock;
5499 }
5500 
5501 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
5502 {
5503  int nResult;
5504 
5505  if (hashUnset())
5506  nResult = 0;
5507  else {
5509 
5510  // Find the block it claims to be in
5511  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
5512  if (mi == mapBlockIndex.end())
5513  nResult = 0;
5514  else {
5515  CBlockIndex* pindex = (*mi).second;
5516  if (!pindex || !chainActive.Contains(pindex))
5517  nResult = 0;
5518  else {
5519  pindexRet = pindex;
5520  nResult = ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
5521 
5522  if (nResult == 0 && !mempool.exists(GetHash()))
5523  return -1; // Not in chain, not in mempool
5524  }
5525  }
5526  }
5527 
5528  return nResult;
5529 }
5530 
5532 {
5534 }
5535 
5537 {
5539  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
5540  if (mi != mapBlockIndex.end() && mi->second != nullptr) {
5541  return llmq::chainLocksHandler->HasChainLock(mi->second->nHeight, hashBlock);
5542  }
5543  return false;
5544 }
5545 
5547 {
5548  if (!IsCoinBase())
5549  return 0;
5550  return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
5551 }
5552 
5553 
5555 {
5556  // Quick check to avoid re-setting fInMempool to false
5557  if (mempool.exists(tx->GetHash())) {
5558  return false;
5559  }
5560 
5561  // We must set fInMempool here - while it will be re-set to true by the
5562  // entered-mempool callback, if we did not there would be a race where a
5563  // user could call sendmoney in a loop and hit spurious out of funds errors
5564  // because we think that the transaction they just generated's change is
5565  // unavailable as we're not yet aware its in mempool.
5566  bool ret = ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
5567  false /* bypass_limits */, nAbsurdFee);
5568  fInMempool = ret;
5569  return ret;
5570 }
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: wallet.cpp:2452
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:905
static std::unique_ptr< BerkeleyDatabase > CreateDummy()
Return object for accessing dummy database with no read/write capabilities.
Definition: db.h:123
int64_t nTimeCreated
Definition: wallet.h:605
CAmount nValue
Definition: transaction.h:147
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:29
std::unordered_set< const CWalletTx *, WalletTxHasher > GetSpendableTXs() const
Definition: wallet.cpp:2520
bool fChangeCached
Definition: wallet.h:347
const CWallet * pwallet
Definition: wallet.h:283
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:648
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:66
CTxMemPool mempool
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:872
EstimatorBucket pass
Definition: fees.h:119
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:42
bool SelectCoinsMinConf(const CAmount &nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector< COutput > vCoins, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, CoinType nCoinType=CoinType::ALL_COINS) const
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
Definition: wallet.cpp:3025
std::set< std::set< CTxDestination > > GetAddressGroupings()
Definition: wallet.cpp:4614
bool SetHDChain(const CHDChain &chain)
Definition: crypter.cpp:515
void UpdateTransaction(CMutableTransaction &tx, unsigned int nIn, const SignatureData &data)
Definition: sign.cpp:161
bool GetAccountDestination(CTxDestination &dest, std::string strAccount, bool bForceNew=false)
Definition: wallet.cpp:1043
CWallet * pwallet
Definition: wallet.h:1276
void SetTx(CTransactionRef arg)
Definition: wallet.h:238
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned.
Definition: wallet.h:207
bool CanSupportFeature(enum WalletFeature wf) const
check whether we are allowed to upgrade (or already support) to the named feature ...
Definition: wallet.h:917
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:70
int64_t nNextResend
Definition: wallet.h:739
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:784
Account information.
Definition: wallet.h:1308
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:799
static CAmount GetSmallestDenomination()
Definition: privatesend.h:437
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
int i
Definition: wallet.h:570
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:640
CFeeRate GetDiscardRate(const CBlockPolicyEstimator &estimator)
Return the maximum feerate for discarding change.
Definition: fees.cpp:78
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:166
void SetMerkleBranch(const CBlockIndex *pIndex, int posInBlock)
Definition: wallet.cpp:5492
CAmount nImmatureWatchCreditCached
Definition: wallet.h:358
void UnlockAllCoins()
Definition: wallet.cpp:4814
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:470
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:41
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:80
bool Lock(bool fForMixing=false)
Definition: crypter.cpp:230
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:68
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:46
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:230
int64_t IncOrderPosNext(WalletBatch *batch=nullptr)
Increment the next transaction order id.
Definition: wallet.cpp:997
uint256 GetRandHash()
Definition: random.cpp:384
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:74
static const CAmount DEFAULT_DISCARD_FEE
-m_discard_rate default
Definition: wallet.h:60
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:4988
CAmount GetDenominatedCredit(bool unconfirmed, bool fUseCache=true) const
Definition: wallet.cpp:2360
const CWalletTx * GetWalletTx(const uint256 &hash) const
Definition: wallet.cpp:178
CAmount GetImmatureBalance() const
Definition: wallet.cpp:2666
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
bool IsLockedByInstantSend() const
Definition: wallet.cpp:5531
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:4553
bool fAllowWatchOnly
Includes watch only addresses which match the ISMINE_WATCH_SOLVABLE criteria.
Definition: coincontrol.h:37
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:124
static bool Verify(std::string wallet_file, bool salvage_wallet, std::string &error_string, std::string &warning_string)
Verify wallet naming and perform salvage on the wallet if required.
Definition: wallet.cpp:5024
EstimationResult est
Definition: fees.h:127
bool HaveKey(const CKeyID &address) const override
Check whether a key corresponding to a given address is present in the store.
Definition: crypter.cpp:334
void updatePassphrase(const SecureString &sWalletPassphrase)
Definition: keepass.cpp:533
void Process(const CScript &script)
Definition: wallet.cpp:142
int64_t GetBlockTime() const
Definition: chain.h:297
static bool IsDenominatedAmount(CAmount nInputAmount)
void GetKeyBirthTimes(std::map< CTxDestination, int64_t > &mapKeyBirth) const
Definition: wallet.cpp:4856
bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment="")
Definition: wallet.cpp:1009
int64_t nIndex
Definition: wallet.h:1277
int returnedTarget
Definition: fees.h:130
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:127
void TransactionAddedToMempool(const CTransactionRef &tx, int64_t nAcceptTime) override
Notifies listeners of a transaction having been added to mempool.
Definition: wallet.cpp:1431
CScript scriptPubKey
Definition: transaction.h:148
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:76
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:14
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
Definition: crypter.cpp:74
int GetRandInt(int nMax)
Definition: random.cpp:379
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
CAmount nCreditCached
Definition: wallet.h:350
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:5302
static CAmount GetCollateralAmount()
Definition: privatesend.h:460
CKey key
Definition: key.h:146
uint64_t nAccountingEntryNumber
Definition: wallet.h:904
CAmount GetAvailableBalance(const CCoinControl *coinControl=nullptr) const
Definition: wallet.cpp:2760
bool WriteHDPubKey(const CHDPubKey &hdPubKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:892
char fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
Definition: wallet.h:330
CAmount nChangeCached
Definition: wallet.h:360
int Priority() const
Definition: wallet.cpp:166
CScript prevPubKey
Definition: privatesend.h:125
Definition: block.h:72
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:906
std::vector< std::string > GetDestValues(const std::string &prefix) const
Get all destination values matching a prefix.
Definition: wallet.cpp:5010
std::set< uint256 > GetConflicts() const
Definition: wallet.cpp:2157
CCriticalSection cs_wallet
Definition: wallet.h:836
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
CAmount GetLegacyBalance(const isminefilter &filter, int minDepth, const std::string *account, const bool fAddLocked) const
Definition: wallet.cpp:2723
#define strprintf
Definition: tinyformat.h:1066
Encryption/decryption context with key information.
Definition: crypter.h:76
const uint256 & GetHash() const
Definition: wallet.h:272
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:496
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:207
bool SignSignature(const CKeyStore &keystore, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType)
Produce a script signature for a transaction.
Definition: sign.cpp:167
CAmount maxTxFee
Absolute maximum transaction fee (in duffs) used by wallet and mempool (rejects high fee in sendrawtr...
Definition: validation.cpp:247
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:179
double start
Definition: fees.h:108
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1861
uint32_t nExternalChainCounter
Definition: hdchain.h:13
bool HasChainLock(int nHeight, const uint256 &blockHash)
static int64_t GetOldestKeyInPool(const std::set< int64_t > &setKeyPool, WalletBatch &batch)
Definition: wallet.cpp:4543
int nIndex
Definition: wallet.h:218
bool IsCrypted() const
Definition: crypter.h:155
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:37
uint256 nPrivateSendSalt
Pulled from wallet DB ("ps_salt") and used when mixing a random number of rounds. ...
Definition: wallet.h:824
bool RemoveWallet(CWallet *wallet)
Definition: wallet.cpp:63
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: walletdb.cpp:734
std::vector< CTxIn > vin
Definition: transaction.h:293
bool bSpendZeroConfChange
Definition: wallet.cpp:97
BlockMap & mapBlockIndex
Definition: validation.cpp:215
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:150
bool fImmatureCreditCached
Definition: wallet.h:338
std::string strFromAccount
Definition: wallet.h:331
WalletFeature
(client) version numbers for particular wallet features
Definition: wallet.h:95
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:1295
bool IsChainLocked() const
Definition: wallet.cpp:5536
static const CAmount COIN
Definition: amount.h:14
bool SelectDenominatedAmounts(CAmount nValueMax, std::set< CAmount > &setAmountsRet) const
Definition: wallet.cpp:3458
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:93
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:64
#define DBG(x)
Server/client environment: argument handling, config file parsing, logging, thread wrappers...
Definition: util.h:47
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:877
static const uint32_t SEQUENCE_FINAL
Definition: transaction.h:79
TxItems wtxOrdered
Definition: wallet.h:901
const char * prefix
Definition: rest.cpp:574
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
Definition: wallet.cpp:405
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:2169
Definition: key.h:141
bool fInternal
Definition: wallet.h:1279
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key...
Definition: crypter.h:34
void ListSelected(std::vector< COutPoint > &vOutpoints) const
Definition: coincontrol.h:96
Implementation of BIP69 https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki.
Definition: transaction.h:352
void ReacceptWalletTransactions()
Definition: wallet.cpp:2106
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
bool FundTransaction(CMutableTransaction &tx, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, CCoinControl)
Insert additional inputs into the transaction by calling CreateTransaction();.
Definition: wallet.cpp:3252
int Height() const
Return the maximal height in the chain.
Definition: chain.h:484
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:75
uint256 hashBlock
Definition: wallet.h:211
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:76
FeeReason reason
Definition: fees.h:128
const std::string & GetAccountName(const CScript &scriptPubKey) const
Definition: wallet.cpp:4315
CCriticalSection cs_main
Definition: validation.cpp:213
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 ...
Definition: serialize.h:225
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:102
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:258
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:57
bool fAnonymizableTallyCachedNonDenom
Definition: wallet.h:745
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:264
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:332
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:62
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: keystore.h:85
std::set< int64_t > setInternalKeyPool
Definition: wallet.h:773
bool SelectPSInOutPairsByDenominations(int nDenom, CAmount nValueMax, std::vector< std::pair< CTxDSIn, CTxOut > > &vecPSInOutPairsRet)
Definition: wallet.cpp:3311
A signature creator for transactions.
Definition: sign.h:34
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule) ...
Definition: consensus.h:24
static bool VerifyDatabaseFile(const fs::path &wallet_path, std::string &warningStr, std::string &errorStr)
Definition: walletdb.cpp:862
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:64
uint256 GetID() const
Definition: hdchain.h:110
bool less_then_denom(const COutput &out1, const COutput &out2)
Definition: wallet.cpp:3010
std::string StringForFeeReason(FeeReason reason)
Definition: fees.cpp:30
bool HasSelected() const
Definition: coincontrol.h:71
value_type * data()
Definition: streams.h:203
void GetStrongRandBytes(unsigned char *out, int num)
Function to gather random data from multiple sources, failing whenever any of those source fail to pr...
Definition: random.cpp:317
void ListAccountCreditDebit(const std::string &strAccount, std::list< CAccountingEntry > &acentries)
Definition: walletdb.cpp:193
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid)
Definition: wallet.cpp:774
bool AutoBackupWallet(const fs::path &wallet_path, std::string &strBackupWarningRet, std::string &strBackupErrorRet)
Definition: wallet.cpp:5327
bool SetMaxVersion(int nVersion)
change which version we&#39;re allowed to upgrade to (note that this does not immediately imply upgrading...
Definition: wallet.cpp:673
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:499
bool EncryptKeys(CKeyingMaterial &vMasterKeyIn)
will encrypt previously unencrypted keys
Definition: crypter.cpp:389
uint8_t isminefilter
used for bitflags of isminetype
Definition: ismine.h:29
bool fRequireAllInputs
If false, only include as many inputs as necessary to fulfill a coin selection request. Only usable together with fAllowOtherInputs.
Definition: coincontrol.h:35
int64_t nTimeFirstKey
Definition: wallet.h:778
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:448
boost::signals2::signal< void(CWallet *wallet)> LoadWallet
A wallet has been loaded.
Definition: ui_interface.h:96
bool fAnonymizedCreditCached
Definition: wallet.h:340
std::map< CKeyID, int64_t > m_pool_key_to_index
Definition: wallet.h:776
CPubKey vchPubKey
Definition: wallet.h:1278
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:454
CChainParams defines various tweakable parameters of a given instance of the Dash system...
Definition: chainparams.h:41
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:647
void BlockDisconnected(const std::shared_ptr< const CBlock > &pblock, const CBlockIndex *pindexDisconnected) override
Notifies listeners of a block being disconnected.
Definition: wallet.cpp:1502
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:900
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:103
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:824
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:92
bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey)
Definition: wallet.cpp:369
uint256 hdchainID
Definition: hdchain.h:130
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: walletdb.cpp:772
bool GetKeyFromPool(CPubKey &key, bool fInternal)
Definition: wallet.cpp:4521
bool Unlock(const CKeyingMaterial &vMasterKeyIn, bool fForMixingOnly=false)
Definition: crypter.cpp:245
CWalletKey(int64_t nExpires=0)
todo: add something to note what created it (user, getnewaddress, change) maybe should have a map<str...
Definition: wallet.cpp:5486
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:51
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:161
fs::path Directory() const
Definition: db.h:49
CoinType
Definition: coincontrol.h:14
static CWallet * CreateWalletFromFile(const std::string &name, const fs::path &path)
Definition: wallet.cpp:5075
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:564
virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Definition: crypter.cpp:323
static std::vector< CAmount > GetStandardDenominations()
Definition: privatesend.h:436
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
std::atomic< bool > fAbortRescan
Definition: wallet.h:718
void ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fInternal)
Definition: wallet.cpp:4458
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:49
CAmount nWatchDebitCached
Definition: wallet.h:356
CAmount GetUnconfirmedWatchOnlyBalance() const
Definition: wallet.cpp:2692
int64_t m_max_keypool_index
Definition: wallet.h:775
void Debug(const std::string &strName) const
Definition: hdchain.cpp:42
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Definition: wallet.cpp:4366
bool LoadHDPubKey(const CHDPubKey &hdPubKey)
loads a HDPubKey into the wallets memory
Definition: wallet.cpp:336
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:797
const CBlockIndex * m_last_block_processed
The following is used to keep track of how far behind the wallet is from the chain sync...
Definition: wallet.h:818
uint256 GetSeedHash()
Definition: hdchain.cpp:146
bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
Look up a destination data tuple in the store, return true if found false otherwise.
Definition: wallet.cpp:4994
unsigned char * begin()
Definition: uint256.h:57
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:345
std::map< COutPoint, int > mapOutpointRoundsCache
Definition: wallet.h:759
std::unique_ptr< CDeterministicMNManager > deterministicMNManager
int64_t nTimeExpires
Definition: wallet.h:606
double withinTarget
Definition: fees.h:110
unsigned int nChild
Definition: pubkey.h:203
static const unsigned int DEFAULT_KEYPOOL_SIZE
Definition: wallet.h:54
bool ProduceSignature(const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:124
std::set< uint256 > GetConflicts(const uint256 &txid) const
Get wallet transactions that conflict with given transaction (spend same outputs) ...
Definition: wallet.cpp:685
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:1517
bool fAvailableCreditCached
Definition: wallet.h:339
bool IsSpent(const uint256 &hash, unsigned int n) const
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:755
bool IsChange(const CTxOut &txout) const
Definition: wallet.cpp:1715
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:149
bool IsNull() const
Definition: uint256.h:33
CAmount GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.cpp:2233
bool SetHDChain(WalletBatch &batch, const CHDChain &chain, bool memonly)
Definition: wallet.cpp:1781
std::vector< CompactTallyItem > vecAnonymizableTallyCachedNonDenom
Definition: wallet.h:746
bool operator()(const CInputCoin &t1, const CInputCoin &t2) const
Definition: wallet.cpp:122
static bool Recover(const fs::path &wallet_path, void *callbackDataIn, bool(*recoverKVcallback)(void *callbackData, CDataStream ssKey, CDataStream ssValue), std::string &out_backup_filename)
Definition: walletdb.cpp:822
void SyncTransaction(const CTransactionRef &tx, const CBlockIndex *pindex=nullptr, int posInBlock=0)
Definition: wallet.cpp:1411
bool AddWatchOnly(const CScript &dest) override
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
Definition: wallet.cpp:490
Coin Control Features.
Definition: coincontrol.h:28
static bool LogAcceptCategory(uint64_t category)
Definition: util.h:152
CAmount GetBalance() const
Definition: wallet.cpp:2541
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:446
bool SetCryptedHDChain(const CHDChain &chain)
Definition: crypter.cpp:527
const std::vector< CTxIn > vin
Definition: transaction.h:215
std::map< CScriptID, CKeyMetadata > m_script_metadata
Definition: wallet.h:856
std::map< CTxDestination, CAmount > GetAddressBalances()
Definition: wallet.cpp:4574
bool SetAccount(uint32_t nAccountIndex, const CHDAccount &hdAccount)
Definition: hdchain.cpp:193
WalletBatch * encrypted_batch
Definition: wallet.h:731
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Definition: crypter.cpp:360
std::string ToString() const
Definition: wallet.cpp:129
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:110
int desiredTarget
Definition: fees.h:129
Access to the wallet database.
Definition: walletdb.h:96
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
Definition: script.h:659
boost::optional< CFeeRate > m_discard_feerate
Override the discard feerate estimation with m_discard_feerate in CreateTransaction if set...
Definition: coincontrol.h:43
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:311
bool ReadAccount(const std::string &strAccount, CAccount &account)
Definition: walletdb.cpp:155
CAmount GetImmatureWatchOnlyCredit(const bool fUseCache=true) const
Definition: wallet.cpp:2277
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:69
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:188
void operator()(const CNoDestination &none)
Definition: wallet.cpp:163
CInstantSendManager * quorumInstantSendManager
bool fDebitCached
Definition: wallet.h:336
static const CAmount MIN_CHANGE
target minimum change amount
Definition: wallet.h:66
std::list< CAccountingEntry > laccentries
Definition: wallet.h:897
void KeepKey(int64_t nIndex)
Definition: wallet.cpp:4495
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
std::multimap< int64_t, TxPair > TxItems
Definition: wallet.h:900
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:118
bool fAvailableWatchCreditCached
Definition: wallet.h:346
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Add a key to the store.
Definition: crypter.cpp:299
void MarkReserveKeysAsUsed(int64_t keypool_id)
Marks all keys in the keypool up to and including reserve_key as used.
Definition: wallet.cpp:4758
uint256 GetBlockHash() const
Definition: chain.h:292
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:910
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:1197
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:72
std::vector< CWallet * > GetWallets()
Definition: wallet.cpp:79
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:249
bool done
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:4277
void MarkConflicted(const uint256 &hashBlock, const uint256 &hashTx)
Definition: wallet.cpp:1347
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:346
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: utiltime.cpp:22
bool fMasternodeMode
Definition: util.cpp:93
void MarkDirty()
Definition: wallet.cpp:1082
uint32_t nInternalChainCounter
Definition: hdchain.h:14
std::string strComment
Definition: wallet.h:638
DBErrors ReorderTransactions()
Definition: wallet.cpp:920
boost::signals2::signal< void(CCryptoKeyStore *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: crypter.h:172
#define LOCK2(cs1, cs2)
Definition: sync.h:179
size_t KeypoolCountExternalKeys()
Definition: wallet.cpp:4360
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:4295
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:867
unsigned int nTxConfirmTarget
Definition: wallet.cpp:96
int64_t nTime
Definition: wallet.h:122
int nWalletBackups
nWalletBackups: 1..10 - number of automatic backups to keep 0 - disabled by command-line -1 - disable...
Definition: util.cpp:102
CChainLocksHandler * chainLocksHandler
boost::signals2::signal< void(int height)> NotifyChainLockReceived
ChainLock received.
Definition: wallet.h:1209
CAmount GetAnonymizableBalance(bool fSkipDenominated=false, bool fSkipUnconfirmed=true) const
Definition: wallet.cpp:2555
#define LogPrintf(...)
Definition: util.h:203
unsigned int nMasterKeyMaxID
Definition: wallet.h:860
static CFeeRate m_discard_rate
Definition: wallet.h:1107
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:317
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:4928
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:7
int GetDepthInMainChain() const
Definition: wallet.h:263
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1283
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:4160
size_type size() const
Definition: streams.h:194
void UnlockCoin(const COutPoint &output)
Definition: wallet.cpp:4803
int nDepth
Definition: wallet.h:571
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:97
WatchKeyMap mapWatchKeys
Definition: keystore.h:60
uint64_t nEntryNo
Definition: wallet.h:641
bool LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
Definition: wallet.cpp:430
bool fDenomUnconfCreditCached
Definition: wallet.h:341
bool HasCollateralInputs(bool fOnlyConfirmed=true) const
Definition: wallet.cpp:3577
double end
Definition: fees.h:109
CTransactionRef tx
Definition: wallet.h:210
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:246
EstimatorBucket fail
Definition: fees.h:120
bool operator()(const COutput &t1, const COutput &t2) const
Definition: wallet.cpp:3002
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
Definition: wallet.cpp:4334
static bool VerifyEnvironment(const fs::path &wallet_path, std::string &errorStr)
Definition: walletdb.cpp:857
isminetype
IsMine() return codes.
Definition: ismine.h:17
An input of a transaction.
Definition: transaction.h:70
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: wallet.cpp:467
bool IsHDEnabled() const
HD Wallet Functions.
Definition: wallet.cpp:1847
CWallet * GetWallet(const std::string &name)
Definition: wallet.cpp:85
#define LOCK(cs)
Definition: sync.h:178
const char * name
Definition: rest.cpp:36
bool InMempool() const
Definition: wallet.cpp:2414
void NotifyChainLock(const CBlockIndex *pindexChainLock, const llmq::CChainLockSig &clsig) override
Definition: wallet.cpp:5468
const uint256 & GetHash() const
Definition: transaction.h:256
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1175
bool GetKey(const CKeyID &address, CKey &keyOut) const override
GetKey implementation that can derive a HD private key on the fly.
Definition: wallet.cpp:300
CKeyPool()
Definition: wallet.cpp:5473
std::set< COutPoint > setWalletUTXO
Definition: wallet.h:758
void ListProTxCoins(std::vector< COutPoint > &vOutpts)
Definition: wallet.cpp:4838
void SetBestChain(const CBlockLocator &loc) override
Notifies listeners of the new active block chain on-disk.
Definition: wallet.cpp:641
BerkeleyEnvironment * GetWalletEnv(const fs::path &wallet_path, std::string &database_filename)
Get BerkeleyEnvironment and database filename given a wallet path.
Definition: db.cpp:60
void operator()(const CScriptID &scriptId)
Definition: wallet.cpp:157
bool IsDenominated(const COutPoint &outpoint) const
Definition: wallet.cpp:1664
CTxDestination destChange
Definition: coincontrol.h:31
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:471
bool SelectCoins(const std::vector< COutput > &vAvailableCoins, const CAmount &nTargetValue, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CCoinControl *coinControl=nullptr) const
Select a set of coins such that nValueRet >= nTargetValue and at least all coins from coinControl are...
Definition: wallet.cpp:3168
bool IsValid() const
Definition: pubkey.h:165
Fast randomness source.
Definition: random.h:48
virtual bool HaveKey(const CKeyID &address) const =0
Check whether a key corresponding to a given address is present in the store.
int64_t nKeysLeftSinceAutoBackup
Definition: wallet.h:910
std::vector< unsigned char, secure_allocator< unsigned char > > SecureVector
Definition: secure.h:59
void Select(const COutPoint &output)
Definition: coincontrol.h:81
uint256 uint256S(const char *str)
Definition: uint256.h:143
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
Definition: chain.cpp:62
An encapsulated public key.
Definition: pubkey.h:30
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used if fAllowOtherInputs is ...
Definition: coincontrol.h:33
void DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_t nChildIndex, CExtKey &extKeyRet)
Definition: hdchain.cpp:151
bool SelectCoinsGroupedByAddresses(std::vector< CompactTallyItem > &vecTallyRet, bool fSkipDenominated=true, bool fAnonymizable=true, bool fSkipUnconfirmed=true, int nMaxOupointsPerAddress=-1) const
Definition: wallet.cpp:3355
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1276
std::set< COutPoint > setLockedCoins
Definition: wallet.h:908
virtual bool GetHDChain(CHDChain &hdChainRet) const override
Definition: crypter.cpp:539
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:476
TxSpends mapTxSpends
Definition: wallet.h:754
bool IsLockedCoin(uint256 hash, unsigned int n) const
Definition: wallet.cpp:4820
std::string GetRejectReason() const
Definition: validation.h:81
uint32_t n
Definition: transaction.h:30
bool IsLocked(const uint256 &txHash)
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:158
bool IsHex(const std::string &str)
const std::vector< CTxOut > vout
Definition: transaction.h:216
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:70
bool IsCoinBase() const
Definition: wallet.h:273
ScriptMap mapScripts
Definition: keystore.h:61
CAmount GetUnconfirmedBalance() const
Definition: wallet.cpp:2653
double inMempool
Definition: fees.h:112
int64_t GetBlockTimeMax() const
Definition: chain.h:302
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:92
int GetBlocksToMaturity() const
Definition: wallet.cpp:5546
CAmount GetImmatureWatchOnlyBalance() const
Definition: wallet.cpp:2705
bool IsNull() const
Definition: hdchain.cpp:27
bool AddWallet(CWallet *wallet)
Definition: wallet.cpp:53
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
Definition: wallet.cpp:708
bool EraseDestData(const CTxDestination &dest, const std::string &key)
Erases a destination data tuple in the store and on disk.
Definition: wallet.cpp:4981
void UpdateTimeFirstKey(int64_t nCreateTime)
Update wallet first key creation time.
Definition: wallet.cpp:455
void InitPrivateSendSalt()
Fetches PrivateSend salt from database or generates and saves a new one if no salt was found in the d...
Definition: wallet.cpp:2934
size_t KeypoolCountInternalKeys()
Definition: wallet.cpp:4385
bool IsTrusted() const
Definition: wallet.cpp:2419
void ResendWalletTransactions(int64_t nBestBlockTime, CConnman *connman) override
Tells listeners to broadcast their data.
Definition: wallet.cpp:2486
static const bool DEFAULT_USE_HD_WALLET
if set, all keys will be derived by using BIP39/BIP44
Definition: wallet.h:81
WatchOnlySet setWatchOnly
Definition: keystore.h:62
bool EncryptHDChain(const CKeyingMaterial &vMasterKeyIn)
Definition: crypter.cpp:411
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: wallet.cpp:4220
bool GetKey(const CKeyID &address, CKey &keyOut) const override
Definition: crypter.cpp:343
bool exists(uint256 hash) const
Definition: txmempool.h:672
Definition: net.h:136
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:130
An output of a transaction.
Definition: transaction.h:144
std::atomic_bool fImporting
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:154
std::string ToString() const
Definition: uint256.cpp:62
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, const CBlockIndex *pIndex, int posInBlock, bool fUpdate)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1217
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:256
static const int MAX_PRIVATESEND_ROUNDS
CAmount GetDenominatedBalance(bool unconfirmed=false) const
Definition: wallet.cpp:2638
bool LoadToWallet(const CWalletTx &wtxIn)
Definition: wallet.cpp:1181
std::set< int64_t > setExternalKeyPool
Definition: wallet.h:774
CoinType nCoinType
Controls which types of coins are allowed to be used (default: ALL_COINS)
Definition: coincontrol.h:49
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
bool fWatchCreditCached
Definition: wallet.h:344
int64_t nCreateTime
Definition: walletdb.h:64
static CCriticalSection cs_wallets
Definition: wallet.cpp:50
static void ApproximateBestSubset(const std::vector< CInputCoin > &vValue, const CAmount &nTotalLower, const CAmount &nTargetValue, std::vector< char > &vfBest, CAmount &nBest, int iterations=1000)
Definition: wallet.cpp:2949
std::vector< CTxOut > vout
Definition: transaction.h:294
uint32_t nChangeIndex
Definition: hdchain.h:132
void TransactionRemovedFromMempool(const CTransactionRef &ptx) override
Notifies listeners of a transaction leaving mempool.
Definition: wallet.cpp:1441
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:313
bool AddHDPubKey(WalletBatch &batch, const CExtPubKey &extPubKey, bool fInternal)
Adds a HDPubKey into the wallet(database)
Definition: wallet.cpp:344
bool IsAllFromMe(const CTransaction &tx, const isminefilter &filter) const
Returns whether all of the inputs match the filter.
Definition: wallet.cpp:1878
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
CAmount GetAnonymizedBalance(const CCoinControl *coinControl=nullptr) const
Definition: wallet.cpp:2577
bool RemoveWatchOnly(const CScript &dest) override
Definition: keystore.cpp:128
void LockCoin(const COutPoint &output)
Definition: wallet.cpp:4792
bool Unlock(const SecureString &strWalletPassphrase, bool fForMixingOnly=false)
Definition: wallet.cpp:524
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
Definition: wallet.cpp:1094
void ForceRemoveArg(const std::string &strArg)
Definition: util.cpp:854
const CTxOut & FindNonChangeParentOutput(const CTransaction &tx, int output) const
Find non-change parent output.
Definition: wallet.cpp:2917
CCriticalSection cs
Definition: txmempool.h:488
static std::unique_ptr< BerkeleyDatabase > Create(const fs::path &path)
Return object for accessing database at specified path.
Definition: db.h:117
bool fCreditCached
Definition: wallet.h:337
bool LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
Definition: wallet.cpp:438
CAmount GetAccountCreditDebit(const std::string &strAccount)
Definition: walletdb.cpp:181
int nWalletMaxVersion
the maximum wallet format version: memory-only variable that specifies to what version this wallet ma...
Definition: wallet.h:737
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1336
bool GetCollateralTxDSIn(CTxDSIn &txdsinRet, CAmount &nValueRet) const
Definition: wallet.cpp:3481
static std::vector< COutput > vCoins
bool WriteAccount(const std::string &strAccount, const CAccount &account)
Definition: walletdb.cpp:161
void AvailableCoins(std::vector< COutput > &vCoins, bool fOnlySafe=true, const CCoinControl *coinControl=nullptr, const CAmount &nMinimumAmount=1, const CAmount &nMaximumAmount=MAX_MONEY, const CAmount &nMinimumSumAmount=MAX_MONEY, const uint64_t nMaximumCount=0, const int nMinDepth=0, const int nMaxDepth=9999999) const
populate vCoins with vector of available COutputs.
Definition: wallet.cpp:2775
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:280
bool AcceptToMemoryPool(const CAmount &nAbsurdFee, CValidationState &state)
Pass this transaction to the mempool.
Definition: wallet.cpp:5554
CAmount GetNormalizedAnonymizedBalance() const
Definition: wallet.cpp:2616
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
CAmount GetWatchOnlyBalance() const
Definition: wallet.cpp:2678
bool SetCryptedHDChain(WalletBatch &batch, const CHDChain &chain, bool memonly)
Definition: wallet.cpp:1794
bool IsInMainChain() const
Definition: wallet.h:264
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1212
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:1545
CAmount nAnonymizedCreditCached
Definition: wallet.h:353
bool fBroadcastTransactions
Definition: wallet.h:741
CPubKey vchPubKey
Definition: wallet.h:1311
KeyMap mapKeys
Definition: keystore.h:59
void KeepKey()
Definition: wallet.cpp:4740
#define LogPrint(category,...)
Definition: util.h:214
CBlockIndex * ScanForWalletTransactions(CBlockIndex *pindexStart, CBlockIndex *pindexStop, const WalletRescanReserver &reserver, bool fUpdate=false)
Scan the block chain (starting in pindexStart) for transactions from or to us.
Definition: wallet.cpp:2030
bool fInMempool
Definition: wallet.h:348
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:145
std::atomic_bool fReindex
int GetCappedOutpointPrivateSendRounds(const COutPoint &outpoint) const
Definition: wallet.cpp:1657
std::vector< uint8_t > vExtraPayload
Definition: transaction.h:298
CAmount GetAvailableCredit(bool fUseCache=true) const
Definition: wallet.cpp:2247
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:140
txnouttype
Definition: standard.h:56
Capture information about block/transaction validation.
Definition: validation.h:22
std::vector< uint256 > ResendWalletTransactionsBefore(int64_t nTime, CConnman *connman)
Definition: wallet.cpp:2461
256-bit opaque blob.
Definition: uint256.h:123
CPubKey vchPubKey
Definition: wallet.h:123
std::set< CTxDestination > GetAccountAddresses(const std::string &strAccount) const
Definition: wallet.cpp:4707
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:15
CAmount nWatchCreditCached
Definition: wallet.h:357
ArgsManager gArgs
Definition: util.cpp:108
bool GetOutpointAndKeysFromOutput(const COutput &out, COutPoint &outpointRet, CPubKey &pubKeyRet, CKey &keyRet)
Extract txin information and keys from output.
Definition: wallet.cpp:3531
void GetScriptForMining(std::shared_ptr< CReserveScript > &script)
Definition: wallet.cpp:4781
bool IsFullyMixed(const COutPoint &outpoint) const
Definition: wallet.cpp:1680
static bool InitAutoBackup()
Definition: wallet.cpp:5309
std::vector< CTransactionRef > vtx
Definition: block.h:76
CryptedKeyMap mapCryptedKeys
Definition: crypter.h:148
CAmount nDenomUnconfCreditCached
Definition: wallet.h:354
const ChainTxData & TxData() const
Definition: chainparams.h:83
SecureVector GetSeed() const
Definition: hdchain.cpp:141
bool InitError(const std::string &str)
Show error message.
CAmount nAvailableCreditCached
Definition: wallet.h:352
static bool IsValidDenomination(int nDenom)
std::map< CTxDestination, std::vector< COutput > > ListCoins() const
Return list of available coins and locked coins grouped by non-change output address.
Definition: wallet.cpp:2871
bool randbool()
Generate a random boolean.
Definition: random.h:135
std::string EncodeDestination(const CTxDestination &dest)
Definition: base58.cpp:329
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:4252
CPrivateSendClientManager privateSendClient
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:1190
static CFeeRate fallbackFee
If fee estimation does not have enough data to provide estimates, use this fee instead.
Definition: wallet.h:1106
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Returns amount of debit if the input matches the filter, otherwise returns 0.
Definition: wallet.cpp:1559
bool SetCryptedHDChainSingle(const CHDChain &chain, bool memonly)
Definition: wallet.cpp:1820
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:567
static std::vector< CWallet * > vpwallets GUARDED_BY(cs_wallets)
CExtPubKey Neuter() const
Definition: key.cpp:287
bool IsLocked(bool fForMixing=false) const
Definition: crypter.cpp:209
MasterKeyMap mapMasterKeys
Definition: wallet.h:859
void NotifyTransactionLock(const CTransaction &tx, const llmq::CInstantSendLock &islock) override
Definition: wallet.cpp:5450
CAmount GetCredit(const isminefilter &filter) const
Definition: wallet.cpp:2200
int64_t GetTxTime() const
Definition: wallet.cpp:1923
A key allocated from the key pool.
Definition: wallet.h:1273
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >)
Definition: wallet.cpp:713
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:389
CKeePassIntegrator keePassInt
Definition: keepass.cpp:33
int64_t nOrderPosNext
Definition: wallet.h:903
std::map< CKeyID, CHDPubKey > mapHdPubKeys
Definition: wallet.h:912
bool IsSelected(const COutPoint &output) const
Definition: coincontrol.h:76
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:4391
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:412
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:14
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: utiltime.cpp:56
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:324
void BlockConnected(const std::shared_ptr< const CBlock > &pblock, const CBlockIndex *pindex, const std::vector< CTransactionRef > &vtxConflicted) override
Notifies listeners of a block being connected.
Definition: wallet.cpp:1449
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
void ListAccountCreditDebit(const std::string &strAccount, std::list< CAccountingEntry > &entries)
Definition: wallet.cpp:4135
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:808
A virtual base class for key stores.
Definition: keystore.h:19
bool SetHDChainSingle(const CHDChain &chain, bool memonly)
Set the HD chain model (chain child index counters) using temporary wallet db object which causes db ...
Definition: wallet.cpp:1814
boost::signals2::signal< void()> NotifyISLockReceived
IS-lock received.
Definition: wallet.h:1206
bool RelayWalletTransaction(CConnman *connman)
Definition: wallet.cpp:2137
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:284
void GenerateNewHDChain()
Definition: wallet.cpp:1744
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
void runCommand(const std::string &strCommand)
Definition: util.cpp:1236
double leftMempool
Definition: fees.h:113
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
Internal transfers.
Definition: wallet.h:631
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:453
const CWalletTx * tx
Definition: wallet.h:569
std::string GetHex() const
Definition: uint256.cpp:21
bool CreateTransaction(const std::vector< CRecipient > &vecSend, CWalletTx &wtxNew, CReserveKey &reservekey, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, const CCoinControl &coin_control, bool sign=true, int nExtraPayloadSize=0)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: wallet.cpp:3658
static CFeeRate minTxFee
Fees smaller than this (in duffs) are considered zero fee (for transaction creation) Override with -m...
Definition: wallet.h:1105
int nWalletVersion
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:734
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:715
void operator()(const CKeyID &keyId)
Definition: wallet.cpp:152
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:41
bool fAnonymizableTallyCached
Definition: wallet.h:743
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:23
bool GetAccount(uint32_t nAccountIndex, CHDAccount &hdAccountRet)
Definition: hdchain.cpp:184
#define AssertLockNotHeld(cs)
Definition: sync.h:88
bool LoadCScript(const CScript &redeemScript)
Definition: wallet.cpp:474
CPubKey GenerateNewKey(WalletBatch &batch, uint32_t nAccountIndex, bool fInternal)
keystore implementation Generate a new key
Definition: wallet.cpp:187
fs::path GetBackupsDir()
Definition: util.cpp:960
std::map< CKeyID, CKeyMetadata > mapKeyMetadata
Definition: wallet.h:853
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
Transaction fee set by the user.
bool SetMnemonic(const SecureVector &vchMnemonic, const SecureVector &vchMnemonicPassphrase, bool fUpdateID)
Definition: hdchain.cpp:72
int GetRealOutpointPrivateSendRounds(const COutPoint &outpoint, int nRounds=0) const
Definition: wallet.cpp:1576
std::vector< unsigned char > vchSalt
Definition: crypter.h:38
bool error(const char *fmt, const Args &... args)
Definition: util.h:222
Definition: wallet.h:195
static bool IsCollateralAmount(CAmount nInputAmount)
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:135
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:896
SecureString retrievePassphrase()
Definition: keepass.cpp:499
std::vector< CompactTallyItem > vecAnonymizableTallyCached
Definition: wallet.h:744
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1200
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:22
bool CreateCollateralTransaction(CMutableTransaction &txCollateral, std::string &strReason)
Definition: wallet.cpp:3587
std::vector< CKeyID > & vKeys
Definition: wallet.cpp:137
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:35
CAmount GetAnonymizedCredit(const CCoinControl *coinControl=nullptr) const
Definition: wallet.cpp:2320
A mutable version of CTransaction.
Definition: transaction.h:291
size_type size() const
Definition: prevector.h:310
double totalConfirmed
Definition: fees.h:111
CPubKey pubkey
Definition: pubkey.h:205
CAmount GetAvailableWatchOnlyCredit(const bool fUseCache=true) const
Definition: wallet.cpp:2291
CAmount nAvailableWatchCreditCached
Definition: wallet.h:359
bool GetReservedKey(CPubKey &pubkey, bool fInternalIn)
Definition: wallet.cpp:4721
Indicates that we know how to create a scriptSig that would solve this if we were given the appropria...
Definition: ismine.h:23
std::multimap< int64_t, std::pair< CWalletTx *, CAccountingEntry * > >::const_iterator m_it_wtxOrdered
Definition: wallet.h:333
static const CAmount DEFAULT_TRANSACTION_FEE
-paytxfee default
Definition: wallet.h:56
void ReturnKey()
Definition: wallet.cpp:4749
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:61
int64_t nLastResend
Definition: wallet.h:740
bool WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry &acentry)
This writes directly to the database, and will not update the CWallet&#39;s cached accounting entries! Us...
Definition: walletdb.cpp:166
bool IsNull() const
Definition: transaction.h:44
bool SetSeed(const SecureVector &vchSeedIn, bool fUpdateID)
Definition: hdchain.cpp:130
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:314
bool fWatchDebitCached
Definition: wallet.h:343
void InitWarning(const std::string &str)
Show warning message.
An encapsulated private key.
Definition: key.h:27
std::string m_name
Wallet filename from wallet=<path> command line or config option.
Definition: wallet.h:796
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:39
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
bool GetMasternodeOutpointAndKeys(COutPoint &outpointRet, CPubKey &pubKeyRet, CKey &keyRet, const std::string &strTxHash="", const std::string &strOutputIndex="")
Get 1000DASH output and keys which can be used for the Masternode.
Definition: wallet.cpp:3501
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:4972
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const
Definition: wallet.cpp:4828
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
GetPubKey implementation that also checks the mapHdPubKeys.
Definition: wallet.cpp:286
bool isReserved() const
Definition: wallet.h:1356
void printf(const char *fmt, const Args &... args)
Format list of arguments to std::cout, according to the given format string.
Definition: tinyformat.h:984
CAmount GetCredit(const CTxOut &txout, const isminefilter &filter) const
Definition: wallet.cpp:1708
bool fDenomConfCreditCached
Definition: wallet.h:342
bool HaveWatchOnly() const override
Definition: keystore.cpp:144
unsigned int nDeriveIterations
Definition: crypter.h:42
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:110
full block available in blk*.dat
Definition: chain.h:154
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1993
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1542
bool hashUnset() const
Definition: wallet.h:268
uint256 hashPrevBestCoinbase
Definition: wallet.h:803
bool fImmatureWatchCreditCached
Definition: wallet.h:345
std::set< CKeyID > GetKeys() const override
Definition: crypter.cpp:376
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:217
uint64_t GetCheapHash() const
A cheap hash function that just returns 64 bits from the result, it can be used when the contents are...
Definition: uint256.h:133
std::pair< CWalletTx *, CAccountingEntry * > TxPair
Definition: wallet.h:899
AssertLockHeld(g_cs_orphans)
void RelayTransaction(const CTransaction &tx)
Definition: net.cpp:3465
A hasher class for SHA-256.
Definition: sha256.h:13
bool BackupWallet(const std::string &strDest)
Definition: wallet.cpp:5320
bool HasWallets()
Definition: wallet.cpp:73
bool AddAccountingEntry(const CAccountingEntry &)
Definition: wallet.cpp:4140
COutPoint prevout
Definition: transaction.h:73
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:1203
float GetAverageAnonymizedRounds() const
Definition: wallet.cpp:2594
static const int CLIENT_VERSION
dashd-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
bool GetDecryptedHDChain(CHDChain &hdChainRet)
Definition: wallet.cpp:1826
Holds a mixing input.
Definition: privatesend.h:121
static CAmount DenominationToAmount(int nDenom)
std::string strOtherAccount
Definition: wallet.h:637
void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey &pubkey)
Definition: wallet.cpp:4506
int GetDepthInMainChain(const CBlockIndex *&pindexRet) const
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:5501
void AutoLockMasternodeCollaterals()
Definition: wallet.cpp:4204
static const int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:29
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:58
static bool RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue)
Definition: walletdb.cpp:834
CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl &coin_control, const CTxMemPool &pool, const CBlockPolicyEstimator &estimator, FeeCalculation *feeCalc)
Estimate the minimum fee considering user set parameters and the required fee.
Definition: fees.cpp:21
isminetype IsMine(const CKeyStore &keystore, const CTxDestination &dest)
Definition: ismine.cpp:28
bool fInternal
Definition: wallet.h:124
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:199
bool HaveKey(const CKeyID &address) const override
HaveKey implementation that also checks the mapHdPubKeys.
Definition: wallet.cpp:328
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
Definition: wallet.cpp:519
CAmount nCreditDebit
Definition: wallet.h:635
void DeriveNewChildKey(WalletBatch &batch, const CKeyMetadata &metadata, CKey &secretRet, uint32_t nAccountIndex, bool fInternal)
Definition: wallet.cpp:225
CExtPubKey extPubKey
Definition: hdchain.h:129
int64_t nTime
Definition: wallet.h:636
CAmount GetChange(const CTxOut &txout) const
Definition: wallet.cpp:1737
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:92
CTxOut txout
Definition: wallet.h:541
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
Definition: sync.h:94
int atoi(const std::string &str)
CAmount nImmatureCreditCached
Definition: wallet.h:351
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: ui_interface.h:82
CAmount GetChange() const
Definition: wallet.cpp:2405
bool RemoveWatchOnly(const CScript &dest) override
Definition: wallet.cpp:506
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const =0
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:354
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector< CKeyID > &vKeysIn)
Definition: wallet.cpp:140
int CountInputsWithAmount(CAmount nInputAmount) const
Definition: wallet.cpp:3559
A signature creator that just produces 72-byte empty signatures.
Definition: sign.h:55
bool AddWatchOnly(const CScript &dest) override
Support for Watch-only addresses.
Definition: keystore.cpp:118
bool GetBudgetSystemCollateralTX(CWalletTx &tx, uint256 hash, CAmount amount, const COutPoint &outpoint=COutPoint())
Definition: wallet.cpp:3631
A key pool entry.
Definition: wallet.h:119
bool DecryptHDChain(CHDChain &hdChainRet) const
Definition: crypter.cpp:464
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:42
const CKeyStore & keystore
Definition: wallet.cpp:136
CAmount nDenomConfCreditCached
Definition: wallet.h:355
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:34
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:312
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23
bool isAbandoned() const
Definition: wallet.h:269
std::vector< unsigned char > ParseHex(const char *psz)
bool WriteCryptedHDChain(const CHDChain &chain)
Definition: walletdb.cpp:882
uint256 hash
Definition: transaction.h:29
bool CommitTransaction(CWalletTx &wtxNew, CReserveKey &reservekey, CConnman *connman, CValidationState &state)
Call after CreateTransaction unless you want to abort.
Definition: wallet.cpp:4089
CAmount nDebitCached
Definition: wallet.h:349
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, std::string &strSentAccount, const isminefilter &filter) const
Definition: wallet.cpp:1929
CFeeRate dustRelayFee
Definition: policy.cpp:177
double decay
Definition: fees.h:121
static const unsigned int MAX_STANDARD_TX_SIZE
The maximum size for transactions we&#39;re willing to relay/mine.
Definition: policy.h:24
std::string strAccount
Definition: wallet.h:634
std::string ToStringShort() const
Definition: transaction.cpp:17
uint32_t nAccountIndex
Definition: hdchain.h:131
Released under the MIT license