Dash Core  0.12.2.1
P2P Digital Currency
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-2017 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 "coincontrol.h"
13 #include "consensus/consensus.h"
14 #include "consensus/validation.h"
15 #include "key.h"
16 #include "keystore.h"
17 #include "validation.h"
18 #include "net.h"
19 #include "policy/policy.h"
20 #include "primitives/block.h"
21 #include "primitives/transaction.h"
22 #include "script/script.h"
23 #include "script/sign.h"
24 #include "timedata.h"
25 #include "txmempool.h"
26 #include "util.h"
27 #include "utilmoneystr.h"
28 
29 #include "governance.h"
30 #include "instantx.h"
31 #include "keepass.h"
32 #include "privatesend-client.h"
33 #include "spork.h"
34 
35 #include <assert.h>
36 
37 #include <boost/algorithm/string/replace.hpp>
38 #include <boost/filesystem.hpp>
39 #include <boost/thread.hpp>
40 
41 
42 using namespace std;
43 
50 
62 
63 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
64 
71 {
72  bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
73  const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
74  {
75  return t1.first < t2.first;
76  }
77 };
78 
79 std::string COutput::ToString() const
80 {
81  return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
82 }
83 
84 int COutput::Priority() const
85 {
87  if(tx->vout[i].nValue == d) return 10000;
88  if(tx->vout[i].nValue < 1*COIN) return 20000;
89 
90  //nondenom return largest first
91  return -(tx->vout[i].nValue/COIN);
92 }
93 
94 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
95 {
96  LOCK(cs_wallet);
97  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
98  if (it == mapWallet.end())
99  return NULL;
100  return &(it->second);
101 }
102 
103 CPubKey CWallet::GenerateNewKey(uint32_t nAccountIndex, bool fInternal)
104 {
105  AssertLockHeld(cs_wallet); // mapKeyMetadata
106  bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
107 
108  CKey secret;
109 
110  // Create new metadata
111  int64_t nCreationTime = GetTime();
112  CKeyMetadata metadata(nCreationTime);
113 
114  CPubKey pubkey;
115  // use HD key derivation if HD was enabled during wallet creation
116  if (IsHDEnabled()) {
117  DeriveNewChildKey(metadata, secret, nAccountIndex, fInternal);
118  pubkey = secret.GetPubKey();
119  } else {
120  secret.MakeNewKey(fCompressed);
121 
122  // Compressed public keys were introduced in version 0.6.0
123  if (fCompressed)
124  SetMinVersion(FEATURE_COMPRPUBKEY);
125 
126  pubkey = secret.GetPubKey();
127  assert(secret.VerifyPubKey(pubkey));
128 
129  // Create new metadata
130  mapKeyMetadata[pubkey.GetID()] = metadata;
131  if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
132  nTimeFirstKey = nCreationTime;
133 
134  if (!AddKeyPubKey(secret, pubkey))
135  throw std::runtime_error(std::string(__func__) + ": AddKey failed");
136  }
137  return pubkey;
138 }
139 
140 void CWallet::DeriveNewChildKey(const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal)
141 {
142  CHDChain hdChainTmp;
143  if (!GetHDChain(hdChainTmp)) {
144  throw std::runtime_error(std::string(__func__) + ": GetHDChain failed");
145  }
146 
147  if (!DecryptHDChain(hdChainTmp))
148  throw std::runtime_error(std::string(__func__) + ": DecryptHDChainSeed failed");
149  // make sure seed matches this chain
150  if (hdChainTmp.GetID() != hdChainTmp.GetSeedHash())
151  throw std::runtime_error(std::string(__func__) + ": Wrong HD chain!");
152 
153  CHDAccount acc;
154  if (!hdChainTmp.GetAccount(nAccountIndex, acc))
155  throw std::runtime_error(std::string(__func__) + ": Wrong HD account!");
156 
157  // derive child key at next index, skip keys already known to the wallet
158  CExtKey childKey;
159  uint32_t nChildIndex = fInternal ? acc.nInternalChainCounter : acc.nExternalChainCounter;
160  do {
161  hdChainTmp.DeriveChildExtKey(nAccountIndex, fInternal, nChildIndex, childKey);
162  // increment childkey index
163  nChildIndex++;
164  } while (HaveKey(childKey.key.GetPubKey().GetID()));
165  secretRet = childKey.key;
166 
167  CPubKey pubkey = secretRet.GetPubKey();
168  assert(secretRet.VerifyPubKey(pubkey));
169 
170  // store metadata
171  mapKeyMetadata[pubkey.GetID()] = metadata;
172  if (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey)
173  nTimeFirstKey = metadata.nCreateTime;
174 
175  // update the chain model in the database
176  CHDChain hdChainCurrent;
177  GetHDChain(hdChainCurrent);
178 
179  if (fInternal) {
180  acc.nInternalChainCounter = nChildIndex;
181  }
182  else {
183  acc.nExternalChainCounter = nChildIndex;
184  }
185 
186  if (!hdChainCurrent.SetAccount(nAccountIndex, acc))
187  throw std::runtime_error(std::string(__func__) + ": SetAccount failed");
188 
189  if (IsCrypted()) {
190  if (!SetCryptedHDChain(hdChainCurrent, false))
191  throw std::runtime_error(std::string(__func__) + ": SetCryptedHDChain failed");
192  }
193  else {
194  if (!SetHDChain(hdChainCurrent, false))
195  throw std::runtime_error(std::string(__func__) + ": SetHDChain failed");
196  }
197 
198  if (!AddHDPubKey(childKey.Neuter(), fInternal))
199  throw std::runtime_error(std::string(__func__) + ": AddHDPubKey failed");
200 }
201 
202 bool CWallet::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
203 {
204  LOCK(cs_wallet);
205  std::map<CKeyID, CHDPubKey>::const_iterator mi = mapHdPubKeys.find(address);
206  if (mi != mapHdPubKeys.end())
207  {
208  const CHDPubKey &hdPubKey = (*mi).second;
209  vchPubKeyOut = hdPubKey.extPubKey.pubkey;
210  return true;
211  }
212  else
213  return CCryptoKeyStore::GetPubKey(address, vchPubKeyOut);
214 }
215 
216 bool CWallet::GetKey(const CKeyID &address, CKey& keyOut) const
217 {
218  LOCK(cs_wallet);
219  std::map<CKeyID, CHDPubKey>::const_iterator mi = mapHdPubKeys.find(address);
220  if (mi != mapHdPubKeys.end())
221  {
222  // if the key has been found in mapHdPubKeys, derive it on the fly
223  const CHDPubKey &hdPubKey = (*mi).second;
224  CHDChain hdChainCurrent;
225  if (!GetHDChain(hdChainCurrent))
226  throw std::runtime_error(std::string(__func__) + ": GetHDChain failed");
227  if (!DecryptHDChain(hdChainCurrent))
228  throw std::runtime_error(std::string(__func__) + ": DecryptHDChainSeed failed");
229  // make sure seed matches this chain
230  if (hdChainCurrent.GetID() != hdChainCurrent.GetSeedHash())
231  throw std::runtime_error(std::string(__func__) + ": Wrong HD chain!");
232 
233  CExtKey extkey;
234  hdChainCurrent.DeriveChildExtKey(hdPubKey.nAccountIndex, hdPubKey.nChangeIndex != 0, hdPubKey.extPubKey.nChild, extkey);
235  keyOut = extkey.key;
236 
237  return true;
238  }
239  else {
240  return CCryptoKeyStore::GetKey(address, keyOut);
241  }
242 }
243 
244 bool CWallet::HaveKey(const CKeyID &address) const
245 {
246  LOCK(cs_wallet);
247  if (mapHdPubKeys.count(address) > 0)
248  return true;
249  return CCryptoKeyStore::HaveKey(address);
250 }
251 
252 bool CWallet::LoadHDPubKey(const CHDPubKey &hdPubKey)
253 {
254  AssertLockHeld(cs_wallet);
255 
256  mapHdPubKeys[hdPubKey.extPubKey.pubkey.GetID()] = hdPubKey;
257  return true;
258 }
259 
260 bool CWallet::AddHDPubKey(const CExtPubKey &extPubKey, bool fInternal)
261 {
262  AssertLockHeld(cs_wallet);
263 
264  CHDChain hdChainCurrent;
265  GetHDChain(hdChainCurrent);
266 
267  CHDPubKey hdPubKey;
268  hdPubKey.extPubKey = extPubKey;
269  hdPubKey.hdchainID = hdChainCurrent.GetID();
270  hdPubKey.nChangeIndex = fInternal ? 1 : 0;
271  mapHdPubKeys[extPubKey.pubkey.GetID()] = hdPubKey;
272 
273  // check if we need to remove from watch-only
274  CScript script;
275  script = GetScriptForDestination(extPubKey.pubkey.GetID());
276  if (HaveWatchOnly(script))
277  RemoveWatchOnly(script);
278  script = GetScriptForRawPubKey(extPubKey.pubkey);
279  if (HaveWatchOnly(script))
280  RemoveWatchOnly(script);
281 
282  if (!fFileBacked)
283  return true;
284 
285  return CWalletDB(strWalletFile).WriteHDPubKey(hdPubKey, mapKeyMetadata[extPubKey.pubkey.GetID()]);
286 }
287 
288 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
289 {
290  AssertLockHeld(cs_wallet); // mapKeyMetadata
291  if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
292  return false;
293 
294  // check if we need to remove from watch-only
295  CScript script;
296  script = GetScriptForDestination(pubkey.GetID());
297  if (HaveWatchOnly(script))
298  RemoveWatchOnly(script);
299  script = GetScriptForRawPubKey(pubkey);
300  if (HaveWatchOnly(script))
301  RemoveWatchOnly(script);
302 
303  if (!fFileBacked)
304  return true;
305  if (!IsCrypted()) {
306  return CWalletDB(strWalletFile).WriteKey(pubkey,
307  secret.GetPrivKey(),
308  mapKeyMetadata[pubkey.GetID()]);
309  }
310  return true;
311 }
312 
313 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
314  const vector<unsigned char> &vchCryptedSecret)
315 {
316  if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
317  return false;
318  if (!fFileBacked)
319  return true;
320  {
321  LOCK(cs_wallet);
322  if (pwalletdbEncryption)
323  return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
324  vchCryptedSecret,
325  mapKeyMetadata[vchPubKey.GetID()]);
326  else
327  return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
328  vchCryptedSecret,
329  mapKeyMetadata[vchPubKey.GetID()]);
330  }
331  return false;
332 }
333 
334 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
335 {
336  AssertLockHeld(cs_wallet); // mapKeyMetadata
337  if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
338  nTimeFirstKey = meta.nCreateTime;
339 
340  mapKeyMetadata[pubkey.GetID()] = meta;
341  return true;
342 }
343 
344 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
345 {
346  return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
347 }
348 
349 bool CWallet::AddCScript(const CScript& redeemScript)
350 {
351  if (!CCryptoKeyStore::AddCScript(redeemScript))
352  return false;
353  if (!fFileBacked)
354  return true;
355  return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
356 }
357 
358 bool CWallet::LoadCScript(const CScript& redeemScript)
359 {
360  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
361  * that never can be redeemed. However, old wallets may still contain
362  * these. Do not add them to the wallet and warn. */
363  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
364  {
365  std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
366  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",
367  __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
368  return true;
369  }
370 
371  return CCryptoKeyStore::AddCScript(redeemScript);
372 }
373 
375 {
377  return false;
378  nTimeFirstKey = 1; // No birthday information for watch-only keys.
380  if (!fFileBacked)
381  return true;
382  return CWalletDB(strWalletFile).WriteWatchOnly(dest);
383 }
384 
386 {
387  AssertLockHeld(cs_wallet);
389  return false;
390  if (!HaveWatchOnly())
391  NotifyWatchonlyChanged(false);
392  if (fFileBacked)
393  if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
394  return false;
395 
396  return true;
397 }
398 
400 {
401  return CCryptoKeyStore::AddWatchOnly(dest);
402 }
403 
404 bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly)
405 {
406  SecureString strWalletPassphraseFinal;
407 
408  if (!IsLocked()) // was already fully unlocked, not only for mixing
409  return true;
410 
411  // Verify KeePassIntegration
412  if (strWalletPassphrase == "keepass" && GetBoolArg("-keepass", false)) {
413  try {
414  strWalletPassphraseFinal = keePassInt.retrievePassphrase();
415  } catch (std::exception& e) {
416  LogPrintf("CWallet::Unlock could not retrieve passphrase from KeePass: Error: %s\n", e.what());
417  return false;
418  }
419  } else {
420  strWalletPassphraseFinal = strWalletPassphrase;
421  }
422 
423  CCrypter crypter;
424  CKeyingMaterial vMasterKey;
425 
426  {
427  LOCK(cs_wallet);
428  BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
429  {
430  if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
431  return false;
432  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
433  continue; // try another master key
434  if (CCryptoKeyStore::Unlock(vMasterKey, fForMixingOnly)) {
435  if(nWalletBackups == -2) {
436  TopUpKeyPool();
437  LogPrintf("Keypool replenished, re-initializing automatic backups.\n");
438  nWalletBackups = GetArg("-createwalletbackups", 10);
439  }
440  return true;
441  }
442  }
443  }
444  return false;
445 }
446 
447 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
448 {
449  bool fWasLocked = IsLocked(true);
450  bool bUseKeePass = false;
451 
452  SecureString strOldWalletPassphraseFinal;
453 
454  // Verify KeePassIntegration
455  if(strOldWalletPassphrase == "keepass" && GetBoolArg("-keepass", false)) {
456  bUseKeePass = true;
457  try {
458  strOldWalletPassphraseFinal = keePassInt.retrievePassphrase();
459  } catch (std::exception& e) {
460  LogPrintf("CWallet::ChangeWalletPassphrase -- could not retrieve passphrase from KeePass: Error: %s\n", e.what());
461  return false;
462  }
463  } else {
464  strOldWalletPassphraseFinal = strOldWalletPassphrase;
465  }
466 
467  {
468  LOCK(cs_wallet);
469  Lock();
470 
471  CCrypter crypter;
472  CKeyingMaterial vMasterKey;
473  BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
474  {
475  if(!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
476  return false;
477  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
478  return false;
479  if (CCryptoKeyStore::Unlock(vMasterKey))
480  {
481  int64_t nStartTime = GetTimeMillis();
482  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
483  pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
484 
485  nStartTime = GetTimeMillis();
486  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
487  pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
488 
489  if (pMasterKey.second.nDeriveIterations < 25000)
490  pMasterKey.second.nDeriveIterations = 25000;
491 
492  LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
493 
494  if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
495  return false;
496  if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
497  return false;
498  CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
499  if (fWasLocked)
500  Lock();
501 
502  // Update KeePass if necessary
503  if(bUseKeePass) {
504  LogPrintf("CWallet::ChangeWalletPassphrase -- Updating KeePass with new passphrase");
505  try {
506  keePassInt.updatePassphrase(strNewWalletPassphrase);
507  } catch (std::exception& e) {
508  LogPrintf("CWallet::ChangeWalletPassphrase -- could not update passphrase in KeePass: Error: %s\n", e.what());
509  return false;
510  }
511  }
512 
513  return true;
514  }
515  }
516  }
517 
518  return false;
519 }
520 
522 {
523  CWalletDB walletdb(strWalletFile);
524  walletdb.WriteBestBlock(loc);
525 }
526 
527 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
528 {
529  LOCK(cs_wallet); // nWalletVersion
530  if (nWalletVersion >= nVersion)
531  return true;
532 
533  // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
534  if (fExplicit && nVersion > nWalletMaxVersion)
535  nVersion = FEATURE_LATEST;
536 
537  nWalletVersion = nVersion;
538 
539  if (nVersion > nWalletMaxVersion)
540  nWalletMaxVersion = nVersion;
541 
542  if (fFileBacked)
543  {
544  CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
545  if (nWalletVersion > 40000)
546  pwalletdb->WriteMinVersion(nWalletVersion);
547  if (!pwalletdbIn)
548  delete pwalletdb;
549  }
550 
551  return true;
552 }
553 
554 bool CWallet::SetMaxVersion(int nVersion)
555 {
556  LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
557  // cannot downgrade below current version
558  if (nWalletVersion > nVersion)
559  return false;
560 
561  nWalletMaxVersion = nVersion;
562 
563  return true;
564 }
565 
566 set<uint256> CWallet::GetConflicts(const uint256& txid) const
567 {
568  set<uint256> result;
569  AssertLockHeld(cs_wallet);
570 
571  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
572  if (it == mapWallet.end())
573  return result;
574  const CWalletTx& wtx = it->second;
575 
576  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
577 
578  BOOST_FOREACH(const CTxIn& txin, wtx.vin)
579  {
580  if (mapTxSpends.count(txin.prevout) <= 1)
581  continue; // No conflict if zero or one spends
582  range = mapTxSpends.equal_range(txin.prevout);
583  for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
584  result.insert(it->second);
585  }
586  return result;
587 }
588 
589 void CWallet::Flush(bool shutdown)
590 {
591  bitdb.Flush(shutdown);
592 }
593 
594 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
595 {
596  if (!bitdb.Open(GetDataDir()))
597  {
598  // try moving the database env out of the way
599  boost::filesystem::path pathDatabase = GetDataDir() / "database";
600  boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
601  try {
602  boost::filesystem::rename(pathDatabase, pathDatabaseBak);
603  LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
604  } catch (const boost::filesystem::filesystem_error&) {
605  // failure is ok (well, not really, but it's not worse than what we started with)
606  }
607 
608  // try again
609  if (!bitdb.Open(GetDataDir())) {
610  // if it still fails, it probably means we can't even create the database env
611  string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
612  errorString += msg;
613  return true;
614  }
615  }
616 
617  if (GetBoolArg("-salvagewallet", false))
618  {
619  // Recover readable keypairs:
620  if (!CWalletDB::Recover(bitdb, walletFile, true))
621  return false;
622  }
623 
624  if (boost::filesystem::exists(GetDataDir() / walletFile))
625  {
627  if (r == CDBEnv::RECOVER_OK)
628  {
629  warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
630  " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
631  " your balance or transactions are incorrect you should"
632  " restore from a backup."), GetDataDir());
633  }
634  if (r == CDBEnv::RECOVER_FAIL)
635  errorString += _("wallet.dat corrupt, salvage failed");
636  }
637 
638  return true;
639 }
640 
641 void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
642 {
643  // We want all the wallet transactions in range to have the same metadata as
644  // the oldest (smallest nOrderPos).
645  // So: find smallest nOrderPos:
646 
647  int nMinOrderPos = std::numeric_limits<int>::max();
648  const CWalletTx* copyFrom = NULL;
649  for (TxSpends::iterator it = range.first; it != range.second; ++it)
650  {
651  const uint256& hash = it->second;
652  int n = mapWallet[hash].nOrderPos;
653  if (n < nMinOrderPos)
654  {
655  nMinOrderPos = n;
656  copyFrom = &mapWallet[hash];
657  }
658  }
659  // Now copy data from copyFrom to rest:
660  for (TxSpends::iterator it = range.first; it != range.second; ++it)
661  {
662  const uint256& hash = it->second;
663  CWalletTx* copyTo = &mapWallet[hash];
664  if (copyFrom == copyTo) continue;
665  if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
666  copyTo->mapValue = copyFrom->mapValue;
667  copyTo->vOrderForm = copyFrom->vOrderForm;
668  // fTimeReceivedIsTxTime not copied on purpose
669  // nTimeReceived not copied on purpose
670  copyTo->nTimeSmart = copyFrom->nTimeSmart;
671  copyTo->fFromMe = copyFrom->fFromMe;
672  copyTo->strFromAccount = copyFrom->strFromAccount;
673  // nOrderPos not copied on purpose
674  // cached members not copied on purpose
675  }
676 }
677 
682 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
683 {
684  const COutPoint outpoint(hash, n);
685  pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
686  range = mapTxSpends.equal_range(outpoint);
687 
688  for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
689  {
690  const uint256& wtxid = it->second;
691  std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
692  if (mit != mapWallet.end()) {
693  int depth = mit->second.GetDepthInMainChain();
694  if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
695  return true; // Spent
696  }
697  }
698  return false;
699 }
700 
701 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
702 {
703  mapTxSpends.insert(make_pair(outpoint, wtxid));
704  setWalletUTXO.erase(outpoint);
705 
706  pair<TxSpends::iterator, TxSpends::iterator> range;
707  range = mapTxSpends.equal_range(outpoint);
708  SyncMetaData(range);
709 }
710 
711 
712 void CWallet::AddToSpends(const uint256& wtxid)
713 {
714  assert(mapWallet.count(wtxid));
715  CWalletTx& thisTx = mapWallet[wtxid];
716  if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
717  return;
718 
719  BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
720  AddToSpends(txin.prevout, wtxid);
721 }
722 
723 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
724 {
725  if (IsCrypted())
726  return false;
727 
728  CKeyingMaterial vMasterKey;
730 
731  vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
732  GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
733 
734  CMasterKey kMasterKey;
736 
737  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
739 
740  CCrypter crypter;
741  int64_t nStartTime = GetTimeMillis();
742  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
743  kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
744 
745  nStartTime = GetTimeMillis();
746  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
747  kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
748 
749  if (kMasterKey.nDeriveIterations < 25000)
750  kMasterKey.nDeriveIterations = 25000;
751 
752  LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
753 
754  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
755  return false;
756  if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
757  return false;
758 
759  {
760  LOCK(cs_wallet);
761  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
762  if (fFileBacked)
763  {
764  assert(!pwalletdbEncryption);
765  pwalletdbEncryption = new CWalletDB(strWalletFile);
766  if (!pwalletdbEncryption->TxnBegin()) {
767  delete pwalletdbEncryption;
768  pwalletdbEncryption = NULL;
769  return false;
770  }
771  pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
772  }
773 
774  // must get current HD chain before EncryptKeys
775  CHDChain hdChainCurrent;
776  GetHDChain(hdChainCurrent);
777 
778  if (!EncryptKeys(vMasterKey))
779  {
780  if (fFileBacked) {
781  pwalletdbEncryption->TxnAbort();
782  delete pwalletdbEncryption;
783  }
784  // We now probably have half of our keys encrypted in memory, and half not...
785  // die and let the user reload the unencrypted wallet.
786  assert(false);
787  }
788 
789  if (!hdChainCurrent.IsNull()) {
790  assert(EncryptHDChain(vMasterKey));
791 
792  CHDChain hdChainCrypted;
793  assert(GetHDChain(hdChainCrypted));
794 
795  DBG(
796  printf("EncryptWallet -- current seed: '%s'\n", HexStr(hdChainCurrent.GetSeed()).c_str());
797  printf("EncryptWallet -- crypted seed: '%s'\n", HexStr(hdChainCrypted.GetSeed()).c_str());
798  );
799 
800  // ids should match, seed hashes should not
801  assert(hdChainCurrent.GetID() == hdChainCrypted.GetID());
802  assert(hdChainCurrent.GetSeedHash() != hdChainCrypted.GetSeedHash());
803 
804  assert(SetCryptedHDChain(hdChainCrypted, false));
805  }
806 
807  // Encryption was introduced in version 0.4.0
808  SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
809 
810  if (fFileBacked)
811  {
812  if (!pwalletdbEncryption->TxnCommit()) {
813  delete pwalletdbEncryption;
814  // We now have keys encrypted in memory, but not on disk...
815  // die to avoid confusion and let the user reload the unencrypted wallet.
816  assert(false);
817  }
818 
819  delete pwalletdbEncryption;
820  pwalletdbEncryption = NULL;
821  }
822 
823  Lock();
824  Unlock(strWalletPassphrase);
825 
826  // if we are not using HD, generate new keypool
827  if(IsHDEnabled()) {
828  TopUpKeyPool();
829  }
830  else {
831  NewKeyPool();
832  }
833 
834  Lock();
835 
836  // Need to completely rewrite the wallet file; if we don't, bdb might keep
837  // bits of the unencrypted private key in slack space in the database file.
838  CDB::Rewrite(strWalletFile);
839 
840  // Update KeePass if necessary
841  if(GetBoolArg("-keepass", false)) {
842  LogPrintf("CWallet::EncryptWallet -- Updating KeePass with new passphrase");
843  try {
844  keePassInt.updatePassphrase(strWalletPassphrase);
845  } catch (std::exception& e) {
846  LogPrintf("CWallet::EncryptWallet -- could not update passphrase in KeePass: Error: %s\n", e.what());
847  }
848  }
849 
850  }
851  NotifyStatusChanged(this);
852 
853  return true;
854 }
855 
857 {
858  AssertLockHeld(cs_wallet); // nOrderPosNext
859  int64_t nRet = nOrderPosNext++;
860  if (pwalletdb) {
861  pwalletdb->WriteOrderPosNext(nOrderPosNext);
862  } else {
863  CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
864  }
865  return nRet;
866 }
867 
869 {
870  {
871  LOCK(cs_wallet);
872  BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
873  item.second.MarkDirty();
874  }
875 
876  fAnonymizableTallyCached = false;
877  fAnonymizableTallyCachedNonDenom = false;
878 }
879 
880 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
881 {
882  uint256 hash = wtxIn.GetHash();
883 
884  if (fFromLoadWallet)
885  {
886  mapWallet[hash] = wtxIn;
887  CWalletTx& wtx = mapWallet[hash];
888  wtx.BindWallet(this);
889  wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
890  AddToSpends(hash);
891  BOOST_FOREACH(const CTxIn& txin, wtx.vin) {
892  if (mapWallet.count(txin.prevout.hash)) {
893  CWalletTx& prevtx = mapWallet[txin.prevout.hash];
894  if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
895  MarkConflicted(prevtx.hashBlock, wtx.GetHash());
896  }
897  }
898  }
899  }
900  else
901  {
902  LOCK(cs_wallet);
903  // Inserts only if not already there, returns tx inserted or tx found
904  pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
905  CWalletTx& wtx = (*ret.first).second;
906  wtx.BindWallet(this);
907  bool fInsertedNew = ret.second;
908  if (fInsertedNew)
909  {
911  wtx.nOrderPos = IncOrderPosNext(pwalletdb);
912  wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
913 
914  wtx.nTimeSmart = wtx.nTimeReceived;
915  if (!wtxIn.hashUnset())
916  {
917  if (mapBlockIndex.count(wtxIn.hashBlock))
918  {
919  int64_t latestNow = wtx.nTimeReceived;
920  int64_t latestEntry = 0;
921  {
922  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
923  int64_t latestTolerated = latestNow + 300;
924  const TxItems & txOrdered = wtxOrdered;
925  for (TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
926  {
927  CWalletTx *const pwtx = (*it).second.first;
928  if (pwtx == &wtx)
929  continue;
930  CAccountingEntry *const pacentry = (*it).second.second;
931  int64_t nSmartTime;
932  if (pwtx)
933  {
934  nSmartTime = pwtx->nTimeSmart;
935  if (!nSmartTime)
936  nSmartTime = pwtx->nTimeReceived;
937  }
938  else
939  nSmartTime = pacentry->nTime;
940  if (nSmartTime <= latestTolerated)
941  {
942  latestEntry = nSmartTime;
943  if (nSmartTime > latestNow)
944  latestNow = nSmartTime;
945  break;
946  }
947  }
948  }
949 
950  int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
951  wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
952  }
953  else
954  LogPrintf("AddToWallet(): found %s in block %s not in index\n",
955  wtxIn.GetHash().ToString(),
956  wtxIn.hashBlock.ToString());
957  }
958  AddToSpends(hash);
959  for(int i = 0; i < wtx.vout.size(); ++i) {
960  if (IsMine(wtx.vout[i]) && !IsSpent(hash, i)) {
961  setWalletUTXO.insert(COutPoint(hash, i));
962  }
963  }
964  }
965 
966  bool fUpdated = false;
967  if (!fInsertedNew)
968  {
969  // Merge
970  if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
971  {
972  wtx.hashBlock = wtxIn.hashBlock;
973  fUpdated = true;
974  }
975  // If no longer abandoned, update
976  if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
977  {
978  wtx.hashBlock = wtxIn.hashBlock;
979  fUpdated = true;
980  }
981  if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
982  {
983  wtx.nIndex = wtxIn.nIndex;
984  fUpdated = true;
985  }
986  if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
987  {
988  wtx.fFromMe = wtxIn.fFromMe;
989  fUpdated = true;
990  }
991  }
992 
994  LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
995 
996  // Write to disk
997  if (fInsertedNew || fUpdated)
998  if (!wtx.WriteToDisk(pwalletdb))
999  return false;
1000 
1001  // Break debit/credit balance caches:
1002  wtx.MarkDirty();
1003 
1004  // Notify UI of new or updated transaction
1005  NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1006 
1007  // notify an external script when a wallet transaction comes in or is updated
1008  std::string strCmd = GetArg("-walletnotify", "");
1009 
1010  if ( !strCmd.empty())
1011  {
1012  boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1013  boost::thread t(runCommand, strCmd); // thread runs free
1014  }
1015 
1016  fAnonymizableTallyCached = false;
1017  fAnonymizableTallyCachedNonDenom = false;
1018 
1019  }
1020  return true;
1021 }
1022 
1028 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1029 {
1030  {
1031  AssertLockHeld(cs_wallet);
1032 
1033  if (pblock) {
1034  BOOST_FOREACH(const CTxIn& txin, tx.vin) {
1035  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1036  while (range.first != range.second) {
1037  if (range.first->second != tx.GetHash()) {
1038  LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pblock->GetHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1039  MarkConflicted(pblock->GetHash(), range.first->second);
1040  }
1041  range.first++;
1042  }
1043  }
1044  }
1045 
1046  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1047  if (fExisted && !fUpdate) return false;
1048  if (fExisted || IsMine(tx) || IsFromMe(tx))
1049  {
1050  CWalletTx wtx(this,tx);
1051 
1052  // Get merkle branch if transaction was found in a block
1053  if (pblock)
1054  wtx.SetMerkleBranch(*pblock);
1055 
1056  // Do not flush the wallet here for performance reasons
1057  // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1058  CWalletDB walletdb(strWalletFile, "r+", false);
1059 
1060  return AddToWallet(wtx, false, &walletdb);
1061  }
1062  }
1063  return false;
1064 }
1065 
1067 {
1068  LOCK2(cs_main, cs_wallet);
1069 
1070  // Do not flush the wallet here for performance reasons
1071  CWalletDB walletdb(strWalletFile, "r+", false);
1072 
1073  std::set<uint256> todo;
1074  std::set<uint256> done;
1075 
1076  // Can't mark abandoned if confirmed or in mempool
1077  assert(mapWallet.count(hashTx));
1078  CWalletTx& origtx = mapWallet[hashTx];
1079  if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1080  return false;
1081  }
1082 
1083  todo.insert(hashTx);
1084 
1085  while (!todo.empty()) {
1086  uint256 now = *todo.begin();
1087  todo.erase(now);
1088  done.insert(now);
1089  assert(mapWallet.count(now));
1090  CWalletTx& wtx = mapWallet[now];
1091  int currentconfirm = wtx.GetDepthInMainChain();
1092  // If the orig tx was not in block, none of its spends can be
1093  assert(currentconfirm <= 0);
1094  // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1095  if (currentconfirm == 0 && !wtx.isAbandoned()) {
1096  // If the orig tx was not in block/mempool, none of its spends can be in mempool
1097  assert(!wtx.InMempool());
1098  wtx.nIndex = -1;
1099  wtx.setAbandoned();
1100  wtx.MarkDirty();
1101  wtx.WriteToDisk(&walletdb);
1102  NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1103  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1104  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1105  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1106  if (!done.count(iter->second)) {
1107  todo.insert(iter->second);
1108  }
1109  iter++;
1110  }
1111  // If a transaction changes 'conflicted' state, that changes the balance
1112  // available of the outputs it spends. So force those to be recomputed
1113  BOOST_FOREACH(const CTxIn& txin, wtx.vin)
1114  {
1115  if (mapWallet.count(txin.prevout.hash))
1116  mapWallet[txin.prevout.hash].MarkDirty();
1117  }
1118  }
1119  }
1120 
1121  fAnonymizableTallyCached = false;
1122  fAnonymizableTallyCachedNonDenom = false;
1123 
1124  return true;
1125 }
1126 
1127 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1128 {
1129  LOCK2(cs_main, cs_wallet);
1130 
1131  int conflictconfirms = 0;
1132  if (mapBlockIndex.count(hashBlock)) {
1133  CBlockIndex* pindex = mapBlockIndex[hashBlock];
1134  if (chainActive.Contains(pindex)) {
1135  conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1136  }
1137  }
1138  // If number of conflict confirms cannot be determined, this means
1139  // that the block is still unknown or not yet part of the main chain,
1140  // for example when loading the wallet during a reindex. Do nothing in that
1141  // case.
1142  if (conflictconfirms >= 0)
1143  return;
1144 
1145  // Do not flush the wallet here for performance reasons
1146  CWalletDB walletdb(strWalletFile, "r+", false);
1147 
1148  std::set<uint256> todo;
1149  std::set<uint256> done;
1150 
1151  todo.insert(hashTx);
1152 
1153  while (!todo.empty()) {
1154  uint256 now = *todo.begin();
1155  todo.erase(now);
1156  done.insert(now);
1157  assert(mapWallet.count(now));
1158  CWalletTx& wtx = mapWallet[now];
1159  int currentconfirm = wtx.GetDepthInMainChain();
1160  if (conflictconfirms < currentconfirm) {
1161  // Block is 'more conflicted' than current confirm; update.
1162  // Mark transaction as conflicted with this block.
1163  wtx.nIndex = -1;
1164  wtx.hashBlock = hashBlock;
1165  wtx.MarkDirty();
1166  wtx.WriteToDisk(&walletdb);
1167  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1168  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1169  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1170  if (!done.count(iter->second)) {
1171  todo.insert(iter->second);
1172  }
1173  iter++;
1174  }
1175  // If a transaction changes 'conflicted' state, that changes the balance
1176  // available of the outputs it spends. So force those to be recomputed
1177  BOOST_FOREACH(const CTxIn& txin, wtx.vin)
1178  {
1179  if (mapWallet.count(txin.prevout.hash))
1180  mapWallet[txin.prevout.hash].MarkDirty();
1181  }
1182  }
1183  }
1184 
1185  fAnonymizableTallyCached = false;
1186  fAnonymizableTallyCachedNonDenom = false;
1187 }
1188 
1189 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1190 {
1191  LOCK2(cs_main, cs_wallet);
1192 
1193  if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1194  return; // Not one of ours
1195 
1196  // If a transaction changes 'conflicted' state, that changes the balance
1197  // available of the outputs it spends. So force those to be
1198  // recomputed, also:
1199  BOOST_FOREACH(const CTxIn& txin, tx.vin)
1200  {
1201  if (mapWallet.count(txin.prevout.hash))
1202  mapWallet[txin.prevout.hash].MarkDirty();
1203  }
1204 
1205  fAnonymizableTallyCached = false;
1206  fAnonymizableTallyCachedNonDenom = false;
1207 }
1208 
1209 
1211 {
1212  {
1213  LOCK(cs_wallet);
1214  map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1215  if (mi != mapWallet.end())
1216  {
1217  const CWalletTx& prev = (*mi).second;
1218  if (txin.prevout.n < prev.vout.size())
1219  return IsMine(prev.vout[txin.prevout.n]);
1220  }
1221  }
1222  return ISMINE_NO;
1223 }
1224 
1225 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1226 {
1227  {
1228  LOCK(cs_wallet);
1229  map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1230  if (mi != mapWallet.end())
1231  {
1232  const CWalletTx& prev = (*mi).second;
1233  if (txin.prevout.n < prev.vout.size())
1234  if (IsMine(prev.vout[txin.prevout.n]) & filter)
1235  return prev.vout[txin.prevout.n].nValue;
1236  }
1237  }
1238  return 0;
1239 }
1240 
1241 // Recursively determine the rounds of a given input (How deep is the PrivateSend chain for a given input)
1242 int CWallet::GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds) const
1243 {
1244  static std::map<uint256, CMutableTransaction> mDenomWtxes;
1245 
1246  if(nRounds >= 16) return 15; // 16 rounds max
1247 
1248  uint256 hash = outpoint.hash;
1249  unsigned int nout = outpoint.n;
1250 
1251  const CWalletTx* wtx = GetWalletTx(hash);
1252  if(wtx != NULL)
1253  {
1254  std::map<uint256, CMutableTransaction>::const_iterator mdwi = mDenomWtxes.find(hash);
1255  if (mdwi == mDenomWtxes.end()) {
1256  // not known yet, let's add it
1257  LogPrint("privatesend", "GetRealOutpointPrivateSendRounds INSERTING %s\n", hash.ToString());
1258  mDenomWtxes[hash] = CMutableTransaction(*wtx);
1259  } else if(mDenomWtxes[hash].vout[nout].nRounds != -10) {
1260  // found and it's not an initial value, just return it
1261  return mDenomWtxes[hash].vout[nout].nRounds;
1262  }
1263 
1264 
1265  // bounds check
1266  if (nout >= wtx->vout.size()) {
1267  // should never actually hit this
1268  LogPrint("privatesend", "GetRealOutpointPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, -4);
1269  return -4;
1270  }
1271 
1272  if (IsCollateralAmount(wtx->vout[nout].nValue)) {
1273  mDenomWtxes[hash].vout[nout].nRounds = -3;
1274  LogPrint("privatesend", "GetRealOutpointPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
1275  return mDenomWtxes[hash].vout[nout].nRounds;
1276  }
1277 
1278  //make sure the final output is non-denominate
1279  if (!IsDenominatedAmount(wtx->vout[nout].nValue)) { //NOT DENOM
1280  mDenomWtxes[hash].vout[nout].nRounds = -2;
1281  LogPrint("privatesend", "GetRealOutpointPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
1282  return mDenomWtxes[hash].vout[nout].nRounds;
1283  }
1284 
1285  bool fAllDenoms = true;
1286  BOOST_FOREACH(CTxOut out, wtx->vout) {
1287  fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue);
1288  }
1289 
1290  // this one is denominated but there is another non-denominated output found in the same tx
1291  if (!fAllDenoms) {
1292  mDenomWtxes[hash].vout[nout].nRounds = 0;
1293  LogPrint("privatesend", "GetRealOutpointPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
1294  return mDenomWtxes[hash].vout[nout].nRounds;
1295  }
1296 
1297  int nShortest = -10; // an initial value, should be no way to get this by calculations
1298  bool fDenomFound = false;
1299  // only denoms here so let's look up
1300  BOOST_FOREACH(CTxIn txinNext, wtx->vin) {
1301  if (IsMine(txinNext)) {
1302  int n = GetRealOutpointPrivateSendRounds(txinNext.prevout, nRounds + 1);
1303  // denom found, find the shortest chain or initially assign nShortest with the first found value
1304  if(n >= 0 && (n < nShortest || nShortest == -10)) {
1305  nShortest = n;
1306  fDenomFound = true;
1307  }
1308  }
1309  }
1310  mDenomWtxes[hash].vout[nout].nRounds = fDenomFound
1311  ? (nShortest >= 15 ? 16 : nShortest + 1) // good, we a +1 to the shortest one but only 16 rounds max allowed
1312  : 0; // too bad, we are the fist one in that chain
1313  LogPrint("privatesend", "GetRealOutpointPrivateSendRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
1314  return mDenomWtxes[hash].vout[nout].nRounds;
1315  }
1316 
1317  return nRounds - 1;
1318 }
1319 
1320 // respect current settings
1322 {
1323  LOCK(cs_wallet);
1324  int realPrivateSendRounds = GetRealOutpointPrivateSendRounds(outpoint, 0);
1325  return realPrivateSendRounds > privateSendClient.nPrivateSendRounds ? privateSendClient.nPrivateSendRounds : realPrivateSendRounds;
1326 }
1327 
1328 bool CWallet::IsDenominated(const COutPoint& outpoint) const
1329 {
1330  LOCK(cs_wallet);
1331 
1332  map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(outpoint.hash);
1333  if (mi != mapWallet.end()) {
1334  const CWalletTx& prev = (*mi).second;
1335  if (outpoint.n < prev.vout.size()) {
1336  return IsDenominatedAmount(prev.vout[outpoint.n].nValue);
1337  }
1338  }
1339 
1340  return false;
1341 }
1342 
1343 bool CWallet::IsDenominatedAmount(CAmount nInputAmount) const
1344 {
1346  if(nInputAmount == d)
1347  return true;
1348  return false;
1349 }
1350 
1351 isminetype CWallet::IsMine(const CTxOut& txout) const
1352 {
1353  return ::IsMine(*this, txout.scriptPubKey);
1354 }
1355 
1356 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1357 {
1358  if (!MoneyRange(txout.nValue))
1359  throw std::runtime_error("CWallet::GetCredit(): value out of range");
1360  return ((IsMine(txout) & filter) ? txout.nValue : 0);
1361 }
1362 
1363 bool CWallet::IsChange(const CTxOut& txout) const
1364 {
1365  // TODO: fix handling of 'change' outputs. The assumption is that any
1366  // payment to a script that is ours, but is not in the address book
1367  // is change. That assumption is likely to break when we implement multisignature
1368  // wallets that return change back into a multi-signature-protected address;
1369  // a better way of identifying which outputs are 'the send' and which are
1370  // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1371  // which output, if any, was change).
1372  if (::IsMine(*this, txout.scriptPubKey))
1373  {
1374  CTxDestination address;
1375  if (!ExtractDestination(txout.scriptPubKey, address))
1376  return true;
1377 
1378  LOCK(cs_wallet);
1379  if (!mapAddressBook.count(address))
1380  return true;
1381  }
1382  return false;
1383 }
1384 
1385 CAmount CWallet::GetChange(const CTxOut& txout) const
1386 {
1387  if (!MoneyRange(txout.nValue))
1388  throw std::runtime_error("CWallet::GetChange(): value out of range");
1389  return (IsChange(txout) ? txout.nValue : 0);
1390 }
1391 
1393 {
1394  CHDChain newHdChain;
1395 
1396  std::string strSeed = GetArg("-hdseed", "not hex");
1397 
1398  if(mapArgs.count("-hdseed") && IsHex(strSeed)) {
1399  std::vector<unsigned char> vchSeed = ParseHex(strSeed);
1400  if (!newHdChain.SetSeed(SecureVector(vchSeed.begin(), vchSeed.end()), true))
1401  throw std::runtime_error(std::string(__func__) + ": SetSeed failed");
1402  }
1403  else {
1404  if (mapArgs.count("-hdseed") && !IsHex(strSeed))
1405  LogPrintf("CWallet::GenerateNewHDChain -- Incorrect seed, generating random one instead\n");
1406 
1407  // NOTE: empty mnemonic means "generate a new one for me"
1408  std::string strMnemonic = GetArg("-mnemonic", "");
1409  // NOTE: default mnemonic passphrase is an empty string
1410  std::string strMnemonicPassphrase = GetArg("-mnemonicpassphrase", "");
1411 
1412  SecureVector vchMnemonic(strMnemonic.begin(), strMnemonic.end());
1413  SecureVector vchMnemonicPassphrase(strMnemonicPassphrase.begin(), strMnemonicPassphrase.end());
1414 
1415  if (!newHdChain.SetMnemonic(vchMnemonic, vchMnemonicPassphrase, true))
1416  throw std::runtime_error(std::string(__func__) + ": SetMnemonic failed");
1417  }
1418  newHdChain.Debug(__func__);
1419 
1420  if (!SetHDChain(newHdChain, false))
1421  throw std::runtime_error(std::string(__func__) + ": SetHDChain failed");
1422 
1423  // clean up
1424  mapArgs.erase("-hdseed");
1425  mapArgs.erase("-mnemonic");
1426  mapArgs.erase("-mnemonicpassphrase");
1427 }
1428 
1429 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1430 {
1431  LOCK(cs_wallet);
1432 
1433  if (!CCryptoKeyStore::SetHDChain(chain))
1434  return false;
1435 
1436  if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain))
1437  throw std::runtime_error(std::string(__func__) + ": WriteHDChain failed");
1438 
1439  return true;
1440 }
1441 
1442 bool CWallet::SetCryptedHDChain(const CHDChain& chain, bool memonly)
1443 {
1444  LOCK(cs_wallet);
1445 
1447  return false;
1448 
1449  if (!memonly) {
1450  if (!fFileBacked)
1451  return false;
1452  if (pwalletdbEncryption) {
1453  if (!pwalletdbEncryption->WriteCryptedHDChain(chain))
1454  throw std::runtime_error(std::string(__func__) + ": WriteCryptedHDChain failed");
1455  } else {
1456  if (!CWalletDB(strWalletFile).WriteCryptedHDChain(chain))
1457  throw std::runtime_error(std::string(__func__) + ": WriteCryptedHDChain failed");
1458  }
1459  }
1460 
1461  return true;
1462 }
1463 
1465 {
1466  LOCK(cs_wallet);
1467 
1468  CHDChain hdChainTmp;
1469  if (!GetHDChain(hdChainTmp)) {
1470  return false;
1471  }
1472 
1473  if (!DecryptHDChain(hdChainTmp))
1474  return false;
1475 
1476  // make sure seed matches this chain
1477  if (hdChainTmp.GetID() != hdChainTmp.GetSeedHash())
1478  return false;
1479 
1480  hdChainRet = hdChainTmp;
1481 
1482  return true;
1483 }
1484 
1486 {
1487  CHDChain hdChainCurrent;
1488  return GetHDChain(hdChainCurrent);
1489 }
1490 
1491 bool CWallet::IsMine(const CTransaction& tx) const
1492 {
1493  BOOST_FOREACH(const CTxOut& txout, tx.vout)
1494  if (IsMine(txout))
1495  return true;
1496  return false;
1497 }
1498 
1499 bool CWallet::IsFromMe(const CTransaction& tx) const
1500 {
1501  return (GetDebit(tx, ISMINE_ALL) > 0);
1502 }
1503 
1504 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1505 {
1506  CAmount nDebit = 0;
1507  BOOST_FOREACH(const CTxIn& txin, tx.vin)
1508  {
1509  nDebit += GetDebit(txin, filter);
1510  if (!MoneyRange(nDebit))
1511  throw std::runtime_error("CWallet::GetDebit(): value out of range");
1512  }
1513  return nDebit;
1514 }
1515 
1516 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1517 {
1518  CAmount nCredit = 0;
1519  BOOST_FOREACH(const CTxOut& txout, tx.vout)
1520  {
1521  nCredit += GetCredit(txout, filter);
1522  if (!MoneyRange(nCredit))
1523  throw std::runtime_error("CWallet::GetCredit(): value out of range");
1524  }
1525  return nCredit;
1526 }
1527 
1529 {
1530  CAmount nChange = 0;
1531  BOOST_FOREACH(const CTxOut& txout, tx.vout)
1532  {
1533  nChange += GetChange(txout);
1534  if (!MoneyRange(nChange))
1535  throw std::runtime_error("CWallet::GetChange(): value out of range");
1536  }
1537  return nChange;
1538 }
1539 
1540 int64_t CWalletTx::GetTxTime() const
1541 {
1542  int64_t n = nTimeSmart;
1543  return n ? n : nTimeReceived;
1544 }
1545 
1547 {
1548  // Returns -1 if it wasn't being tracked
1549  int nRequests = -1;
1550  {
1551  LOCK(pwallet->cs_wallet);
1552  if (IsCoinBase())
1553  {
1554  // Generated block
1555  if (!hashUnset())
1556  {
1557  map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1558  if (mi != pwallet->mapRequestCount.end())
1559  nRequests = (*mi).second;
1560  }
1561  }
1562  else
1563  {
1564  // Did anyone request this transaction?
1565  map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1566  if (mi != pwallet->mapRequestCount.end())
1567  {
1568  nRequests = (*mi).second;
1569 
1570  // How about the block it's in?
1571  if (nRequests == 0 && !hashUnset())
1572  {
1573  map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1574  if (mi != pwallet->mapRequestCount.end())
1575  nRequests = (*mi).second;
1576  else
1577  nRequests = 1; // If it's in someone else's block it must have got out
1578  }
1579  }
1580  }
1581  }
1582  return nRequests;
1583 }
1584 
1585 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1586  list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1587 {
1588  nFee = 0;
1589  listReceived.clear();
1590  listSent.clear();
1591  strSentAccount = strFromAccount;
1592 
1593  // Compute fee:
1594  CAmount nDebit = GetDebit(filter);
1595  if (nDebit > 0) // debit>0 means we signed/sent this transaction
1596  {
1597  CAmount nValueOut = GetValueOut();
1598  nFee = nDebit - nValueOut;
1599  }
1600 
1601  // Sent/received.
1602  for (unsigned int i = 0; i < vout.size(); ++i)
1603  {
1604  const CTxOut& txout = vout[i];
1605  isminetype fIsMine = pwallet->IsMine(txout);
1606  // Only need to handle txouts if AT LEAST one of these is true:
1607  // 1) they debit from us (sent)
1608  // 2) the output is to us (received)
1609  if (nDebit > 0)
1610  {
1611  // Don't report 'change' txouts
1612  if (pwallet->IsChange(txout))
1613  continue;
1614  }
1615  else if (!(fIsMine & filter))
1616  continue;
1617 
1618  // In either case, we need to get the destination address
1619  CTxDestination address;
1620 
1621  if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1622  {
1623  LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1624  this->GetHash().ToString());
1625  address = CNoDestination();
1626  }
1627 
1628  COutputEntry output = {address, txout.nValue, (int)i};
1629 
1630  // If we are debited by the transaction, add the output as a "sent" entry
1631  if (nDebit > 0)
1632  listSent.push_back(output);
1633 
1634  // If we are receiving the output, add it as a "received" entry
1635  if (fIsMine & filter)
1636  listReceived.push_back(output);
1637  }
1638 
1639 }
1640 
1641 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1642  CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1643 {
1644  nReceived = nSent = nFee = 0;
1645 
1646  CAmount allFee;
1647  string strSentAccount;
1648  list<COutputEntry> listReceived;
1649  list<COutputEntry> listSent;
1650  GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1651 
1652  if (strAccount == strSentAccount)
1653  {
1654  BOOST_FOREACH(const COutputEntry& s, listSent)
1655  nSent += s.amount;
1656  nFee = allFee;
1657  }
1658  {
1659  LOCK(pwallet->cs_wallet);
1660  BOOST_FOREACH(const COutputEntry& r, listReceived)
1661  {
1662  if (pwallet->mapAddressBook.count(r.destination))
1663  {
1664  map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1665  if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1666  nReceived += r.amount;
1667  }
1668  else if (strAccount.empty())
1669  {
1670  nReceived += r.amount;
1671  }
1672  }
1673  }
1674 }
1675 
1676 
1678 {
1679  return pwalletdb->WriteTx(GetHash(), *this);
1680 }
1681 
1687 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1688 {
1689  int ret = 0;
1690  int64_t nNow = GetTime();
1691  const CChainParams& chainParams = Params();
1692 
1693  CBlockIndex* pindex = pindexStart;
1694  {
1695  LOCK2(cs_main, cs_wallet);
1696 
1697  // no need to read and scan block, if block was created before
1698  // our wallet birthday (as adjusted for block time variability)
1699  while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1700  pindex = chainActive.Next(pindex);
1701 
1702  ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1703  double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1704  double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1705  while (pindex)
1706  {
1707  if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1708  ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1709 
1710  CBlock block;
1711  ReadBlockFromDisk(block, pindex, Params().GetConsensus());
1712  BOOST_FOREACH(CTransaction& tx, block.vtx)
1713  {
1714  if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1715  ret++;
1716  }
1717  pindex = chainActive.Next(pindex);
1718  if (GetTime() >= nNow + 60) {
1719  nNow = GetTime();
1720  LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1721  }
1722  }
1723  ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1724  }
1725  return ret;
1726 }
1727 
1729 {
1730  // If transactions aren't being broadcasted, don't let them into local mempool either
1731  if (!fBroadcastTransactions)
1732  return;
1733  LOCK2(cs_main, cs_wallet);
1734  std::map<int64_t, CWalletTx*> mapSorted;
1735 
1736  // Sort pending wallet transactions based on their initial wallet insertion order
1737  BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1738  {
1739  const uint256& wtxid = item.first;
1740  CWalletTx& wtx = item.second;
1741  assert(wtx.GetHash() == wtxid);
1742 
1743  int nDepth = wtx.GetDepthInMainChain();
1744 
1745  if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1746  mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1747  }
1748  }
1749 
1750  // Try to add wallet transactions to memory pool
1751  BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1752  {
1753  CWalletTx& wtx = *(item.second);
1754 
1755  LOCK(mempool.cs);
1756  wtx.AcceptToMemoryPool(false);
1757  }
1758 }
1759 
1760 bool CWalletTx::RelayWalletTransaction(CConnman* connman, std::string strCommand)
1761 {
1762  assert(pwallet->GetBroadcastTransactions());
1763  if (!IsCoinBase())
1764  {
1765  if (GetDepthInMainChain() == 0 && !isAbandoned() && InMempool()) {
1766  uint256 hash = GetHash();
1767  LogPrintf("Relaying wtx %s\n", hash.ToString());
1768 
1769  if(strCommand == NetMsgType::TXLOCKREQUEST) {
1770  instantsend.ProcessTxLockRequest(((CTxLockRequest)*this), *connman);
1771  }
1772  if (connman) {
1773  connman->RelayTransaction((CTransaction)*this);
1774  return true;
1775  }
1776  }
1777  }
1778  return false;
1779 }
1780 
1781 set<uint256> CWalletTx::GetConflicts() const
1782 {
1783  set<uint256> result;
1784  if (pwallet != NULL)
1785  {
1786  uint256 myHash = GetHash();
1787  result = pwallet->GetConflicts(myHash);
1788  result.erase(myHash);
1789  }
1790  return result;
1791 }
1792 
1794 {
1795  if (vin.empty())
1796  return 0;
1797 
1798  CAmount debit = 0;
1799  if(filter & ISMINE_SPENDABLE)
1800  {
1801  if (fDebitCached)
1802  debit += nDebitCached;
1803  else
1804  {
1805  nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1806  fDebitCached = true;
1807  debit += nDebitCached;
1808  }
1809  }
1810  if(filter & ISMINE_WATCH_ONLY)
1811  {
1812  if(fWatchDebitCached)
1813  debit += nWatchDebitCached;
1814  else
1815  {
1816  nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1817  fWatchDebitCached = true;
1818  debit += nWatchDebitCached;
1819  }
1820  }
1821  return debit;
1822 }
1823 
1825 {
1826  // Must wait until coinbase is safely deep enough in the chain before valuing it
1827  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1828  return 0;
1829 
1830  int64_t credit = 0;
1831  if (filter & ISMINE_SPENDABLE)
1832  {
1833  // GetBalance can assume transactions in mapWallet won't change
1834  if (fCreditCached)
1835  credit += nCreditCached;
1836  else
1837  {
1838  nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1839  fCreditCached = true;
1840  credit += nCreditCached;
1841  }
1842  }
1843  if (filter & ISMINE_WATCH_ONLY)
1844  {
1845  if (fWatchCreditCached)
1846  credit += nWatchCreditCached;
1847  else
1848  {
1849  nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1850  fWatchCreditCached = true;
1851  credit += nWatchCreditCached;
1852  }
1853  }
1854  return credit;
1855 }
1856 
1858 {
1859  if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1860  {
1861  if (fUseCache && fImmatureCreditCached)
1862  return nImmatureCreditCached;
1863  nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1864  fImmatureCreditCached = true;
1865  return nImmatureCreditCached;
1866  }
1867 
1868  return 0;
1869 }
1870 
1872 {
1873  if (pwallet == 0)
1874  return 0;
1875 
1876  // Must wait until coinbase is safely deep enough in the chain before valuing it
1877  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1878  return 0;
1879 
1880  if (fUseCache && fAvailableCreditCached)
1881  return nAvailableCreditCached;
1882 
1883  CAmount nCredit = 0;
1884  uint256 hashTx = GetHash();
1885  for (unsigned int i = 0; i < vout.size(); i++)
1886  {
1887  if (!pwallet->IsSpent(hashTx, i))
1888  {
1889  const CTxOut &txout = vout[i];
1890  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1891  if (!MoneyRange(nCredit))
1892  throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1893  }
1894  }
1895 
1896  nAvailableCreditCached = nCredit;
1897  fAvailableCreditCached = true;
1898  return nCredit;
1899 }
1900 
1902 {
1903  if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1904  {
1905  if (fUseCache && fImmatureWatchCreditCached)
1906  return nImmatureWatchCreditCached;
1907  nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1908  fImmatureWatchCreditCached = true;
1909  return nImmatureWatchCreditCached;
1910  }
1911 
1912  return 0;
1913 }
1914 
1916 {
1917  if (pwallet == 0)
1918  return 0;
1919 
1920  // Must wait until coinbase is safely deep enough in the chain before valuing it
1921  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1922  return 0;
1923 
1924  if (fUseCache && fAvailableWatchCreditCached)
1925  return nAvailableWatchCreditCached;
1926 
1927  CAmount nCredit = 0;
1928  for (unsigned int i = 0; i < vout.size(); i++)
1929  {
1930  if (!pwallet->IsSpent(GetHash(), i))
1931  {
1932  const CTxOut &txout = vout[i];
1933  nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1934  if (!MoneyRange(nCredit))
1935  throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1936  }
1937  }
1938 
1939  nAvailableWatchCreditCached = nCredit;
1940  fAvailableWatchCreditCached = true;
1941  return nCredit;
1942 }
1943 
1945 {
1946  if (pwallet == 0)
1947  return 0;
1948 
1949  // Must wait until coinbase is safely deep enough in the chain before valuing it
1950  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1951  return 0;
1952 
1953  if (fUseCache && fAnonymizedCreditCached)
1954  return nAnonymizedCreditCached;
1955 
1956  CAmount nCredit = 0;
1957  uint256 hashTx = GetHash();
1958  for (unsigned int i = 0; i < vout.size(); i++)
1959  {
1960  const CTxOut &txout = vout[i];
1961  const COutPoint outpoint = COutPoint(hashTx, i);
1962 
1963  if(pwallet->IsSpent(hashTx, i) || !pwallet->IsDenominated(outpoint)) continue;
1964 
1965  const int nRounds = pwallet->GetOutpointPrivateSendRounds(outpoint);
1966  if(nRounds >= privateSendClient.nPrivateSendRounds){
1967  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1968  if (!MoneyRange(nCredit))
1969  throw std::runtime_error("CWalletTx::GetAnonymizedCredit() : value out of range");
1970  }
1971  }
1972 
1973  nAnonymizedCreditCached = nCredit;
1974  fAnonymizedCreditCached = true;
1975  return nCredit;
1976 }
1977 
1978 CAmount CWalletTx::GetDenominatedCredit(bool unconfirmed, bool fUseCache) const
1979 {
1980  if (pwallet == 0)
1981  return 0;
1982 
1983  // Must wait until coinbase is safely deep enough in the chain before valuing it
1984  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1985  return 0;
1986 
1987  int nDepth = GetDepthInMainChain(false);
1988  if(nDepth < 0) return 0;
1989 
1990  bool isUnconfirmed = IsTrusted() && nDepth == 0;
1991  if(unconfirmed != isUnconfirmed) return 0;
1992 
1993  if (fUseCache) {
1994  if(unconfirmed && fDenomUnconfCreditCached)
1995  return nDenomUnconfCreditCached;
1996  else if (!unconfirmed && fDenomConfCreditCached)
1997  return nDenomConfCreditCached;
1998  }
1999 
2000  CAmount nCredit = 0;
2001  uint256 hashTx = GetHash();
2002  for (unsigned int i = 0; i < vout.size(); i++)
2003  {
2004  const CTxOut &txout = vout[i];
2005 
2006  if(pwallet->IsSpent(hashTx, i) || !pwallet->IsDenominatedAmount(vout[i].nValue)) continue;
2007 
2008  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
2009  if (!MoneyRange(nCredit))
2010  throw std::runtime_error("CWalletTx::GetDenominatedCredit() : value out of range");
2011  }
2012 
2013  if(unconfirmed) {
2014  nDenomUnconfCreditCached = nCredit;
2015  fDenomUnconfCreditCached = true;
2016  } else {
2017  nDenomConfCreditCached = nCredit;
2018  fDenomConfCreditCached = true;
2019  }
2020  return nCredit;
2021 }
2022 
2024 {
2025  if (fChangeCached)
2026  return nChangeCached;
2027  nChangeCached = pwallet->GetChange(*this);
2028  fChangeCached = true;
2029  return nChangeCached;
2030 }
2031 
2033 {
2034  LOCK(mempool.cs);
2035  if (mempool.exists(GetHash())) {
2036  return true;
2037  }
2038  return false;
2039 }
2040 
2042 {
2043  // Quick answer in most cases
2044  if (!CheckFinalTx(*this))
2045  return false;
2046  int nDepth = GetDepthInMainChain();
2047  if (nDepth >= 1)
2048  return true;
2049  if (nDepth < 0)
2050  return false;
2051  if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2052  return false;
2053 
2054  // Don't trust unconfirmed transactions from us unless they are in the mempool.
2055  if (!InMempool())
2056  return false;
2057 
2058  // Trusted if all inputs are from us and are in the mempool:
2059  BOOST_FOREACH(const CTxIn& txin, vin)
2060  {
2061  // Transactions not sent by us: not trusted
2062  const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2063  if (parent == NULL)
2064  return false;
2065  const CTxOut& parentOut = parent->vout[txin.prevout.n];
2066  if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2067  return false;
2068  }
2069  return true;
2070 }
2071 
2073 {
2074  CMutableTransaction tx1 = *this;
2075  CMutableTransaction tx2 = tx;
2076  for (unsigned int i = 0; i < tx1.vin.size(); i++) tx1.vin[i].scriptSig = CScript();
2077  for (unsigned int i = 0; i < tx2.vin.size(); i++) tx2.vin[i].scriptSig = CScript();
2078  return CTransaction(tx1) == CTransaction(tx2);
2079 }
2080 
2081 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
2082 {
2083  std::vector<uint256> result;
2084 
2085  LOCK(cs_wallet);
2086  // Sort them in chronological order
2087  multimap<unsigned int, CWalletTx*> mapSorted;
2088  BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2089  {
2090  CWalletTx& wtx = item.second;
2091  // Don't rebroadcast if newer than nTime:
2092  if (wtx.nTimeReceived > nTime)
2093  continue;
2094  mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2095  }
2096  BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2097  {
2098  CWalletTx& wtx = *item.second;
2099  if (wtx.RelayWalletTransaction(connman))
2100  result.push_back(wtx.GetHash());
2101  }
2102  return result;
2103 }
2104 
2105 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
2106 {
2107  // Do this infrequently and randomly to avoid giving away
2108  // that these are our transactions.
2109  if (GetTime() < nNextResend || !fBroadcastTransactions)
2110  return;
2111  bool fFirst = (nNextResend == 0);
2112  nNextResend = GetTime() + GetRand(30 * 60);
2113  if (fFirst)
2114  return;
2115 
2116  // Only do it if there's been a new block since last time
2117  if (nBestBlockTime < nLastResend)
2118  return;
2119  nLastResend = GetTime();
2120 
2121  // Rebroadcast unconfirmed txes older than 5 minutes before the last
2122  // block was found:
2123  std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
2124  if (!relayed.empty())
2125  LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2126 }
2127  // end of mapWallet
2129 
2130 
2131 
2132 
2140 {
2141  CAmount nTotal = 0;
2142  {
2143  LOCK2(cs_main, cs_wallet);
2144  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2145  {
2146  const CWalletTx* pcoin = &(*it).second;
2147  if (pcoin->IsTrusted())
2148  nTotal += pcoin->GetAvailableCredit();
2149  }
2150  }
2151 
2152  return nTotal;
2153 }
2154 
2155 CAmount CWallet::GetAnonymizableBalance(bool fSkipDenominated, bool fSkipUnconfirmed) const
2156 {
2157  if(fLiteMode) return 0;
2158 
2159  std::vector<CompactTallyItem> vecTally;
2160  if(!SelectCoinsGrouppedByAddresses(vecTally, fSkipDenominated, true, fSkipUnconfirmed)) return 0;
2161 
2162  CAmount nTotal = 0;
2163 
2164  const CAmount nSmallestDenom = CPrivateSend::GetSmallestDenomination();
2165  const CAmount nMixingCollateral = CPrivateSend::GetCollateralAmount();
2166  BOOST_FOREACH(CompactTallyItem& item, vecTally) {
2167  bool fIsDenominated = IsDenominatedAmount(item.nAmount);
2168  if(fSkipDenominated && fIsDenominated) continue;
2169  // assume that the fee to create denoms should be mixing collateral at max
2170  if(item.nAmount >= nSmallestDenom + (fIsDenominated ? 0 : nMixingCollateral))
2171  nTotal += item.nAmount;
2172  }
2173 
2174  return nTotal;
2175 }
2176 
2178 {
2179  if(fLiteMode) return 0;
2180 
2181  CAmount nTotal = 0;
2182 
2183  LOCK2(cs_main, cs_wallet);
2184 
2185  std::set<uint256> setWalletTxesCounted;
2186  for (auto& outpoint : setWalletUTXO) {
2187 
2188  if (setWalletTxesCounted.find(outpoint.hash) != setWalletTxesCounted.end()) continue;
2189  setWalletTxesCounted.insert(outpoint.hash);
2190 
2191  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash); it != mapWallet.end() && it->first == outpoint.hash; ++it) {
2192  if (it->second.IsTrusted())
2193  nTotal += it->second.GetAnonymizedCredit();
2194  }
2195  }
2196 
2197  return nTotal;
2198 }
2199 
2200 // Note: calculated including unconfirmed,
2201 // that's ok as long as we use it for informational purposes only
2203 {
2204  if(fLiteMode) return 0;
2205 
2206  int nTotal = 0;
2207  int nCount = 0;
2208 
2209  LOCK2(cs_main, cs_wallet);
2210  for (auto& outpoint : setWalletUTXO) {
2211  if(!IsDenominated(outpoint)) continue;
2212 
2213  nTotal += GetOutpointPrivateSendRounds(outpoint);
2214  nCount++;
2215  }
2216 
2217  if(nCount == 0) return 0;
2218 
2219  return (float)nTotal/nCount;
2220 }
2221 
2222 // Note: calculated including unconfirmed,
2223 // that's ok as long as we use it for informational purposes only
2225 {
2226  if(fLiteMode) return 0;
2227 
2228  CAmount nTotal = 0;
2229 
2230  LOCK2(cs_main, cs_wallet);
2231  for (auto& outpoint : setWalletUTXO) {
2232  map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2233  if (it == mapWallet.end()) continue;
2234  if (!IsDenominated(outpoint)) continue;
2235  if (it->second.GetDepthInMainChain() < 0) continue;
2236 
2237  int nRounds = GetOutpointPrivateSendRounds(outpoint);
2238  nTotal += it->second.vout[outpoint.n].nValue * nRounds / privateSendClient.nPrivateSendRounds;
2239  }
2240 
2241  return nTotal;
2242 }
2243 
2245 {
2246  if(fLiteMode) return 0;
2247 
2248  CAmount nAnonymizedBalance = GetAnonymizedBalance();
2249  CAmount nNeedsToAnonymizeBalance = privateSendClient.nPrivateSendAmount*COIN - nAnonymizedBalance;
2250 
2251  // try to overshoot target DS balance up to nMinBalance
2252  nNeedsToAnonymizeBalance += nMinBalance;
2253 
2254  CAmount nAnonymizableBalance = GetAnonymizableBalance();
2255 
2256  // anonymizable balance is way too small
2257  if(nAnonymizableBalance < nMinBalance) return 0;
2258 
2259  // not enough funds to anonymze amount we want, try the max we can
2260  if(nNeedsToAnonymizeBalance > nAnonymizableBalance) nNeedsToAnonymizeBalance = nAnonymizableBalance;
2261 
2262  // we should never exceed the pool max
2263  if (nNeedsToAnonymizeBalance > CPrivateSend::GetMaxPoolAmount()) nNeedsToAnonymizeBalance = CPrivateSend::GetMaxPoolAmount();
2264 
2265  return nNeedsToAnonymizeBalance;
2266 }
2267 
2269 {
2270  if(fLiteMode) return 0;
2271 
2272  CAmount nTotal = 0;
2273  {
2274  LOCK2(cs_main, cs_wallet);
2275  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2276  {
2277  const CWalletTx* pcoin = &(*it).second;
2278 
2279  nTotal += pcoin->GetDenominatedCredit(unconfirmed);
2280  }
2281  }
2282 
2283  return nTotal;
2284 }
2285 
2287 {
2288  CAmount nTotal = 0;
2289  {
2290  LOCK2(cs_main, cs_wallet);
2291  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2292  {
2293  const CWalletTx* pcoin = &(*it).second;
2294  if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2295  nTotal += pcoin->GetAvailableCredit();
2296  }
2297  }
2298  return nTotal;
2299 }
2300 
2302 {
2303  CAmount nTotal = 0;
2304  {
2305  LOCK2(cs_main, cs_wallet);
2306  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2307  {
2308  const CWalletTx* pcoin = &(*it).second;
2309  nTotal += pcoin->GetImmatureCredit();
2310  }
2311  }
2312  return nTotal;
2313 }
2314 
2316 {
2317  CAmount nTotal = 0;
2318  {
2319  LOCK2(cs_main, cs_wallet);
2320  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2321  {
2322  const CWalletTx* pcoin = &(*it).second;
2323  if (pcoin->IsTrusted())
2324  nTotal += pcoin->GetAvailableWatchOnlyCredit();
2325  }
2326  }
2327 
2328  return nTotal;
2329 }
2330 
2332 {
2333  CAmount nTotal = 0;
2334  {
2335  LOCK2(cs_main, cs_wallet);
2336  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2337  {
2338  const CWalletTx* pcoin = &(*it).second;
2339  if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2340  nTotal += pcoin->GetAvailableWatchOnlyCredit();
2341  }
2342  }
2343  return nTotal;
2344 }
2345 
2347 {
2348  CAmount nTotal = 0;
2349  {
2350  LOCK2(cs_main, cs_wallet);
2351  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2352  {
2353  const CWalletTx* pcoin = &(*it).second;
2354  nTotal += pcoin->GetImmatureWatchOnlyCredit();
2355  }
2356  }
2357  return nTotal;
2358 }
2359 
2360 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, AvailableCoinsType nCoinType, bool fUseInstantSend) const
2361 {
2362  vCoins.clear();
2363 
2364  {
2365  LOCK2(cs_main, cs_wallet);
2366  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2367  {
2368  const uint256& wtxid = it->first;
2369  const CWalletTx* pcoin = &(*it).second;
2370 
2371  if (!CheckFinalTx(*pcoin))
2372  continue;
2373 
2374  if (fOnlyConfirmed && !pcoin->IsTrusted())
2375  continue;
2376 
2377  if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2378  continue;
2379 
2380  int nDepth = pcoin->GetDepthInMainChain(false);
2381  // do not use IX for inputs that have less then INSTANTSEND_CONFIRMATIONS_REQUIRED blockchain confirmations
2382  if (fUseInstantSend && nDepth < INSTANTSEND_CONFIRMATIONS_REQUIRED)
2383  continue;
2384 
2385  // We should not consider coins which aren't at least in our mempool
2386  // It's possible for these to be conflicted via ancestors which we may never be able to detect
2387  if (nDepth == 0 && !pcoin->InMempool())
2388  continue;
2389 
2390  for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2391  bool found = false;
2392  if(nCoinType == ONLY_DENOMINATED) {
2393  found = IsDenominatedAmount(pcoin->vout[i].nValue);
2394  } else if(nCoinType == ONLY_NOT1000IFMN) {
2395  found = !(fMasterNode && pcoin->vout[i].nValue == 1000*COIN);
2396  } else if(nCoinType == ONLY_NONDENOMINATED_NOT1000IFMN) {
2397  if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts
2398  found = !IsDenominatedAmount(pcoin->vout[i].nValue);
2399  if(found && fMasterNode) found = pcoin->vout[i].nValue != 1000*COIN; // do not use Hot MN funds
2400  } else if(nCoinType == ONLY_1000) {
2401  found = pcoin->vout[i].nValue == 1000*COIN;
2402  } else if(nCoinType == ONLY_PRIVATESEND_COLLATERAL) {
2403  found = IsCollateralAmount(pcoin->vout[i].nValue);
2404  } else {
2405  found = true;
2406  }
2407  if(!found) continue;
2408 
2409  isminetype mine = IsMine(pcoin->vout[i]);
2410  if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2411  (!IsLockedCoin((*it).first, i) || nCoinType == ONLY_1000) &&
2412  (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
2413  (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected(COutPoint((*it).first, i))))
2414  vCoins.push_back(COutput(pcoin, i, nDepth,
2415  ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
2416  (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO),
2418  }
2419  }
2420  }
2421 }
2422 
2423 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2424  vector<char>& vfBest, CAmount& nBest, int iterations = 1000, bool fUseInstantSend = false)
2425 {
2426  vector<char> vfIncluded;
2427 
2428  vfBest.assign(vValue.size(), true);
2429  nBest = nTotalLower;
2430 
2432 
2433  for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2434  {
2435  vfIncluded.assign(vValue.size(), false);
2436  CAmount nTotal = 0;
2437  bool fReachedTarget = false;
2438  for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2439  {
2440  for (unsigned int i = 0; i < vValue.size(); i++)
2441  {
2442  if (fUseInstantSend && nTotal + vValue[i].first > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN) {
2443  continue;
2444  }
2445  //The solver here uses a randomized algorithm,
2446  //the randomness serves no real security purpose but is just
2447  //needed to prevent degenerate behavior and it is important
2448  //that the rng is fast. We do not use a constant random sequence,
2449  //because there may be some privacy improvement by making
2450  //the selection random.
2451  if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
2452  {
2453  nTotal += vValue[i].first;
2454  vfIncluded[i] = true;
2455  if (nTotal >= nTargetValue)
2456  {
2457  fReachedTarget = true;
2458  if (nTotal < nBest)
2459  {
2460  nBest = nTotal;
2461  vfBest = vfIncluded;
2462  }
2463  nTotal -= vValue[i].first;
2464  vfIncluded[i] = false;
2465  }
2466  }
2467  }
2468  }
2469  }
2470 
2471  //Reduces the approximate best subset by removing any inputs that are smaller than the surplus of nTotal beyond nTargetValue.
2472  for (unsigned int i = 0; i < vValue.size(); i++)
2473  {
2474  if (vfBest[i] && (nBest - vValue[i].first) >= nTargetValue )
2475  {
2476  vfBest[i] = false;
2477  nBest -= vValue[i].first;
2478  }
2479  }
2480 }
2481 
2482 // move denoms down
2483 bool less_then_denom (const COutput& out1, const COutput& out2)
2484 {
2485  const CWalletTx *pcoin1 = out1.tx;
2486  const CWalletTx *pcoin2 = out2.tx;
2487 
2488  bool found1 = false;
2489  bool found2 = false;
2490  BOOST_FOREACH(CAmount d, CPrivateSend::GetStandardDenominations()) // loop through predefined denoms
2491  {
2492  if(pcoin1->vout[out1.i].nValue == d) found1 = true;
2493  if(pcoin2->vout[out2.i].nValue == d) found2 = true;
2494  }
2495  return (!found1 && found2);
2496 }
2497 
2498 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2499  set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool fUseInstantSend) const
2500 {
2501  setCoinsRet.clear();
2502  nValueRet = 0;
2503 
2504  // List of values less than target
2505  pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2506  coinLowestLarger.first = fUseInstantSend
2508  : std::numeric_limits<CAmount>::max();
2509  coinLowestLarger.second.first = NULL;
2510  vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2511  CAmount nTotalLower = 0;
2512 
2513  random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2514 
2515  // move denoms down on the list
2516  sort(vCoins.begin(), vCoins.end(), less_then_denom);
2517 
2518  // try to find nondenom first to prevent unneeded spending of mixed coins
2519  for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++)
2520  {
2521  LogPrint("selectcoins", "tryDenom: %d\n", tryDenom);
2522  vValue.clear();
2523  nTotalLower = 0;
2524  BOOST_FOREACH(const COutput &output, vCoins)
2525  {
2526  if (!output.fSpendable)
2527  continue;
2528 
2529  const CWalletTx *pcoin = output.tx;
2530 
2531 // if (fDebug) LogPrint("selectcoins", "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth);
2532  if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2533  continue;
2534 
2535  int i = output.i;
2536  CAmount n = pcoin->vout[i].nValue;
2537  if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run
2538 
2539  pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2540 
2541  if (n == nTargetValue)
2542  {
2543  setCoinsRet.insert(coin.second);
2544  nValueRet += coin.first;
2545  return true;
2546  }
2547  else if (n < nTargetValue + MIN_CHANGE)
2548  {
2549  vValue.push_back(coin);
2550  nTotalLower += n;
2551  }
2552  else if (n < coinLowestLarger.first)
2553  {
2554  coinLowestLarger = coin;
2555  }
2556  }
2557 
2558  if (nTotalLower == nTargetValue)
2559  {
2560  for (unsigned int i = 0; i < vValue.size(); ++i)
2561  {
2562  setCoinsRet.insert(vValue[i].second);
2563  nValueRet += vValue[i].first;
2564  }
2565  return true;
2566  }
2567 
2568  if (nTotalLower < nTargetValue)
2569  {
2570  if (coinLowestLarger.second.first == NULL) // there is no input larger than nTargetValue
2571  {
2572  if (tryDenom == 0)
2573  // we didn't look at denom yet, let's do it
2574  continue;
2575  else
2576  // we looked at everything possible and didn't find anything, no luck
2577  return false;
2578  }
2579  setCoinsRet.insert(coinLowestLarger.second);
2580  nValueRet += coinLowestLarger.first;
2581  return true;
2582  }
2583 
2584  // nTotalLower > nTargetValue
2585  break;
2586 
2587  }
2588 
2589  // Solve subset sum by stochastic approximation
2590  sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
2591  vector<char> vfBest;
2592  CAmount nBest;
2593 
2594  ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, fUseInstantSend);
2595  if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2596  ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest, fUseInstantSend);
2597 
2598  // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2599  // or the next bigger coin is closer), return the bigger coin
2600  if (coinLowestLarger.second.first &&
2601  ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest))
2602  {
2603  setCoinsRet.insert(coinLowestLarger.second);
2604  nValueRet += coinLowestLarger.first;
2605  }
2606  else {
2607  string s = "CWallet::SelectCoinsMinConf best subset: ";
2608  for (unsigned int i = 0; i < vValue.size(); i++)
2609  {
2610  if (vfBest[i])
2611  {
2612  setCoinsRet.insert(vValue[i].second);
2613  nValueRet += vValue[i].first;
2614  s += FormatMoney(vValue[i].first) + " ";
2615  }
2616  }
2617  LogPrint("selectcoins", "%s - total %s\n", s, FormatMoney(nBest));
2618  }
2619 
2620  return true;
2621 }
2622 
2623 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType nCoinType, bool fUseInstantSend) const
2624 {
2625  // Note: this function should never be used for "always free" tx types like dstx
2626 
2627  vector<COutput> vCoins;
2628  AvailableCoins(vCoins, true, coinControl, false, nCoinType, fUseInstantSend);
2629 
2630  // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2631  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2632  {
2633  BOOST_FOREACH(const COutput& out, vCoins)
2634  {
2635  if(!out.fSpendable)
2636  continue;
2637 
2638  if(nCoinType == ONLY_DENOMINATED) {
2639  COutPoint outpoint = COutPoint(out.tx->GetHash(),out.i);
2640  int nRounds = GetOutpointPrivateSendRounds(outpoint);
2641  // make sure it's actually anonymized
2642  if(nRounds < privateSendClient.nPrivateSendRounds) continue;
2643  }
2644  nValueRet += out.tx->vout[out.i].nValue;
2645  setCoinsRet.insert(make_pair(out.tx, out.i));
2646  }
2647 
2648  return (nValueRet >= nTargetValue);
2649  }
2650 
2651  //if we're doing only denominated, we need to round up to the nearest smallest denomination
2652  if(nCoinType == ONLY_DENOMINATED) {
2653  std::vector<CAmount> vecPrivateSendDenominations = CPrivateSend::GetStandardDenominations();
2654  CAmount nSmallestDenom = vecPrivateSendDenominations.back();
2655  // Make outputs by looping through denominations, from large to small
2656  BOOST_FOREACH(CAmount nDenom, vecPrivateSendDenominations)
2657  {
2658  BOOST_FOREACH(const COutput& out, vCoins)
2659  {
2660  //make sure it's the denom we're looking for, round the amount up to smallest denom
2661  if(out.tx->vout[out.i].nValue == nDenom && nValueRet + nDenom < nTargetValue + nSmallestDenom) {
2662  COutPoint outpoint = COutPoint(out.tx->GetHash(),out.i);
2663  int nRounds = GetOutpointPrivateSendRounds(outpoint);
2664  // make sure it's actually anonymized
2665  if(nRounds < privateSendClient.nPrivateSendRounds) continue;
2666  nValueRet += nDenom;
2667  setCoinsRet.insert(make_pair(out.tx, out.i));
2668  }
2669  }
2670  }
2671  return (nValueRet >= nTargetValue);
2672  }
2673  // calculate value from preset inputs and store them
2674  set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2675  CAmount nValueFromPresetInputs = 0;
2676 
2677  std::vector<COutPoint> vPresetInputs;
2678  if (coinControl)
2679  coinControl->ListSelected(vPresetInputs);
2680  BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2681  {
2682  map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2683  if (it != mapWallet.end())
2684  {
2685  const CWalletTx* pcoin = &it->second;
2686  // Clearly invalid input, fail
2687  if (pcoin->vout.size() <= outpoint.n)
2688  return false;
2689  nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
2690  setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2691  } else
2692  return false; // TODO: Allow non-wallet inputs
2693  }
2694 
2695  // remove preset inputs from vCoins
2696  for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2697  {
2698  if (setPresetCoins.count(make_pair(it->tx, it->i)))
2699  it = vCoins.erase(it);
2700  else
2701  ++it;
2702  }
2703 
2704  bool res = nTargetValue <= nValueFromPresetInputs ||
2705  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet, fUseInstantSend) ||
2706  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet, fUseInstantSend) ||
2707  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet, fUseInstantSend));
2708 
2709  // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2710  setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2711 
2712  // add preset inputs to the total value selected
2713  nValueRet += nValueFromPresetInputs;
2714 
2715  return res;
2716 }
2717 
2719 {
2720  bool operator()(const COutput& t1,
2721  const COutput& t2) const
2722  {
2723  return t1.Priority() > t2.Priority();
2724  }
2725 };
2726 
2727 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching)
2728 {
2729  vector<CRecipient> vecSend;
2730 
2731  // Turn the txout set into a CRecipient vector
2732  BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2733  {
2734  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2735  vecSend.push_back(recipient);
2736  }
2737 
2738  CCoinControl coinControl;
2739  coinControl.fAllowOtherInputs = true;
2740  coinControl.fAllowWatchOnly = includeWatching;
2741  BOOST_FOREACH(const CTxIn& txin, tx.vin)
2742  coinControl.Select(txin.prevout);
2743 
2744  CReserveKey reservekey(this);
2745  CWalletTx wtx;
2746  if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
2747  return false;
2748 
2749  if (nChangePosRet != -1)
2750  tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
2751 
2752  // Add new txins (keeping original txin scriptSig/order)
2753  BOOST_FOREACH(const CTxIn& txin, wtx.vin)
2754  {
2755  if (!coinControl.IsSelected(txin.prevout))
2756  tx.vin.push_back(txin);
2757  }
2758 
2759  return true;
2760 }
2761 
2762 bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, std::vector<COutput>& vCoinsRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax)
2763 {
2764  vecTxInRet.clear();
2765  vCoinsRet.clear();
2766  nValueRet = 0;
2767 
2768  vector<COutput> vCoins;
2769  AvailableCoins(vCoins, true, NULL, false, ONLY_DENOMINATED);
2770 
2771  std::random_shuffle(vCoins.rbegin(), vCoins.rend(), GetRandInt);
2772 
2773  // ( bit on if present )
2774  // bit 0 - 100DASH+1
2775  // bit 1 - 10DASH+1
2776  // bit 2 - 1DASH+1
2777  // bit 3 - .1DASH+1
2778 
2779  std::vector<int> vecBits;
2780  if (!CPrivateSend::GetDenominationsBits(nDenom, vecBits)) {
2781  return false;
2782  }
2783 
2784  int nDenomResult = 0;
2785 
2786  std::vector<CAmount> vecPrivateSendDenominations = CPrivateSend::GetStandardDenominations();
2787  InsecureRand insecureRand;
2788  BOOST_FOREACH(const COutput& out, vCoins)
2789  {
2790  // masternode-like input should not be selected by AvailableCoins now anyway
2791  //if(out.tx->vout[out.i].nValue == 1000*COIN) continue;
2792  if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){
2793 
2794  CTxIn txin = CTxIn(out.tx->GetHash(), out.i);
2795 
2796  int nRounds = GetOutpointPrivateSendRounds(txin.prevout);
2797  if(nRounds >= nPrivateSendRoundsMax) continue;
2798  if(nRounds < nPrivateSendRoundsMin) continue;
2799 
2800  BOOST_FOREACH(int nBit, vecBits) {
2801  if(out.tx->vout[out.i].nValue == vecPrivateSendDenominations[nBit]) {
2802  if(nValueRet >= nValueMin) {
2803  //randomly reduce the max amount we'll submit (for anonymity)
2804  nValueMax -= insecureRand(nValueMax/5);
2805  //on average use 50% of the inputs or less
2806  int r = insecureRand(vCoins.size());
2807  if((int)vecTxInRet.size() > r) return true;
2808  }
2809  txin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
2810  nValueRet += out.tx->vout[out.i].nValue;
2811  vecTxInRet.push_back(txin);
2812  vCoinsRet.push_back(out);
2813  nDenomResult |= 1 << nBit;
2814  }
2815  }
2816  }
2817  }
2818 
2819  return nValueRet >= nValueMin && nDenom == nDenomResult;
2820 }
2821 
2823 {
2825  const CompactTallyItem& t2) const
2826  {
2827  return t1.nAmount > t2.nAmount;
2828  }
2829 };
2830 
2831 bool CWallet::SelectCoinsGrouppedByAddresses(std::vector<CompactTallyItem>& vecTallyRet, bool fSkipDenominated, bool fAnonymizable, bool fSkipUnconfirmed) const
2832 {
2833  LOCK2(cs_main, cs_wallet);
2834 
2835  isminefilter filter = ISMINE_SPENDABLE;
2836 
2837  // try to use cache for already confirmed anonymizable inputs
2838  if(fAnonymizable && fSkipUnconfirmed) {
2839  if(fSkipDenominated && fAnonymizableTallyCachedNonDenom) {
2840  vecTallyRet = vecAnonymizableTallyCachedNonDenom;
2841  LogPrint("selectcoins", "SelectCoinsGrouppedByAddresses - using cache for non-denom inputs %d\n", vecTallyRet.size());
2842  return vecTallyRet.size() > 0;
2843  }
2844  if(!fSkipDenominated && fAnonymizableTallyCached) {
2845  vecTallyRet = vecAnonymizableTallyCached;
2846  LogPrint("selectcoins", "SelectCoinsGrouppedByAddresses - using cache for all inputs %d\n", vecTallyRet.size());
2847  return vecTallyRet.size() > 0;
2848  }
2849  }
2850 
2852 
2853  // Tally
2854  map<CTxDestination, CompactTallyItem> mapTally;
2855  std::set<uint256> setWalletTxesCounted;
2856  for (auto& outpoint : setWalletUTXO) {
2857 
2858  if (setWalletTxesCounted.find(outpoint.hash) != setWalletTxesCounted.end()) continue;
2859  setWalletTxesCounted.insert(outpoint.hash);
2860 
2861  map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2862  if (it == mapWallet.end()) continue;
2863 
2864  const CWalletTx& wtx = (*it).second;
2865 
2866  if(wtx.IsCoinBase() && wtx.GetBlocksToMaturity() > 0) continue;
2867  if(fSkipUnconfirmed && !wtx.IsTrusted()) continue;
2868 
2869  for (unsigned int i = 0; i < wtx.vout.size(); i++) {
2870  CTxDestination txdest;
2871  if (!ExtractDestination(wtx.vout[i].scriptPubKey, txdest)) continue;
2872 
2873  isminefilter mine = ::IsMine(*this, txdest);
2874  if(!(mine & filter)) continue;
2875 
2876  if(IsSpent(outpoint.hash, i) || IsLockedCoin(outpoint.hash, i)) continue;
2877 
2878  if(fSkipDenominated && IsDenominatedAmount(wtx.vout[i].nValue)) continue;
2879 
2880  if(fAnonymizable) {
2881  // ignore collaterals
2882  if(IsCollateralAmount(wtx.vout[i].nValue)) continue;
2883  if(fMasterNode && wtx.vout[i].nValue == 1000*COIN) continue;
2884  // ignore outputs that are 10 times smaller then the smallest denomination
2885  // otherwise they will just lead to higher fee / lower priority
2886  if(wtx.vout[i].nValue <= nSmallestDenom/10) continue;
2887  // ignore anonymized
2888  if(GetOutpointPrivateSendRounds(COutPoint(outpoint.hash, i)) >= privateSendClient.nPrivateSendRounds) continue;
2889  }
2890 
2891  CompactTallyItem& item = mapTally[txdest];
2892  item.txdest = txdest;
2893  item.nAmount += wtx.vout[i].nValue;
2894  item.vecTxIn.push_back(CTxIn(outpoint.hash, i));
2895  }
2896  }
2897 
2898  // construct resulting vector
2899  vecTallyRet.clear();
2900  BOOST_FOREACH(const PAIRTYPE(CTxDestination, CompactTallyItem)& item, mapTally) {
2901  if(fAnonymizable && item.second.nAmount < nSmallestDenom) continue;
2902  vecTallyRet.push_back(item.second);
2903  }
2904 
2905  // order by amounts per address, from smallest to largest
2906  sort(vecTallyRet.rbegin(), vecTallyRet.rend(), CompareByAmount());
2907 
2908  // cache already confirmed anonymizable entries for later use
2909  if(fAnonymizable && fSkipUnconfirmed) {
2910  if(fSkipDenominated) {
2911  vecAnonymizableTallyCachedNonDenom = vecTallyRet;
2912  fAnonymizableTallyCachedNonDenom = true;
2913  } else {
2914  vecAnonymizableTallyCached = vecTallyRet;
2915  fAnonymizableTallyCached = true;
2916  }
2917  }
2918 
2919  // debug
2920  if (LogAcceptCategory("selectcoins")) {
2921  std::string strMessage = "SelectCoinsGrouppedByAddresses - vecTallyRet:\n";
2922  BOOST_FOREACH(CompactTallyItem& item, vecTallyRet)
2923  strMessage += strprintf(" %s %f\n", CBitcoinAddress(item.txdest).ToString().c_str(), float(item.nAmount)/COIN);
2924  LogPrint("selectcoins", "%s", strMessage);
2925  }
2926 
2927  return vecTallyRet.size() > 0;
2928 }
2929 
2930 bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax) const
2931 {
2932  CCoinControl *coinControl=NULL;
2933 
2934  vecTxInRet.clear();
2935  nValueRet = 0;
2936 
2937  vector<COutput> vCoins;
2938  AvailableCoins(vCoins, true, coinControl, false, nPrivateSendRoundsMin < 0 ? ONLY_NONDENOMINATED_NOT1000IFMN : ONLY_DENOMINATED);
2939 
2940  //order the array so largest nondenom are first, then denominations, then very small inputs.
2941  sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority());
2942 
2943  BOOST_FOREACH(const COutput& out, vCoins)
2944  {
2945  //do not allow inputs less than 1/10th of minimum value
2946  if(out.tx->vout[out.i].nValue < nValueMin/10) continue;
2947  //do not allow collaterals to be selected
2948  if(IsCollateralAmount(out.tx->vout[out.i].nValue)) continue;
2949  if(fMasterNode && out.tx->vout[out.i].nValue == 1000*COIN) continue; //masternode input
2950 
2951  if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){
2952  CTxIn txin = CTxIn(out.tx->GetHash(),out.i);
2953 
2954  int nRounds = GetOutpointPrivateSendRounds(txin.prevout);
2955  if(nRounds >= nPrivateSendRoundsMax) continue;
2956  if(nRounds < nPrivateSendRoundsMin) continue;
2957 
2958  txin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
2959  nValueRet += out.tx->vout[out.i].nValue;
2960  vecTxInRet.push_back(txin);
2961  }
2962  }
2963 
2964  return nValueRet >= nValueMin;
2965 }
2966 
2967 bool CWallet::GetCollateralTxIn(CTxIn& txinRet, CAmount& nValueRet) const
2968 {
2969  vector<COutput> vCoins;
2970 
2971  AvailableCoins(vCoins);
2972 
2973  BOOST_FOREACH(const COutput& out, vCoins)
2974  {
2975  if(IsCollateralAmount(out.tx->vout[out.i].nValue))
2976  {
2977  txinRet = CTxIn(out.tx->GetHash(), out.i);
2978  txinRet.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
2979  nValueRet = out.tx->vout[out.i].nValue;
2980  return true;
2981  }
2982  }
2983 
2984  return false;
2985 }
2986 
2987 bool CWallet::GetMasternodeOutpointAndKeys(COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex)
2988 {
2989  // wait for reindex and/or import to finish
2990  if (fImporting || fReindex) return false;
2991 
2992  // Find possible candidates
2993  std::vector<COutput> vPossibleCoins;
2994  AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_1000);
2995  if(vPossibleCoins.empty()) {
2996  LogPrintf("CWallet::GetMasternodeOutpointAndKeys -- Could not locate any valid masternode vin\n");
2997  return false;
2998  }
2999 
3000  if(strTxHash.empty()) // No output specified, select the first one
3001  return GetOutpointAndKeysFromOutput(vPossibleCoins[0], outpointRet, pubKeyRet, keyRet);
3002 
3003  // Find specific vin
3004  uint256 txHash = uint256S(strTxHash);
3005  int nOutputIndex = atoi(strOutputIndex.c_str());
3006 
3007  BOOST_FOREACH(COutput& out, vPossibleCoins)
3008  if(out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it!
3009  return GetOutpointAndKeysFromOutput(out, outpointRet, pubKeyRet, keyRet);
3010 
3011  LogPrintf("CWallet::GetMasternodeOutpointAndKeys -- Could not locate specified masternode vin\n");
3012  return false;
3013 }
3014 
3015 bool CWallet::GetOutpointAndKeysFromOutput(const COutput& out, COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet)
3016 {
3017  // wait for reindex and/or import to finish
3018  if (fImporting || fReindex) return false;
3019 
3020  CScript pubScript;
3021 
3022  outpointRet = COutPoint(out.tx->GetHash(), out.i);
3023  pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
3024 
3025  CTxDestination address1;
3026  ExtractDestination(pubScript, address1);
3027  CBitcoinAddress address2(address1);
3028 
3029  CKeyID keyID;
3030  if (!address2.GetKeyID(keyID)) {
3031  LogPrintf("CWallet::GetOutpointAndKeysFromOutput -- Address does not refer to a key\n");
3032  return false;
3033  }
3034 
3035  if (!GetKey(keyID, keyRet)) {
3036  LogPrintf ("CWallet::GetOutpointAndKeysFromOutput -- Private key for address is not known\n");
3037  return false;
3038  }
3039 
3040  pubKeyRet = keyRet.GetPubKey();
3041  return true;
3042 }
3043 
3045 {
3046  CAmount nTotal = 0;
3047  {
3048  LOCK2(cs_main, cs_wallet);
3049  for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3050  {
3051  const CWalletTx* pcoin = &(*it).second;
3052  if (pcoin->IsTrusted()){
3053  int nDepth = pcoin->GetDepthInMainChain(false);
3054 
3055  for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
3056  COutput out = COutput(pcoin, i, nDepth, true, true);
3057  COutPoint outpoint = COutPoint(out.tx->GetHash(), out.i);
3058 
3059  if(out.tx->vout[out.i].nValue != nInputAmount) continue;
3060  if(!IsDenominatedAmount(pcoin->vout[i].nValue)) continue;
3061  if(IsSpent(out.tx->GetHash(), i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(outpoint)) continue;
3062 
3063  nTotal++;
3064  }
3065  }
3066  }
3067  }
3068 
3069  return nTotal;
3070 }
3071 
3072 bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const
3073 {
3074  vector<COutput> vCoins;
3075  AvailableCoins(vCoins, fOnlyConfirmed, NULL, false, ONLY_PRIVATESEND_COLLATERAL);
3076 
3077  return !vCoins.empty();
3078 }
3079 
3080 bool CWallet::IsCollateralAmount(CAmount nInputAmount) const
3081 {
3082  // collateral inputs should always be a 2x..4x of mixing collateral
3083  return nInputAmount > CPrivateSend::GetCollateralAmount() &&
3084  nInputAmount <= CPrivateSend::GetMaxCollateralAmount() &&
3085  nInputAmount % CPrivateSend::GetCollateralAmount() == 0;
3086 }
3087 
3088 bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason)
3089 {
3090  txCollateral.vin.clear();
3091  txCollateral.vout.clear();
3092 
3093  CReserveKey reservekey(this);
3094  CAmount nValue = 0;
3095  CTxIn txinCollateral;
3096 
3097  if (!GetCollateralTxIn(txinCollateral, nValue)) {
3098  strReason = "PrivateSend requires a collateral transaction and could not locate an acceptable input!";
3099  return false;
3100  }
3101 
3102  // make our change address
3103  CScript scriptChange;
3104  CPubKey vchPubKey;
3105  assert(reservekey.GetReservedKey(vchPubKey, true)); // should never fail, as we just unlocked
3106  scriptChange = GetScriptForDestination(vchPubKey.GetID());
3107  reservekey.KeepKey();
3108 
3109  txCollateral.vin.push_back(txinCollateral);
3110 
3111  //pay collateral charge in fees
3112  CTxOut txout = CTxOut(nValue - CPrivateSend::GetCollateralAmount(), scriptChange);
3113  txCollateral.vout.push_back(txout);
3114 
3115  if(!SignSignature(*this, txinCollateral.prevPubKey, txCollateral, 0, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) {
3116  strReason = "Unable to sign collateral transaction!";
3117  return false;
3118  }
3119 
3120  return true;
3121 }
3122 
3123 bool CWallet::GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, CAmount amount, bool fUseInstantSend)
3124 {
3125  CWalletTx wtx;
3126  if(GetBudgetSystemCollateralTX(wtx, hash, amount, fUseInstantSend)){
3127  tx = (CTransaction)wtx;
3128  return true;
3129  }
3130  return false;
3131 }
3132 
3133 bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, CAmount amount, bool fUseInstantSend)
3134 {
3135  // make our change address
3136  CReserveKey reservekey(this);
3137 
3138  CScript scriptChange;
3139  scriptChange << OP_RETURN << ToByteVector(hash);
3140 
3141  CAmount nFeeRet = 0;
3142  int nChangePosRet = -1;
3143  std::string strFail = "";
3144  vector< CRecipient > vecSend;
3145  vecSend.push_back((CRecipient){scriptChange, amount, false});
3146 
3147  CCoinControl *coinControl=NULL;
3148  bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, nChangePosRet, strFail, coinControl, true, ALL_COINS, fUseInstantSend);
3149  if(!success){
3150  LogPrintf("CWallet::GetBudgetSystemCollateralTX -- Error: %s\n", strFail);
3151  return false;
3152  }
3153 
3154  return true;
3155 }
3156 
3157 
3158 bool CWallet::ConvertList(std::vector<CTxIn> vecTxIn, std::vector<CAmount>& vecAmounts)
3159 {
3160  BOOST_FOREACH(CTxIn txin, vecTxIn) {
3161  if (mapWallet.count(txin.prevout.hash)) {
3162  CWalletTx& wtx = mapWallet[txin.prevout.hash];
3163  if(txin.prevout.n < wtx.vout.size()){
3164  vecAmounts.push_back(wtx.vout[txin.prevout.n].nValue);
3165  }
3166  } else {
3167  LogPrintf("CWallet::ConvertList -- Couldn't find transaction\n");
3168  }
3169  }
3170  return true;
3171 }
3172 
3173 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
3174  int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign, AvailableCoinsType nCoinType, bool fUseInstantSend)
3175 {
3176  CAmount nFeePay = fUseInstantSend ? CTxLockRequest().GetMinFee() : 0;
3177 
3178  CAmount nValue = 0;
3179  unsigned int nSubtractFeeFromAmount = 0;
3180  BOOST_FOREACH (const CRecipient& recipient, vecSend)
3181  {
3182  if (nValue < 0 || recipient.nAmount < 0)
3183  {
3184  strFailReason = _("Transaction amounts must be positive");
3185  return false;
3186  }
3187  nValue += recipient.nAmount;
3188 
3189  if (recipient.fSubtractFeeFromAmount)
3190  nSubtractFeeFromAmount++;
3191  }
3192  if (vecSend.empty() || nValue < 0)
3193  {
3194  strFailReason = _("Transaction amounts must be positive");
3195  return false;
3196  }
3197 
3198  wtxNew.fTimeReceivedIsTxTime = true;
3199  wtxNew.BindWallet(this);
3200  CMutableTransaction txNew;
3201 
3202  // Discourage fee sniping.
3203  //
3204  // For a large miner the value of the transactions in the best block and
3205  // the mempool can exceed the cost of deliberately attempting to mine two
3206  // blocks to orphan the current best block. By setting nLockTime such that
3207  // only the next block can include the transaction, we discourage this
3208  // practice as the height restricted and limited blocksize gives miners
3209  // considering fee sniping fewer options for pulling off this attack.
3210  //
3211  // A simple way to think about this is from the wallet's point of view we
3212  // always want the blockchain to move forward. By setting nLockTime this
3213  // way we're basically making the statement that we only want this
3214  // transaction to appear in the next block; we don't want to potentially
3215  // encourage reorgs by allowing transactions to appear at lower heights
3216  // than the next block in forks of the best chain.
3217  //
3218  // Of course, the subsidy is high enough, and transaction volume low
3219  // enough, that fee sniping isn't a problem yet, but by implementing a fix
3220  // now we ensure code won't be written that makes assumptions about
3221  // nLockTime that preclude a fix later.
3222 
3223  txNew.nLockTime = chainActive.Height();
3224 
3225  // Secondly occasionally randomly pick a nLockTime even further back, so
3226  // that transactions that are delayed after signing for whatever reason,
3227  // e.g. high-latency mix networks and some CoinJoin implementations, have
3228  // better privacy.
3229  if (GetRandInt(10) == 0)
3230  txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
3231 
3232  assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
3233  assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
3234 
3235  {
3236  LOCK2(cs_main, cs_wallet);
3237  {
3238  nFeeRet = 0;
3239  if(nFeePay > 0) nFeeRet = nFeePay;
3240  // Start with no fee and loop until there is enough fee
3241  while (true)
3242  {
3243  txNew.vin.clear();
3244  txNew.vout.clear();
3245  wtxNew.fFromMe = true;
3246  nChangePosRet = -1;
3247  bool fFirst = true;
3248 
3249  CAmount nValueToSelect = nValue;
3250  if (nSubtractFeeFromAmount == 0)
3251  nValueToSelect += nFeeRet;
3252  double dPriority = 0;
3253  // vouts to the payees
3254  BOOST_FOREACH (const CRecipient& recipient, vecSend)
3255  {
3256  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
3257 
3258  if (recipient.fSubtractFeeFromAmount)
3259  {
3260  txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
3261 
3262  if (fFirst) // first receiver pays the remainder not divisible by output count
3263  {
3264  fFirst = false;
3265  txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
3266  }
3267  }
3268 
3269  if (txout.IsDust(::minRelayTxFee))
3270  {
3271  if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
3272  {
3273  if (txout.nValue < 0)
3274  strFailReason = _("The transaction amount is too small to pay the fee");
3275  else
3276  strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3277  }
3278  else
3279  strFailReason = _("Transaction amount too small");
3280  return false;
3281  }
3282  txNew.vout.push_back(txout);
3283  }
3284 
3285  // Choose coins to use
3286  set<pair<const CWalletTx*,unsigned int> > setCoins;
3287  CAmount nValueIn = 0;
3288 
3289  if (!SelectCoins(nValueToSelect, setCoins, nValueIn, coinControl, nCoinType, fUseInstantSend))
3290  {
3291  if (nCoinType == ONLY_NOT1000IFMN) {
3292  strFailReason = _("Unable to locate enough funds for this transaction that are not equal 1000 DASH.");
3293  } else if (nCoinType == ONLY_NONDENOMINATED_NOT1000IFMN) {
3294  strFailReason = _("Unable to locate enough PrivateSend non-denominated funds for this transaction that are not equal 1000 DASH.");
3295  } else if (nCoinType == ONLY_DENOMINATED) {
3296  strFailReason = _("Unable to locate enough PrivateSend denominated funds for this transaction.");
3297  strFailReason += " " + _("PrivateSend uses exact denominated amounts to send funds, you might simply need to anonymize some more coins.");
3298  } else if (nValueIn < nValueToSelect) {
3299  strFailReason = _("Insufficient funds.");
3300  if (fUseInstantSend) {
3301  // could be not true but most likely that's the reason
3302  strFailReason += " " + strprintf(_("InstantSend requires inputs with at least %d confirmations, you might need to wait a few minutes and try again."), INSTANTSEND_CONFIRMATIONS_REQUIRED);
3303  }
3304  }
3305 
3306  return false;
3307  }
3308  if (fUseInstantSend && nValueIn > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN) {
3309  strFailReason += " " + strprintf(_("InstantSend doesn't support sending values that high yet. Transactions are currently limited to %1 DASH."), sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE));
3310  return false;
3311  }
3312 
3313  BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
3314  {
3315  CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
3316  //The coin age after the next block (depth+1) is used instead of the current,
3317  //reflecting an assumption the user would accept a bit more delay for
3318  //a chance at a free transaction.
3319  //But mempool inputs might still be in the mempool, so their age stays 0
3320  int age = pcoin.first->GetDepthInMainChain();
3321  assert(age >= 0);
3322  if (age != 0)
3323  age += 1;
3324  dPriority += (double)nCredit * age;
3325  }
3326 
3327  const CAmount nChange = nValueIn - nValueToSelect;
3328  CTxOut newTxOut;
3329 
3330  if (nChange > 0)
3331  {
3332 
3333  //over pay for denominated transactions
3334  if (nCoinType == ONLY_DENOMINATED) {
3335  nFeeRet += nChange;
3336  wtxNew.mapValue["DS"] = "1";
3337  // recheck skipped denominations during next mixing
3339  } else {
3340 
3341  // Fill a vout to ourself
3342  // TODO: pass in scriptChange instead of reservekey so
3343  // change transaction isn't always pay-to-dash-address
3344  CScript scriptChange;
3345 
3346  // coin control: send change to custom address
3347  if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
3348  scriptChange = GetScriptForDestination(coinControl->destChange);
3349 
3350  // no coin control: send change to newly generated address
3351  else
3352  {
3353  // Note: We use a new key here to keep it from being obvious which side is the change.
3354  // The drawback is that by not reusing a previous key, the change may be lost if a
3355  // backup is restored, if the backup doesn't have the new private key for the change.
3356  // If we reused the old key, it would be possible to add code to look for and
3357  // rediscover unknown transactions that were written with keys of ours to recover
3358  // post-backup change.
3359 
3360  // Reserve a new key pair from key pool
3361  CPubKey vchPubKey;
3362  if (!reservekey.GetReservedKey(vchPubKey, true))
3363  {
3364  strFailReason = _("Keypool ran out, please call keypoolrefill first");
3365  return false;
3366  }
3367  scriptChange = GetScriptForDestination(vchPubKey.GetID());
3368  }
3369 
3370  newTxOut = CTxOut(nChange, scriptChange);
3371 
3372  // We do not move dust-change to fees, because the sender would end up paying more than requested.
3373  // This would be against the purpose of the all-inclusive feature.
3374  // So instead we raise the change and deduct from the recipient.
3375  if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
3376  {
3377  CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
3378  newTxOut.nValue += nDust; // raise change until no more dust
3379  for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
3380  {
3381  if (vecSend[i].fSubtractFeeFromAmount)
3382  {
3383  txNew.vout[i].nValue -= nDust;
3384  if (txNew.vout[i].IsDust(::minRelayTxFee))
3385  {
3386  strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3387  return false;
3388  }
3389  break;
3390  }
3391  }
3392  }
3393 
3394  // Never create dust outputs; if we would, just
3395  // add the dust to the fee.
3396  if (newTxOut.IsDust(::minRelayTxFee))
3397  {
3398  nFeeRet += nChange;
3399  reservekey.ReturnKey();
3400  }
3401  else
3402  {
3403  // Insert change txn at random position:
3404  nChangePosRet = GetRandInt(txNew.vout.size()+1);
3405  vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
3406  txNew.vout.insert(position, newTxOut);
3407  }
3408  }
3409  }
3410  else
3411  reservekey.ReturnKey();
3412 
3413  // Fill vin
3414  //
3415  // Note how the sequence number is set to max()-1 so that the
3416  // nLockTime set above actually works.
3417  BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins){
3418  CTxIn txin = CTxIn(coin.first->GetHash(),coin.second,CScript(),
3419  std::numeric_limits<unsigned int>::max()-1);
3420  txin.prevPubKey = coin.first->vout[coin.second].scriptPubKey;
3421  txNew.vin.push_back(txin);
3422  }
3423 
3424  sort(txNew.vin.begin(), txNew.vin.end(), CompareInputBIP69());
3425  sort(txNew.vout.begin(), txNew.vout.end(), CompareOutputBIP69());
3426 
3427  // If there was change output added before, we must update its position now
3428  if (nChangePosRet != -1) {
3429  int i = 0;
3430  BOOST_FOREACH(const CTxOut& txOut, txNew.vout)
3431  {
3432  if (txOut == newTxOut)
3433  {
3434  nChangePosRet = i;
3435  break;
3436  }
3437  i++;
3438  }
3439  }
3440 
3441  // Sign
3442  int nIn = 0;
3443  CTransaction txNewConst(txNew);
3444  BOOST_FOREACH(const CTxIn& txin, txNew.vin)
3445  {
3446  bool signSuccess;
3447  const CScript& scriptPubKey = txin.prevPubKey;
3448  CScript& scriptSigRes = txNew.vin[nIn].scriptSig;
3449  if (sign)
3450  signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, SIGHASH_ALL), scriptPubKey, scriptSigRes);
3451  else
3452  signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, scriptSigRes);
3453 
3454  if (!signSuccess)
3455  {
3456  strFailReason = _("Signing transaction failed");
3457  return false;
3458  }
3459  nIn++;
3460  }
3461 
3462  unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
3463 
3464  // Remove scriptSigs if we used dummy signatures for fee calculation
3465  if (!sign) {
3466  BOOST_FOREACH (CTxIn& txin, txNew.vin)
3467  txin.scriptSig = CScript();
3468  }
3469 
3470  // Embed the constructed transaction data in wtxNew.
3471  *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
3472 
3473  // Limit size
3474  if (nBytes >= MAX_STANDARD_TX_SIZE)
3475  {
3476  strFailReason = _("Transaction too large");
3477  return false;
3478  }
3479 
3480  dPriority = wtxNew.ComputePriority(dPriority, nBytes);
3481 
3482  // Can we complete this as a free transaction?
3484  {
3485  // Not enough fee: enough priority?
3486  double dPriorityNeeded = mempool.estimateSmartPriority(nTxConfirmTarget);
3487  // Require at least hard-coded AllowFree.
3488  if (dPriority >= dPriorityNeeded && AllowFree(dPriority))
3489  break;
3490 
3491  // Small enough, and priority high enough, to send for free
3492 // if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
3493 // break;
3494  }
3495  CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool));
3496  if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
3497  nFeeNeeded = coinControl->nMinimumTotalFee;
3498  }
3499  if(fUseInstantSend) {
3500  nFeeNeeded = std::max(nFeeNeeded, CTxLockRequest(txNew).GetMinFee());
3501  }
3502 
3503  // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
3504  // because we must be at the maximum allowed fee.
3505  if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
3506  {
3507  strFailReason = _("Transaction too large for fee policy");
3508  return false;
3509  }
3510 
3511  if (nFeeRet >= nFeeNeeded)
3512  break; // Done, enough fee included.
3513 
3514  // Include more fee and try again.
3515  nFeeRet = nFeeNeeded;
3516  continue;
3517  }
3518  }
3519  }
3520 
3521  return true;
3522 }
3523 
3527 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, std::string strCommand)
3528 {
3529  {
3530  LOCK2(cs_main, cs_wallet);
3531  LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
3532  {
3533  // This is only to keep the database open to defeat the auto-flush for the
3534  // duration of this scope. This is the only place where this optimization
3535  // maybe makes sense; please don't do it anywhere else.
3536  CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
3537 
3538  // Take key pair from key pool so it won't be used again
3539  reservekey.KeepKey();
3540 
3541  // Add tx to wallet, because if it has change it's also ours,
3542  // otherwise just for transaction history.
3543  AddToWallet(wtxNew, false, pwalletdb);
3544 
3545  // Notify that old coins are spent
3546  set<uint256> updated_hahes;
3547  BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3548  {
3549  // notify only once
3550  if(updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue;
3551 
3552  CWalletTx &coin = mapWallet[txin.prevout.hash];
3553  coin.BindWallet(this);
3555  updated_hahes.insert(txin.prevout.hash);
3556  }
3557  if (fFileBacked)
3558  delete pwalletdb;
3559  }
3560 
3561  // Track how many getdata requests our transaction gets
3562  mapRequestCount[wtxNew.GetHash()] = 0;
3563 
3564  if (fBroadcastTransactions)
3565  {
3566  // Broadcast
3567  if (!wtxNew.AcceptToMemoryPool(false))
3568  {
3569  // This must not fail. The transaction has already been signed and recorded.
3570  LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
3571  return false;
3572  }
3573  wtxNew.RelayWalletTransaction(connman, strCommand);
3574  }
3575  }
3576  return true;
3577 }
3578 
3579 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pwalletdb)
3580 {
3581  if (!pwalletdb.WriteAccountingEntry_Backend(acentry))
3582  return false;
3583 
3584  laccentries.push_back(acentry);
3585  CAccountingEntry & entry = laccentries.back();
3586  wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
3587 
3588  return true;
3589 }
3590 
3591 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
3592 {
3593  return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
3594 }
3595 
3596 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
3597 {
3598  // payTxFee is user-set "I want to pay this much"
3599  CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
3600  // User didn't set: use -txconfirmtarget to estimate...
3601  if (nFeeNeeded == 0) {
3602  int estimateFoundTarget = nConfirmTarget;
3603  nFeeNeeded = pool.estimateSmartFee(nConfirmTarget, &estimateFoundTarget).GetFee(nTxBytes);
3604  // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
3605  if (nFeeNeeded == 0)
3606  nFeeNeeded = fallbackFee.GetFee(nTxBytes);
3607  }
3608  // prevent user from paying a fee below minRelayTxFee or minTxFee
3609  nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
3610  // But always obey the maximum
3611  if (nFeeNeeded > maxTxFee)
3612  nFeeNeeded = maxTxFee;
3613  return nFeeNeeded;
3614 }
3615 
3616 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3617 {
3618  if (!fFileBacked)
3619  return DB_LOAD_OK;
3620  fFirstRunRet = false;
3621  DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
3622  if (nLoadWalletRet == DB_NEED_REWRITE)
3623  {
3624  if (CDB::Rewrite(strWalletFile, "\x04pool"))
3625  {
3626  LOCK(cs_wallet);
3627  setInternalKeyPool.clear();
3628  setExternalKeyPool.clear();
3629  nKeysLeftSinceAutoBackup = 0;
3630  // Note: can't top-up keypool here, because wallet is locked.
3631  // User will be prompted to unlock wallet the next operation
3632  // that requires a new key.
3633  }
3634  }
3635 
3636  {
3637  LOCK2(cs_main, cs_wallet);
3638  for (auto& pair : mapWallet) {
3639  for(int i = 0; i < pair.second.vout.size(); ++i) {
3640  if (IsMine(pair.second.vout[i]) && !IsSpent(pair.first, i)) {
3641  setWalletUTXO.insert(COutPoint(pair.first, i));
3642  }
3643  }
3644  }
3645  }
3646 
3647  if (nLoadWalletRet != DB_LOAD_OK)
3648  return nLoadWalletRet;
3649  fFirstRunRet = !vchDefaultKey.IsValid();
3650 
3651  uiInterface.LoadWallet(this);
3652 
3653  return DB_LOAD_OK;
3654 }
3655 
3656 
3657 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3658 {
3659  if (!fFileBacked)
3660  return DB_LOAD_OK;
3661  DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
3662  if (nZapWalletTxRet == DB_NEED_REWRITE)
3663  {
3664  if (CDB::Rewrite(strWalletFile, "\x04pool"))
3665  {
3666  LOCK(cs_wallet);
3667  setInternalKeyPool.clear();
3668  setExternalKeyPool.clear();
3669  nKeysLeftSinceAutoBackup = 0;
3670  // Note: can't top-up keypool here, because wallet is locked.
3671  // User will be prompted to unlock wallet the next operation
3672  // that requires a new key.
3673  }
3674  }
3675 
3676  if (nZapWalletTxRet != DB_LOAD_OK)
3677  return nZapWalletTxRet;
3678 
3679  return DB_LOAD_OK;
3680 }
3681 
3682 
3683 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
3684 {
3685  bool fUpdated = false;
3686  {
3687  LOCK(cs_wallet); // mapAddressBook
3688  std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3689  fUpdated = mi != mapAddressBook.end();
3690  mapAddressBook[address].name = strName;
3691  if (!strPurpose.empty()) /* update purpose only if requested */
3692  mapAddressBook[address].purpose = strPurpose;
3693  }
3694  NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3695  strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3696  if (!fFileBacked)
3697  return false;
3698  if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3699  return false;
3700  return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
3701 }
3702 
3704 {
3705  {
3706  LOCK(cs_wallet); // mapAddressBook
3707 
3708  if(fFileBacked)
3709  {
3710  // Delete destdata tuples associated with address
3711  std::string strAddress = CBitcoinAddress(address).ToString();
3712  BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3713  {
3714  CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3715  }
3716  }
3717  mapAddressBook.erase(address);
3718  }
3719 
3720  NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3721 
3722  if (!fFileBacked)
3723  return false;
3724  CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
3725  return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
3726 }
3727 
3728 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3729 {
3730  if (fFileBacked)
3731  {
3732  if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3733  return false;
3734  }
3735  vchDefaultKey = vchPubKey;
3736  return true;
3737 }
3738 
3744 {
3745  {
3746  LOCK(cs_wallet);
3747  CWalletDB walletdb(strWalletFile);
3748  BOOST_FOREACH(int64_t nIndex, setInternalKeyPool) {
3749  walletdb.ErasePool(nIndex);
3750  }
3751  setInternalKeyPool.clear();
3752  BOOST_FOREACH(int64_t nIndex, setExternalKeyPool) {
3753  walletdb.ErasePool(nIndex);
3754  }
3755  setExternalKeyPool.clear();
3757  nKeysLeftSinceAutoBackup = 0;
3758 
3759  if (!TopUpKeyPool())
3760  return false;
3761 
3762  LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3763  }
3764  return true;
3765 }
3766 
3768 {
3769  AssertLockHeld(cs_wallet); // setExternalKeyPool
3770  return setExternalKeyPool.size();
3771 }
3772 
3774 {
3775  AssertLockHeld(cs_wallet); // setInternalKeyPool
3776  return setInternalKeyPool.size();
3777 }
3778 
3779 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3780 {
3781  {
3782  LOCK(cs_wallet);
3783 
3784  if (IsLocked(true))
3785  return false;
3786 
3787  // Top up key pool
3788  unsigned int nTargetSize;
3789  if (kpSize > 0)
3790  nTargetSize = kpSize;
3791  else
3792  nTargetSize = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3793 
3794  // count amount of available keys (internal, external)
3795  // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3796  int64_t amountExternal = setExternalKeyPool.size();
3797  int64_t amountInternal = setInternalKeyPool.size();
3798  int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountExternal, (int64_t) 0);
3799  int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountInternal, (int64_t) 0);
3800 
3801  if (!IsHDEnabled())
3802  {
3803  // don't create extra internal keys
3804  missingInternal = 0;
3805  } else {
3806  nTargetSize *= 2;
3807  }
3808  bool fInternal = false;
3809  CWalletDB walletdb(strWalletFile);
3810  for (int64_t i = missingInternal + missingExternal; i--;)
3811  {
3812  int64_t nEnd = 1;
3813  if (i < missingInternal) {
3814  fInternal = true;
3815  }
3816  if (!setInternalKeyPool.empty()) {
3817  nEnd = *(--setInternalKeyPool.end()) + 1;
3818  }
3819  if (!setExternalKeyPool.empty()) {
3820  nEnd = std::max(nEnd, *(--setExternalKeyPool.end()) + 1);
3821  }
3822  // TODO: implement keypools for all accounts?
3823  if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey(0, fInternal), fInternal)))
3824  throw runtime_error("TopUpKeyPool(): writing generated key failed");
3825 
3826  if (fInternal) {
3827  setInternalKeyPool.insert(nEnd);
3828  } else {
3829  setExternalKeyPool.insert(nEnd);
3830  }
3831  LogPrintf("keypool added key %d, size=%u, internal=%d\n", nEnd, setInternalKeyPool.size() + setExternalKeyPool.size(), fInternal);
3832 
3833  double dProgress = 100.f * nEnd / (nTargetSize + 1);
3834  std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress);
3835  uiInterface.InitMessage(strMsg);
3836  }
3837  }
3838  return true;
3839 }
3840 
3841 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fInternal)
3842 {
3843  nIndex = -1;
3844  keypool.vchPubKey = CPubKey();
3845  {
3846  LOCK(cs_wallet);
3847 
3848  if (!IsLocked(true))
3849  TopUpKeyPool();
3850 
3851  fInternal = fInternal && IsHDEnabled();
3852  std::set<int64_t>& setKeyPool = fInternal ? setInternalKeyPool : setExternalKeyPool;
3853 
3854  // Get the oldest key
3855  if(setKeyPool.empty())
3856  return;
3857 
3858  CWalletDB walletdb(strWalletFile);
3859 
3860  nIndex = *setKeyPool.begin();
3861  setKeyPool.erase(nIndex);
3862  if (!walletdb.ReadPool(nIndex, keypool)) {
3863  throw std::runtime_error(std::string(__func__) + ": read failed");
3864  }
3865  if (!HaveKey(keypool.vchPubKey.GetID())) {
3866  throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3867  }
3868  if (keypool.fInternal != fInternal) {
3869  throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3870  }
3871 
3872  assert(keypool.vchPubKey.IsValid());
3873  LogPrintf("keypool reserve %d\n", nIndex);
3874  }
3875 }
3876 
3877 void CWallet::KeepKey(int64_t nIndex)
3878 {
3879  // Remove from key pool
3880  if (fFileBacked)
3881  {
3882  CWalletDB walletdb(strWalletFile);
3883  walletdb.ErasePool(nIndex);
3884  nKeysLeftSinceAutoBackup = nWalletBackups ? nKeysLeftSinceAutoBackup - 1 : 0;
3885  }
3886  LogPrintf("keypool keep %d\n", nIndex);
3887 }
3888 
3889 void CWallet::ReturnKey(int64_t nIndex, bool fInternal)
3890 {
3891  // Return to key pool
3892  {
3893  LOCK(cs_wallet);
3894  if (fInternal) {
3895  setInternalKeyPool.insert(nIndex);
3896  } else {
3897  setExternalKeyPool.insert(nIndex);
3898  }
3899  }
3900  LogPrintf("keypool return %d\n", nIndex);
3901 }
3902 
3904 {
3905  int64_t nIndex = 0;
3906  CKeyPool keypool;
3907  {
3908  LOCK(cs_wallet);
3909  ReserveKeyFromKeyPool(nIndex, keypool, fInternal);
3910  if (nIndex == -1)
3911  {
3912  if (IsLocked(true)) return false;
3913  // TODO: implement keypool for all accouts?
3914  result = GenerateNewKey(0, fInternal);
3915  return true;
3916  }
3917  KeepKey(nIndex);
3918  result = keypool.vchPubKey;
3919  }
3920  return true;
3921 }
3922 
3923 static int64_t GetOldestKeyInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3924  CKeyPool keypool;
3925  int64_t nIndex = *(setKeyPool.begin());
3926  if (!walletdb.ReadPool(nIndex, keypool)) {
3927  throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3928  }
3929  assert(keypool.vchPubKey.IsValid());
3930  return keypool.nTime;
3931 }
3932 
3934 {
3935  LOCK(cs_wallet);
3936 
3937  // if the keypool is empty, return <NOW>
3938  if (setExternalKeyPool.empty() && setInternalKeyPool.empty())
3939  return GetTime();
3940 
3941  CWalletDB walletdb(strWalletFile);
3942  int64_t oldestKey = -1;
3943 
3944  // load oldest key from keypool, get time and return
3945  if (!setInternalKeyPool.empty()) {
3946  oldestKey = std::max(GetOldestKeyInPool(setInternalKeyPool, walletdb), oldestKey);
3947  }
3948  if (!setExternalKeyPool.empty()) {
3949  oldestKey = std::max(GetOldestKeyInPool(setExternalKeyPool, walletdb), oldestKey);
3950  }
3951  return oldestKey;
3952 }
3953 
3954 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3955 {
3956  map<CTxDestination, CAmount> balances;
3957 
3958  {
3959  LOCK(cs_wallet);
3960  BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3961  {
3962  CWalletTx *pcoin = &walletEntry.second;
3963 
3964  if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
3965  continue;
3966 
3967  if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3968  continue;
3969 
3970  int nDepth = pcoin->GetDepthInMainChain();
3971  if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3972  continue;
3973 
3974  for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3975  {
3976  CTxDestination addr;
3977  if (!IsMine(pcoin->vout[i]))
3978  continue;
3979  if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3980  continue;
3981 
3982  CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
3983 
3984  if (!balances.count(addr))
3985  balances[addr] = 0;
3986  balances[addr] += n;
3987  }
3988  }
3989  }
3990 
3991  return balances;
3992 }
3993 
3994 set< set<CTxDestination> > CWallet::GetAddressGroupings()
3995 {
3996  AssertLockHeld(cs_wallet); // mapWallet
3997  set< set<CTxDestination> > groupings;
3998  set<CTxDestination> grouping;
3999 
4000  BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
4001  {
4002  CWalletTx *pcoin = &walletEntry.second;
4003 
4004  if (pcoin->vin.size() > 0)
4005  {
4006  bool any_mine = false;
4007  // group all input addresses with each other
4008  BOOST_FOREACH(CTxIn txin, pcoin->vin)
4009  {
4010  CTxDestination address;
4011  if(!IsMine(txin)) /* If this input isn't mine, ignore it */
4012  continue;
4013  if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
4014  continue;
4015  grouping.insert(address);
4016  any_mine = true;
4017  }
4018 
4019  // group change with input addresses
4020  if (any_mine)
4021  {
4022  BOOST_FOREACH(CTxOut txout, pcoin->vout)
4023  if (IsChange(txout))
4024  {
4025  CTxDestination txoutAddr;
4026  if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
4027  continue;
4028  grouping.insert(txoutAddr);
4029  }
4030  }
4031  if (grouping.size() > 0)
4032  {
4033  groupings.insert(grouping);
4034  grouping.clear();
4035  }
4036  }
4037 
4038  // group lone addrs by themselves
4039  for (unsigned int i = 0; i < pcoin->vout.size(); i++)
4040  if (IsMine(pcoin->vout[i]))
4041  {
4042  CTxDestination address;
4043  if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
4044  continue;
4045  grouping.insert(address);
4046  groupings.insert(grouping);
4047  grouping.clear();
4048  }
4049  }
4050 
4051  set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
4052  map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
4053  BOOST_FOREACH(set<CTxDestination> grouping, groupings)
4054  {
4055  // make a set of all the groups hit by this new group
4056  set< set<CTxDestination>* > hits;
4057  map< CTxDestination, set<CTxDestination>* >::iterator it;
4058  BOOST_FOREACH(CTxDestination address, grouping)
4059  if ((it = setmap.find(address)) != setmap.end())
4060  hits.insert((*it).second);
4061 
4062  // merge all hit groups into a new single group and delete old groups
4063  set<CTxDestination>* merged = new set<CTxDestination>(grouping);
4064  BOOST_FOREACH(set<CTxDestination>* hit, hits)
4065  {
4066  merged->insert(hit->begin(), hit->end());
4067  uniqueGroupings.erase(hit);
4068  delete hit;
4069  }
4070  uniqueGroupings.insert(merged);
4071 
4072  // update setmap
4073  BOOST_FOREACH(CTxDestination element, *merged)
4074  setmap[element] = merged;
4075  }
4076 
4077  set< set<CTxDestination> > ret;
4078  BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
4079  {
4080  ret.insert(*uniqueGrouping);
4081  delete uniqueGrouping;
4082  }
4083 
4084  return ret;
4085 }
4086 
4087 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
4088 {
4089  LOCK(cs_wallet);
4090  set<CTxDestination> result;
4091  BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
4092  {
4093  const CTxDestination& address = item.first;
4094  const string& strName = item.second.name;
4095  if (strName == strAccount)
4096  result.insert(address);
4097  }
4098  return result;
4099 }
4100 
4101 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool fInternalIn)
4102 {
4103  if (nIndex == -1)
4104  {
4105  CKeyPool keypool;
4106  pwallet->ReserveKeyFromKeyPool(nIndex, keypool, fInternalIn);
4107  if (nIndex != -1) {
4108  vchPubKey = keypool.vchPubKey;
4109  }
4110  else {
4111  return false;
4112  }
4113  fInternal = keypool.fInternal;
4114  }
4115  assert(vchPubKey.IsValid());
4116  pubkey = vchPubKey;
4117  return true;
4118 }
4119 
4121 {
4122  if (nIndex != -1) {
4123  pwallet->KeepKey(nIndex);
4124  }
4125  nIndex = -1;
4126  vchPubKey = CPubKey();
4127 }
4128 
4130 {
4131  if (nIndex != -1) {
4132  pwallet->ReturnKey(nIndex, fInternal);
4133  }
4134  nIndex = -1;
4135  vchPubKey = CPubKey();
4136 }
4137 
4138 static void LoadReserveKeysToSet(std::set<CKeyID>& setAddress, const std::set<int64_t>& setKeyPool, CWalletDB& walletdb)
4139 {
4140  BOOST_FOREACH(const int64_t& id, setKeyPool)
4141  {
4142  CKeyPool keypool;
4143  if (!walletdb.ReadPool(id, keypool))
4144  throw runtime_error("GetAllReserveKeyHashes(): read failed");
4145  assert(keypool.vchPubKey.IsValid());
4146  CKeyID keyID = keypool.vchPubKey.GetID();
4147  setAddress.insert(keyID);
4148  }
4149 }
4150 
4151 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
4152 {
4153  setAddress.clear();
4154 
4155  CWalletDB walletdb(strWalletFile);
4156 
4157  LOCK2(cs_main, cs_wallet);
4158  LoadReserveKeysToSet(setAddress, setInternalKeyPool, walletdb);
4159  LoadReserveKeysToSet(setAddress, setExternalKeyPool, walletdb);
4160 
4161  BOOST_FOREACH (const CKeyID& keyID, setAddress) {
4162  if (!HaveKey(keyID)) {
4163  throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
4164  }
4165  }
4166 }
4167 
4169 {
4170  {
4171  LOCK(cs_wallet);
4172  // Only notify UI if this transaction is in this wallet
4173  map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
4174  if (mi != mapWallet.end()){
4175  NotifyTransactionChanged(this, hashTx, CT_UPDATED);
4176  return true;
4177  }
4178  }
4179  return false;
4180 }
4181 
4182 void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
4183 {
4184  boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
4185  CPubKey pubkey;
4186  if (!rKey->GetReservedKey(pubkey, false))
4187  return;
4188 
4189  script = rKey;
4190  script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
4191 }
4192 
4194 {
4195  AssertLockHeld(cs_wallet); // setLockedCoins
4196  setLockedCoins.insert(output);
4197  std::map<uint256, CWalletTx>::iterator it = mapWallet.find(output.hash);
4198  if (it != mapWallet.end()) it->second.MarkDirty(); // recalculate all credits for this tx
4199 
4200  fAnonymizableTallyCached = false;
4201  fAnonymizableTallyCachedNonDenom = false;
4202 }
4203 
4205 {
4206  AssertLockHeld(cs_wallet); // setLockedCoins
4207  setLockedCoins.erase(output);
4208  std::map<uint256, CWalletTx>::iterator it = mapWallet.find(output.hash);
4209  if (it != mapWallet.end()) it->second.MarkDirty(); // recalculate all credits for this tx
4210 
4211  fAnonymizableTallyCached = false;
4212  fAnonymizableTallyCachedNonDenom = false;
4213 }
4214 
4216 {
4217  AssertLockHeld(cs_wallet); // setLockedCoins
4218  setLockedCoins.clear();
4219 }
4220 
4221 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
4222 {
4223  AssertLockHeld(cs_wallet); // setLockedCoins
4224  COutPoint outpt(hash, n);
4225 
4226  return (setLockedCoins.count(outpt) > 0);
4227 }
4228 
4229 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
4230 {
4231  AssertLockHeld(cs_wallet); // setLockedCoins
4232  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
4233  it != setLockedCoins.end(); it++) {
4234  COutPoint outpt = (*it);
4235  vOutpts.push_back(outpt);
4236  }
4237 }
4238  // end of Actions
4240 
4241 class CAffectedKeysVisitor : public boost::static_visitor<void> {
4242 private:
4244  std::vector<CKeyID> &vKeys;
4245 
4246 public:
4247  CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
4248 
4249  void Process(const CScript &script) {
4250  txnouttype type;
4251  std::vector<CTxDestination> vDest;
4252  int nRequired;
4253  if (ExtractDestinations(script, type, vDest, nRequired)) {
4254  BOOST_FOREACH(const CTxDestination &dest, vDest)
4255  boost::apply_visitor(*this, dest);
4256  }
4257  }
4258 
4259  void operator()(const CKeyID &keyId) {
4260  if (keystore.HaveKey(keyId))
4261  vKeys.push_back(keyId);
4262  }
4263 
4264  void operator()(const CScriptID &scriptId) {
4265  CScript script;
4266  if (keystore.GetCScript(scriptId, script))
4267  Process(script);
4268  }
4269 
4270  void operator()(const CNoDestination &none) {}
4271 };
4272 
4273 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
4274  AssertLockHeld(cs_wallet); // mapKeyMetadata
4275  mapKeyBirth.clear();
4276 
4277  // get birth times for keys with metadata
4278  for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
4279  if (it->second.nCreateTime)
4280  mapKeyBirth[it->first] = it->second.nCreateTime;
4281 
4282  // map in which we'll infer heights of other keys
4283  CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
4284  std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
4285  std::set<CKeyID> setKeys;
4286  GetKeys(setKeys);
4287  BOOST_FOREACH(const CKeyID &keyid, setKeys) {
4288  if (mapKeyBirth.count(keyid) == 0)
4289  mapKeyFirstBlock[keyid] = pindexMax;
4290  }
4291  setKeys.clear();
4292 
4293  // if there are no such keys, we're done
4294  if (mapKeyFirstBlock.empty())
4295  return;
4296 
4297  // find first block that affects those keys, if there are any left
4298  std::vector<CKeyID> vAffected;
4299  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
4300  // iterate over all wallet transactions...
4301  const CWalletTx &wtx = (*it).second;
4302  BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
4303  if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
4304  // ... which are already in a block
4305  int nHeight = blit->second->nHeight;
4306  BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
4307  // iterate over all their outputs
4308  CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
4309  BOOST_FOREACH(const CKeyID &keyid, vAffected) {
4310  // ... and all their affected keys
4311  std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
4312  if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
4313  rit->second = blit->second;
4314  }
4315  vAffected.clear();
4316  }
4317  }
4318  }
4319 
4320  // Extract block timestamps for those keys
4321  for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
4322  mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
4323 }
4324 
4325 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
4326 {
4327  if (boost::get<CNoDestination>(&dest))
4328  return false;
4329 
4330  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
4331  if (!fFileBacked)
4332  return true;
4333  return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
4334 }
4335 
4336 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
4337 {
4338  if (!mapAddressBook[dest].destdata.erase(key))
4339  return false;
4340  if (!fFileBacked)
4341  return true;
4342  return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
4343 }
4344 
4345 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
4346 {
4347  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
4348  return true;
4349 }
4350 
4351 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
4352 {
4353  std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
4354  if(i != mapAddressBook.end())
4355  {
4356  CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
4357  if(j != i->second.destdata.end())
4358  {
4359  if(value)
4360  *value = j->second;
4361  return true;
4362  }
4363  }
4364  return false;
4365 }
4366 
4368 {
4369  nTime = GetTime();
4370  fInternal = false;
4371 }
4372 
4373 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool fInternalIn)
4374 {
4375  nTime = GetTime();
4376  vchPubKey = vchPubKeyIn;
4377  fInternal = fInternalIn;
4378 }
4379 
4380 CWalletKey::CWalletKey(int64_t nExpires)
4381 {
4382  nTimeCreated = (nExpires ? GetTime() : 0);
4383  nTimeExpires = nExpires;
4384 }
4385 
4387 {
4389  CBlock blockTmp;
4390 
4391  // Update the tx's hashBlock
4392  hashBlock = block.GetHash();
4393 
4394  // Locate the transaction
4395  for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
4396  if (block.vtx[nIndex] == *(CTransaction*)this)
4397  break;
4398  if (nIndex == (int)block.vtx.size())
4399  {
4400  nIndex = -1;
4401  LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
4402  return 0;
4403  }
4404 
4405  // Is the tx in a block that's in the main chain
4406  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4407  if (mi == mapBlockIndex.end())
4408  return 0;
4409  const CBlockIndex* pindex = (*mi).second;
4410  if (!pindex || !chainActive.Contains(pindex))
4411  return 0;
4412 
4413  return chainActive.Height() - pindex->nHeight + 1;
4414 }
4415 
4416 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX) const
4417 {
4418  int nResult;
4419 
4420  if (hashUnset())
4421  nResult = 0;
4422  else {
4424 
4425  // Find the block it claims to be in
4426  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4427  if (mi == mapBlockIndex.end())
4428  nResult = 0;
4429  else {
4430  CBlockIndex* pindex = (*mi).second;
4431  if (!pindex || !chainActive.Contains(pindex))
4432  nResult = 0;
4433  else {
4434  pindexRet = pindex;
4435  nResult = ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4436 
4437  if (nResult == 0 && !mempool.exists(GetHash()))
4438  return -1; // Not in chain, not in mempool
4439  }
4440  }
4441  }
4442 
4443  if(enableIX && nResult < 6 && instantsend.IsLockedInstantSendTransaction(GetHash()))
4444  return nInstantSendDepth + nResult;
4445 
4446  return nResult;
4447 }
4448 
4450 {
4451  if (!IsCoinBase())
4452  return 0;
4453  return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4454 }
4455 
4456 
4457 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
4458 {
4459  CValidationState state;
4460  return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, false, fRejectAbsurdFee);
4461 }
VerifyResult Verify(const std::string &strFile, bool(*recoverFunc)(CDBEnv &dbenv, const std::string &strFile))
Definition: db.cpp:151
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:547
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:52
static CAmount GetMaxCollateralAmount()
Definition: privatesend.h:350
CAmount GetCredit(const isminefilter &filter) const
Definition: wallet.cpp:1824
uint32_t n
Definition: transaction.h:19
std::vector< unsigned char > vchSalt
Definition: crypter.h:37
unsigned int nChild
Definition: pubkey.h:198
CTxDestination destChange
Definition: coincontrol.h:14
static const int INSTANTSEND_CONFIRMATIONS_REQUIRED
Definition: instantx.h:28
int CountInputsWithAmount(CAmount nInputAmount)
Definition: wallet.cpp:3044
void KeepKey(int64_t nIndex)
Definition: wallet.cpp:3877
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:66
bool isAbandoned() const
Definition: wallet.h:267
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:114
bool fAllowWatchOnly
Includes watch only addresses which match the ISMINE_WATCH_SOLVABLE criteria.
Definition: coincontrol.h:20
const CWalletTx * tx
Definition: wallet.h:485
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
Definition: standard.h:69
void ReturnKey(int64_t nIndex, bool fInternal)
Definition: wallet.cpp:3889
CAmount GetAnonymizedBalance() const
Definition: wallet.cpp:2177
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:70
bool HaveKey(const CKeyID &address) const
Check whether a key corresponding to a given address is present in the store.
Definition: crypter.h:191
CAmount nAmount
Definition: wallet.h:176
bool IsFromMe(const CTransaction &tx) const
Definition: wallet.cpp:1499
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Definition: standard.cpp:164
void SetBestChain(const CBlockLocator &loc)
Definition: wallet.cpp:521
std::set< CTxDestination > GetAccountAddresses(const std::string &strAccount) const
Definition: wallet.cpp:4087
boost::signals2::signal< void(const std::string &message)> InitMessage
Definition: ui_interface.h:83
CExtPubKey extPubKey
Definition: hdchain.h:130
bool AddAccountingEntry(const CAccountingEntry &, CWalletDB &pwalletdb)
Definition: wallet.cpp:3579
void RelayTransaction(const CTransaction &tx)
Definition: net.cpp:2477
bool fSpendable
Definition: wallet.h:488
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:14
void operator()(const CKeyID &keyId)
Definition: wallet.cpp:4259
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3683
char fFromMe
Definition: wallet.h:286
std::set< uint256 > GetConflicts(const uint256 &txid) const
Get wallet transactions that conflict with given transaction (spend same outputs) ...
Definition: wallet.cpp:566
std::vector< CTxIn > vecTxIn
Definition: wallet.h:115
int GetRandInt(int nMax)
Definition: random.cpp:109
bool fSubtractFeeFromAmount
Definition: wallet.h:177
void operator()(const CScriptID &scriptId)
Definition: wallet.cpp:4264
uint32_t nChangeIndex
Definition: hdchain.h:133
CWalletKey(int64_t nExpires=0)
Definition: wallet.cpp:4380
bool IsSelected(const COutPoint &output) const
Definition: coincontrol.h:45
bool SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector< CTxIn > &vecTxInRet, CAmount &nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax) const
Definition: wallet.cpp:2930
bool GetCollateralTxIn(CTxIn &txinRet, CAmount &nValueRet) const
Definition: wallet.cpp:2967
bool SelectCoinsMinConf(const CAmount &nTargetValue, int nConfMine, int nConfTheirs, std::vector< COutput > vCoins, std::set< std::pair< const CWalletTx *, unsigned int > > &setCoinsRet, CAmount &nValueRet, bool fUseInstantSend=false) const
Definition: wallet.cpp:2498
void ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fInternal)
Definition: wallet.cpp:3841
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext)
Definition: crypter.cpp:50
bool IsHDEnabled()
Definition: wallet.cpp:1485
void GenerateNewHDChain()
Definition: wallet.cpp:1392
#define strprintf
Definition: tinyformat.h:1011
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:1152
static void NotifyTransactionChanged(TransactionTableModel *ttm, CWallet *wallet, const uint256 &hash, ChangeType status)
static const int SPORK_5_INSTANTSEND_MAX_VALUE
Definition: spork.h:24
bool operator()(const pair< CAmount, pair< const CWalletTx *, unsigned int > > &t1, const pair< CAmount, pair< const CWalletTx *, unsigned int > > &t2) const
Definition: wallet.cpp:72
double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const
bool IsNull() const
Definition: hdchain.cpp:27
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:458
int nIndex
Definition: wallet.h:223
CAmount GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.cpp:1857
bool bSpendZeroConfChange
Definition: wallet.cpp:48
void RandAddSeedPerfmon()
Definition: random.cpp:46
WalletFeature
Definition: wallet.h:89
CFeeRate estimateSmartFee(int nBlocks, int *answerFoundAtBlocks=NULL) const
Definition: txmempool.cpp:883
static const CAmount COIN
Definition: amount.h:16
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:4325
#define DBG(x)
Definition: util.h:41
CAmount nAmount
Definition: wallet.h:114
CAmount maxTxFee
Definition: wallet.cpp:46
bool AddToWallet(const CWalletTx &wtxIn, bool fFromLoadWallet, CWalletDB *pwalletdb)
Definition: wallet.cpp:880
CAmount GetUnconfirmedBalance() const
Definition: wallet.cpp:2286
int64_t IncOrderPosNext(CWalletDB *pwalletdb=NULL)
Definition: wallet.cpp:856
bool GetOutpointAndKeysFromOutput(const COutput &out, COutPoint &outpointRet, CPubKey &pubKeyRet, CKey &keyRet)
Extract txin information and keys from output.
Definition: wallet.cpp:3015
std::multimap< int64_t, TxPair > TxItems
Definition: wallet.h:742
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1066
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:31
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
Add a key to the store.
Definition: crypter.cpp:302
bool HasSelected() const
Definition: coincontrol.h:40
double estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks=NULL) const
Definition: txmempool.cpp:893
CCriticalSection cs_main
Definition: validation.cpp:62
bool SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector< CTxIn > &vecTxInRet, std::vector< COutput > &vCoinsRet, CAmount &nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax)
Definition: wallet.cpp:2762
isminetype IsMine(const CKeyStore &keystore, const CTxDestination &dest)
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:344
bool fReindex
Definition: validation.cpp:71
bool WriteHDPubKey(const CHDPubKey &hdPubKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:1182
bool IsSpent(const uint256 &hash, unsigned int n) const
Definition: wallet.cpp:682
bool operator()(const COutput &t1, const COutput &t2) const
Definition: wallet.cpp:2720
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
CAmount nValue
Definition: transaction.h:136
bool VerifyPubKey(const CPubKey &vchPubKey) const
Definition: key.cpp:184
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:61
SecureVector GetSeed() const
Definition: hdchain.cpp:141
CAmount GetImmatureWatchOnlyCredit(const bool &fUseCache=true) const
Definition: wallet.cpp:1901
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Definition: standard.cpp:270
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: keystore.h:116
static const int COINBASE_MATURITY
Definition: consensus.h:23
bool Unlock(const SecureString &strWalletPassphrase, bool fForMixingOnly=false)
Definition: wallet.cpp:404
Definition: pubkey.h:27
mapValue_t mapValue
Definition: wallet.h:281
CAmount GetImmatureWatchOnlyBalance() const
Definition: wallet.cpp:2346
std::string ToString() const
Definition: wallet.cpp:79
DBErrors ZapWalletTx(CWallet *pwallet, std::vector< CWalletTx > &vWtx)
Definition: walletdb.cpp:825
static const uint256 ABANDON_HASH
Definition: wallet.h:213
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:17
Definition: net.h:108
int64_t nCreateTime
Definition: walletdb.h:49
static CAmount GetCollateralAmount()
Definition: privatesend.h:349
void UnlockAllCoins()
Definition: wallet.cpp:4215
void Select(const COutPoint &output)
Definition: coincontrol.h:50
bool GetDecryptedHDChain(CHDChain &hdChainRet)
Definition: wallet.cpp:1464
int GetRealOutpointPrivateSendRounds(const COutPoint &outpoint, int nRounds) const
Definition: wallet.cpp:1242
bool HasCollateralInputs(bool fOnlyConfirmed=true) const
Definition: wallet.cpp:3072
CAmount GetAvailableCredit(bool fUseCache=true) const
Definition: wallet.cpp:1871
bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true)
Definition: wallet.cpp:4457
virtual bool AddWatchOnly(const CScript &dest)
Support for Watch-only addresses.
Definition: keystore.cpp:85
uint256 hdchainID
Definition: hdchain.h:131
static CAmount GetSmallestDenomination()
Definition: privatesend.h:329
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, vector< CTxDestination > &addressRet, int &nRequiredRet)
Definition: standard.cpp:194
uint32_t nInternalChainCounter
Definition: hdchain.h:14
const CWalletTx * GetWalletTx(const uint256 &hash) const
Definition: wallet.cpp:94
std::vector< CTxIn > vin
Definition: transaction.h:306
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee, bool fDryRun)
bool IsHex(const string &str)
bool IsLockedCoin(uint256 hash, unsigned int n) const
Definition: wallet.cpp:4221
std::set< uint256 > GetConflicts() const
Definition: wallet.cpp:1781
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
Definition: wallet.cpp:589
CAmount GetChange(const CTxOut &txout) const
Definition: wallet.cpp:1385
CAmount GetFee(size_t size) const
Definition: amount.cpp:20
std::string name
Definition: wallet.h:161
bool GetKey(const CKeyID &address, CKey &keyOut) const
Definition: crypter.cpp:336
uint160 Hash160(const T1 pbegin, const T1 pend)
Definition: hash.h:214
std::pair< CWalletTx *, CAccountingEntry * > TxPair
Definition: wallet.h:741
bool AddToWalletIfInvolvingMe(const CTransaction &tx, const CBlock *pblock, bool fUpdate)
Definition: wallet.cpp:1028
bool CommitTransaction(CWalletTx &wtxNew, CReserveKey &reservekey, CConnman *connman, std::string strCommand="tx")
Definition: wallet.cpp:3527
CAmount GetNeedsToBeAnonymizedBalance(CAmount nMinBalance=0) const
Definition: wallet.cpp:2244
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:22
DBErrors
Definition: walletdb.h:34
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:87
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:3779
unsigned char * begin()
Definition: uint256.h:55
static const unsigned int DEFAULT_KEYPOOL_SIZE
Definition: wallet.h:45
CAmount GetAnonymizableBalance(bool fSkipDenominated=false, bool fSkipUnconfirmed=true) const
Definition: wallet.cpp:2155
static uint32_t insecure_rand(void)
Definition: random.h:42
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const =0
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
GetPubKey implementation that also checks the mapHdPubKeys.
Definition: wallet.cpp:202
bool SetHDChain(const CHDChain &chain)
Definition: crypter.cpp:501
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:145
int SetMerkleBranch(const CBlock &block)
Definition: wallet.cpp:4386
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:144
bool IsNull() const
Definition: uint256.h:33
bool LoadCScript(const CScript &redeemScript)
Definition: wallet.cpp:358
static int64_t GetOldestKeyInPool(const std::set< int64_t > &setKeyPool, CWalletDB &walletdb)
Definition: wallet.cpp:3923
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:3703
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
Definition: crypter.cpp:354
static void LoadReserveKeysToSet(std::set< CKeyID > &setAddress, const std::set< int64_t > &setKeyPool, CWalletDB &walletdb)
Definition: wallet.cpp:4138
virtual bool RemoveWatchOnly(const CScript &dest)
Definition: keystore.cpp:95
CPrivKey GetPrivKey() const
Definition: key.cpp:143
static void ApproximateBestSubset(vector< pair< CAmount, pair< const CWalletTx *, unsigned int > > >vValue, const CAmount &nTotalLower, const CAmount &nTargetValue, vector< char > &vfBest, CAmount &nBest, int iterations=1000, bool fUseInstantSend=false)
Definition: wallet.cpp:2423
unsigned int nTimeReceived
Definition: wallet.h:284
CAmount GetChange() const
Definition: wallet.cpp:2023
void DeriveNewChildKey(const CKeyMetadata &metadata, CKey &secretRet, uint32_t nAccountIndex, bool fInternal)
Definition: wallet.cpp:140
void DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_t nChildIndex, CExtKey &extKeyRet)
Definition: hdchain.cpp:151
std::vector< CTransaction > vtx
Definition: block.h:77
CAmount GetWatchOnlyBalance() const
Definition: wallet.cpp:2315
std::string ToString() const
Definition: base58.cpp:193
void ListSelected(std::vector< COutPoint > &vOutpoints) const
Definition: coincontrol.h:65
AvailableCoinsType
Definition: wallet.h:101
CAmount GetDenominatedCredit(bool unconfirmed, bool fUseCache=true) const
Definition: wallet.cpp:1978
bool AddCScript(const CScript &redeemScript)
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: wallet.cpp:349
CDBEnv bitdb
Definition: db.cpp:34
bool GetKey(const CKeyID &address, CKey &keyOut) const
GetKey implementation that can derive a HD private key on the fly.
Definition: wallet.cpp:216
bool fMasterNode
Definition: util.cpp:108
bool GetAccount(uint32_t nAccountIndex, CHDAccount &hdAccountRet)
Definition: hdchain.cpp:184
bool Contains(const CBlockIndex *pindex) const
Definition: chain.h:384
bool SelectCoins(const CAmount &nTargetValue, std::set< std::pair< const CWalletTx *, unsigned int > > &setCoinsRet, CAmount &nValueRet, const CCoinControl *coinControl=NULL, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=true) const
Definition: wallet.cpp:2623
CScript scriptSig
Definition: transaction.h:62
static const CAmount MIN_CHANGE
minimum change amount
Definition: wallet.h:64
bool UpdatedTransaction(const uint256 &hashTx)
Definition: wallet.cpp:4168
int64_t CAmount
Definition: amount.h:14
bool SetMinVersion(enum WalletFeature, CWalletDB *pwalletdbIn=NULL, bool fExplicit=false)
signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVe...
Definition: wallet.cpp:527
static bool Rewrite(const std::string &strFile, const char *pszSkip=NULL)
Definition: db.cpp:340
bool exists(uint256 hash) const
Definition: txmempool.h:563
bool IsChange(const CTxOut &txout) const
Definition: wallet.cpp:1363
uint32_t nAccountIndex
Definition: hdchain.h:132
CPubKey GenerateNewKey(uint32_t nAccountIndex, bool fInternal)
Definition: wallet.cpp:103
#define AssertLockHeld(cs)
Definition: sync.h:96
bool IsUnspendable() const
Definition: script.h:634
bool fLiteMode
Definition: util.cpp:109
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:648
#define LOCK2(cs1, cs2)
Definition: sync.h:169
static CFeeRate minTxFee
Definition: wallet.h:909
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:3657
CAmount GetBalance() const
Definition: wallet.cpp:2139
CKey key
Definition: key.h:159
unsigned int nTxConfirmTarget
Definition: wallet.cpp:47
bool fSendFreeTransactions
Definition: wallet.cpp:49
int nDepth
Definition: wallet.h:487
int nWalletBackups
Definition: util.cpp:117
size_t KeypoolCountInternalKeys()
Definition: wallet.cpp:3773
bool GetKeyFromPool(CPubKey &key, bool fInternal)
Definition: wallet.cpp:3903
CCriticalSection cs
Definition: txmempool.h:402
bool GetBoolArg(const std::string &strArg, bool fDefault)
Definition: util.cpp:455
#define LogPrintf(...)
Definition: util.h:98
bool CreateTransaction(const std::vector< CRecipient > &vecSend, CWalletTx &wtxNew, CReserveKey &reservekey, CAmount &nFeeRet, int &nChangePosRet, std::string &strFailReason, const CCoinControl *coinControl=NULL, bool sign=true, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false)
Definition: wallet.cpp:3173
bool CheckFinalTx(const CTransaction &tx, int flags)
Definition: validation.cpp:213
bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
Definition: wallet.cpp:334
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:3933
boost::signals2::signal< void(CWallet *wallet)> LoadWallet
Definition: ui_interface.h:101
COutPoint prevout
Definition: transaction.h:61
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:162
bool hashUnset() const
Definition: wallet.h:266
CExtPubKey Neuter() const
Definition: key.cpp:268
bool WriteCryptedHDChain(const CHDChain &chain)
Definition: walletdb.cpp:1170
unsigned int GetSerializeSize(char a, int, int=0)
Definition: serialize.h:202
bool AddWatchOnly(const CScript &dest)
Adds a watch-only address to the store, and saves it to disk.
Definition: wallet.cpp:374
bool SetHDChain(const CHDChain &chain, bool memonly)
Definition: wallet.cpp:1429
CFeeRate minRelayTxFee
Definition: validation.cpp:94
void UnlockCoin(COutPoint &output)
Definition: wallet.cpp:4204
bool RemoveWatchOnly(const CScript &dest)
Definition: wallet.cpp:385
static int LogPrint(const char *category, const char *format)
Definition: util.h:126
CAmount GetUnconfirmedWatchOnlyBalance() const
Definition: wallet.cpp:2331
#define LOCK(cs)
Definition: sync.h:168
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:132
static bool Recover(CDBEnv &dbenv, const std::string &filename, bool fOnlyKeys)
Definition: walletdb.cpp:1066
static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE
Largest (in bytes) free transaction we&#39;re willing to create.
Definition: wallet.h:74
bool WriteTx(uint256 hash, const CWalletTx &wtx)
Definition: walletdb.cpp:58
int64_t GetTxTime() const
Definition: wallet.cpp:1540
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:18
CAmount nMinimumTotalFee
Minimum absolute fee (not per kilobyte)
Definition: coincontrol.h:22
CAmount GetCredit(const CTxOut &txout, const isminefilter &filter) const
Definition: wallet.cpp:1356
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:554
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:108
unsigned int nDeriveIterations
Definition: crypter.h:41
bool HaveKey(const CKeyID &address) const
HaveKey implementation that also checks the mapHdPubKeys.
Definition: wallet.cpp:244
std::vector< unsigned char, secure_allocator< unsigned char > > SecureVector
Definition: secure.h:63
uint256 uint256S(const char *str)
Definition: uint256.h:140
bool Open(const boost::filesystem::path &path)
Definition: db.cpp:74
uint32_t nExternalChainCounter
Definition: hdchain.h:13
CClientUIInterface uiInterface
Definition: init.cpp:130
float GetAverageAnonymizedRounds() const
Definition: wallet.cpp:2202
static CFeeRate fallbackFee
Definition: wallet.h:910
virtual bool AddCScript(const CScript &redeemScript)
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:41
int Height() const
Definition: chain.h:397
void Process(const CScript &script)
Definition: wallet.cpp:4249
unsigned int nTimeSmart
time received by this node
Definition: wallet.h:285
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:4351
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:32
std::vector< uint256 > ResendWalletTransactionsBefore(int64_t nTime, CConnman *connman)
Definition: wallet.cpp:2081
bool ConvertList(std::vector< CTxIn > vecTxIn, std::vector< CAmount > &vecAmounts)
Definition: wallet.cpp:3158
static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool &pool)
Definition: wallet.cpp:3596
CInstantSend instantsend
Definition: instantx.cpp:30
static const CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:62
vector< unsigned char > ParseHex(const char *psz)
void GetAllReserveKeys(std::set< CKeyID > &setAddress) const
Definition: wallet.cpp:4151
bool AllowFree(double dPriority)
Definition: txmempool.h:31
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:70
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:1793
bool NewKeyPool()
Definition: wallet.cpp:3743
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:282
bool IsLockedInstantSendTransaction(const uint256 &txHash)
Definition: instantx.cpp:770
static const CAmount DEFAULT_LEGACY_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:59
CChain chainActive
Definition: validation.cpp:65
static const bool DEFAULT_SEND_FREE_TRANSACTIONS
Default for -sendfreetransactions.
Definition: wallet.h:68
std::string ToString() const
Definition: uint256.cpp:65
bool SetCryptedHDChain(const CHDChain &chain, bool memonly)
Definition: wallet.cpp:1442
static bool GetDenominationsBits(int nDenom, std::vector< int > &vecBitsRet)
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:262
static const CAmount DEFAULT_LEGACY_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:51
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector< CKeyID > &vKeysIn)
Definition: wallet.cpp:4247
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, std::string &strSentAccount, const isminefilter &filter) const
Definition: wallet.cpp:1585
void KeepKey()
Definition: wallet.cpp:4120
uint8_t isminefilter
Definition: wallet_ismine.h:29
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Definition: wallet.cpp:1225
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:4345
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: wallet.cpp:2072
std::string FormatMoney(const CAmount &n)
bool IsDenominatedAmount(CAmount nInputAmount) const
Definition: wallet.cpp:1343
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:36
CScript scriptPubKey
Definition: transaction.h:137
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:168
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid)
Definition: wallet.cpp:701
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:174
void MarkDirty()
Definition: wallet.cpp:868
double GuessVerificationProgress(const CCheckpointData &data, CBlockIndex *pindex, bool fSigchecks)
Guess how far we are in the verification process at the given block index.
Definition: checkpoints.cpp:30
void MarkConflicted(const uint256 &hashBlock, const uint256 &hashTx)
Definition: wallet.cpp:1127
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:3616
bool CreateCollateralTransaction(CMutableTransaction &txCollateral, std::string &strReason)
Definition: wallet.cpp:3088
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:80
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext)
Definition: crypter.cpp:81
std::vector< CTxOut > vout
Definition: transaction.h:307
int64_t nOrderPos
Definition: wallet.h:288
bool EraseDestData(const CTxDestination &dest, const std::string &key)
Erases a destination data tuple in the store and on disk.
Definition: wallet.cpp:4336
bool SelectCoinsGrouppedByAddresses(std::vector< CompactTallyItem > &vecTallyRet, bool fSkipDenominated=true, bool fAnonymizable=true, bool fSkipUnconfirmed=true) const
Definition: wallet.cpp:2831
int nInstantSendDepth
Definition: instantx.cpp:27
static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)
CSporkManager sporkManager
Definition: spork.cpp:14
std::string strFromAccount
Definition: wallet.h:287
size_t KeypoolCountExternalKeys()
Definition: wallet.cpp:3767
bool AddHDPubKey(const CExtPubKey &extPubKey, bool fInternal)
Adds a HDPubKey into the wallet(database)
Definition: wallet.cpp:260
void ReturnKey()
Definition: wallet.cpp:4129
void seed_insecure_rand(bool fDeterministic)
Definition: random.cpp:123
txnouttype
Definition: standard.h:45
CPrivateSendClient privateSendClient
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:15
bool GetReservedKey(CPubKey &pubkey, bool fInternalIn)
Definition: wallet.cpp:4101
unsigned int nDerivationMethod
Definition: crypter.h:40
const std::vector< CTxIn > vin
Definition: transaction.h:233
const char * TXLOCKREQUEST
Definition: protocol.cpp:39
int ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate=false)
Definition: wallet.cpp:1687
CPubKey pubkey
Definition: pubkey.h:200
static vector< COutput > vCoins
bool IsCollateralAmount(CAmount nInputAmount) const
Definition: wallet.cpp:3080
bool IsDust(const CFeeRate &minRelayTxFee) const
Definition: transaction.h:185
void Flush(bool fShutdown)
Definition: db.cpp:424
CTxMemPool mempool
int GetOutpointPrivateSendRounds(const COutPoint &outpoint) const
Definition: wallet.cpp:1321
std::vector< CKeyID > & vKeys
Definition: wallet.cpp:4244
bool GetBudgetSystemCollateralTX(CTransaction &tx, uint256 hash, CAmount amount, bool fUseInstantSend)
Definition: wallet.cpp:3123
bool WriteAccountingEntry_Backend(const CAccountingEntry &acentry)
Definition: walletdb.cpp:195
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:723
uint256 GetID() const
Definition: hdchain.h:111
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1210
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:418
void GetScriptForMining(boost::shared_ptr< CReserveScript > &script)
Definition: wallet.cpp:4182
static bool Verify(const std::string &walletFile, std::string &warningString, std::string &errorString)
Verify the wallet database and perform salvage if required.
Definition: wallet.cpp:594
static std::vector< CAmount > GetStandardDenominations()
Definition: privatesend.h:328
CBlockIndex * Next(const CBlockIndex *pindex) const
Definition: chain.h:389
const CChainParams & Params()
void updatePassphrase(const SecureString &sWalletPassphrase)
Definition: keepass.cpp:613
CKeePassIntegrator keePassInt
Definition: keepass.cpp:35
void ResendWalletTransactions(int64_t nBestBlockTime, CConnman *connman)
Definition: wallet.cpp:2105
static CAmount GetMaxPoolAmount()
Definition: privatesend.h:345
bool Unlock(const CKeyingMaterial &vMasterKeyIn, bool fForMixingOnly=false)
Definition: crypter.cpp:248
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:38
CAmount GetDenominatedBalance(bool unconfirmed=false) const
Definition: wallet.cpp:2268
CTxDestination txdest
Definition: wallet.h:113
static const int PROTOCOL_VERSION
Definition: version.h:13
int64_t GetTimeMillis()
Definition: utiltime.cpp:34
const uint256 & GetHash() const
Definition: transaction.h:262
CAmount GetMinFee() const
Definition: instantx.cpp:984
const CKeyStore & keystore
Definition: wallet.cpp:4243
bool ProcessTxLockRequest(const CTxLockRequest &txLockRequest, CConnman &connman)
Definition: instantx.cpp:80
int64_t GetAdjustedTime()
Definition: timedata.cpp:33
void runCommand(const std::string &strCommand)
Definition: util.cpp:866
void GetAccountAmounts(const std::string &strAccount, CAmount &nReceived, CAmount &nSent, CAmount &nFee, const isminefilter &filter) const
Definition: wallet.cpp:1641
bool IsTrusted() const
Definition: wallet.cpp:2041
bool fImporting
Definition: validation.cpp:70
std::string ToString() const
bool operator()(const CompactTallyItem &t1, const CompactTallyItem &t2) const
Definition: wallet.cpp:2824
bool IsCoinBase() const
Definition: transaction.h:284
void ReacceptWalletTransactions()
Definition: wallet.cpp:1728
virtual bool HaveKey(const CKeyID &address) const =0
Check whether a key corresponding to a given address is present in the store.
int i
Definition: wallet.h:486
std::string GetHex() const
Definition: uint256.cpp:21
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:157
bool LogAcceptCategory(const char *category)
Definition: util.cpp:247
std::map< CTxDestination, CAmount > GetAddressBalances()
Definition: wallet.cpp:3954
Indicates that we know how to create a scriptSig that would solve this if we were given the appropria...
Definition: wallet_ismine.h:23
CPubKey GetPubKey() const
Definition: key.cpp:156
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:283
void operator()(const CNoDestination &none)
Definition: wallet.cpp:4270
const std::vector< CTxOut > vout
Definition: transaction.h:234
void GetRandBytes(unsigned char *buf, int num)
Definition: random.cpp:86
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
CScript scriptPubKey
Definition: wallet.h:175
virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Definition: crypter.cpp:324
bool GetKeyID(CKeyID &keyID) const
Definition: base58.cpp:291
bool FundTransaction(CMutableTransaction &tx, CAmount &nFeeRet, int &nChangePosRet, std::string &strFailReason, bool includeWatching)
Definition: wallet.cpp:2727
bool ProduceSignature(const BaseSignatureCreator &creator, const CScript &fromPubKey, CScript &scriptSig)
Definition: sign.cpp:104
CBlockIndex * Tip() const
Definition: chain.h:366
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:447
bool IsDenominated(const COutPoint &outpoint) const
Definition: wallet.cpp:1328
bool WriteWatchOnly(const CScript &script)
Definition: walletdb.cpp:120
bool GetMasternodeOutpointAndKeys(COutPoint &outpointRet, CPubKey &pubKeyRet, CKey &keyRet, std::string strTxHash="", std::string strOutputIndex="")
Get 1000DASH output and keys which can be used for the Masternode.
Definition: wallet.cpp:2987
Definition: pubkey.h:37
SecureString retrievePassphrase()
Definition: keepass.cpp:579
size_type size() const
Definition: prevector.h:262
CTxDestination destination
Definition: wallet.h:203
static CAmount GetRequiredFee(unsigned int nTxBytes)
Definition: wallet.cpp:3591
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
Definition: wallet.cpp:399
static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly)
int64_t GetBlockTime() const
Definition: chain.h:223
bool WriteToDisk(CWalletDB *pwalletdb)
Definition: wallet.cpp:1677
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Definition: util.cpp:441
static const CAmount DEFAULT_TRANSACTION_FEE
-paytxfee default
Definition: wallet.h:47
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:1158
int Priority() const
Definition: wallet.cpp:84
CAmount amount
Definition: wallet.h:204
CKeyPool()
Definition: wallet.cpp:4367
bool LoadHDPubKey(const CHDPubKey &hdPubKey)
loads a HDPubKey into the wallets memory
Definition: wallet.cpp:252
int64_t GetTime()
For unit testing.
Definition: utiltime.cpp:20
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:32
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
Definition: wallet.cpp:313
isminetype
Definition: wallet_ismine.h:17
VerifyResult
Definition: db.h:58
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
void LockCoin(COutPoint &output)
Definition: wallet.cpp:4193
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:434
bool SetMnemonic(const SecureVector &vchMnemonic, const SecureVector &vchMnemonicPassphrase, bool fUpdateID)
Definition: hdchain.cpp:72
int64_t GetSporkValue(int nSporkID)
Definition: spork.cpp:148
bool SetAccount(uint32_t nAccountIndex, const CHDAccount &hdAccount)
Definition: hdchain.cpp:193
int64_t nTime
Definition: wallet.h:540
bool SetSeed(const SecureVector &vchSeedIn, bool fUpdateID)
Definition: hdchain.cpp:130
Definition: block.h:73
bool SetCryptedHDChain(const CHDChain &chain)
Definition: crypter.cpp:513
void ListLockedCoins(std::vector< COutPoint > &vOutpts)
Definition: wallet.cpp:4229
int64_t nOrderPos
Definition: wallet.h:544
uint256 GetHash() const
Definition: block.cpp:13
Definition: key.h:35
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:113
CAmount GetImmatureBalance() const
Definition: wallet.cpp:2301
#define PAIRTYPE(t1, t2)
bool SignSignature(const CKeyStore &keystore, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, int nHashType)
Definition: sign.cpp:129
uint256 hash
Definition: transaction.h:18
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >)
Definition: wallet.cpp:641
int GetBlocksToMaturity() const
Definition: wallet.cpp:4449
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:46
int GetDepthInMainChain(const CBlockIndex *&pindexRet, bool enableIX=true) const
Definition: wallet.cpp:4416
BlockMap mapBlockIndex
Definition: validation.cpp:64
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:126
bool less_then_denom(const COutput &out1, const COutput &out2)
Definition: wallet.cpp:2483
uint256 hashBlock
Definition: wallet.h:216
bool RelayWalletTransaction(CConnman *connman, std::string strCommand="tx")
Definition: wallet.cpp:1760
CAmount GetAnonymizedCredit(bool fUseCache=true) const
Definition: wallet.cpp:1944
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const
Definition: wallet.cpp:4273
Definition: key.h:154
bool SetDefaultKey(const CPubKey &vchPubKey)
Definition: wallet.cpp:3728
bool InMempool() const
Definition: wallet.cpp:2032
std::string _(const char *psz)
Definition: util.h:84
CAmount GetNormalizedAnonymizedBalance() const
Definition: wallet.cpp:2224
CScript prevPubKey
Definition: transaction.h:64
int atoi(const std::string &str)
CAmount GetDustThreshold(const CFeeRate &minRelayTxFee) const
Definition: transaction.h:169
map< string, string > mapArgs
Definition: util.cpp:122
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, and saves it to disk.
Definition: wallet.cpp:288
CAmount GetAvailableWatchOnlyCredit(const bool &fUseCache=true) const
Definition: wallet.cpp:1915
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:94
std::set< std::set< CTxDestination > > GetAddressGroupings()
Definition: wallet.cpp:3994
result
Definition: rpcuser.py:37
int GetRequestCount() const
Definition: wallet.cpp:1546
void SyncTransaction(const CTransaction &tx, const CBlock *pblock)
Definition: wallet.cpp:1189
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:35
void Debug(std::string strName) const
Definition: hdchain.cpp:42
uint256 GetSeedHash()
Definition: hdchain.cpp:146
void AvailableCoins(std::vector< COutput > &vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL, bool fIncludeZeroValue=false, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false) const
Definition: wallet.cpp:2360
static const unsigned int MAX_STANDARD_TX_SIZE
Definition: policy.h:23