PRCYCoin  2.0.0.7rc1
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2014-2015 The Dash developers
4 // Copyright (c) 2015-2018 The PIVX developers
5 // Copyright (c) 2018-2020 The DAPS Project developers
6 // Distributed under the MIT software license, see the accompanying
7 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 
9 #include "wallet/wallet.h"
10 
11 #include "amount.h"
12 #include "base58.h"
13 #include "checkpoints.h"
14 #include "coincontrol.h"
15 #include "guiinterfaceutil.h"
16 #include "kernel.h"
17 #include "invalid.h"
18 #include "masternode-budget.h"
19 #include "masternode-payments.h"
20 #include "masternode-sync.h"
21 #include "net.h"
22 #include "primitives/transaction.h"
23 #include "script/script.h"
24 #include "script/sign.h"
25 #include "stakeinput.h"
26 #include "swifttx.h"
27 #include "timedata.h"
28 #include "util.h"
29 #include "utilmoneystr.h"
30 
31 #include "secp256k1.h"
32 #include <assert.h>
33 #include <boost/algorithm/string.hpp>
34 
35 #include "ecdhutil.h"
36 #include "secp256k1_bulletproofs.h"
37 #include "secp256k1_commitment.h"
38 #include "secp256k1_generator.h"
39 #include "txdb.h"
40 #include <boost/algorithm/string/replace.hpp>
41 #include <boost/thread.hpp>
42 #include <boost/date_time/posix_time/posix_time.hpp>
43 #include "masternodeconfig.h"
44 
45 #ifdef __linux__ //linux only
46 #include <malloc.h>
47 #endif
48 
49 CWallet* pwalletMain = nullptr;
51 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
52 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
53 unsigned int nTxConfirmTarget = 1;
55 bool bdisableSystemnotifications = false; // Those bubbles can be annoying and slow down the UI when you get lots of trx
56 bool fSendFreeTransactions = false;
58 int64_t nStartupTime = GetTime();
59 int64_t nReserveBalance = 0;
60 bool fTxDeleteEnabled = false;
62 int fDeleteInterval = DEFAULT_TX_DELETE_INTERVAL;
63 unsigned int fDeleteTransactionsAfterNBlocks = DEFAULT_TX_RETENTION_BLOCKS;
64 unsigned int fKeepLastNTransactions = DEFAULT_TX_RETENTION_LASTTX;
65 
66 #include "uint256.h"
67 
68 //Elliptic Curve Diffie Helman: encodes and decodes the amount b and mask a
69 void ecdhEncode(unsigned char* unmasked, unsigned char* amount, const unsigned char* sharedSec, int size)
70 {
71  uint256 sharedSec1 = Hash(sharedSec, sharedSec + size);
72  uint256 sharedSec2 = Hash(sharedSec1.begin(), sharedSec1.end());
73 
74  for (int i = 0; i < 32; i++) {
75  unmasked[i] ^= *(sharedSec1.begin() + i);
76  }
77  unsigned char temp[32];
78  memcpy(temp, amount, 32);
79  for (int i = 0; i < 32; i++) {
80  amount[i] = temp[i % 8] ^ *(sharedSec2.begin() + i);
81  }
82 }
83 void ecdhDecode(unsigned char* masked, unsigned char* amount, const unsigned char* sharedSec, int size)
84 {
85  uint256 sharedSec1 = Hash(sharedSec, sharedSec + size);
86  uint256 sharedSec2 = Hash(sharedSec1.begin(), sharedSec1.end());
87 
88  for (int i = 0; i < 32; i++) {
89  masked[i] ^= *(sharedSec1.begin() + i);
90  }
91 
92  unsigned char temp[32];
93  memcpy(temp, amount, 32);
94  memset(amount, 0, 8);
95  for (int i = 0; i < 32; i++) {
96  amount[i] = temp[i % 8] ^ *(sharedSec2.begin() + i);
97  }
98 }
99 
100 static std::string ValueFromAmountToString(const CAmount &amount) {
101  bool sign = amount < 0;
102  int64_t n_abs = (sign ? -amount : amount);
103  int64_t quotient = n_abs / COIN;
104  int64_t remainder = n_abs % COIN;
105  std::string ret(strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder));
106  return ret;
107 }
108 
109 void ECDHInfo::ComputeSharedSec(const CKey& priv, const CPubKey& pubKey, CPubKey& sharedSec)
110 {
111  sharedSec.Set(pubKey.begin(), pubKey.end());
112  unsigned char temp[65];
113  memcpy(temp, sharedSec.begin(), sharedSec.size());
114  if (!secp256k1_ec_pubkey_tweak_mul(temp, sharedSec.size(), priv.begin()))
115  throw std::runtime_error("Cannot compute EC multiplication: secp256k1_ec_pubkey_tweak_mul");
116  sharedSec.Set(temp, temp + 33);
117 }
118 
119 void ECDHInfo::Encode(const CKey& mask, const CAmount& amount, const CPubKey& sharedSec, uint256& encodedMask, uint256& encodedAmount)
120 {
121  memcpy(encodedMask.begin(), mask.begin(), 32);
122  memcpy(encodedAmount.begin(), &amount, 32);
123  ecdhEncode(encodedMask.begin(), encodedAmount.begin(), sharedSec.begin(), sharedSec.size());
124 }
125 
126 void ECDHInfo::Decode(unsigned char* encodedMask, unsigned char* encodedAmount, const CPubKey& sharedSec, CKey& decodedMask, CAmount& decodedAmount)
127 {
128  unsigned char tempAmount[32], tempDecoded[32];
129  memcpy(tempDecoded, encodedMask, 32);
130  decodedMask.Set(tempDecoded, tempDecoded + 32, 32);
131  memcpy(tempAmount, encodedAmount, 32);
132  memcpy(tempDecoded, decodedMask.begin(), 32);
133  ecdhDecode(tempDecoded, tempAmount, sharedSec.begin(), sharedSec.size());
134  memcpy(&decodedAmount, tempAmount, 8);
135 
136  decodedMask.Set(tempDecoded, tempDecoded + 32, true);
137  memcpy(&decodedAmount, tempAmount, 8);
138 }
139 
140 
148 
155  bool operator()(const std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> >& t1,
156  const std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> >& t2) const
157  {
158  return t1.first < t2.first;
159  }
160 };
161 
162 std::string COutput::ToString() const
163 {
164  return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
165 }
166 
167 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
168 {
169  LOCK(cs_wallet);
170  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
171  if (it == mapWallet.end())
172  return NULL;
173  return &(it->second);
174 }
175 
176 std::vector<CWalletTx> CWallet::getWalletTxs()
177 {
178  LOCK(cs_wallet);
179  std::vector<CWalletTx> result;
180  result.reserve(mapWallet.size());
181  for (const auto& entry : mapWallet) {
182  result.emplace_back(entry.second);
183  }
184  return result;
185 }
186 
187 bool CWallet::checkPassPhraseRule(const char* pass)
188 {
189  bool upper = false;
190  bool lower = false;
191  bool digit = false;
192  bool symbol = false;
193  std::string passphrase(pass);
194  for (int i = 0; i < passphrase.size(); i++) {
195  if (isupper(passphrase[i])) {
196  upper = true;
197  continue;
198  } else if (islower(passphrase[i])) {
199  lower = true;
200  continue;
201  } else if (isdigit(passphrase[i])) {
202  digit = true;
203  continue;
204  } else if (!symbol) {
205  symbol = true;
206  continue;
207  }
208 
209  if (upper && lower && digit && symbol)
210  break;
211  }
212 
213  return upper && lower && digit && symbol;
214 }
216 {
217  AssertLockHeld(cs_wallet); // mapKeyMetadata
218  bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
219 
220  CKey secret;
221  secret.MakeNewKey(fCompressed);
222 
223  // Compressed public keys were introduced in version 0.6.0
224  if (fCompressed)
226  CPubKey pubkey = secret.GetPubKey();
227  assert(secret.VerifyPubKey(pubkey));
228 
229  // Create new metadata
230  int64_t nCreationTime = GetTime();
231  mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
232  if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
233  nTimeFirstKey = nCreationTime;
234 
235  if (!AddKeyPubKey(secret, pubkey))
236  throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
237  return pubkey;
238 }
239 
240 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey)
241 {
242  AssertLockHeld(cs_wallet); // mapKeyMetadata
243  if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
244  return false;
245 
246  // check if we need to remove from watch-only
247  CScript script;
248  script = GetScriptForDestination(pubkey);
249  if (HaveWatchOnly(script))
250  RemoveWatchOnly(script);
251 
252  if (!fFileBacked)
253  return true;
254  if (!IsCrypted()) {
255  return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
256  }
257  return true;
258 }
259 
260 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
261 {
262  LOCK(cs_wallet);
263 
264  if (!CCryptoKeyStore::SetHDChain(chain))
265  return false;
266 
267  if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain))
268  throw std::runtime_error(std::string(__func__) + ": WriteHDChain failed");
269 
270  return true;
271 }
272 
273 bool CWallet::SetCryptedHDChain(const CHDChain& chain, bool memonly)
274 {
275  LOCK(cs_wallet);
276 
278  return false;
279 
280  if (!memonly) {
281  if (!fFileBacked)
282  return false;
283  if (pwalletdbEncryption) {
285  throw std::runtime_error(std::string(__func__) + ": WriteCryptedHDChain failed");
286  } else {
287  if (!CWalletDB(strWalletFile).WriteCryptedHDChain(chain))
288  throw std::runtime_error(std::string(__func__) + ": WriteCryptedHDChain failed");
289  }
290  }
291 
292  return true;
293 }
294 
296 {
297  LOCK(cs_wallet);
298 
299  CHDChain hdChainTmp;
300 
301  if (!GetHDChain(hdChainTmp)) {
302  return false;
303  }
304 
305  if (!DecryptHDChain(hdChainTmp))
306  return false;
307 
308  // make sure seed matches this chain
309  if (hdChainTmp.GetID() != hdChainTmp.GetSeedHash())
310  return false;
311 
312  hdChainRet = hdChainTmp;
313 
314  return true;
315 }
316 
317 void CWallet::GenerateNewHDChain(std::string* phrase)
318 {
319  CHDChain newHdChain;
320 
321  // NOTE: empty mnemonic means "generate a new one for me"
322  std::string strMnemonic = GetArg("-mnemonic", "");
323  // NOTE: default mnemonic passphrase is an empty string
324  std::string strMnemonicPassphrase = GetArg("-mnemonicpassphrase", "");
325 
326  if (phrase) {
327  strMnemonic = *phrase;
328  strMnemonicPassphrase = "";
329  }
330 
331  SecureVector vchMnemonic(strMnemonic.begin(), strMnemonic.end());
332  SecureVector vchMnemonicPassphrase(strMnemonicPassphrase.begin(), strMnemonicPassphrase.end());
333 
334  if (!newHdChain.SetMnemonic(vchMnemonic, vchMnemonicPassphrase, true))
335  throw std::runtime_error(std::string(__func__) + ": SetMnemonic failed");
336 
337  if (!SetHDChain(newHdChain, false))
338  throw std::runtime_error(std::string(__func__) + ": SetHDChain failed");
339 
340  if (phrase) {
341  CreatePrivacyAccount(true);
342  }
343 }
344 
346 {
347  CHDChain hdChainCurrent;
348  return GetHDChain(hdChainCurrent);
349 }
350 
351 bool CWallet::GetSeedPhrase(std::string &phrase)
352 {
353  CHDChain hdChainCurrent;
354  if (!GetDecryptedHDChain(hdChainCurrent))
355  return false;
356 
357  SecureString mnemonic;
358  SecureString mnemonicPass;
359  if (!hdChainCurrent.GetMnemonic(mnemonic, mnemonicPass))
360  return false;
361 
362  phrase = std::string(mnemonic.begin(), mnemonic.end()).c_str();
363  return true;
364 }
365 
367 {
369 }
371 {
373 }
374 
375 bool CWallet::Write2FA(bool status)
376 {
377  return CWalletDB(strWalletFile).Write2FA(status);
378 }
380 {
381  return CWalletDB(strWalletFile).Read2FA();
382 }
383 
384 bool CWallet::Write2FASecret(std::string secret)
385 {
386  return CWalletDB(strWalletFile).Write2FASecret(secret);
387 }
389 {
391 }
392 
393 bool CWallet::Write2FAPeriod(int period)
394 {
395  return CWalletDB(strWalletFile).Write2FAPeriod(period);
396 }
398 {
400 }
401 
402 bool CWallet::Write2FALastTime(uint64_t lastTime)
403 {
404  return CWalletDB(strWalletFile).Write2FALastTime(lastTime);
405 }
407 {
409 }
410 
411 bool CWallet::AddCryptedKey(const CPubKey& vchPubKey,
412  const std::vector<unsigned char>& vchCryptedSecret)
413 {
414  if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
415  return false;
416  if (!fFileBacked)
417  return true;
418  {
419  LOCK(cs_wallet);
421  return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
422  vchCryptedSecret,
423  mapKeyMetadata[vchPubKey.GetID()]);
424  else
425  return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
426  }
427  return false;
428 }
429 
430 bool CWallet::LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& meta)
431 {
432  AssertLockHeld(cs_wallet); // mapKeyMetadata
433  if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
434  nTimeFirstKey = meta.nCreateTime;
435 
436  mapKeyMetadata[pubkey.GetID()] = meta;
437  return true;
438 }
439 
440 bool CWallet::LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret)
441 {
442  return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
443 }
444 
445 bool CWallet::AddCScript(const CScript& redeemScript)
446 {
447  if (!CCryptoKeyStore::AddCScript(redeemScript))
448  return false;
449  if (!fFileBacked)
450  return true;
451  return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
452 }
453 
454 bool CWallet::LoadCScript(const CScript& redeemScript)
455 {
456  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
457  * that never can be redeemed. However, old wallets may still contain
458  * these. Do not add them to the wallet and warn. */
459  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
460  std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
461  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",
462  __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
463  return true;
464  }
465 
466  return CCryptoKeyStore::AddCScript(redeemScript);
467 }
468 
470 {
472  return false;
473  nTimeFirstKey = 1; // No birthday information for watch-only keys.
475  if (!fFileBacked)
476  return true;
477  return CWalletDB(strWalletFile).WriteWatchOnly(dest);
478 }
479 
481 {
484  return false;
485  if (!HaveWatchOnly())
486  NotifyWatchonlyChanged(false);
487  if (fFileBacked)
488  if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
489  return false;
490 
491  return true;
492 }
493 
495 {
496  return CCryptoKeyStore::AddWatchOnly(dest);
497 }
498 
499 bool CWallet::RescanAfterUnlock(int fromHeight)
500 {
501  if (IsLocked()) {
502  return false;
503  }
504 
505  if (fImporting || fReindex) {
506  return false;
507  }
508  CBlockIndex* pindex;
509 
510  if (fromHeight == 0) {
512  //rescan from scanned position stored in database
513  int scannedHeight = 0;
515  if (scannedHeight > chainActive.Height() || scannedHeight == 0) {
516  pindex = chainActive.Genesis();
517  } else {
518  pindex = chainActive[scannedHeight];
519  }
520 
521  {
522  if (mapWallet.size() > 0) {
523  //looking for highest blocks
524  for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
525  CWalletTx* wtx = &((*it).second);
526  uint256 wtxid = (*it).first;
527  if (mapBlockIndex.count(wtx->hashBlock) == 1) {
528  CBlockIndex* pForTx = mapBlockIndex[wtx->hashBlock];
529  if (pForTx != NULL && pForTx->nHeight > pindex->nHeight) {
530  if (chainActive.Contains(pForTx)) {
531  pindex = pForTx;
532  }
533  }
534  }
535  }
536  }
537  }
538  } else {
540  //scan from a specific block height
541  if (fromHeight > chainActive.Height()) {
542  pindex = chainActive[chainActive.Height()];
543  } else {
544  pindex = chainActive[fromHeight];
545  }
546  }
547 
548  ScanForWalletTransactions(pindex, true, fromHeight != 0?pindex->nHeight:-1);
549  return true;
550 }
551 
552 bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool stakingOnly)
553 {
554  CCrypter crypter;
556  bool rescanNeeded = false;
557 
558  {
559  LOCK(cs_wallet);
560  for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys) {
561  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
562  return false;
563  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
564  continue; // try another master key
565  if (Unlock(vMasterKey)) {
566  fWalletUnlockStakingOnly = stakingOnly;
567  rescanNeeded = true;
568  break;
569  }
570  }
571  }
572 
573  if (rescanNeeded) {
576  return true;
577  }
578 
579  return false;
580 }
581 
583 {
584  if (!SetCrypted())
585  return false;
586 
587  {
588  LOCK(cs_KeyStore);
589  vMasterKey.clear();
590  }
591 
592  NotifyStatusChanged(this);
593  return true;
594 }
595 
596 bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn)
597 {
598  {
599  LOCK(cs_KeyStore);
600  if (!SetCrypted())
601  return false;
602 
603  bool keyPass = false;
604  bool keyFail = false;
605  CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
606  for (; mi != mapCryptedKeys.end(); ++mi) {
607  const CPubKey& vchPubKey = (*mi).second.first;
608  const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second;
609  CKeyingMaterial vchSecret;
610  if (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) {
611  keyFail = true;
612  break;
613  }
614  if (vchSecret.size() != 32) {
615  keyFail = true;
616  break;
617  }
618  CKey key;
619  key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
620  if (key.GetPubKey() != vchPubKey) {
621  keyFail = true;
622  break;
623  }
624  keyPass = true;
626  break;
627  }
628  if (keyPass && keyFail) {
629  LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
630  throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
631  }
632  if (keyFail || !keyPass)
633  return false;
634  vMasterKey = vMasterKeyIn;
635 
636  if(!cryptedHDChain.IsNull()) {
637  bool chainPass = false;
638  // try to decrypt seed and make sure it matches
639  CHDChain hdChainTmp;
640  if (DecryptHDChain(hdChainTmp)) {
641  // make sure seed matches this chain
642  chainPass = cryptedHDChain.GetID() == hdChainTmp.GetSeedHash();
643  }
644  if (!chainPass) {
645  vMasterKey.clear();
646  return false;
647  }
648  }
649 
651  }
652  NotifyStatusChanged(this);
653  return true;
654 }
655 
656 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
657 {
658  bool fWasLocked = IsLocked();
659  bool rescanNeeded = false;
660  SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase;
661 
662  {
663  LOCK(cs_wallet);
664  Lock();
665 
666  CCrypter crypter;
668  for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys) {
669  if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
670  return false;
671  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
672  return false;
673  if (Unlock(vMasterKey)) {
674  int64_t nStartTime = GetTimeMillis();
675  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
676  pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
677 
678  nStartTime = GetTimeMillis();
679  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
680  pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
681 
682  if (pMasterKey.second.nDeriveIterations < 25000)
683  pMasterKey.second.nDeriveIterations = 25000;
684 
685  LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
686 
687  if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
688  return false;
689  if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
690  return false;
691  CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
692  if (fWasLocked)
693  Lock();
694 
695  nTimeFirstKey = 1;
696  rescanNeeded = true;
697  break;
698  }
699  }
700  }
701 
702  if (rescanNeeded) {
704  return true;
705  }
706 
707  return false;
708 }
709 
711 {
712  CWalletDB walletdb(strWalletFile);
713  walletdb.WriteBestBlock(loc);
714 }
715 
716 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
717 {
718  LOCK(cs_wallet); // nWalletVersion
719  if (nWalletVersion >= nVersion)
720  return true;
721 
722  // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
723  if (fExplicit && nVersion > nWalletMaxVersion)
724  nVersion = FEATURE_LATEST;
725 
726  nWalletVersion = nVersion;
727 
728  if (nVersion > nWalletMaxVersion)
729  nWalletMaxVersion = nVersion;
730 
731  if (fFileBacked) {
732  CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
733  if (nWalletVersion > 40000)
734  pwalletdb->WriteMinVersion(nWalletVersion);
735  if (!pwalletdbIn)
736  delete pwalletdb;
737  }
738 
739  return true;
740 }
741 
742 bool CWallet::SetMaxVersion(int nVersion)
743 {
744  LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
745  // cannot downgrade below current version
746  if (nWalletVersion > nVersion)
747  return false;
748 
749  nWalletMaxVersion = nVersion;
750 
751  return true;
752 }
753 
754 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
755 {
756  std::set<uint256> result;
758 
759  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
760  if (it == mapWallet.end())
761  return result;
762  const CWalletTx& wtx = it->second;
763 
764  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
765 
766  for (const CTxIn& txin : wtx.vin) {
767  COutPoint prevout = findMyOutPoint(txin);
768  if (mapTxSpends.count(prevout) <= 1)
769  continue; // No conflict if zero or one spends
770  range = mapTxSpends.equal_range(prevout);
771  for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
772  result.insert(it->second);
773  }
774  return result;
775 }
776 
777 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
778 {
779  // We want all the wallet transactions in range to have the same metadata as
780  // the oldest (smallest nOrderPos).
781  // So: find smallest nOrderPos:
782 
783  int nMinOrderPos = std::numeric_limits<int>::max();
784  const CWalletTx* copyFrom = NULL;
785  for (TxSpends::iterator it = range.first; it != range.second; ++it) {
786  const uint256& hash = it->second;
787  int n = mapWallet[hash].nOrderPos;
788  if (n < nMinOrderPos) {
789  nMinOrderPos = n;
790  copyFrom = &mapWallet[hash];
791  }
792  }
793  // Now copy data from copyFrom to rest:
794  for (TxSpends::iterator it = range.first; it != range.second; ++it) {
795  const uint256& hash = it->second;
796  CWalletTx* copyTo = &mapWallet[hash];
797  if (copyFrom == copyTo) continue;
798  copyTo->mapValue = copyFrom->mapValue;
799  copyTo->vOrderForm = copyFrom->vOrderForm;
800  // fTimeReceivedIsTxTime not copied on purpose
801  // nTimeReceived not copied on purpose
802  copyTo->nTimeSmart = copyFrom->nTimeSmart;
803  copyTo->fFromMe = copyFrom->fFromMe;
804  copyTo->strFromAccount = copyFrom->strFromAccount;
805  // nOrderPos not copied on purpose
806  // cached members not copied on purpose
807  }
808 }
809 
811 
813 {
814  if (mapArgs.count("-mintxfee")) {
815  CAmount n = 0;
816  if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
818  else
819  return UIError(AmountErrMsg("mintxfee", mapArgs["-mintxfee"]));
820  }
821  if (mapArgs.count("-paytxfee")) {
822  CAmount nFeePerK = 0;
823  if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
824  return UIError(AmountErrMsg("paytxfee", mapArgs["-paytxfee"]));
825  if (nFeePerK > nHighTransactionFeeWarning)
826  UIWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
827  payTxFee = CFeeRate(nFeePerK, 1000);
828  if (payTxFee < ::minRelayTxFee) {
829  return UIError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
830  mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
831  }
832  }
833  if (mapArgs.count("-maxtxfee")) {
834  CAmount nMaxFee = 0;
835  if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
836  return UIError(AmountErrMsg("maxtxfee", mapArgs["-maxtxfee"]));
837  if (nMaxFee > nHighTransactionMaxFeeWarning)
838  UIWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
839  maxTxFee = nMaxFee;
840  if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee) {
841  return UIError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
842  mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
843  }
844  }
845  nTxConfirmTarget = GetArg("-txconfirmtarget", 1);
846  bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", false);
847  bdisableSystemnotifications = GetBoolArg("-disablesystemnotifications", false);
848  fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
849 
850  return true;
851 }
852 
853 
855 
860 bool CWallet::IsSpent(const uint256& hash, unsigned int n)
861 {
862  const COutPoint outpoint(hash, n);
863  std::string keyImageHex;
864 
865  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
866  range = mapTxSpends.equal_range(outpoint);
867  for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
868  const uint256& wtxid = it->second;
869  std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
870  if (mit != mapWallet.end() && int(mit->second.GetDepthInMainChain()) > int(0)) {
871  keyImagesSpends[keyImageHex] = true;
872  return true; // Spent
873  }
874  }
875 
876  std::string outString = outpoint.hash.GetHex() + std::to_string(outpoint.n);
877  CKeyImage ki = outpointToKeyImages[outString];
878  if (IsSpentKeyImage(ki.GetHex(), UINT256_ZERO)) {
879  return true;
880  }
881 
882  return false;
883 }
884 
885 unsigned int CWallet::GetSpendDepth(const uint256& hash, unsigned int n) const
886 {
887  const COutPoint outpoint(hash, n);
888  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
889  range = mapTxSpends.equal_range(outpoint);
890 
891  for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
892  {
893  const uint256& wtxid = it->second;
894  std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
895  if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
896  return mit->second.GetDepthInMainChain(); // Spent
897  }
898  return 0;
899 }
900 
901 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
902 {
903  mapTxSpends.insert(std::make_pair(outpoint, wtxid));
904  std::pair<TxSpends::iterator, TxSpends::iterator> range;
905  range = mapTxSpends.equal_range(outpoint);
906  SyncMetaData(range);
907  inSpendQueueOutpoints.erase(outpoint);
908 }
909 
911 {
912  if (mapWallet.count(tx.GetHash()) < 1) return "other";
913  if (tx.IsCoinBase() || tx.IsCoinStake() || tx.IsCoinAudit()) return "other";
914  bool fAllFromMe = true;
915  bool fToMe = false;
916  bool fAllToMe = true;
917  for(size_t i = 0; i < tx.vin.size(); i++) {
918  if (!IsMine(tx.vin[i])) {
919  fAllFromMe = false;
920  break;
921  }
922  }
923 
924  if (fAllFromMe) return "withdrawal";
925  for(size_t i = 0; i < tx.vout.size(); i++) {
926  if (IsMine(tx.vout[i])) {
927  fToMe = true;
928  } else {
929  fAllToMe = false;
930  }
931  }
932 
933  if (fToMe) return "deposit";
934 
935  return "other";
936 }
937 
938 void CWallet::AddToSpends(const uint256& wtxid)
939 {
940  assert(mapWallet.count(wtxid));
941  CWalletTx& thisTx = mapWallet[wtxid];
942  if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
943  return;
944  for (const CTxIn& txin : thisTx.vin) {
945  CKeyImage ki = txin.keyImage;
946  COutPoint prevout = findMyOutPoint(txin);
947  if (!prevout.IsNull() && isMatchMyKeyImage(ki, prevout)) {
948  AddToSpends(prevout, wtxid);
949  continue;
950  }
951  }
952 
953  if (thisTx.IsCoinStake()) {
954  COutPoint prevout = thisTx.vin[0].prevout;
955  AddToSpends(prevout, wtxid);
956  std::string outpoint = prevout.hash.GetHex() + std::to_string(prevout.n);
957  outpointToKeyImages[outpoint] = thisTx.vin[0].keyImage;
958  }
959 }
960 
961 bool CWallet::isMatchMyKeyImage(const CKeyImage& ki, const COutPoint& out)
962 {
963  if (mapWallet.count(out.hash) == 0) return false;
964  std::string outpoint = out.hash.GetHex() + std::to_string(out.n);
965  CKeyImage computed = outpointToKeyImages[outpoint];
966  bool ret = (computed == ki);
967  return ret;
968 }
969 
970 bool CWallet::GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet)
971 {
972  // wait for reindex and/or import to finish
973  if (fImporting || fReindex) return false;
974 
975  CScript pubScript;
976 
977  txinRet = CTxIn(out.tx->GetHash(), out.i);
978  pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
979 
980  findCorrespondingPrivateKey(out.tx->vout[out.i], keyRet);
981  CTxDestination address1;
982  ExtractDestination(pubScript, address1);
983  CBitcoinAddress address2(address1);
984  CPubKey sharedSec;
985  computeSharedSec(*out.tx, out.tx->vout[out.i], sharedSec);
986  txinRet.encryptionKey.clear();
987  std::copy(sharedSec.begin(), sharedSec.end(), std::back_inserter(txinRet.encryptionKey));
988 
989  CKeyID keyID;
990  if (!address2.GetKeyID(keyID)) {
991  LogPrintf("%s: Address does not refer to a key\n", __func__);
992  return false;
993  }
994 
995  if (!GetKey(keyID, keyRet)) {
996  LogPrintf("%s: Private key for address is not known\n", __func__);
997  return false;
998  }
999 
1000  pubKeyRet = keyRet.GetPubKey();
1001  std::string mnsa;
1002  ComputeStealthPublicAddress("masteraccount", mnsa);
1003  std::copy(mnsa.begin(), mnsa.end(), std::back_inserter(txinRet.masternodeStealthAddress));
1004  if (!generateKeyImage(out.tx->vout[out.i].scriptPubKey, txinRet.keyImage)) {
1005  LogPrintf("%s: Failed to generate key image\n", __func__);
1006  return false;
1007  }
1008  if (!MakeShnorrSignatureTxIn(txinRet, GetTxInSignatureHash(txinRet))) {
1009  LogPrintf("%s: Failed to make Shnorr signature\n", __func__);
1010  return false;
1011  }
1012 
1013  //test verification masternode broadcast
1014  if (!VerifyShnorrKeyImageTxIn(txinRet, GetTxInSignatureHash(txinRet))) {
1015  LogPrintf("%s: Failed to verify Shnorr signature\n", __func__);
1016  return false;
1017  }
1018 
1019  //Test the commitment and decoded value, if everything goes right, other nodes can verify it as well
1020  COutPoint prevout = txinRet.prevout;
1021  CTransaction prev;
1022  uint256 bh;
1023  if (!GetTransaction(prevout.hash, prev, bh, true)) {
1024  LogPrintf("%s: failed to read transaction hash %s\n", __func__, txinRet.prevout.hash.ToString());
1025  return false;
1026  }
1027 
1028  CTxOut txout = prev.vout[prevout.n];
1029  CPubKey sharedSec1(txinRet.encryptionKey.begin(), txinRet.encryptionKey.end());
1030  CKey mask;
1031  CAmount amount;
1032  ECDHInfo::Decode(txout.maskValue.mask.begin(), txout.maskValue.amount.begin(), sharedSec1, mask, amount);
1033 
1034  std::vector<unsigned char> commitment;
1035  CWallet::CreateCommitment(mask.begin(), amount, commitment);
1036  if (commitment != txout.commitment) {
1037  LogPrintf("%s: decoded masternode commitment does not match %s\n", __func__, txinRet.prevout.hash.ToString());
1038  return false;
1039  }
1040 
1041  if (amount != Params().MNCollateralAmt()) {
1042  LogPrintf("%s: masternode collateralization not equal to 5K %s\n", __func__, txinRet.prevout.hash.ToString());
1043  return false;
1044  }
1045 
1046  return true;
1047 }
1048 
1049 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
1050 {
1051  if (IsCrypted())
1052  return false;
1053 
1055 
1058 
1059  CMasterKey kMasterKey;
1060 
1061  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
1063 
1064  CCrypter crypter;
1065  int64_t nStartTime = GetTimeMillis();
1066  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
1067  kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
1068 
1069  nStartTime = GetTimeMillis();
1070  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
1071  kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
1072 
1073  if (kMasterKey.nDeriveIterations < 25000)
1074  kMasterKey.nDeriveIterations = 25000;
1075 
1076  LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
1077 
1078  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
1079  return false;
1080  if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
1081  return false;
1082 
1083  {
1084  LOCK(cs_wallet);
1085  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
1086  if (fFileBacked) {
1087  assert(!pwalletdbEncryption);
1089  if (!pwalletdbEncryption->TxnBegin()) {
1090  delete pwalletdbEncryption;
1091  pwalletdbEncryption = NULL;
1092  return false;
1093  }
1095  }
1096 
1097  // must get current HD chain before EncryptKeys
1098  CHDChain hdChainCurrent;
1099  GetHDChain(hdChainCurrent);
1100 
1101  if (!EncryptKeys(vMasterKey)) {
1102  if (fFileBacked) {
1104  delete pwalletdbEncryption;
1105  }
1106  // We now probably have half of our keys encrypted in memory, and half not...
1107  // die and let the user reload their unencrypted wallet.
1108  assert(false);
1109  }
1110 
1111  if (!hdChainCurrent.IsNull()) {
1112  assert(EncryptHDChain(vMasterKey));
1113 
1114  CHDChain hdChainCrypted;
1115  assert(GetHDChain(hdChainCrypted));
1116 
1117  // ids should match, seed hashes should not
1118  assert(hdChainCurrent.GetID() == hdChainCrypted.GetID());
1119  assert(hdChainCurrent.GetSeedHash() != hdChainCrypted.GetSeedHash());
1120 
1121  assert(SetCryptedHDChain(hdChainCrypted, false));
1122  }
1123 
1124  // Encryption was introduced in version 0.4.0
1126 
1127  if (fFileBacked) {
1128  if (!pwalletdbEncryption->TxnCommit()) {
1129  delete pwalletdbEncryption;
1130  // We now have keys encrypted in memory, but not on disk...
1131  // die to avoid confusion and let the user reload their unencrypted wallet.
1132  assert(false);
1133  }
1134 
1135  delete pwalletdbEncryption;
1136  pwalletdbEncryption = NULL;
1137  }
1138 
1139  Lock();
1140 
1141  // Need to completely rewrite the wallet file; if we don't, bdb might keep
1142  // bits of the unencrypted private key in slack space in the database file.
1144  }
1145  NotifyStatusChanged(this);
1146 
1147  return true;
1148 }
1149 
1151 {
1152  AssertLockHeld(cs_wallet); // nOrderPosNext
1153  int64_t nRet = nOrderPosNext++;
1154  if (pwalletdb) {
1155  pwalletdb->WriteOrderPosNext(nOrderPosNext);
1156  } else {
1158  }
1159  return nRet;
1160 }
1161 
1163 {
1164  {
1165  LOCK(cs_wallet);
1166  for (PAIRTYPE(const uint256, CWalletTx) & item : mapWallet)
1167  item.second.MarkDirty();
1168  }
1169 }
1170 
1171 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
1172 {
1173  uint256 hash = wtxIn.GetHash();
1174  const uint256& hashBlock = wtxIn.hashBlock;
1175  CBlockIndex* p = mapBlockIndex[hashBlock];
1176  if (p) {
1177  for (CTxIn in : wtxIn.vin) {
1178  pblocktree->WriteKeyImage(in.keyImage.GetHex(), hashBlock);
1179  }
1180  }
1181 
1183  for (size_t i = 0; i < wtxIn.vout.size(); i++) {
1184  std::string outpoint = hash.GetHex() + std::to_string(i);
1185  if (outpointToKeyImages.count(outpoint) == 1 && outpointToKeyImages[outpoint].IsValid()) continue;
1186  CKeyImage ki;
1187  //reading key image
1188  if (db.ReadKeyImage(outpoint, ki)) {
1189  if (ki.IsFullyValid()) {
1190  outpointToKeyImages[outpoint] = ki;
1191  continue;
1192  }
1193  }
1194  if (IsMine(wtxIn.vout[i])) {
1195  if (generateKeyImage(wtxIn.vout[i].scriptPubKey, ki)) {
1196  outpointToKeyImages[outpoint] = ki;
1197  db.WriteKeyImage(outpoint, ki);
1198  }
1199  }
1200  }
1201 
1202  if (fFromLoadWallet) {
1203  mapWallet[hash] = wtxIn;
1204  CWalletTx& wtx = mapWallet[hash];
1205  wtx.BindWallet(this);
1206  wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
1207  AddToSpends(hash);
1208  } else {
1209  LOCK(cs_wallet);
1210  // Inserts only if not already there, returns tx inserted or tx found
1211  std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
1212  CWalletTx& wtx = (*ret.first).second;
1213  wtx.BindWallet(this);
1214  bool fInsertedNew = ret.second;
1215  if (fInsertedNew) {
1216  if (!wtx.nTimeReceived)
1218  wtx.nOrderPos = IncOrderPosNext(pwalletdb);
1219  wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
1220  wtx.nTimeSmart = ComputeTimeSmart(wtx);
1221  AddToSpends(hash);
1222  }
1223 
1224  bool fUpdated = false;
1225  if (!fInsertedNew) {
1226  // Merge
1227  if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) {
1228  wtx.hashBlock = wtxIn.hashBlock;
1229  fUpdated = true;
1230  }
1231  if (wtxIn.nIndex != -1 && wtxIn.nIndex != wtx.nIndex) {
1232  wtx.nIndex = wtxIn.nIndex;
1233  fUpdated = true;
1234  }
1235  if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) {
1236  wtx.fFromMe = wtxIn.fFromMe;
1237  fUpdated = true;
1238  }
1239  }
1240 
1242  //LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1243 
1244  // Write to disk
1245  if (fInsertedNew || fUpdated)
1246  if (!wtx.WriteToDisk(pwalletdb))
1247  return false;
1248 
1249  // Break debit/credit balance caches:
1250  wtx.MarkDirty();
1251  //LogPrintf("MarkDirty %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1252 
1253  // Notify UI of new or updated transaction
1254  NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1255 
1256  // notify an external script when a wallet transaction comes in or is updated
1257  std::string strCmd = GetArg("-walletnotify", "");
1258 
1259  if (!strCmd.empty()) {
1260  boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1261  boost::thread t(runCommand, strCmd); // thread runs free
1262  }
1263  }
1264  return true;
1265 }
1266 
1272 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1273 {
1274  {
1276  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1277  if (fExisted && !fUpdate) return false;
1278  IsTransactionForMe(tx);
1279  if (pblock && mapBlockIndex.count(pblock->GetHash()) == 1) {
1280  if (!IsLocked()) {
1281  try {
1283  } catch (const std::exception& e) {
1284  LogPrintf("Cannot open data base or wallet is locked\n");
1285  }
1286  }
1287  }
1288  if (fExisted || IsMine(tx) || IsFromMe(tx)) {
1289  CWalletTx wtx(this, tx);
1290  // Get merkle branch if transaction was found in a block
1291  if (pblock)
1292  wtx.SetMerkleBranch(*pblock);
1293  // Do not flush the wallet here for performance reasons
1294  // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1295  CWalletDB walletdb(strWalletFile, "r+", false);
1296 
1297  return AddToWallet(wtx, false, &walletdb);
1298  }
1299  }
1300  return false;
1301 }
1302 
1303 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1304 {
1305  if (IsLocked()) return;
1307  if (!AddToWalletIfInvolvingMe(tx, pblock, true)) {
1308  return; // Not one of ours
1309  }
1310  // If a transaction changes 'conflicted' state, that changes the balance
1311  // available of the outputs it spends. So force those to be
1312  // recomputed, also:
1313  for (const CTxIn& txin : tx.vin) {
1314  COutPoint prevout = findMyOutPoint(txin);
1315  if (mapWallet.count(prevout.hash))
1316  mapWallet[prevout.hash].MarkDirty();
1317  }
1318 }
1319 
1321 {
1322  if (!fFileBacked)
1323  return false;
1324  {
1325  LOCK(cs_wallet);
1326  if (mapWallet.erase(hash))
1327  return CWalletDB(strWalletFile).EraseTx(hash);
1328  }
1329  return false;
1330 }
1331 
1332 
1334 {
1335  {
1336  LOCK(cs_wallet);
1337  COutPoint prevout = findMyOutPoint(txin);
1338  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(prevout.hash);
1339  if (mi != mapWallet.end()) {
1340  const CWalletTx& prev = (*mi).second;
1341  if (prevout.n < prev.vout.size())
1342  return IsMine(prev.vout[prevout.n]);
1343  }
1344  }
1345  return ISMINE_NO;
1346 }
1347 
1349 {
1350  std::string prevout = txin.prevout.hash.GetHex() + std::to_string(txin.prevout.n);
1351  if (outpointToKeyImages.count(prevout) == 1 && outpointToKeyImages[prevout] == txin.keyImage) return txin.prevout;
1352 
1353  for (size_t i = 0; i < txin.decoys.size(); i++) {
1354  std::string out = txin.decoys[i].hash.GetHex() + std::to_string(txin.decoys[i].n);
1355  if (outpointToKeyImages.count(out) == 1 && outpointToKeyImages[out] == txin.keyImage) return txin.decoys[i];
1356  }
1357 
1358  COutPoint outpoint;
1359  {
1360  //AssertLockHeld(cs_wallet); // mapWallet
1361  bool ret = false;
1362  CWalletTx prev;
1363  if (mapWallet.count(txin.prevout.hash))
1364  prev = mapWallet[txin.prevout.hash];
1365  if (txin.prevout.n < prev.vout.size())
1366  ret = IsMine(prev.vout[txin.prevout.n]);
1367  if (ret) {
1368  CKeyImage ki;
1369  if (generateKeyImage(prev.vout[txin.prevout.n].scriptPubKey, ki)) {
1370  if (ki == txin.keyImage) {
1371  outpoint = txin.prevout;
1372  prevout = txin.prevout.hash.GetHex() + std::to_string(txin.prevout.n);
1373  outpointToKeyImages[prevout] = ki;
1374  return outpoint;
1375  }
1376  }
1377  }
1378 
1379  for (size_t i = 0; i < txin.decoys.size(); i++) {
1380  if (mapWallet.count(txin.decoys[i].hash))
1381  prev = mapWallet[txin.decoys[i].hash];
1382  else
1383  continue;
1384  if (txin.decoys[i].n < prev.vout.size())
1385  ret = IsMine(prev.vout[txin.decoys[i].n]);
1386  if (ret) {
1387  CKeyImage ki;
1388  if (generateKeyImage(prev.vout[txin.decoys[i].n].scriptPubKey, ki)) {
1389  if (ki == txin.keyImage) {
1390  outpoint = txin.decoys[i];
1391  std::string out = txin.decoys[i].hash.GetHex() + std::to_string(txin.decoys[i].n);
1392  outpointToKeyImages[out] = ki;
1393  return outpoint;
1394  }
1395  }
1396  }
1397  }
1398  }
1399  return outpoint;
1400 }
1401 
1402 CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const
1403 {
1404  {
1405  LOCK(cs_wallet);
1406  if (txin.prevout.IsNull()) return 0;
1407  COutPoint prevout = findMyOutPoint(txin);
1408  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(prevout.hash);
1409  if (mi != mapWallet.end()) {
1410  const CWalletTx& prev = (*mi).second;
1411  if (prevout.n < prev.vout.size())
1412  if (IsMine(prev.vout[prevout.n]) & filter)
1413  return getCTxOutValue(prev, prev.vout[prevout.n]);
1414  }
1415  }
1416  return 0;
1417 }
1418 
1419 bool CWallet::IsChange(const CTxOut& txout) const
1420 {
1421  if (::IsMine(*this, txout.scriptPubKey)) {
1422  CTxDestination address;
1423  if (!ExtractDestination(txout.scriptPubKey, address))
1424  return true;
1425 
1426  LOCK(cs_wallet);
1427  if (!mapAddressBook.count(address))
1428  return true;
1429  }
1430  return false;
1431 }
1432 
1433 int64_t CWalletTx::GetTxTime() const
1434 {
1435  int64_t n = nTimeSmart;
1436  return n ? n : nTimeReceived;
1437 }
1438 
1440 {
1441  LOCK(cs_main);
1442  return GetTxTime();
1443 }
1444 
1446 {
1447  // Returns -1 if it wasn't being tracked
1448  int nRequests = -1;
1449  {
1451  if (IsCoinBase()) {
1452  // Generated block
1453  if (hashBlock != 0) {
1454  std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1455  if (mi != pwallet->mapRequestCount.end())
1456  nRequests = (*mi).second;
1457  }
1458  } else {
1459  // Did anyone request this transaction?
1460  std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1461  if (mi != pwallet->mapRequestCount.end()) {
1462  nRequests = (*mi).second;
1463 
1464  // How about the block it's in?
1465  if (nRequests == 0 && hashBlock != 0) {
1466  std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1467  if (mi != pwallet->mapRequestCount.end())
1468  nRequests = (*mi).second;
1469  else
1470  nRequests = 1; // If it's in someone else's block it must have got out
1471  }
1472  }
1473  }
1474  }
1475  return nRequests;
1476 }
1477 
1479 {
1480  if (vin.empty())
1481  return 0;
1482 
1483  CAmount debit = 0;
1484  if (filter & ISMINE_SPENDABLE) {
1485  if (fDebitCached)
1486  debit += nDebitCached;
1487  else {
1489  fDebitCached = true;
1490  debit += nDebitCached;
1491  }
1492  }
1493  if (filter & ISMINE_WATCH_ONLY) {
1494  if (fWatchDebitCached)
1495  debit += nWatchDebitCached;
1496  else {
1498  fWatchDebitCached = true;
1499  debit += nWatchDebitCached;
1500  }
1501  }
1502  return debit;
1503 }
1504 
1506 {
1507  // Must wait until coinbase is safely deep enough in the chain before valuing it
1508  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1509  return 0;
1510 
1511  CAmount credit = 0;
1512  if (filter & ISMINE_SPENDABLE) {
1513  // GetBalance can assume transactions in mapWallet won't change
1514  if (fCreditCached)
1515  credit += nCreditCached;
1516  else {
1518  fCreditCached = true;
1519  credit += nCreditCached;
1520  }
1521  }
1522  if (filter & ISMINE_WATCH_ONLY) {
1523  if (fWatchCreditCached)
1524  credit += nWatchCreditCached;
1525  else {
1527  fWatchCreditCached = true;
1528  credit += nWatchCreditCached;
1529  }
1530  }
1531  return credit;
1532 }
1533 
1535 {
1536  LOCK(cs_main);
1537  if (IsInMainChainImmature()) {
1538  if (fUseCache && fImmatureCreditCached)
1539  return nImmatureCreditCached;
1541  fImmatureCreditCached = true;
1542  return nImmatureCreditCached;
1543  }
1544  return 0;
1545 }
1546 
1548 {
1549  if (pwallet == 0)
1550  return 0;
1551 
1552  // Must wait until coinbase is safely deep enough in the chain before valuing it
1553  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1554  return 0;
1555 
1556  if (fUseCache && fAvailableCreditCached) {
1557  if (nAvailableCreditCached) {
1558  return nAvailableCreditCached;
1559  }
1560  }
1561 
1562  CAmount nCredit = 0;
1563  uint256 hashTx = GetHash();
1564  for (unsigned int i = 0; i < vout.size(); i++) {
1565  //dont count if output is in mempool
1566  COutPoint outpoint(hashTx, i);
1567  if (pwallet->inSpendQueueOutpoints.count(outpoint) == 1) continue;
1568 
1569  if (!pwallet->IsSpent(hashTx, i)) {
1570  const CTxOut& txout = vout[i];
1571  CAmount cre = pwallet->GetCredit(*this, txout, ISMINE_SPENDABLE);
1572  if (cre == 0 && fCreditCached) {
1573  fCreditCached = false;
1574  cre = pwallet->GetCredit(*this, txout, ISMINE_SPENDABLE);
1575  }
1576  nCredit += cre;
1577  }
1578  }
1579 
1580  nAvailableCreditCached = nCredit;
1581  fAvailableCreditCached = true;
1582  return nCredit;
1583 }
1584 
1585 // Return sum of unlocked coins
1587 {
1588  if (pwallet == 0)
1589  return 0;
1590 
1591  // Must wait until coinbase is safely deep enough in the chain before valuing it
1592  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1593  return 0;
1594 
1595  CAmount nCredit = 0;
1596  uint256 hashTx = GetHash();
1597  for (unsigned int i = 0; i < vout.size(); i++) {
1598  const CTxOut& txout = vout[i];
1599 
1600  if (pwallet->IsSpent(hashTx, i) || pwallet->IsLockedCoin(hashTx, i)) continue;
1601  if (fMasterNode && pwallet->getCTxOutValue(*this, vout[i]) == Params().MNCollateralAmt()) continue; // do not count MN-like outputs
1602 
1603  nCredit += pwallet->GetCredit(*this, txout, ISMINE_SPENDABLE);
1604  }
1605 
1606  return nCredit;
1607 }
1608 
1609 // Return sum of unlocked coins
1611 {
1612  if (pwallet == 0)
1613  return 0;
1614 
1615  // Must wait until coinbase is safely deep enough in the chain before valuing it
1616  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1617  return 0;
1618 
1619  CAmount nCredit = 0;
1620  uint256 hashTx = GetHash();
1621  for (unsigned int i = 0; i < vout.size(); i++) {
1622  const CTxOut& txout = vout[i];
1623 
1624  // Skip spent coins
1625  if (pwallet->IsSpent(hashTx, i)) continue;
1626 
1627  // Add locked coins
1628  if (pwallet->IsLockedCoin(hashTx, i)) {
1629  nCredit += pwallet->GetCredit(*this, txout, ISMINE_SPENDABLE);
1630  }
1631 
1632  // Add masternode collaterals which are handled likc locked coins
1633  else if (fMasterNode && pwallet->getCTxOutValue(*this, vout[i]) == Params().MNCollateralAmt()) {
1634  nCredit += pwallet->GetCredit(*this, txout, ISMINE_SPENDABLE);
1635  }
1636 
1637  }
1638 
1639  return nCredit;
1640 }
1641 
1643 {
1644  LOCK(cs_main);
1645  if (IsInMainChainImmature()) {
1646  if (fUseCache && fImmatureWatchCreditCached)
1651  }
1652 
1653  return 0;
1654 }
1655 
1657 {
1658  if (pwallet == 0)
1659  return 0;
1660 
1661  // Must wait until coinbase is safely deep enough in the chain before valuing it
1662  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1663  return 0;
1664 
1665  if (fUseCache && fAvailableWatchCreditCached)
1667 
1668  CAmount nCredit = 0;
1669  for (unsigned int i = 0; i < vout.size(); i++) {
1670  if (!pwallet->IsSpent(GetHash(), i)) {
1671  const CTxOut& txout = vout[i];
1672  nCredit += pwallet->GetCredit(*this, txout, ISMINE_WATCH_ONLY);
1673  }
1674  }
1675 
1676  nAvailableWatchCreditCached = nCredit;
1678  return nCredit;
1679 }
1680 
1681 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1682  std::list<COutputEntry>& listSent,
1683  CAmount& nFee,
1684  std::string& strSentAccount,
1685  const isminefilter& filter) const
1686 {
1687  nFee = 0;
1688  listReceived.clear();
1689  listSent.clear();
1690  strSentAccount = strFromAccount;
1691 
1692  // Compute fee:
1693  CAmount nDebit = GetDebit(filter);
1694  nFee = nTxFee;
1695 
1696  // Sent/received.
1697  for (unsigned int i = 0; i < vout.size(); ++i) {
1698  const CTxOut& txout = vout[i];
1699  isminetype fIsMine = pwallet->IsMine(txout);
1700  // Only need to handle txouts if AT LEAST one of these is true:
1701  // 1) they debit from us (sent)
1702  // 2) the output is to us (received)
1703  if (nDebit > 0) {
1704  // Don't report 'change' txouts
1705  if (pwallet->IsChange(txout))
1706  continue;
1707  } else if (!(fIsMine & filter))
1708  continue;
1709 
1710  // In either case, we need to get the destination address
1711  CTxDestination address;
1712  if (!ExtractDestination(txout.scriptPubKey, address)) {
1713  if (!IsCoinStake() && !IsCoinBase()) {
1714  LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString());
1715  }
1716  address = CNoDestination();
1717  }
1718 
1719  COutputEntry output = {address, pwallet->getCTxOutValue(*this, txout), (int)i};
1720 
1721  // If we are debited by the transaction, add the output as a "sent" entry
1722  if (nDebit > 0)
1723  listSent.push_back(output);
1724 
1725  // If we are receiving the output, add it as a "received" entry
1726  if (fIsMine & filter)
1727  listReceived.push_back(output);
1728  }
1729 }
1730 
1731 void CWalletTx::GetAccountAmounts(const std::string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1732 {
1733  nReceived = nSent = nFee = 0;
1734 
1735  CAmount allFee;
1736  std::string strSentAccount;
1737  std::list<COutputEntry> listReceived;
1738  std::list<COutputEntry> listSent;
1739  GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1740 
1741  if (strAccount == strSentAccount) {
1742  for (const COutputEntry& s : listSent)
1743  nSent += s.amount;
1744  nFee = allFee;
1745  }
1746  {
1748  for (const COutputEntry& r : listReceived) {
1749  if (pwallet->mapAddressBook.count(r.destination)) {
1750  std::map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1751  if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1752  nReceived += r.amount;
1753  } else if (strAccount.empty()) {
1754  nReceived += r.amount;
1755  }
1756  }
1757  }
1758 }
1759 
1760 
1762 {
1763  if (pwalletdb)
1764  return pwalletdb->WriteTx(GetHash(), *this);
1765  return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1766 }
1767 
1769 {
1770  if (mapTxSpends.size() > 0)
1771  {
1772  std::multimap<COutPoint, uint256>::const_iterator itr = mapTxSpends.cbegin();
1773  while (itr != mapTxSpends.cend())
1774  {
1775  if (itr->second == wtxid)
1776  {
1777  itr = mapTxSpends.erase(itr);
1778  }
1779  else
1780  {
1781  ++itr;
1782  }
1783  }
1784  }
1785 }
1786 
1792 void CWallet::ReorderWalletTransactions(std::map<std::pair<int,int>, CWalletTx*> &mapSorted, int64_t &maxOrderPos)
1793 {
1794 <<<<<<< HEAD
1795 =======
1796  LogPrintf("%s: start\n", __func__);
1797 >>>>>>> 8b6832858a1ed35a91aa239a94722b31d6e659f1
1800 
1801  int maxSortNumber = chainActive.Tip()->nHeight + 1;
1802 
1803  for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1804  {
1805  CWalletTx* pwtx = &(it->second);
1806  maxOrderPos = std::max(maxOrderPos, pwtx->nOrderPos);
1807 
1808  if (mapBlockIndex.count(pwtx->hashBlock) > 0) {
1809  int wtxHeight = mapBlockIndex[pwtx->hashBlock]->nHeight;
1810  auto key = std::make_pair(wtxHeight, pwtx->nIndex);
1811  mapSorted.insert(make_pair(key, pwtx));
1812  }
1813  else {
1814  auto key = std::make_pair(maxSortNumber, 0);
1815  mapSorted.insert(std::make_pair(key, pwtx));
1816  maxSortNumber++;
1817  }
1818  }
1819  LogPrintf("%s: end\n", __func__);
1820 }
1821 
1825 void CWallet::UpdateWalletTransactionOrder(std::map<std::pair<int,int>, CWalletTx*> &mapSorted, bool resetOrder)
1826 {
1827 <<<<<<< HEAD
1828 =======
1829  LogPrintf("%s: start\n", __func__);
1830 >>>>>>> 8b6832858a1ed35a91aa239a94722b31d6e659f1
1833 
1834  int64_t previousPosition = 0;
1835  std::map<const uint256, CWalletTx*> mapUpdatedTxs;
1836 
1837  //Check the postion of each transaction relative to the previous one.
1838  for (std::map<std::pair<int,int>, CWalletTx*>::iterator it = mapSorted.begin(); it != mapSorted.end(); ++it) {
1839  CWalletTx* pwtx = it->second;
1840  const uint256 wtxid = pwtx->GetHash();
1841 
1842  if (pwtx->nOrderPos <= previousPosition || resetOrder) {
1843  previousPosition++;
1844  pwtx->nOrderPos = previousPosition;
1845  mapUpdatedTxs.insert(std::make_pair(wtxid, pwtx));
1846  }
1847  else {
1848  previousPosition = pwtx->nOrderPos;
1849  }
1850  }
1851 
1852  //Update transactions nOrderPos for transactions that changed
1853  CWalletDB walletdb(strWalletFile, "r+", false);
1854  for (std::map<const uint256, CWalletTx*>::iterator it = mapUpdatedTxs.begin(); it != mapUpdatedTxs.end(); ++it) {
1855  CWalletTx* pwtx = it->second;
1856  LogPrint(BCLog::DELETETX,"Reorder Tx - Updating Positon to %i for Tx %s\n", pwtx->nOrderPos, pwtx->GetHash().ToString());
1857  pwtx->WriteToDisk(&walletdb);
1858  const auto itmw = mapWallet.find(pwtx->GetHash());
1859  if (itmw != mapWallet.end()) {
1860  mapWallet[pwtx->GetHash()].nOrderPos = pwtx->nOrderPos;
1861  }
1862  }
1863 
1864  //Update Next Wallet Tx Positon
1865  nOrderPosNext = previousPosition++;
1867  LogPrint(BCLog::DELETETX,"Reorder Tx - Total Transactions Reordered %i, Next Position %i\n ", mapUpdatedTxs.size(), nOrderPosNext);
1868 <<<<<<< HEAD
1869 =======
1870  LogPrintf("%s: end\n", __func__);
1871 >>>>>>> 8b6832858a1ed35a91aa239a94722b31d6e659f1
1872 }
1873 
1877 bool CWallet::DeleteTransactions(std::vector<uint256> &removeTxs, bool fRescan)
1878 {
1880 
1881  bool removingTransactions = false;
1882  if (removeTxs.size() > 0) {
1883  removingTransactions = true;
1884  }
1885 
1886  CWalletDB walletdb(strWalletFile, "r+", false);
1887 
1888  for (int i = 0; i < removeTxs.size(); i++) {
1889  bool fRemoveFromSpends = !(mapWallet.at(removeTxs[i]).IsCoinBase());
1890  if (EraseFromWallet(removeTxs[i])) {
1891  if (fRemoveFromSpends) {
1892  RemoveFromSpends(removeTxs[i]);
1893  }
1894  LogPrint(BCLog::DELETETX,"DeleteTx - Deleting tx %s, %i.\n", removeTxs[i].ToString(),i);
1895  } else {
1896  LogPrint(BCLog::DELETETX,"DeleteTx - Deleting tx %s failed.\n", removeTxs[i].ToString());
1897  return false;
1898  }
1899  }
1900 
1901  // Miodrag: release memory back to the OS, only works on linux
1902  #ifdef __linux__
1903  malloc_trim(0);
1904  #endif
1905 
1906  return removingTransactions;
1907 }
1908 
1909 bool CWallet::DeleteWalletTransactions(const CBlockIndex* pindex, bool fRescan)
1910 {
1913 
1914  int nDeleteAfter = (int)fDeleteTransactionsAfterNBlocks;
1915  bool runCompact = false;
1916  bool deletedTransactions = false;
1917  auto startTime = GetTime();
1918 
1919  if (pindex && fTxDeleteEnabled) {
1920  //Check for acentries - exit function if found
1921  {
1922  std::list<CAccountingEntry> acentries;
1923  CWalletDB walletdb(strWalletFile);
1924  walletdb.ListAccountCreditDebit("*", acentries);
1925  if (acentries.size() > 0) {
1926  LogPrintf("deletetx not compatible to account entries\n");
1927  return false;
1928  }
1929  }
1930  //delete transactions
1931 
1932  //Sort Transactions by block and block index
1933  int64_t maxOrderPos = 0;
1934  std::map<std::pair<int,int>, CWalletTx*> mapSorted;
1935  ReorderWalletTransactions(mapSorted, maxOrderPos);
1936  if (maxOrderPos > int64_t(mapSorted.size())*10) {
1937  //reset the postion when the max postion is 10x bigger than the
1938  //number of transactions in the wallet
1939  UpdateWalletTransactionOrder(mapSorted, true);
1940  }
1941  else {
1942  UpdateWalletTransactionOrder(mapSorted, false);
1943  }
1944  auto reorderTime = GetTime();
1945  LogPrint(BCLog::DELETETX,"DeleteTx - Time to Reorder %s\n", DateTimeStrFormat("%H:%M:%S", reorderTime-startTime));
1946 
1947  //Process Transactions in sorted order
1948  int txConflictCount = 0;
1949  int txUnConfirmed = 0;
1950  int txCount = 0;
1951  int txSaveCount = 0;
1952  std::vector<uint256> removeTxs;
1953 
1954  for (auto & item : mapSorted)
1955  {
1956  CWalletTx* pwtx = item.second;
1957  const uint256& wtxid = pwtx->GetHash();
1958  bool deleteTx = true;
1959  txCount += 1;
1960  int wtxDepth = pwtx->GetDepthInMainChain();
1961 
1962  //Keep anything newer than N Blocks
1963  if (wtxDepth == 0)
1964  txUnConfirmed++;
1965 
1966  if (wtxDepth < nDeleteAfter && wtxDepth >= 0) {
1967  LogPrint(BCLog::DELETETX,"DeleteTx - Transaction above minimum depth, tx %s\n", pwtx->GetHash().ToString());
1968  deleteTx = false;
1969  txSaveCount++;
1970  continue;
1971  } else if (wtxDepth == -1) {
1972  //Enabled by default
1973  if (!fTxConflictDeleteEnabled) {
1974  LogPrint(BCLog::DELETETX,"DeleteTx - Conflict delete is not enabled tx %s\n", pwtx->GetHash().ToString());
1975  deleteTx = false;
1976  txSaveCount++;
1977  continue;
1978  } else {
1979  txConflictCount++;
1980  }
1981  } else {
1982  //Check for unspent inputs or spend less than N Blocks ago.
1983  for (unsigned int i = 0; i < pwtx->vout.size(); i++) {
1984  CTxDestination address;
1985  ExtractDestination(pwtx->vout[i].scriptPubKey, address);
1986  if(IsMine(pwtx->vout[i])) {
1988  LogPrint(BCLog::DELETETX,"DeleteTx - Unspent input tx %s\n", pwtx->GetHash().ToString());
1989  deleteTx = false;
1990  continue;
1991  }
1992  }
1993  }
1994 
1995  if (!deleteTx) {
1996  txSaveCount++;
1997  continue;
1998  }
1999 
2000  //Check for output with that no longer have parents in the wallet.
2001  for (int i = 0; i < pwtx->vin.size(); i++) {
2002  const CTxIn& txin = pwtx->vin[i];
2003  const uint256& parentHash = txin.prevout.hash;
2004  const CWalletTx* parent = pwalletMain->GetWalletTx(txin.prevout.hash);
2005  if (parent != NULL && parentHash != wtxid) {
2006  LogPrint(BCLog::DELETETX,"DeleteTx - Parent of tx %s found\n", pwtx->GetHash().ToString());
2007  deleteTx = false;
2008  continue;
2009  }
2010  }
2011 
2012  if (!deleteTx) {
2013  txSaveCount++;
2014  continue;
2015  }
2016 
2017  //Keep Last N Transactions
2018  if (mapSorted.size() - txCount < fKeepLastNTransactions + txConflictCount + txUnConfirmed) {
2019  LogPrint(BCLog::DELETETX,"DeleteTx - Transaction set position %i, tx %s\n", mapSorted.size() - txCount, wtxid.ToString());
2020  deleteTx = false;
2021  txSaveCount++;
2022  continue;
2023  }
2024  }
2025 
2026  //Collect everything else for deletion
2027  if (deleteTx && int(removeTxs.size()) < MAX_DELETE_TX_SIZE) {
2028  removeTxs.push_back(wtxid);
2029  runCompact = true;
2030  } else {
2031  break; //no need to continue with the loop
2032  }
2033  }
2034 
2035  auto selectTime = GetTime();
2036  LogPrint(BCLog::DELETETX,"DeleteTx - Time to Select %s\n", DateTimeStrFormat("%H:%M:%S", selectTime - reorderTime));
2037 
2038  //Delete Transactions from wallet
2039  deletedTransactions = DeleteTransactions(removeTxs, fRescan);
2040 
2041  auto deleteTime = GetTime();
2042  LogPrint(BCLog::DELETETX,"DeleteTx - Time to Delete %s\n", DateTimeStrFormat("%H:%M:%S", deleteTime - selectTime));
2043  LogPrintf("DeleteTx - Total Transaction Count %i, Transactions Deleted %i\n", txCount, int(removeTxs.size()));
2044 
2045  if (runCompact) {
2047  }
2048 
2049  auto totalTime = GetTime();
2050  LogPrint(BCLog::DELETETX,"DeleteTx - Time to Run Total Function %s\n", DateTimeStrFormat("%H:%M:%S", totalTime - startTime));
2051  }
2052 
2053  return deletedTransactions;
2054 }
2055 
2062 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate, bool fromStartup, int height)
2063 {
2064  int ret = 0;
2065  int64_t nNow = GetTime();
2066  CBlockIndex* pindex = pindexStart;
2067  {
2069  if (pindexStart == chainActive.Genesis()) {
2070  pindex = chainActive.Tip();
2071  } else if (height == -1) {
2072  // no need to read and scan block, if block was created before
2073  // our wallet birthday (as adjusted for block time variability)
2074  while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) {
2075  pindex = chainActive.Next(pindex);
2076  }
2077  }
2078 
2079  ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
2080  double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false);
2081  double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false);
2082  while (!IsLocked() && pindex) {
2083  if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
2084  ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
2085 
2086  if (fromStartup && ShutdownRequested()) {
2087  return -1;
2088  }
2089 
2090  CBlock block;
2091  ReadBlockFromDisk(block, pindex);
2092  for (CTransaction& tx : block.vtx) {
2093  if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
2094  ret++;
2095  }
2096 
2097 <<<<<<< HEAD
2098  //Delete Transactions
2099  if (pindex->nHeight % fDeleteInterval == 0)
2100  while(DeleteWalletTransactions(pindex, true)) {}
2101 =======
2102  LogPrintf("%s: Deleting Txes 1 start\n", __func__);
2103  //Delete Transactions
2104  if (pindex->nHeight % fDeleteInterval == 0)
2105  while(DeleteWalletTransactions(pindex, true)) {}
2106  LogPrintf("%s: Deleting Txes 1 end\n", __func__);
2107 >>>>>>> 8b6832858a1ed35a91aa239a94722b31d6e659f1
2108 
2109  pindex = chainActive.Next(pindex);
2110  if (GetTime() >= nNow + 60) {
2111  nNow = GetTime();
2112  LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex));
2113  }
2114  if (ShutdownRequested()) {
2115  LogPrintf("Rescan aborted at block %d. Please rescanwallettransactions %f from the Debug Console to continue.\n", pindex->nHeight, pindex->nHeight);
2116  return false;
2117  }
2118  }
2119  ShowProgress(_("Rescanning... Please do not interrupt this process as it could lead to a corrupt wallet."), 100); // hide progress dialog in GUI
2120  //Delete transactions
2121 <<<<<<< HEAD
2122  while(DeleteWalletTransactions(chainActive.Tip(), true)) {}
2123 =======
2124  LogPrintf("%s: Deleting Txes 2 start\n", __func__);
2125  while(DeleteWalletTransactions(chainActive.Tip(), true)) {}
2126  LogPrintf("%s: Deleting Txes 2 end\n", __func__);
2127 >>>>>>> 8b6832858a1ed35a91aa239a94722b31d6e659f1
2128  }
2129  return ret;
2130 }
2131 
2133 {
2135  std::map<int64_t, CWalletTx*> mapSorted;
2136 
2137  // Sort pending wallet transactions based on their initial wallet insertion order
2138  for (PAIRTYPE(const uint256, CWalletTx)& item: mapWallet) {
2139  const uint256& wtxid = item.first;
2140  CWalletTx& wtx = item.second;
2141  assert(wtx.GetHash() == wtxid);
2142 
2143  int nDepth = wtx.GetDepthInMainChain();
2144 
2145  if (!wtx.IsCoinBase() && !wtx.IsCoinStake() && nDepth < 0) {
2146  mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
2147  }
2148  }
2149 
2150  // Try to add wallet transactions to memory pool
2151  for (PAIRTYPE(const int64_t, CWalletTx*)& item: mapSorted)
2152  {
2153  CWalletTx& wtx = *(item.second);
2154 
2155  LOCK(mempool.cs);
2156  wtx.AcceptToMemoryPool(false);
2157  }
2158 }
2159 
2161 {
2162  LOCK(mempool.cs);
2163  if (mempool.exists(GetHash())) {
2164  return true;
2165  }
2166  return false;
2167 }
2168 
2169 void CWalletTx::RelayWalletTransaction(std::string strCommand)
2170 {
2171  LOCK(cs_main);
2172  if (!IsCoinBase()) {
2173  if (GetDepthInMainChain() == 0) {
2174  uint256 hash = GetHash();
2175  LogPrintf("Relaying wtx %s\n", hash.ToString());
2176 
2177  if (strCommand == NetMsgType::IX) {
2178  mapTxLockReq.insert(std::make_pair(hash, (CTransaction) * this));
2179  CreateNewLock(((CTransaction) * this));
2180  RelayTransactionLockReq((CTransaction) * this, true);
2181  } else {
2182  RelayTransaction((CTransaction) * this);
2183  }
2184  }
2185  }
2186 }
2187 
2188 std::set<uint256> CWalletTx::GetConflicts() const
2189 {
2190  std::set<uint256> result;
2191  if (pwallet != NULL) {
2192  uint256 myHash = GetHash();
2193  result = pwallet->GetConflicts(myHash);
2194  result.erase(myHash);
2195  }
2196  return result;
2197 }
2198 
2200 {
2201  // Do this infrequently and randomly to avoid giving away
2202  // that these are our transactions.
2203  if (GetTime() < nNextResend)
2204  return;
2205  bool fFirst = (nNextResend == 0);
2206  nNextResend = GetTime() + GetRand(30 * 60);
2207  if (fFirst)
2208  return;
2209 
2210  // Only do it if there's been a new block since last time
2212  return;
2213  nLastResend = GetTime();
2214 
2215  // Rebroadcast any of our txes that aren't in a block yet
2216  LogPrintf("ResendWalletTransactions()\n");
2217  {
2218  LOCK(cs_wallet);
2219  // Sort them in chronological order
2220  std::multimap<unsigned int, CWalletTx*> mapSorted;
2221  for (PAIRTYPE(const uint256, CWalletTx) & item : mapWallet) {
2222  CWalletTx& wtx = item.second;
2223  // Don't rebroadcast until it's had plenty of time that
2224  // it should have gotten in already by now.
2225  if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
2226  mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
2227  }
2228  for (PAIRTYPE(const unsigned int, CWalletTx*) & item : mapSorted) {
2229  CWalletTx& wtx = *item.second;
2230  wtx.RelayWalletTransaction();
2231  }
2232  }
2233 }
2234  // end of mapWallet
2236 
2237 
2244 {
2245  CAmount nTotal = 0;
2246  {
2248  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2249  const CWalletTx* pcoin = &(*it).second;
2250  if (pcoin->IsTrusted()) {
2251  CAmount ac = pcoin->GetAvailableCredit();
2252  nTotal += ac;
2253  }
2254  }
2255  }
2256  dirtyCachedBalance = nTotal;
2257  return nTotal;
2258 }
2259 
2261 {
2262  CAmount nLockedBalance = 0;
2263  CAmount nTotal = 0;
2264  {
2266  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2267  const CWalletTx* pcoin = &(*it).second;
2268  if (pcoin->IsTrusted()) {
2269  if (!((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0 && pcoin->IsInMainChain())) {
2270  nTotal += pcoin->GetAvailableCredit();
2271  }
2272  }
2273  }
2274  }
2275 
2276  nLockedBalance = GetLockedCoins();
2277  nTotal = nTotal - nLockedBalance;
2278  return nTotal;
2279 }
2280 
2281 
2283 {
2284  if (fLiteMode) return 0;
2285 
2286  CAmount nTotal = 0;
2287  {
2289  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2290  const CWalletTx* pcoin = &(*it).second;
2291 
2292  if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0)
2293  nTotal += pcoin->GetUnlockedCredit();
2294  }
2295  }
2296 
2297  return nTotal;
2298 }
2299 
2301 {
2302  if (fLiteMode) return 0;
2303 
2304  CAmount nTotal = 0;
2305  {
2307  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2308  const CWalletTx* pcoin = &(*it).second;
2309 
2310  if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0)
2311  nTotal += pcoin->GetLockedCredit();
2312  }
2313  }
2314 
2315  return nTotal;
2316 }
2317 
2318 
2320 {
2321  CAmount nTotal = 0;
2322  {
2324  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2325  const CWalletTx* pcoin = &(*it).second;
2326  if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2327  nTotal += pcoin->GetAvailableCredit(false);
2328  }
2329  }
2330  return nTotal;
2331 }
2332 
2334 {
2335  CAmount nTotal = 0;
2336  {
2338  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2339  const CWalletTx* pcoin = &(*it).second;
2340  nTotal += pcoin->GetImmatureCredit(false);
2341  }
2342  }
2343  return nTotal;
2344 }
2345 
2347 {
2348  CAmount nTotal = 0;
2349  {
2351  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2352  const CWalletTx* pcoin = &(*it).second;
2353  if (pcoin->IsTrusted())
2354  nTotal += pcoin->GetAvailableWatchOnlyCredit();
2355  }
2356  }
2357 
2358  return nTotal;
2359 }
2360 
2362 {
2363  CAmount nTotal = 0;
2364  {
2366  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2367  const CWalletTx* pcoin = &(*it).second;
2368  if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2369  nTotal += pcoin->GetAvailableWatchOnlyCredit();
2370  }
2371  }
2372  return nTotal;
2373 }
2374 
2376 {
2377  CAmount nTotal = 0;
2378  {
2380  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2381  const CWalletTx* pcoin = &(*it).second;
2382  nTotal += pcoin->GetImmatureWatchOnlyCredit();
2383  }
2384  }
2385  return nTotal;
2386 }
2387 
2391 bool CheckTXAvailability(const CWalletTx* pcoin, bool fOnlyConfirmed, bool fUseIX, int& nDepth)
2392 {
2394  if (!CheckFinalTx(*pcoin)) return false;
2395  if (fOnlyConfirmed && !pcoin->IsTrusted()) return false;
2396  if (pcoin->GetBlocksToMaturity() > 0) return false;
2397 
2398  nDepth = pcoin->GetDepthInMainChain(false);
2399  // do not use IX for inputs that have less then 6 blockchain confirmations
2400  if (fUseIX && nDepth < 6) return false;
2401 
2402  // We should not consider coins which aren't at least in our mempool
2403  // It's possible for these to be conflicted via ancestors which we may never be able to detect
2404  if (nDepth == 0 && !pcoin->InMempool()) return false;
2405 
2406  return true;
2407 }
2408 
2409 bool CWallet::GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex, std::string& strError)
2410 {
2411  // wait for reindex and/or import to finish
2412  if (fImporting || fReindex) return false;
2413 
2414  if (strTxHash.empty() || strOutputIndex.empty()) {
2415  strError = "Invalid masternode collateral hash or output index";
2416  return error("%s: %s", __func__, strError);
2417  }
2418 
2419  int nOutputIndex;
2420  try {
2421  nOutputIndex = std::stoi(strOutputIndex.c_str());
2422  } catch (const std::exception& e) {
2423  strError = "Invalid masternode output index";
2424  return error("%s: %s on strOutputIndex", __func__, e.what());
2425  }
2426 
2427  // Find specific vin
2428  uint256 txHash = uint256S(strTxHash);
2429  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txHash);
2430  if (mi == mapWallet.end()) {
2431  strError = "collateral tx not found in the wallet";
2432  return error("%s: %s", __func__, strError);
2433  }
2434 
2435  const CWalletTx& wtx = mi->second;
2436 
2437  // Verify index limits
2438  if (nOutputIndex < 0 || nOutputIndex >= (int) wtx.vout.size()) {
2439  strError = "Invalid masternode output index";
2440  return error("%s: output index %d not found in %s", __func__, nOutputIndex, strTxHash);
2441  }
2442 
2443  CTxOut txOut = wtx.vout[nOutputIndex];
2444  CAmount nValue = getCTxOutValue(wtx, txOut);
2445 
2446  // Masternode collateral value
2447  if (nValue != Params().MNCollateralAmt()) {
2448  strError = "Invalid collateral tx value, must be 5,000 PRCY";
2449  return error("%s: tx %s, index %d not a masternode collateral", __func__, strTxHash, nOutputIndex);
2450  }
2451 
2452  // Check availability
2453  int nDepth = 0;
2454  {
2455  LOCK(cs_main);
2456  if (!CheckTXAvailability(&wtx, true, false, nDepth)) {
2457  strError = "Not available collateral transaction";
2458  return error("%s: tx %s not available", __func__, strTxHash);
2459  }
2460  }
2461  // Skip spent coins
2462  if (IsSpent(txHash, nOutputIndex)) {
2463  strError = "Error: collateral already spent";
2464  return error("%s: tx %s already spent", __func__, strTxHash);
2465  }
2466 
2467  // Depth must be at least MASTERNODE_MIN_CONFIRMATIONS
2468  if (nDepth < MASTERNODE_MIN_CONFIRMATIONS) {
2469  strError = strprintf("Collateral tx must have at least %d confirmations", MASTERNODE_MIN_CONFIRMATIONS);
2470  return error("%s: %s", __func__, strError);
2471  }
2472 
2473  // utxo need to be mine.
2474  isminetype mine = IsMine(txOut);
2475  if (mine != ISMINE_SPENDABLE) {
2476  strError = "Invalid collateral transaction. Not from this wallet";
2477  return error("%s: tx %s not mine", __func__, strTxHash);
2478  }
2479 
2480  return GetVinAndKeysFromOutput(
2481  COutput(&wtx, nOutputIndex, nDepth, true),
2482  txinRet,
2483  pubKeyRet,
2484  keyRet);
2485 }
2486 
2491  std::vector<COutput>& vCoins,
2492  bool fOnlyConfirmed,
2493  const CCoinControl* coinControl,
2494  bool fIncludeZeroValue,
2495  AvailableCoinsType nCoinType,
2496  bool fUseIX
2497  )
2498 {
2499  if (IsLocked()) return false;
2500  vCoins.clear();
2501  const bool fCoinsSelected = (coinControl != nullptr) && coinControl->HasSelected();
2502 
2503  {
2505  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2506  const uint256& wtxid = it->first;
2507  const CWalletTx* pcoin = &(*it).second;
2508 
2509  // Check if the tx is selectable
2510  int nDepth;
2511  if (!CheckTXAvailability(pcoin, fOnlyConfirmed, fUseIX, nDepth))
2512  continue;
2513 
2514  for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2515  if (pcoin->vout[i].IsEmpty()) {
2516  continue;
2517  }
2518  bool found = false;
2519  CAmount value = getCTxOutValue(*pcoin, pcoin->vout[i]);
2520  if (nCoinType == ONLY_5000) {
2521  found = value == Params().MNCollateralAmt();
2522  } else {
2523  COutPoint outpoint(pcoin->GetHash(), i);
2524  if (IsCollateralized(outpoint)) {
2525  continue;
2526  }
2527  if (inSpendQueueOutpoints.count(outpoint)) {
2528  continue;
2529  }
2530  found = true;
2531  }
2532  if (!found) continue;
2533 
2534  isminetype mine = IsMine(pcoin->vout[i]);
2535  if (mine == ISMINE_NO)
2536  continue;
2537  if (mine == ISMINE_WATCH_ONLY)
2538  continue;
2539  if (IsLockedCoin(wtxid, i) && nCoinType != ONLY_5000)
2540  continue;
2541  if (value <= 0 && !fIncludeZeroValue)
2542  continue;
2543  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs &&
2544  !coinControl->IsSelected(wtxid, i))
2545  continue;
2546 
2547  bool fIsSpendable = false;
2548  if ((mine & ISMINE_SPENDABLE) != ISMINE_NO)
2549  fIsSpendable = true;
2550 
2551  if (IsSpent(wtxid, i)) {
2552  continue;
2553  }
2554 
2555  vCoins.emplace_back(COutput(pcoin, i, nDepth, fIsSpendable));
2556  }
2557  }
2558  }
2559  return true;
2560 }
2561 
2562 std::map<CBitcoinAddress, std::vector<COutput> > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue)
2563 {
2564  std::vector<COutput> vCoins;
2565  AvailableCoins(vCoins, fConfirmed);
2566 
2567  std::map<CBitcoinAddress, std::vector<COutput> > mapCoins;
2568  for (COutput out : vCoins) {
2569  CAmount value = getCOutPutValue(out);
2570  if (maxCoinValue > 0 && value > maxCoinValue)
2571  continue;
2572 
2573  CTxDestination address;
2574  if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
2575  continue;
2576 
2577  mapCoins[CBitcoinAddress(address)].push_back(out);
2578  }
2579 
2580  return mapCoins;
2581 }
2582 
2583 static CAmount ApproximateBestSubset(int numOut, int ringSize, std::vector<std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2584 {
2585  std::vector<char> vfIncluded;
2586 
2587  vfBest.assign(vValue.size(), true);
2588  nBest = nTotalLower;
2589  int estimateTxSize = 0;
2590  CAmount nFeeNeeded = 0;
2591  FastRandomContext insecure_rand;
2592 
2593  for (int nRep = 0; nRep < iterations && nBest != nTargetValue + nFeeNeeded; nRep++) {
2594  vfIncluded.assign(vValue.size(), false);
2595  CAmount nTotal = 0;
2596  bool fReachedTarget = false;
2597  for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) {
2598  int numSelected = 0;
2599  for (unsigned int i = 0; i < vValue.size(); i++) {
2600  //The solver here uses a randomized algorithm,
2601  //the randomness serves no real security purpose but is just
2602  //needed to prevent degenerate behavior and it is important
2603  //that the rng is fast. We do not use a constant random sequence,
2604  //because there may be some privacy improvement by making
2605  //the selection random.
2606  if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i]) {
2607  nTotal += vValue[i].first;
2608  vfIncluded[i] = true;
2609  numSelected++;
2610  estimateTxSize = CWallet::ComputeTxSize(numSelected, numOut, ringSize);
2611  nFeeNeeded = CWallet::GetMinimumFee(estimateTxSize, nTxConfirmTarget, mempool);
2612  if (nTotal >= nTargetValue + nFeeNeeded) {
2613  fReachedTarget = true;
2614  if (nTotal < nBest) {
2615  nBest = nTotal;
2616  vfBest = vfIncluded;
2617  }
2618  nTotal -= vValue[i].first;
2619  vfIncluded[i] = false;
2620  numSelected--;
2621  }
2622  }
2623  }
2624  }
2625  }
2626  return nFeeNeeded;
2627 }
2628 
2629 bool CWallet::SelectStakeCoins(std::list<std::unique_ptr<CStakeInput> >& listInputs, CAmount nTargetAmount)
2630 {
2631  std::vector<COutput> vCoins;
2632  AvailableCoins(vCoins, true, NULL, false, STAKABLE_COINS);
2633  CAmount nAmountSelected = 0;
2634  if (GetBoolArg("-prcystake", true)) {
2635  for (const COutput &out : vCoins) {
2636  //make sure not to outrun target amount
2637  CAmount value = getCOutPutValue(out);
2638  if (nAmountSelected + value > nTargetAmount)
2639  continue;
2640 
2641  //check that it is above Minimum Stake Amount
2642  if (value < Params().MinimumStakeAmount())
2643  continue;
2644 
2645  //check that it is not MN Collateral
2646  if (value == Params().MNCollateralAmt()) {
2647  COutPoint outpoint(out.tx->GetHash(), out.i);
2648  if (IsCollateralized(outpoint)) {
2649  continue;
2650  }
2651  }
2652 
2653  int64_t nTxTime = out.tx->GetTxTime();
2654 
2655  //check for min age
2656  if (GetAdjustedTime() - nTxTime < Params().StakeMinAge() && !Params().IsRegTestNet())
2657  continue;
2658 
2659  //check that it is matured
2660  if (out.nDepth < (out.tx->IsCoinStake() ? Params().COINBASE_MATURITY() : 10))
2661  continue;
2662 
2663  //add to our stake set
2664  nAmountSelected += value;
2665 
2666  std::unique_ptr<CPrcyStake> input(new CPrcyStake());
2667  input->SetInput((CTransaction) *out.tx, out.i);
2668  listInputs.emplace_back(std::move(input));
2669  }
2670  }
2671  return true;
2672 }
2673 
2675 {
2676  CAmount nBalance = GetBalance();
2677 
2678  // Regular PRCY
2679  if (nBalance > 0) {
2680  if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
2681  return error("%s : invalid reserve balance amount", __func__);
2682  if (nBalance <= nReserveBalance)
2683  return false;
2684 
2685  std::vector<COutput> vCoins;
2686  AvailableCoins(vCoins, true);
2687 
2688  for (const COutput& out : vCoins) {
2689  int64_t nTxTime = out.tx->GetTxTime();
2690 
2691  //add in-wallet minimum staking
2692  CAmount nVal = getCOutPutValue(out);
2693 
2694  //check that it is not MN Collateral
2695  bool isCollateral = false;
2696  if (nVal == Params().MNCollateralAmt()) {
2697  COutPoint outpoint(out.tx->GetHash(), out.i);
2698  if (IsCollateralized(outpoint)) {
2699  isCollateral = true;
2700  }
2701  }
2702 
2703  //nTxTime <= nTime: only stake with UTXOs that are received before nTime time
2704  if (Params().IsRegTestNet() || (GetAdjustedTime() > Params().StakeMinAge() + nTxTime && nVal >= Params().MinimumStakeAmount() && !isCollateral))
2705  return true;
2706  }
2707  }
2708 
2709  return false;
2710 }
2711 
2713 {
2714  minFee = 0;
2715  maxFee = 0;
2716  SetRingSize(0);
2717  CAmount nBalance = GetBalance();
2718  const CAmount minStakingAmount = Params().MinimumStakeAmount();
2719  if (IsMasternodeController()) {
2720  nBalance = GetSpendableBalance();
2721  }
2722  if (nBalance < minStakingAmount) {
2724  }
2725  if (nBalance - nReserveBalance < minStakingAmount) {
2727  }
2728 
2729  std::vector<COutput> vCoins, coinsUnderThreshold, coinsOverThreshold;
2731  CAmount nSpendableBalance = GetSpendableBalance();
2732 
2733  {
2735  {
2736  uint32_t nTime = ReadAutoConsolidateSettingTime();
2737  nTime = (nTime == 0)? GetAdjustedTime() : nTime;
2738 
2739  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
2740  const uint256& wtxid = it->first;
2741  const CWalletTx* pcoin = &(*it).second;
2742 
2743  {
2744  if (!CheckFinalTx(*pcoin))
2745  continue;
2746 
2747  int nDepth = pcoin->GetDepthInMainChain(false);
2748 
2749  // We should not consider coins which aren't at least in our mempool
2750  // It's possible for these to be conflicted via ancestors which we may never be able to detect
2751  if (nDepth <= 0)
2752  continue;
2753 
2754  if (pcoin->GetTxTime() > nTime) continue;
2755 
2756  for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2757  if (pcoin->vout[i].IsEmpty()) {
2758  continue;
2759  }
2760  CAmount value = getCTxOutValue(*pcoin, pcoin->vout[i]);
2761  if (value == Params().MNCollateralAmt()) {
2762  COutPoint outpoint(wtxid, i);
2763  if (IsCollateralized(outpoint)) {
2764  continue;
2765  }
2766  }
2767 
2768  isminetype mine = IsMine(pcoin->vout[i]);
2769  if (mine == ISMINE_NO)
2770  continue;
2771  if (mine == ISMINE_WATCH_ONLY)
2772  continue;
2773  if (IsLockedCoin(wtxid, i))
2774  continue;
2775  if (value <= 0)
2776  continue;
2777  if (IsSpent(wtxid, i)) {
2778  continue;
2779  }
2780 
2781  {
2782  COutPoint outpoint(wtxid, i);
2783  if (inSpendQueueOutpoints.count(outpoint)) {
2784  continue;
2785  }
2786  }
2787  COutput out(pcoin, i, nDepth, true);
2788  if (value >= minStakingAmount) {
2789  coinsOverThreshold.push_back(out);
2790  } else {
2791  coinsUnderThreshold.push_back(out);
2792  }
2793 
2794  vCoins.emplace_back(out);
2795  }
2796  }
2797  }
2798 
2799  //compute the number of consolidatation transaction will be made
2800  int numUTXOs = coinsUnderThreshold.size();
2801  int numConsolidationTxs = numUTXOs > 0? 1:0;
2802  minFee = ComputeFee(numUTXOs % (MAX_TX_INPUTS + 1), 1, MIN_RING_SIZE);
2803  maxFee = ComputeFee((numUTXOs >= MAX_TX_INPUTS? MAX_TX_INPUTS : numUTXOs + 1) % (MAX_TX_INPUTS + 1), 1, MAX_RING_SIZE);
2804  while (numUTXOs > MAX_TX_INPUTS) {
2805  numUTXOs -= (MAX_TX_INPUTS - 1);
2806  numConsolidationTxs++;
2807  minFee += ComputeFee(MAX_TX_INPUTS, 1, MIN_RING_SIZE);
2808  maxFee += ComputeFee(MAX_TX_INPUTS, 1, MAX_RING_SIZE);
2809  }
2810 
2811  if (nReserveBalance == 0) {
2812  if (coinsUnderThreshold.size() == 0) {
2814  } else {
2815  if (nBalance < minStakingAmount + maxFee) {
2817  }
2819  }
2820  } else {
2821  std::set<std::pair<const CWalletTx*, unsigned int> > setCoinsRet;
2822  CAmount nValueRet;
2823  //check whether need consolidation
2824  int ringSize = MIN_RING_SIZE + secp256k1_rand32() % (MAX_RING_SIZE - MIN_RING_SIZE + 1);
2825  CAmount MaxFeeSpendingReserve = ComputeFee(1, 2, MAX_RING_SIZE);
2826  CAmount estimatedFee = 0;
2827  bool selectCoinRet = SelectCoinsMinConf(true, estimatedFee, ringSize, 2, nReserveBalance + MaxFeeSpendingReserve, 1, 6, vCoins, setCoinsRet, nValueRet);
2828  if (!selectCoinRet) {
2829  //fail to even select coins to consolidation for reserve funds => ask to reduce
2831  }
2832  minFee += estimatedFee;
2833  maxFee += estimatedFee;
2835  }
2836 
2837  /* if (nReserveBalance == 0 && coinsOverThreshold.empty() && nBalance > minStakingAmount) {
2838  if (nSpendableBalance < minStakingAmount) {
2839  return StakingStatusError::UNSTAKABLE_DUE_TO_CONSILIDATION_FAILED; //not enough spendable balance
2840  }
2841  std::set<std::pair<const CWalletTx*, unsigned int> > setCoinsRet;
2842  CAmount nValueRet;
2843  int ringSize = MIN_RING_SIZE + secp256k1_rand32() % (MAX_RING_SIZE - MIN_RING_SIZE + 1);
2844  bool selectCoinRet = SelectCoins(true, ringSize, 1, minStakingAmount, setCoinsRet, nValueRet, NULL, AvailableCoinsType::ALL_COINS, false);
2845  if (!selectCoinRet) {
2846  return StakingStatusError::UNSTAKABLE_DUE_TO_CONSILIDATION_FAILED; //not enough spendable balance
2847  }
2848 
2849  return StakingStatusError::NEED_CONSOLIDATION_UTXO_UNDER_THRESHOLD;
2850  }
2851 
2852  if (nReserveBalance > 0) {
2853 
2854  }*/
2855  }
2856  }
2857 
2858  return ret;
2859 }
2860 
2861 bool CWallet::SelectCoinsMinConf(bool needFee, CAmount& feeNeeded, int ringSize, int numOut, const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet)
2862 {
2863  setCoinsRet.clear();
2864  nValueRet = 0;
2865  feeNeeded = 0;
2866  CAmount feeForOneInput = 0;
2867 
2868  // List of values less than target
2869  std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > coinLowestLarger;
2870  coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2871  coinLowestLarger.second.first = NULL;
2872  std::vector<std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > > vValue;
2873  CAmount nTotalLower = 0;
2874  std::string s = "";
2875 
2876  random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2877 
2878  for (const COutput& output : vCoins) {
2879  if (!output.fSpendable)
2880  continue;
2881 
2882  const CWalletTx* pcoin = output.tx;
2883  CAmount n = 0;
2884 
2885  if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2886  continue;
2887 
2888  if (!IsSpent(pcoin->GetHash(), output.i)) {
2889  n = getCTxOutValue(*pcoin, pcoin->vout[output.i]);
2890  }
2891  if (n == 0) continue;
2892  int i = output.i;
2893 
2894  std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > coin = std::make_pair(n, std::make_pair(pcoin, i));
2895 
2896  if (needFee) {
2897  feeNeeded = ComputeFee(vValue.size() + 1, numOut, ringSize);
2898  feeForOneInput = ComputeFee(1, numOut, ringSize);
2899  }
2900  if (n == nTargetValue + feeForOneInput) {
2901  setCoinsRet.clear();
2902  setCoinsRet.insert(coin.second);
2903  nValueRet = coin.first;
2904  feeNeeded = feeForOneInput;
2905  return true;
2906  } else if (n < nTargetValue + feeNeeded) {
2907  vValue.push_back(coin);
2908  nTotalLower += n;
2909  } else if (n < coinLowestLarger.first) {
2910  coinLowestLarger = coin;
2911  }
2912  }
2913 
2914  if (vValue.size() <= MAX_TX_INPUTS) {
2915  if (nTotalLower == nTargetValue + feeNeeded) {
2916  for (unsigned int i = 0; i < vValue.size(); ++i) {
2917  setCoinsRet.insert(vValue[i].second);
2918  nValueRet += vValue[i].first;
2919  }
2920  return true;
2921  }
2922  }
2923  if (nTotalLower < nTargetValue + feeNeeded) {
2924  if (coinLowestLarger.second.first == NULL)
2925  return false;
2926  setCoinsRet.insert(coinLowestLarger.second);
2927  nValueRet += coinLowestLarger.first;
2928  return true;
2929  } else {
2930  CAmount maxFee = ComputeFee(50, numOut, ringSize);
2931  if (vValue.size() <= MAX_TX_INPUTS) {
2932  //putting all into the transaction
2933  s = "";
2934  for (unsigned int i = 0; i < vValue.size(); i++) {
2935  setCoinsRet.insert(vValue[i].second);
2936  nValueRet += vValue[i].first;
2937  s += FormatMoney(vValue[i].first) + " ";
2938  }
2939  LogPrintf("%s: best subset: %s - total %s\n", __func__, s, FormatMoney(nValueRet));
2940  return true;
2941  } else {
2942  }
2943  }
2944  if (vValue.size() <= MAX_TX_INPUTS) {
2945  //putting all into the transaction
2946  s = "";
2947  for (unsigned int i = 0; i < vValue.size(); i++) {
2948  setCoinsRet.insert(vValue[i].second);
2949  nValueRet += vValue[i].first;
2950  s += FormatMoney(vValue[i].first) + " ";
2951  }
2952  LogPrintf("%s: best subset: %s - total %s\n", __func__, s, FormatMoney(nValueRet));
2953  return true;
2954  }
2955 
2956  // Solve subset sum by stochastic approximation
2957  std::sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
2958  //fees for 50 inputs
2959  feeNeeded = ComputeFee(50, numOut, ringSize);
2960  //check if the sum of first 50 largest UTXOs > nTargetValue + nfeeNeeded
2961  for (unsigned int i = 0; i <= MAX_TX_INPUTS; i++) {
2962  nValueRet += vValue[i].first;
2963  }
2964  if (nValueRet < nTargetValue + feeNeeded) {
2965  nValueRet = 0;
2966  for (unsigned int i = 0; i < vValue.size(); i++) {
2967  setCoinsRet.insert(vValue[i].second);
2968  }
2969  return false; //transaction too large
2970  }
2971  nValueRet = 0;
2972 
2973  std::vector<char> vfBest;
2974  CAmount nBest;
2975  feeNeeded = ApproximateBestSubset(numOut, ringSize, vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
2976 
2977  // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2978  // or the next bigger coin is closer), return the bigger coin
2979  if (coinLowestLarger.second.first &&
2980  ((nBest != nTargetValue + feeNeeded && nBest < nTargetValue + feeNeeded) || coinLowestLarger.first <= nBest)) {
2981  setCoinsRet.insert(coinLowestLarger.second);
2982  nValueRet += coinLowestLarger.first;
2983  } else {
2984  s = "";
2985  for (unsigned int i = 0; i < vValue.size(); i++) {
2986  if (vfBest[i]) {
2987  setCoinsRet.insert(vValue[i].second);
2988  nValueRet += vValue[i].first;
2989  s += FormatMoney(vValue[i].first) + " ";
2990  }
2991  }
2992  LogPrintf("%s: best subset: %s - total %s\n", __func__, s, FormatMoney(nBest));
2993  }
2994 
2995  return true;
2996 }
2997 
2999 {
3001  if (chainActive.Height() > 0 && !inSpendQueueOutpoints.empty()) return;
3002  {
3003  {
3004  LOCK(mempool.cs);
3005  {
3006  inSpendQueueOutpoints.clear();
3007  for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mempool.mapTx.begin(); it != mempool.mapTx.end(); ++it) {
3008  const CTransaction& tx = it->second.GetTx();
3009  for (size_t i = 0; i < tx.vin.size(); i++) {
3010  COutPoint prevout = findMyOutPoint(tx.vin[i]);
3011  if (prevout.hash.IsNull()) {
3012  break;
3013  } else {
3014  inSpendQueueOutpoints[prevout] = true;
3015  }
3016  }
3017  }
3018  }
3019  }
3020  }
3021 }
3022 
3023 bool CWallet::SelectCoins(bool needFee, CAmount& estimatedFee, int ringSize, int numOut, const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX)
3024 {
3025  // Note: this function should never be used for "always free" tx types like dstx
3026  std::vector<COutput> vCoins;
3027  vCoins.clear();
3028 
3029  AvailableCoins(vCoins, true, coinControl, false, coin_type, useIX);
3030 
3031  // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
3032  if (coinControl && coinControl->HasSelected()) {
3033  for (const COutput& out : vCoins) {
3034  if (!out.fSpendable)
3035  continue;
3036 
3037  nValueRet += getCOutPutValue(out);
3038  setCoinsRet.insert(std::make_pair(out.tx, out.i));
3039  }
3040  return (nValueRet >= nTargetValue);
3041  }
3042 
3043  return (SelectCoinsMinConf(needFee, estimatedFee, ringSize, numOut, nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
3044  SelectCoinsMinConf(needFee, estimatedFee, ringSize, numOut, nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
3045  (bSpendZeroConfChange && SelectCoinsMinConf(needFee, estimatedFee, ringSize, numOut, nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
3046 }
3047 
3049 {
3051  if (mne.getTxHash() == outpoint.hash.GetHex() && mne.getOutputIndex() == outpoint.n) {
3052  return true;
3053  }
3054  }
3055  return false;
3056 }
3057 
3059 {
3060  return masternodeConfig.getEntries().size() > 0;
3061 }
3062 
3064 {
3065  CWalletTx wtx;
3066  if (GetBudgetSystemCollateralTX(wtx, hash, useIX)) {
3067  tx = (CTransaction)wtx;
3068  return true;
3069  }
3070  return false;
3071 }
3072 
3074 {
3075  // make our change address
3076  CReserveKey reservekey(this);
3077 
3078  CScript scriptChange;
3079  scriptChange << OP_RETURN << ToByteVector(hash);
3080 
3081  CAmount nFeeRet = 0;
3082  std::string strFail = "";
3083  std::vector<std::pair<CScript, CAmount> > vecSend;
3084  vecSend.push_back(std::make_pair(scriptChange, BUDGET_FEE_TX));
3085 
3086  CCoinControl* coinControl = NULL;
3087  bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0);
3088  if (!success) {
3089  LogPrintf("GetBudgetSystemCollateralTX: Error - %s\n", strFail);
3090  return false;
3091  }
3092 
3093  return true;
3094 }
3095 
3096 bool CWallet::CreateCommitment(const CAmount val, CKey& blind, std::vector<unsigned char>& commitment)
3097 {
3098  blind.MakeNewKey(true);
3099  return CreateCommitment(blind.begin(), val, commitment);
3100 }
3101 
3102 bool CWallet::CreateCommitmentWithZeroBlind(const CAmount val, unsigned char* pBlind, std::vector<unsigned char>& commitment)
3103 {
3104  memset(pBlind, 0, 32);
3105  return CreateCommitment(pBlind, val, commitment);
3106 }
3107 
3108 bool CWallet::CreateCommitment(const unsigned char* blind, CAmount val, std::vector<unsigned char>& commitment)
3109 {
3110  secp256k1_context2* both = GetContext();
3111  secp256k1_pedersen_commitment commitmentD;
3112  if (!secp256k1_pedersen_commit(both, &commitmentD, blind, val, &secp256k1_generator_const_h, &secp256k1_generator_const_g)) {
3113  return false;
3114  }
3115  unsigned char output[33];
3116  if (!secp256k1_pedersen_commitment_serialize(both, output, &commitmentD)) {
3117  return false;
3118  }
3119  std::copy(output, output + 33, std::back_inserter(commitment));
3120  return true;
3121 }
3122 
3123 int CWallet::ComputeTxSize(size_t numIn, size_t numOut, size_t ringSize)
3124 {
3125  int txinSize = 36 + 4 + 33 + 36 * ringSize;
3126  int txoutSize = 8 + 35 + 33 + 32 + 32 + 32 + 33;
3127  int bpSize = numOut == 1 ? 675 : 738;
3128  int txSize = 4 + numIn * txinSize + numOut * txoutSize + 4 + 1 + 8 + 4 + bpSize + 8 + 32 + (numIn + 1) * (ringSize + 1) * 32 + 33;
3129  return txSize;
3130 }
3131 
3132 //compute the amount that let users send reserve balance
3134  SetRingSize(0);
3135  CAmount fee = ComputeFee(1, 2, MAX_RING_SIZE);
3136  return nReserveBalance + fee;
3137 }
3138 
3139 int CWallet::ComputeFee(size_t numIn, size_t numOut, size_t ringSize)
3140 {
3141  int txSize = ComputeTxSize(numIn, numOut, ringSize);
3142  CAmount nFeeNeeded = GetMinimumFee(txSize, nTxConfirmTarget, mempool);
3143  if (nFeeNeeded > MAX_FEE) nFeeNeeded = MAX_FEE;
3144  return nFeeNeeded;
3145 }
3146 
3147 bool CWallet::CreateTransactionBulletProof(const CKey& txPrivDes, const CPubKey& recipientViewKey, CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay, int ringSize, bool sendtoMyself)
3148 {
3149  std::vector<std::pair<CScript, CAmount> > vecSend;
3150  vecSend.push_back(std::make_pair(scriptPubKey, nValue));
3151  return CreateTransactionBulletProof(txPrivDes, recipientViewKey, vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay, ringSize, sendtoMyself);
3152 }
3153 
3154 //settingTime = 0 => auto consolidate on
3155 //settingTime > 0 => only consolidate transactions came before this settingTime
3157 {
3159 }
3160 
3162 {
3164 }
3165 
3167 {
3168  return ReadAutoConsolidateSettingTime() > 0;
3169 }
3170 
3171 bool CWallet::CreateTransactionBulletProof(const CKey& txPrivDes, const CPubKey& recipientViewKey, const std::vector<std::pair<CScript, CAmount> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay, int ringSize, bool tomyself)
3172 {
3173  if (useIX && nFeePay < CENT) nFeePay = CENT;
3174  SetRingSize(0);
3175 
3176  //randomize ring size
3177  unsigned char rand_seed[16];
3178  memcpy(rand_seed, txPrivDes.begin(), 16);
3179  secp256k1_rand_seed(rand_seed);
3180  ringSize = MIN_RING_SIZE + secp256k1_rand32() % (MAX_RING_SIZE - MIN_RING_SIZE + 1);
3181 
3182  //Currently we only allow transaction with one or two recipients
3183  //If two, the second recipient is a change output
3184  if (vecSend.size() > 1) {
3185  strFailReason = _("Currently the Number of supported recipients must be 1");
3186  return false;
3187  }
3188 
3189  CAmount nValue = 0;
3190 
3191  for (const PAIRTYPE(CScript, CAmount) & s : vecSend) {
3192  if (nValue < 0) {
3193  strFailReason = _("Transaction amounts must be positive");
3194  return false;
3195  }
3196  nValue += s.second;
3197  }
3198  if (vecSend.empty() || nValue < 0) {
3199  strFailReason = _("Transaction amounts must be positive");
3200  return false;
3201  }
3202 
3203  wtxNew.fTimeReceivedIsTxTime = true;
3204  wtxNew.BindWallet(this);
3205  CMutableTransaction txNew;
3206  txNew.hasPaymentID = wtxNew.hasPaymentID;
3207  txNew.paymentID = wtxNew.paymentID;
3208  CAmount nSpendableBalance = GetSpendableBalance();
3209  bool ret = true;
3210  {
3212  {
3213  nFeeRet = 0;
3214  if (nFeePay > 0) nFeeRet = nFeePay;
3215  unsigned int nBytes = 0;
3216  int iterations = 0;
3217  while (true && iterations < 10) {
3218  iterations++;
3219  txNew.vin.clear();
3220  txNew.vout.clear();
3221  wtxNew.fFromMe = true;
3222 
3223  CAmount nTotalValue = nValue + nFeeRet;
3224  double dPriority = 0;
3225 
3226  // vouts to the payees
3227  for (const PAIRTYPE(CScript, CAmount) & s : vecSend) {
3228  CTxOut txout(s.second, s.first);
3229  CPubKey txPub = txPrivDes.GetPubKey();
3230  txPrivKeys.push_back(txPrivDes);
3231  std::copy(txPub.begin(), txPub.end(), std::back_inserter(txout.txPub));
3232  if (txout.IsDust(::minRelayTxFee)) {
3233  strFailReason = _("Transaction amount too small");
3234  ret = false;
3235  break;
3236  }
3237  CPubKey sharedSec;
3238  ECDHInfo::ComputeSharedSec(txPrivDes, recipientViewKey, sharedSec);
3239  EncodeTxOutAmount(txout, txout.nValue, sharedSec.begin());
3240  txNew.vout.push_back(txout);
3241  nBytes += ::GetSerializeSize(*(CTxOut*)&txout, SER_NETWORK, PROTOCOL_VERSION);
3242  }
3243 
3244  if (!ret) break;
3245 
3246  // Choose coins to use
3247  std::set<std::pair<const CWalletTx*, unsigned int> > setCoins;
3248  CAmount nValueIn = 0;
3249  CAmount estimateFee;
3250  if (!SelectCoins(true, estimateFee, ringSize, 2, nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) {
3251  if (coin_type == ALL_COINS) {
3252  if (nSpendableBalance < nTotalValue + estimateFee) {
3253  //spendable is less than total + fee
3254  if (estimateFee > 0)
3255  //fee is greater than 0, causing insufficient funds
3256  strFailReason = "Insufficient funds. Transaction requires a fee of " + ValueFromAmountToString(estimateFee);
3257  else if (nReserveBalance <= nTotalValue && nReserveBalance != 0)
3258  //reserve less than/equal total value
3259  strFailReason = "Insufficient reserved funds! Your wallet is staking with a reserve balance of " + ValueFromAmountToString(nReserveBalance) + " less than the sending amount " + ValueFromAmountToString(nTotalValue);
3260  } else if (nTotalValue >= nReserveBalance && nReserveBalance != 0) {
3261  //total greater than equal to reserve
3262  strFailReason = "Insufficient reserved funds! Your wallet is staking with a reserve balance of " + ValueFromAmountToString(nReserveBalance) + " less than the sending amount " + ValueFromAmountToString(nTotalValue);
3263  } else if (setCoins.size() > MAX_TX_INPUTS) {
3264  //max inputs
3265  strFailReason = _("You have attempted to send more than 50 UTXOs in a single transaction. To work around this limitation, please either lower the total amount of the transaction or send two separate transactions with 50% of your total desired amount.");
3266  } else {
3267  //other
3268  strFailReason = _("Error in CreateTransactionBulletProof. Please try again.");
3269  }
3270  }
3271 
3272  ret = false;
3273  break;
3274  }
3275 
3276  CAmount nChange = nValueIn - nValue - nFeeRet;
3277 
3278  if (nChange >= 0) {
3279  // Fill a vout to ourself
3280  CScript scriptChange;
3281  scriptChange = GetScriptForDestination(coinControl->receiver);
3282 
3283  CTxOut newTxOut(nChange, scriptChange);
3284  txPrivKeys.push_back(coinControl->txPriv);
3285  CPubKey txPubChange = coinControl->txPriv.GetPubKey();
3286  std::copy(txPubChange.begin(), txPubChange.end(), std::back_inserter(newTxOut.txPub));
3287  nBytes += ::GetSerializeSize(*(CTxOut*)&newTxOut, SER_NETWORK, PROTOCOL_VERSION);
3288  //formulae for ring signature size
3289  int rsSize = ComputeTxSize(setCoins.size(), 2, ringSize);
3290  nBytes = rsSize;
3291  CAmount nFeeNeeded = std::max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool));
3292  LogPrintf("%s: nFeeNeeded=%d, rsSize=%d\n", __func__, nFeeNeeded, rsSize);
3293  if (nFeeNeeded >= MAX_FEE) nFeeNeeded = MAX_FEE;
3294  newTxOut.nValue -= nFeeNeeded;
3295  txNew.nTxFee = nFeeNeeded;
3296  if (newTxOut.nValue < 0) {
3297  if (nSpendableBalance > nValueIn) {
3298  continue;
3299  }
3300  ret = false;
3301  break;
3302  }
3303  CPubKey shared;
3304  computeSharedSec(txNew, newTxOut, shared);
3305  EncodeTxOutAmount(newTxOut, newTxOut.nValue, shared.begin());
3306  if (tomyself)
3307  txNew.vout.push_back(newTxOut);
3308  else {
3309  std::vector<CTxOut>::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1);
3310  txNew.vout.insert(position, newTxOut);
3311  }
3312  } else {
3313  if (nSpendableBalance > nValueIn) {
3314  continue;
3315  }
3316  ret = false;
3317  break;
3318  }
3319 
3320  // Fill vin
3321  for (const PAIRTYPE(const CWalletTx*, unsigned int) & coin : setCoins)
3322  txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second));
3323 
3324  // Embed the constructed transaction data in wtxNew.
3325  *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
3326  break;
3327  }
3328  if (ret && !makeRingCT(wtxNew, ringSize, strFailReason)) {
3329  ret = false;
3330  }
3331 
3332  if (ret && !generateBulletProofAggregate(wtxNew)) {
3333  strFailReason = _("Failed to generate bulletproof");
3334  ret = false;
3335  }
3336 
3337  if (ret) {
3338  //set transaction output amounts as 0
3339  for (size_t i = 0; i < wtxNew.vout.size(); i++) {
3340  wtxNew.vout[i].nValue = 0;
3341  }
3342 
3343  if (!CommitTransaction(wtxNew, reservekey, (!useIX ? NetMsgType::TX : NetMsgType::IX))) {
3345  ret = false;
3346  strFailReason = _("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
3347  }
3348  for (size_t i = 0; i < inSpendQueueOutpointsPerSession.size(); i++) {
3350  }
3352 
3353  uint256 hash = wtxNew.GetHash();
3354  int maxTxPrivKeys = txPrivKeys.size() > wtxNew.vout.size() ? wtxNew.vout.size() : txPrivKeys.size();
3355  for (int i = 0; i < maxTxPrivKeys; i++) {
3356  std::string key = hash.GetHex() + std::to_string(i);
3358  }
3359  txPrivKeys.clear();
3360  }
3361  }
3362  }
3363 
3364  return ret;
3365 }
3366 
3367 bool CWallet::CreateTransaction(const std::vector<std::pair<CScript, CAmount> >& vecSend,
3368  CWalletTx& wtxNew,
3369  CReserveKey& reservekey,
3370  CAmount& nFeeRet,
3371  std::string& strFailReason,
3372  const CCoinControl* coinControl,
3373  AvailableCoinsType coin_type,
3374  bool useIX,
3375  CAmount nFeePay)
3376 {
3377  if (useIX && nFeePay < CENT) nFeePay = CENT;
3378 
3379  CAmount nValue = 0;
3380 
3381  for (const PAIRTYPE(CScript, CAmount) & s : vecSend) {
3382  if (nValue < 0) {
3383  strFailReason = _("Transaction amounts must be positive");
3384  return false;
3385  }
3386  nValue += s.second;
3387  }
3388  if (vecSend.empty() || nValue < 0) {
3389  strFailReason = _("Transaction amounts must be positive");
3390  return false;
3391  }
3392 
3393  wtxNew.fTimeReceivedIsTxTime = true;
3394  wtxNew.BindWallet(this);
3395  CMutableTransaction txNew;
3396  txNew.hasPaymentID = wtxNew.hasPaymentID;
3397  txNew.paymentID = wtxNew.paymentID;
3398  wtxNew.txType = TX_TYPE_REVEAL_AMOUNT;
3399  txNew.txType = TX_TYPE_REVEAL_AMOUNT;
3400  txNew.nTxFee = wtxNew.nTxFee;
3401 
3402  {
3404  {
3405  nFeeRet = txNew.nTxFee;
3406  if (nFeePay > 0) nFeeRet = nFeePay;
3407  while (true) {
3408  txNew.vin.clear();
3409  txNew.vout.clear();
3410  wtxNew.fFromMe = true;
3411 
3412  CAmount nTotalValue = nValue + nFeeRet;
3413  double dPriority = 0;
3414 
3415  // vouts to the payees
3416  if (coinControl && !coinControl->fSplitBlock) {
3417  for (const PAIRTYPE(CScript, CAmount) & s : vecSend) {
3418  CTxOut txout(s.second, s.first);
3419  if (txout.IsDust(::minRelayTxFee)) {
3420  strFailReason = _("Transaction amount too small");
3421  return false;
3422  }
3423  txNew.vout.push_back(txout);
3424  }
3425  } else //UTXO Splitter Transaction
3426  {
3427  int nSplitBlock;
3428 
3429  if (coinControl)
3430  nSplitBlock = coinControl->nSplitBlock;
3431  else
3432  nSplitBlock = 1;
3433 
3434  for (const PAIRTYPE(CScript, CAmount) & s : vecSend) {
3435  for (int i = 0; i < nSplitBlock; i++) {
3436  if (i == nSplitBlock - 1) {
3437  uint64_t nRemainder = s.second % nSplitBlock;
3438  txNew.vout.push_back(CTxOut((s.second / nSplitBlock) + nRemainder, s.first));
3439  } else
3440  txNew.vout.push_back(CTxOut(s.second / nSplitBlock, s.first));
3441  }
3442  }
3443  }
3444 
3445  // Choose coins to use
3446  std::set<std::pair<const CWalletTx*, unsigned int> > setCoins;
3447  CAmount nValueIn = 0;
3448  CAmount estimatedFee = 0;
3449  if (!SelectCoins(true, estimatedFee, 10, 2, nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) {
3450  if (coin_type == ALL_COINS) {
3451  strFailReason = _("Insufficient funds.");
3452  } else {
3453  strFailReason = _("Error in CreateTransaction. Please try again.");
3454  }
3455 
3456  return false;
3457  }
3458 
3459 
3460  for (PAIRTYPE(const CWalletTx*, unsigned int) pcoin : setCoins) {
3461  CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
3462  //The coin age after the next block (depth+1) is used instead of the current,
3463  //reflecting an assumption the user would accept a bit more delay for
3464  //a chance at a free transaction.
3465  //But mempool inputs might still be in the mempool, so their age stays 0
3466  int age = pcoin.first->GetDepthInMainChain();
3467  if (age != 0)
3468  age += 1;
3469  dPriority += (double)nCredit * age;
3470  }
3471 
3472  CAmount nChange = nValueIn - nValue - nFeeRet;
3473 
3474  if (nChange > 0) {
3475  // Fill a vout to ourself
3476  // TODO: pass in scriptChange instead of reservekey so
3477  // change transaction isn't always pay-to-prcycoin-address
3478  CScript scriptChange;
3479 
3480  // coin control: send change to custom address
3481 
3482  // Note: We use a new key here to keep it from being obvious which side is the change.
3483  // The drawback is that by not reusing a previous key, the change may be lost if a
3484  // backup is restored, if the backup doesn't have the new private key for the change.
3485  // If we reused the old key, it would be possible to add code to look for and
3486  // rediscover unknown transactions that were written with keys of ours to recover
3487  // post-backup change.
3488 
3489  // Reserve a new key pair from key pool
3490  CPubKey vchPubKey;
3491  bool ret;
3492  ret = reservekey.GetReservedKey(vchPubKey);
3493  assert(ret); // should never fail, as we just unlocked
3494 
3495  scriptChange = GetScriptForDestination(vchPubKey);
3496 
3497  CTxOut newTxOut(nChange, scriptChange);
3498 
3499  // Never create dust outputs; if we would, just
3500  // add the dust to the fee.
3501  if (newTxOut.IsDust(::minRelayTxFee)) {
3502  nFeeRet += nChange;
3503  nChange = 0;
3504  reservekey.ReturnKey();
3505  } else {
3506  // Insert change txn at random position:
3507  std::vector<CTxOut>::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1);
3508  txNew.vout.insert(position, newTxOut);
3509  }
3510  } else
3511  reservekey.ReturnKey();
3512 
3513  // Fill vin
3514  for (const PAIRTYPE(const CWalletTx*, unsigned int) & coin : setCoins)
3515  txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second));
3516 
3517  // Sign
3518  int nIn = 0;
3519  for (const PAIRTYPE(const CWalletTx*, unsigned int) & coin : setCoins)
3520  if (!SignSignature(*this, *coin.first, txNew, nIn++)) {
3521  strFailReason = _("Signing transaction failed");
3522  return false;
3523  }
3524  // Embed the constructed transaction data in wtxNew.
3525  *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
3526 
3527  // Limit size
3528  unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
3529  if (nBytes >= MAX_STANDARD_TX_SIZE) {
3530  strFailReason = _("Transaction too large");
3531  return false;
3532  }
3533  dPriority = wtxNew.ComputePriority(dPriority, nBytes);
3534 
3535  // Can we complete this as a free transaction?
3536  if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) {
3537  // Not enough fee: enough priority?
3538  double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
3539  // Not enough mempool history to estimate: use hard-coded AllowFree.
3540  if (dPriorityNeeded <= 0 && AllowFree(dPriority))
3541  break;
3542 
3543  // Small enough, and priority high enough, to send for free
3544  if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
3545  break;
3546  }
3547 
3548  CAmount nFeeNeeded = std::max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool));
3549 
3550  // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
3551  // because we must be at the maximum allowed fee.
3552  if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) {
3553  strFailReason = _("Transaction too large for fee policy");
3554  return false;
3555  }
3556 
3557  break;
3558  }
3559  }
3560  }
3561  return true;
3562 }
3563 
3565 {
3566  unsigned char proof[2000];
3567  size_t len = 2000;
3568  const size_t MAX_VOUT = 5;
3569  unsigned char nonce[32];
3570  GetRandBytes(nonce, 32);
3571  unsigned char blinds[MAX_VOUT][32];
3572  uint64_t values[MAX_VOUT];
3573  size_t i = 0;
3574  const unsigned char* blind_ptr[MAX_VOUT];
3575  if (tx.vout.size() > MAX_VOUT) return false;
3576  memset(blinds, 0, tx.vout.size() * 32);
3577  for (i = 0; i < tx.vout.size(); i++) {
3578  memcpy(&blinds[i][0], tx.vout[i].maskValue.inMemoryRawBind.begin(), 32);
3579  blind_ptr[i] = blinds[i];
3580  values[i] = tx.vout[i].nValue;
3581  }
3582  int ret = secp256k1_bulletproof_rangeproof_prove(GetContext(), GetScratch(), GetGenerator(), proof, &len, values, NULL, blind_ptr, tx.vout.size(), &secp256k1_generator_const_h, 64, nonce, NULL, 0);
3583  std::copy(proof, proof + len, std::back_inserter(tx.bulletproofs));
3584  return ret;
3585 }
3586 
3587 bool CWallet::makeRingCT(CTransaction& wtxNew, int ringSize, std::string& strFailReason)
3588 {
3589  LogPrintf("Making RingCT using ring size=%d\n", ringSize);
3590  int myIndex;
3591  if (!selectDecoysAndRealIndex(wtxNew, myIndex, ringSize)) {
3592  return false;
3593  }
3594  secp256k1_context2* both = GetContext();
3595 
3596  for (CTxOut& out : wtxNew.vout) {
3597  if (!out.IsEmpty()) {
3598  secp256k1_pedersen_commitment commitment;
3599  CKey blind;
3600  blind.Set(out.maskValue.inMemoryRawBind.begin(), out.maskValue.inMemoryRawBind.end(), true);
3602  throw std::runtime_error("Cannot commit commitment");
3603  unsigned char output[33];
3604  if (!secp256k1_pedersen_commitment_serialize(both, output, &commitment))
3605  throw std::runtime_error("Cannot serialize commitment");
3606  out.commitment.clear();
3607  std::copy(output, output + 33, std::back_inserter(out.commitment));
3608  }
3609  }
3610 
3611  SetRingSize(0);
3612  const size_t MAX_VIN = MAX_TX_INPUTS;
3613  const size_t MAX_DECOYS = MAX_RING_SIZE; //padding 1 for safety reasons
3614  const size_t MAX_VOUT = 5;
3615 
3616  if (wtxNew.vin.size() > MAX_TX_INPUTS || wtxNew.vin.size() == 0) {
3617  strFailReason = _("You have attempted to send a total value that is comprised of more than 50 smaller deposits. This is a rare occurrence, and lowering the total value sent, or sending the same total value in two separate transactions will usually work around this limitation.");
3618  return false;
3619  }
3620 
3621  for (size_t i = 0; i < wtxNew.vin.size(); i++) {
3622  if (wtxNew.vin[i].decoys.size() != wtxNew.vin[0].decoys.size()) {
3623  strFailReason = _("All inputs should have the same number of decoys");
3624  return false;
3625  }
3626  }
3627 
3628  if (wtxNew.vin[0].decoys.size() > MAX_DECOYS || wtxNew.vin[0].decoys.size() < MIN_RING_SIZE) {
3629  strFailReason = _("Too many decoys");
3630  return false; //maximum decoys = 15
3631  }
3632 
3633  std::vector<secp256k1_pedersen_commitment> myInputCommiments;
3634  int totalCommits = wtxNew.vin.size() + wtxNew.vout.size();
3635  int npositive = wtxNew.vin.size();
3636  unsigned char myBlinds[MAX_VIN + MAX_VIN + MAX_VOUT + 1][32]; //myBlinds is used for compuitng additional private key in the ring =
3637  memset(myBlinds, 0, (MAX_VIN + MAX_VIN + MAX_VOUT + 1) * 32);
3638  const unsigned char* bptr[MAX_VIN + MAX_VIN + MAX_VOUT + 1];
3639  //all in pubkeys + an additional public generated from commitments
3640  unsigned char allInPubKeys[MAX_VIN + 1][MAX_DECOYS + 1][33];
3641  unsigned char allKeyImages[MAX_VIN + 1][33];
3642  unsigned char allInCommitments[MAX_VIN][MAX_DECOYS + 1][33];
3643  unsigned char allOutCommitments[MAX_VOUT][33];
3644 
3645  int myBlindsIdx = 0;
3646  //additional member in the ring = Sum of All input public keys + sum of all input commitments - sum of all output commitments
3647  for (size_t j = 0; j < wtxNew.vin.size(); j++) {
3648  COutPoint myOutpoint;
3649  if (myIndex == -1) {
3650  myOutpoint = wtxNew.vin[j].prevout;
3651  } else {
3652  myOutpoint = wtxNew.vin[j].decoys[myIndex];
3653  }
3654  CTransaction& inTx = mapWallet[myOutpoint.hash];
3655  CKey tmp;
3656  if (!findCorrespondingPrivateKey(inTx.vout[myOutpoint.n], tmp))
3657  throw std::runtime_error("Cannot find private key corresponding to the input");
3658  memcpy(&myBlinds[myBlindsIdx][0], tmp.begin(), 32);
3659  bptr[myBlindsIdx] = &myBlinds[myBlindsIdx][0];
3660  myBlindsIdx++;
3661  }
3662 
3663  //Collecting input commitments blinding factors
3664  for (CTxIn& in : wtxNew.vin) {
3665  COutPoint myOutpoint;
3666  if (myIndex == -1) {
3667  myOutpoint = in.prevout;
3668  } else {
3669  myOutpoint = in.decoys[myIndex];
3670  }
3671  CTransaction& inTx = mapWallet[myOutpoint.hash];
3672  secp256k1_pedersen_commitment inCommitment;
3673  if (!secp256k1_pedersen_commitment_parse(both, &inCommitment, &(inTx.vout[myOutpoint.n].commitment[0]))) {
3674  strFailReason = _("Cannot parse the commitment for inputs");
3675  return false;
3676  }
3677 
3678  myInputCommiments.push_back(inCommitment);
3679  CAmount tempAmount;
3680  CKey tmp;
3681  RevealTxOutAmount(inTx, inTx.vout[myOutpoint.n], tempAmount, tmp);
3682  if (tmp.IsValid()) memcpy(&myBlinds[myBlindsIdx][0], tmp.begin(), 32);
3683  //verify input commitments
3684  std::vector<unsigned char> recomputedCommitment;
3685  if (!CreateCommitment(&myBlinds[myBlindsIdx][0], tempAmount, recomputedCommitment))
3686  throw std::runtime_error("Cannot create pedersen commitment");
3687  if (recomputedCommitment != inTx.vout[myOutpoint.n].commitment) {
3688  strFailReason = _("Input commitments are not correct");
3689  return false;
3690  }
3691 
3692  bptr[myBlindsIdx] = myBlinds[myBlindsIdx];
3693  myBlindsIdx++;
3694  }
3695 
3696  //collecting output commitment blinding factors
3697  for (CTxOut& out : wtxNew.vout) {
3698  if (!out.IsEmpty()) {
3699  if (out.maskValue.inMemoryRawBind.IsValid()) {
3700  memcpy(&myBlinds[myBlindsIdx][0], out.maskValue.inMemoryRawBind.begin(), 32);
3701  }
3702  bptr[myBlindsIdx] = &myBlinds[myBlindsIdx][0];
3703  myBlindsIdx++;
3704  }
3705  }
3706  CKey newBlind;
3707  newBlind.MakeNewKey(true);
3708  memcpy(&myBlinds[myBlindsIdx][0], newBlind.begin(), 32);
3709  bptr[myBlindsIdx] = &myBlinds[myBlindsIdx][0];
3710 
3711  int myRealIndex = 0;
3712  if (myIndex != -1) {
3713  myRealIndex = myIndex + 1;
3714  }
3715 
3716  int PI = myRealIndex;
3717  unsigned char SIJ[MAX_VIN + 1][MAX_DECOYS + 1][32];
3718  unsigned char LIJ[MAX_VIN + 1][MAX_DECOYS + 1][33];
3719  unsigned char RIJ[MAX_VIN + 1][MAX_DECOYS + 1][33];
3720  unsigned char ALPHA[MAX_VIN + 1][32];
3721  unsigned char AllPrivKeys[MAX_VIN + 1][32];
3722 
3723  //generating LIJ and RIJ at PI: LIJ[j][PI], RIJ[j][PI], j=0..wtxNew.vin.size()
3724  for (size_t j = 0; j < wtxNew.vin.size(); j++) {
3725  COutPoint myOutpoint;
3726  if (myIndex == -1) {
3727  myOutpoint = wtxNew.vin[j].prevout;
3728  } else {
3729  myOutpoint = wtxNew.vin[j].decoys[myIndex];
3730  }
3731  CTransaction& inTx = mapWallet[myOutpoint.hash];
3732  CKey tempPk;
3733  //looking for private keys corresponding to my real inputs
3734  if (!findCorrespondingPrivateKey(inTx.vout[myOutpoint.n], tempPk)) {
3735  strFailReason = _("Cannot find corresponding private key");
3736  return false;
3737  }
3738  memcpy(AllPrivKeys[j], tempPk.begin(), 32);
3739  //copying corresponding key images
3740  memcpy(allKeyImages[j], wtxNew.vin[j].keyImage.begin(), 33);
3741  //copying corresponding in public keys
3742  CPubKey tempPubKey = tempPk.GetPubKey();
3743  memcpy(allInPubKeys[j][PI], tempPubKey.begin(), 33);
3744 
3745  memcpy(allInCommitments[j][PI], &(inTx.vout[myOutpoint.n].commitment[0]), 33);
3746  CKey alpha;
3747  alpha.MakeNewKey(true);
3748  memcpy(ALPHA[j], alpha.begin(), 32);
3749  CPubKey LIJ_PI = alpha.GetPubKey();
3750  memcpy(LIJ[j][PI], LIJ_PI.begin(), 33);
3751  PointHashingSuccessively(tempPubKey, alpha.begin(), RIJ[j][PI]);
3752  }
3753 
3754  //computing additional input pubkey and key images
3755  //additional private key = sum of all existing private keys + sum of all blinds in - sum of all blind outs
3756  unsigned char outSum[32];
3757  if (!secp256k1_pedersen_blind_sum(both, outSum, (const unsigned char* const*)bptr, npositive + totalCommits, 2 * npositive))
3758  throw std::runtime_error("Cannot compute pedersen blind sum");
3759  memcpy(myBlinds[myBlindsIdx], outSum, 32);
3760  memcpy(AllPrivKeys[wtxNew.vin.size()], outSum, 32);
3761  CKey additionalPkKey;
3762  additionalPkKey.Set(myBlinds[myBlindsIdx], myBlinds[myBlindsIdx] + 32, true);
3763  CPubKey additionalPubKey = additionalPkKey.GetPubKey();
3764  memcpy(allInPubKeys[wtxNew.vin.size()][PI], additionalPubKey.begin(), 33);
3765  PointHashingSuccessively(additionalPubKey, myBlinds[myBlindsIdx], allKeyImages[wtxNew.vin.size()]);
3766 
3767  //verify that additional public key = sum of wtx.vin.size() real public keys + sum of wtx.vin.size() commitments - sum of wtx.vout.size() commitments - commitment to zero of transction fee
3768 
3769  //filling LIJ & RIJ at [j][PI]
3770  CKey alpha_additional;
3771  alpha_additional.MakeNewKey(true);
3772  memcpy(ALPHA[wtxNew.vin.size()], alpha_additional.begin(), 32);
3773  CPubKey LIJ_PI_additional = alpha_additional.GetPubKey();
3774  memcpy(LIJ[wtxNew.vin.size()][PI], LIJ_PI_additional.begin(), 33);
3775  PointHashingSuccessively(additionalPubKey, alpha_additional.begin(), RIJ[wtxNew.vin.size()][PI]);
3776 
3777  //Initialize SIJ except S[..][PI]
3778  for (int i = 0; i < (int)wtxNew.vin.size() + 1; i++) {
3779  for (int j = 0; j < (int)wtxNew.vin[0].decoys.size() + 1; j++) {
3780  if (j != PI) {
3781  CKey randGen;
3782  randGen.MakeNewKey(true);
3783  memcpy(SIJ[i][j], randGen.begin(), 32);
3784  }
3785  }
3786  }
3787 
3788  //extract all public keys
3789  for (int i = 0; i < (int)wtxNew.vin.size(); i++) {
3790  std::vector<COutPoint> decoysForIn;
3791  decoysForIn.push_back(wtxNew.vin[i].prevout);
3792  for (int j = 0; j < (int)wtxNew.vin[i].decoys.size(); j++) {
3793  decoysForIn.push_back(wtxNew.vin[i].decoys[j]);
3794  }
3795  for (int j = 0; j < (int)wtxNew.vin[0].decoys.size() + 1; j++) {
3796  if (j != PI) {
3797  CTransaction txPrev;
3798  uint256 hashBlock;
3799  if (!GetTransaction(decoysForIn[j].hash, txPrev, hashBlock)) {
3800  return false;
3801  }
3802  CPubKey extractedPub;
3803  if (!ExtractPubKey(txPrev.vout[decoysForIn[j].n].scriptPubKey, extractedPub)) {
3804  strFailReason = _("Cannot extract public key from script pubkey");
3805  return false;
3806  }
3807  memcpy(allInPubKeys[i][j], extractedPub.begin(), 33);
3808  memcpy(allInCommitments[i][j], &(txPrev.vout[decoysForIn[j].n].commitment[0]), 33);
3809  }
3810  }
3811  }
3812 
3813  secp256k1_pedersen_commitment allInCommitmentsPacked[MAX_VIN][MAX_DECOYS + 1];
3814  secp256k1_pedersen_commitment allOutCommitmentsPacked[MAX_VOUT + 1]; //+1 for tx fee
3815 
3816  for (size_t i = 0; i < wtxNew.vout.size(); i++) {
3817  memcpy(&(allOutCommitments[i][0]), &(wtxNew.vout[i].commitment[0]), 33);
3818  if (!secp256k1_pedersen_commitment_parse(both, &allOutCommitmentsPacked[i], allOutCommitments[i])) {
3819  strFailReason = _("Cannot parse the commitment for inputs");
3820  return false;
3821  }
3822  }
3823 
3824  //commitment to tx fee, blind = 0
3825  unsigned char txFeeBlind[32];
3826  memset(txFeeBlind, 0, 32);
3827  if (!secp256k1_pedersen_commit(both, &allOutCommitmentsPacked[wtxNew.vout.size()], txFeeBlind, wtxNew.nTxFee, &secp256k1_generator_const_h, &secp256k1_generator_const_g)) {
3828  strFailReason = _("Cannot parse the commitment for transaction fee");
3829  return false;
3830  }
3831 
3832  //filling the additional pubkey elements for decoys: allInPubKeys[wtxNew.vin.size()][..]
3833  //allInPubKeys[wtxNew.vin.size()][j] = sum of allInPubKeys[..][j] + sum of allInCommitments[..][j] - sum of allOutCommitments
3834  const secp256k1_pedersen_commitment* outCptr[MAX_VOUT + 1];
3835  for (size_t i = 0; i < wtxNew.vout.size() + 1; i++) {
3836  outCptr[i] = &allOutCommitmentsPacked[i];
3837  }
3838  secp256k1_pedersen_commitment inPubKeysToCommitments[MAX_VIN][MAX_DECOYS + 1];
3839  for (int i = 0; i < (int)wtxNew.vin.size(); i++) {
3840  for (int j = 0; j < (int)wtxNew.vin[0].decoys.size() + 1; j++) {
3841  secp256k1_pedersen_serialized_pubkey_to_commitment(allInPubKeys[i][j], 33, &inPubKeysToCommitments[i][j]);
3842  }
3843  }
3844 
3845  for (int j = 0; j < (int)wtxNew.vin[0].decoys.size() + 1; j++) {
3846  if (j != PI) {
3847  const secp256k1_pedersen_commitment* inCptr[MAX_VIN * 2];
3848  for (int k = 0; k < (int)wtxNew.vin.size(); k++) {
3849  if (!secp256k1_pedersen_commitment_parse(both, &allInCommitmentsPacked[k][j], allInCommitments[k][j])) {
3850  strFailReason = _("Cannot parse the commitment for inputs");
3851  return false;
3852  }
3853  inCptr[k] = &allInCommitmentsPacked[k][j];
3854  }
3855  for (size_t k = wtxNew.vin.size(); k < 2 * wtxNew.vin.size(); k++) {
3856  inCptr[k] = &inPubKeysToCommitments[k - wtxNew.vin.size()][j];
3857  }
3859  size_t length;
3860  //convert allInPubKeys to pederson commitment to compute sum of all in public keys
3861  if (!secp256k1_pedersen_commitment_sum(both, inCptr, wtxNew.vin.size() * 2, outCptr, wtxNew.vout.size() + 1, &out))
3862  throw std::runtime_error("Cannot compute sum of commitment");
3863  if (!secp256k1_pedersen_commitment_to_serialized_pubkey(&out, allInPubKeys[wtxNew.vin.size()][j], &length))
3864  throw std::runtime_error("Cannot covert from commitment to public key");
3865  }
3866  }
3867 
3868  //Computing C
3869  int PI_interator = PI + 1; //PI_interator: PI + 1 .. wtxNew.vin[0].decoys.size() + 1 .. PI
3870  //unsigned char SIJ[wtxNew.vin.size() + 1][wtxNew.vin[0].decoys.size() + 1][32];
3871  //unsigned char LIJ[wtxNew.vin.size() + 1][wtxNew.vin[0].decoys.size() + 1][33];
3872  //unsigned char RIJ[wtxNew.vin.size() + 1][wtxNew.vin[0].decoys.size() + 1][33];
3873  unsigned char CI[MAX_DECOYS + 1][32];
3874  unsigned char tempForHash[2 * (MAX_VIN + 1) * 33 + 32];
3875  unsigned char* tempForHashPtr = tempForHash;
3876  for (size_t i = 0; i < wtxNew.vin.size() + 1; i++) {
3877  memcpy(tempForHashPtr, &LIJ[i][PI][0], 33);
3878  tempForHashPtr += 33;
3879  memcpy(tempForHashPtr, &RIJ[i][PI][0], 33);
3880  tempForHashPtr += 33;
3881  }
3882  uint256 ctsHash = GetTxSignatureHash(wtxNew);
3883  memcpy(tempForHashPtr, ctsHash.begin(), 32);
3884 
3885  if (PI_interator == (int)wtxNew.vin[0].decoys.size() + 1) PI_interator = 0;
3886  uint256 temppi1 = Hash(tempForHash, tempForHash + 2 * (wtxNew.vin.size() + 1) * 33 + 32);
3887  if (PI_interator == 0) {
3888  memcpy(CI[0], temppi1.begin(), 32);
3889  } else {
3890  memcpy(CI[PI_interator], temppi1.begin(), 32);
3891  }
3892 
3893  while (PI_interator != PI) {
3894  for (int j = 0; j < (int)wtxNew.vin.size() + 1; j++) {
3895  //compute LIJ
3896  unsigned char CP[33];
3897  memcpy(CP, allInPubKeys[j][PI_interator], 33);
3898  if (!secp256k1_ec_pubkey_tweak_mul(CP, 33, CI[PI_interator])) {
3899  strFailReason = _("Cannot compute LIJ for ring signature in secp256k1_ec_pubkey_tweak_mul");
3900  return false;
3901  }
3902  if (!secp256k1_ec_pubkey_tweak_add(CP, 33, SIJ[j][PI_interator])) {
3903  strFailReason = _("Cannot compute LIJ for ring signature in secp256k1_ec_pubkey_tweak_add");
3904  return false;
3905  }
3906  memcpy(LIJ[j][PI_interator], CP, 33);
3907 
3908  //compute RIJ
3909  //first compute CI * I
3910  memcpy(RIJ[j][PI_interator], allKeyImages[j], 33);
3911  if (!secp256k1_ec_pubkey_tweak_mul(RIJ[j][PI_interator], 33, CI[PI_interator])) {
3912  strFailReason = _("Cannot compute RIJ for ring signature in secp256k1_ec_pubkey_tweak_mul");
3913  return false;
3914  }
3915 
3916  //compute S*H(P)
3917  unsigned char SHP[33];
3918  CPubKey tempP;
3919  tempP.Set(allInPubKeys[j][PI_interator], allInPubKeys[j][PI_interator] + 33);
3920  PointHashingSuccessively(tempP, SIJ[j][PI_interator], SHP);
3921  //convert shp into commitment
3922  secp256k1_pedersen_commitment SHP_commitment;
3923  secp256k1_pedersen_serialized_pubkey_to_commitment(SHP, 33, &SHP_commitment);
3924 
3925  //convert CI*I into commitment
3926  secp256k1_pedersen_commitment cii_commitment;
3927  secp256k1_pedersen_serialized_pubkey_to_commitment(RIJ[j][PI_interator], 33, &cii_commitment);
3928 
3929  const secp256k1_pedersen_commitment* twoElements[2];
3930  twoElements[0] = &SHP_commitment;
3931  twoElements[1] = &cii_commitment;
3932 
3934  if (!secp256k1_pedersen_commitment_sum_pos(both, twoElements, 2, &sum))
3935  throw std::runtime_error("Cannot compute sum of commitments");
3936  size_t tempLength;
3937  if (!secp256k1_pedersen_commitment_to_serialized_pubkey(&sum, RIJ[j][PI_interator], &tempLength)) {
3938  strFailReason = _("Cannot compute two elements and serialize it to pubkey");
3939  }
3940  }
3941 
3942  PI_interator++;
3943  if (PI_interator == (int)wtxNew.vin[0].decoys.size() + 1) PI_interator = 0;
3944 
3945  int prev, ciIdx;
3946  if (PI_interator == 0) {
3947  prev = wtxNew.vin[0].decoys.size();
3948  ciIdx = 0;
3949  } else {
3950  prev = PI_interator - 1;
3951  ciIdx = PI_interator;
3952  }
3953 
3954  tempForHashPtr = tempForHash;
3955  for (int i = 0; i < (int)wtxNew.vin.size() + 1; i++) {
3956  memcpy(tempForHashPtr, LIJ[i][prev], 33);
3957  tempForHashPtr += 33;
3958  memcpy(tempForHashPtr, RIJ[i][prev], 33);
3959  tempForHashPtr += 33;
3960  }
3961  memcpy(tempForHashPtr, ctsHash.begin(), 32);
3962  uint256 ciHashTmp = Hash(tempForHash, tempForHash + 2 * (wtxNew.vin.size() + 1) * 33 + 32);
3963  memcpy(CI[ciIdx], ciHashTmp.begin(), 32);
3964  }
3965 
3966  //compute S[j][PI] = alpha_j - c_pi * x_j, x_j = private key corresponding to key image I
3967  for (size_t j = 0; j < wtxNew.vin.size() + 1; j++) {
3968  unsigned char cx[32];
3969  memcpy(cx, CI[PI], 32);
3970  if (!secp256k1_ec_privkey_tweak_mul(cx, AllPrivKeys[j]))
3971  throw std::runtime_error("Cannot compute EC mul");
3972  const unsigned char* sumArray[2];
3973  sumArray[0] = ALPHA[j];
3974  sumArray[1] = cx;
3975  if (!secp256k1_pedersen_blind_sum(both, SIJ[j][PI], sumArray, 2, 1))
3976  throw std::runtime_error("Cannot compute pedersen blind sum");
3977  }
3978  memcpy(wtxNew.c.begin(), CI[0], 32);
3979  //i for decoy index => PI
3980  for (int i = 0; i < (int)wtxNew.vin[0].decoys.size() + 1; i++) {
3981  std::vector<uint256> S_column;
3982  for (int j = 0; j < (int)wtxNew.vin.size() + 1; j++) {
3983  uint256 t;
3984  memcpy(t.begin(), SIJ[j][i], 32);
3985  S_column.push_back(t);
3986  }
3987  wtxNew.S.push_back(S_column);
3988  }
3989  wtxNew.ntxFeeKeyImage.Set(allKeyImages[wtxNew.vin.size()], allKeyImages[wtxNew.vin.size()] + 33);
3990  return true;
3991 }
3992 
3994 {
3995  LOCK(cs_wallet);
3996  {
3997  if (wtxNew.IsCoinAudit() || wtxNew.IsCoinBase()) return true;
3998  //this only generates shnorr signature if either wtxNew is a staking transaction or wtxNew only spends collateralized
3999  if (!wtxNew.IsCoinStake()) return true;
4000 
4001  //generate shnorr per input
4002  uint256 ctsHash = GetTxInSignatureHash(wtxNew.vin[0]);
4003 
4004  return MakeShnorrSignatureTxIn(wtxNew.vin[0], ctsHash);
4005  }
4006 }
4007 
4009 {
4010  COutPoint prevout = txin.prevout;
4011  const CTransaction& prev = mapWallet[prevout.hash];
4012  CTxOut out = prev.vout[prevout.n];
4013  CKey pk;
4014  if (!findCorrespondingPrivateKey(out, pk)) {
4015  return false;
4016  }
4017  CPubKey P = pk.GetPubKey();
4018 
4019  unsigned char R[33];
4020  CKey r;
4021  r.MakeNewKey(true);
4022  PointHashingSuccessively(P, r.begin(), R);
4023  unsigned char buff[33 + 32];
4024  memcpy(buff, R, 33);
4025  memcpy(buff + 33, cts.begin(), 32);
4026  uint256 e = Hash(buff, buff + 65);
4027  //compute s = r + e * pk (private key)
4028 
4029  unsigned char ex[32];
4030  memcpy(ex, e.begin(), 32);
4031  if (!secp256k1_ec_privkey_tweak_mul(ex, pk.begin())) return false;
4032  if (!secp256k1_ec_privkey_tweak_add(ex, r.begin())) return false;
4033  std::copy(ex, ex + 32, std::back_inserter(txin.s));
4034  //copy R to masternodeStealthAddress
4035  std::copy(R, R + 33, std::back_inserter(txin.R));
4036  return true;
4037 }
4038 
4039 bool CWallet::selectDecoysAndRealIndex(CTransaction& tx, int& myIndex, int ringSize)
4040 {
4041  LogPrintf("Selecting coinbase decoys for transaction\n");
4042  if (coinbaseDecoysPool.size() <= 100) {
4043  for (int i = chainActive.Height() - Params().COINBASE_MATURITY(); i > 0; i--) {
4044  if (coinbaseDecoysPool.size() > 100) break;
4045  CBlockIndex* p = chainActive[i];
4046  CBlock b;
4047  if (ReadBlockFromDisk(b, p)) {
4048  int coinbaseIdx = 0;
4049  if (p->IsProofOfStake()) {
4050  coinbaseIdx = 1;
4051  }
4052  //dont select poa as decoy
4053  if (b.posBlocksAudited.size() > 0) continue;
4054  CTransaction& coinbase = b.vtx[coinbaseIdx];
4055 
4056  for (size_t i = 0; i < coinbase.vout.size(); i++) {
4057  if (!coinbase.vout[i].IsNull() && !coinbase.vout[i].commitment.empty() && coinbase.vout[i].nValue > 0 && !coinbase.vout[i].IsEmpty()) {
4058  if ((secp256k1_rand32() % 100) <= CWallet::PROBABILITY_NEW_COIN_SELECTED) {
4059  COutPoint newOutPoint(coinbase.GetHash(), i);
4060  if (coinbaseDecoysPool.count(newOutPoint) == 1) {
4061  continue;
4062  }
4063  if (!ValidOutPoint(newOutPoint)) {
4064  break;
4065  }
4066  //add new coinbase transaction to the pool
4068  int selected = secp256k1_rand32() % CWallet::MAX_DECOY_POOL;
4069  std::map<COutPoint, uint256>::const_iterator it = std::next(coinbaseDecoysPool.begin(), selected);
4070  coinbaseDecoysPool[newOutPoint] = p->GetBlockHash();
4071  } else {
4072  coinbaseDecoysPool[newOutPoint] = p->GetBlockHash();
4073  }
4074  }
4075  }
4076  }
4077  }
4078  }
4079  }
4080  //Choose decoys
4081  myIndex = -1;
4082  for (size_t i = 0; i < tx.vin.size(); i++) {
4083  //generate key images and choose decoys
4084  CTransaction txPrev;
4085  uint256 hashBlock;
4086  if (!GetTransaction(tx.vin[i].prevout.hash, txPrev, hashBlock)) {
4087  LogPrintf("Selected transaction: %s is not in the main chain\n", tx.vin[i].prevout.hash.GetHex().c_str());
4088  return false;
4089  }
4090 
4091  if (tx.nLockTime != 0) {
4092  LogPrintf("tx.nLockTime != 0, currently disabled\n");
4093  return false;
4094  }
4095 
4096  CBlockIndex* atTheblock = mapBlockIndex[hashBlock];
4097  CBlockIndex* tip = chainActive.Tip();
4098  if (!chainActive.Contains(atTheblock)) continue;
4099  uint256 hashTip = tip->GetBlockHash();
4100  //verify that tip and hashBlock must be in the same fork
4101  if (!atTheblock) {
4102  continue;
4103  } else {
4104  CBlockIndex* ancestor = tip->GetAncestor(atTheblock->nHeight);
4105  if (ancestor != atTheblock) {
4106  continue;
4107  }
4108  }
4109 
4110  CKeyImage ki;
4111  if (!generateKeyImage(txPrev.vout[tx.vin[i].prevout.n].scriptPubKey, ki)) {
4112  LogPrintf("Cannot generate key image\n");
4113  return false;
4114  } else {
4115  tx.vin[i].keyImage = ki;
4116  }
4117 
4118  pendingKeyImages.push_back(ki.GetHex());
4119  int numDecoys = 0;
4120  if (txPrev.IsCoinAudit() || txPrev.IsCoinBase() || txPrev.IsCoinStake()) {
4121  if ((int)coinbaseDecoysPool.size() >= ringSize * 5) {
4122  while (numDecoys < ringSize) {
4123  bool duplicated = false;
4124  bool invalid = false;
4125  std::map<COutPoint, uint256>::const_iterator it = std::next(coinbaseDecoysPool.begin(), secp256k1_rand32() % coinbaseDecoysPool.size());
4126  if (mapBlockIndex.count(it->second) < 1) continue;
4127  CBlockIndex* atTheblock = mapBlockIndex[it->second];
4128  if (!atTheblock || !chainActive.Contains(atTheblock)) continue;
4129  if (!chainActive.Contains(atTheblock)) continue;
4130  if (1 + chainActive.Height() - atTheblock->nHeight < DecoyConfirmationMinimum) continue;
4131  COutPoint outpoint = it->first;
4132  for (size_t d = 0; d < tx.vin[i].decoys.size(); d++) {
4133  if (tx.vin[i].decoys[d] == outpoint) {
4134  duplicated = true;
4135  }
4136  if (!ValidOutPoint(outpoint)) {
4137  invalid = true;
4138  }
4139  if (duplicated || invalid) {
4140  break;
4141  }
4142  }
4143  if (duplicated || invalid) {
4144  continue;
4145  }
4146  tx.vin[i].decoys.push_back(outpoint);
4147  numDecoys++;
4148  }
4149  } else if ((int)coinbaseDecoysPool.size() >= ringSize) {
4150  for (size_t j = 0; j < coinbaseDecoysPool.size(); j++) {
4151  std::map<COutPoint, uint256>::const_iterator it = std::next(coinbaseDecoysPool.begin(), j);
4152  if (mapBlockIndex.count(it->second) < 1) continue;
4153  CBlockIndex* atTheblock = mapBlockIndex[it->second];
4154  if (!atTheblock || !chainActive.Contains(atTheblock)) continue;
4155  if (!chainActive.Contains(atTheblock)) continue;
4156  if (1 + chainActive.Height() - atTheblock->nHeight < DecoyConfirmationMinimum) continue;
4157  COutPoint outpoint = it->first;
4158  if (!ValidOutPoint(outpoint)) {
4159  break;
4160  }
4161  tx.vin[i].decoys.push_back(outpoint);
4162  numDecoys++;
4163  if (numDecoys == ringSize) break;
4164  }
4165  } else {
4166  LogPrintf("Not enough decoys. Please wait approximately 10 minutes and try again.\n");
4167  return false;
4168  }
4169  } else {
4170  std::map<COutPoint, uint256> decoySet = userDecoysPool;
4171  decoySet.insert(coinbaseDecoysPool.begin(), coinbaseDecoysPool.end());
4172  if ((int)decoySet.size() >= ringSize * 5) {
4173  while (numDecoys < ringSize) {
4174  bool duplicated = false;
4175  bool invalid = false;
4176  std::map<COutPoint, uint256>::const_iterator it = std::next(decoySet.begin(), secp256k1_rand32() % decoySet.size());
4177  if (mapBlockIndex.count(it->second) < 1) continue;
4178  CBlockIndex* atTheblock = mapBlockIndex[it->second];
4179  if (!atTheblock || !chainActive.Contains(atTheblock)) continue;
4180  if (!chainActive.Contains(atTheblock)) continue;
4181  if (1 + chainActive.Height() - atTheblock->nHeight < DecoyConfirmationMinimum) continue;
4182  COutPoint outpoint = it->first;
4183  for (size_t d = 0; d < tx.vin[i].decoys.size(); d++) {
4184  if (tx.vin[i].decoys[d] == outpoint) {
4185  duplicated = true;
4186  }
4187  if (!ValidOutPoint(outpoint)) {
4188  invalid = true;
4189  }
4190  if (duplicated || invalid) {
4191  break;
4192  }
4193  }
4194  if (duplicated || invalid) {
4195  continue;
4196  }
4197  tx.vin[i].decoys.push_back(outpoint);
4198  numDecoys++;
4199  }
4200  } else if ((int)decoySet.size() >= ringSize) {
4201  for (size_t j = 0; j < decoySet.size(); j++) {
4202  std::map<COutPoint, uint256>::const_iterator it = std::next(decoySet.begin(), j);
4203  if (mapBlockIndex.count(it->second) < 1) continue;
4204  CBlockIndex* atTheblock = mapBlockIndex[it->second];
4205  if (!atTheblock || !chainActive.Contains(atTheblock)) continue;
4206  if (!chainActive.Contains(atTheblock)) continue;
4207  if (1 + chainActive.Height() - atTheblock->nHeight < DecoyConfirmationMinimum) continue;
4208  COutPoint outpoint = it->first;
4209  if (!ValidOutPoint(outpoint)) {
4210  break;
4211  }
4212  tx.vin[i].decoys.push_back(outpoint);
4213  numDecoys++;
4214  if (numDecoys == ringSize) break;
4215  }
4216  } else {
4217  LogPrintf("Not enough decoys. Please wait approximately 10 minutes and try again.\n");
4218  return false;
4219  }
4220  }
4221  }
4222  myIndex = secp256k1_rand32() % (tx.vin[0].decoys.size() + 1) - 1;
4223 
4224  for (size_t i = 0; i < tx.vin.size(); i++) {
4225  COutPoint prevout = tx.vin[i].prevout;
4226  if (!ValidOutPoint(prevout)) {
4227  break;
4228  }
4229  inSpendQueueOutpointsPerSession.push_back(prevout);
4230  }
4231  if (myIndex != -1) {
4232  for (size_t i = 0; i < tx.vin.size(); i++) {
4233  if (tx.vin[i].decoys.size() <= myIndex || tx.vin[i].decoys.size() != ringSize) {
4234  throw std::runtime_error("Failed to annonymize the transaction, please wait about 10 minutes to re-create your transaction");
4235  }
4236  COutPoint prevout = tx.vin[i].prevout;
4237  tx.vin[i].prevout = tx.vin[i].decoys[myIndex];
4238  tx.vin[i].decoys[myIndex] = prevout;
4239  }
4240  }
4241 
4242  return true;
4243 }
4244 
4245 bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay)
4246 {
4247  std::vector<std::pair<CScript, CAmount> > vecSend;
4248  vecSend.push_back(std::make_pair(scriptPubKey, nValue));
4249  return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay);
4250 }
4251 
4252 bool CWallet::computeSharedSec(const CTransaction& tx, const CTxOut& out, CPubKey& sharedSec) const
4253 {
4255  sharedSec.Set(out.txPub.begin(), out.txPub.end());
4256  } else {
4257  CKey view;
4258  myViewPrivateKey(view);
4259  ECDHInfo::ComputeSharedSec(view, out.txPub, sharedSec);
4260  }
4261  return true;
4262 }
4263 
4265 {
4266  if (IsLocked()) return;
4267  {
4268  LOCK(cs_wallet);
4269  CKey spend, view;
4270  mySpendPrivateKey(spend);
4271  myViewPrivateKey(view);
4272 
4273  unsigned char aR[33];
4274  CPubKey txPub = out.txPub;
4275  //copy R into a
4276  memcpy(aR, txPub.begin(), txPub.size());
4277  if (!secp256k1_ec_pubkey_tweak_mul(aR, txPub.size(), view.begin())) {
4278  throw std::runtime_error("Failed to do secp256k1_ec_privkey_tweak_mul");
4279  }
4280  uint256 HS = Hash(aR, aR + txPub.size());
4281 
4282  //Compute private key to spend
4283  //x = Hs(aR) + b, b = spend private key
4284  unsigned char HStemp[32];
4285  unsigned char spendTemp[32];
4286  memcpy(HStemp, HS.begin(), 32);
4287  if (!secp256k1_ec_privkey_tweak_add(HStemp, spend.begin()))
4288  throw std::runtime_error("Failed to do secp256k1_ec_privkey_tweak_add");
4289  CKey privKey;
4290  privKey.Set(HStemp, HStemp + 32, true);
4291  CPubKey computed = privKey.GetPubKey();
4292  CScript scriptPubKey = GetScriptForDestination(computed);
4293  if (scriptPubKey == out.scriptPubKey) {
4294  AddKey(privKey);
4295  } else {
4296  LogPrintf("AddComputedPrivateKey: Fail to generate corresponding private key\n");
4297  }
4298  }
4299 }
4300 
4301 // ppcoin: create coin stake transaction
4303  const CKeyStore& keystore,
4304  unsigned int nBits,
4305  int64_t nSearchInterval,
4306  CMutableTransaction& txNew,
4307  unsigned int& nTxNewTime
4308  )
4309 {
4310  // The following split & combine thresholds are important to security
4311  // Should not be adjusted if you don't understand the consequences
4312  //int64_t nCombineThreshold = 0;
4313  int static wlIdx = 0;
4314  txNew.vin.clear();
4315  txNew.vout.clear();
4316 
4317  // Mark coin stake transaction
4318  CScript scriptEmpty;
4319  scriptEmpty.clear();
4320  txNew.vout.push_back(CTxOut(0, scriptEmpty));
4321  txNew.txType = TX_TYPE_REVEAL_BOTH;
4322 
4323  // Choose coins to use
4324  CAmount nBalance = GetSpendableBalance();
4325 
4326  if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
4327  return error("CreateCoinStake : invalid reserve balance amount");
4328 
4329  if (nBalance > 0 && nBalance <= nReserveBalance)
4330  return false;
4331 
4332  // Get the list of stakable inputs
4333  std::list<std::unique_ptr<CStakeInput> > listInputs;
4334  if (!SelectStakeCoins(listInputs, nBalance - nReserveBalance)) {
4335  LogPrintf("CreateCoinStake(): selectStakeCoins failed\n");
4336  return false;
4337  }
4338 
4339  if (listInputs.empty()) {
4340  LogPrint(BCLog::STAKING, "CreateCoinStake(): listInputs empty\n");
4341  MilliSleep(50000);
4342  return false;
4343  }
4344 
4345  if (GetAdjustedTime() - chainActive.Tip()->GetBlockTime() < 60) {
4346  if (Params().IsRegTestNet()) {
4347  MilliSleep(1000);
4348  }
4349  }
4350 
4351  CAmount nCredit;
4352  CScript scriptPubKeyKernel;
4353  bool fKernelFound = false;
4354  int nAttempts = 0;
4355  for (std::unique_ptr<CStakeInput>& stakeInput : listInputs) {
4356  // Make sure the wallet is unlocked and shutdown hasn't been requested
4357  nCredit = 0;
4358  if (IsLocked() || ShutdownRequested())
4359  return false;
4360 
4361  //make sure that enough time has elapsed between
4362  CBlockIndex* pindex = stakeInput->GetIndexFrom();
4363  if (!pindex || pindex->nHeight < 1) {
4364  LogPrintf("CreateCoinStake(): no pindexfrom\n");
4365  continue;
4366  }
4367 
4368  // Read block header
4369  CBlockHeader block = pindex->GetBlockHeader();
4370  uint256 hashProofOfStake = 0;
4371  nTxNewTime = GetAdjustedTime();
4372 
4373  nAttempts++;
4374  //iterates each utxo inside of CheckStakeKernelHash()
4375  if (Stake(stakeInput.get(), nBits, block.GetBlockTime(), nTxNewTime, hashProofOfStake)) {
4376  //Double check that this will pass time requirements
4377  if (nTxNewTime <= chainActive.Tip()->GetMedianTimePast() && !Params().IsRegTestNet()) {
4378  LogPrintf("CreateCoinStake() : kernel found, but it is too far in the past \n");
4379  continue;
4380  }
4381 
4382  // Found a kernel
4383  LogPrintf("CreateCoinStake : kernel found\n");
4384  nCredit += stakeInput->GetValue();
4385  std::vector<CTxOut> vout;
4386  if (!stakeInput->CreateTxOuts(this, vout, nCredit)) {
4387  LogPrintf("%s : failed to get scriptPubKey\n", __func__);
4388  continue;
4389  }
4390  txNew.vout.insert(txNew.vout.end(), vout.begin(), vout.end());
4391 
4392  // Calculate reward
4393  CAmount nReward;
4394  nReward = GetBlockValue(chainActive.Height());
4395  txNew.vout[1].nValue = nCredit;
4396  txNew.vout[2].nValue = nReward;
4397 
4398  // Limit size
4399  unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
4400  if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5)
4401  return error("CreateCoinStake : exceeded coinstake size limit");
4402 
4403  //Masternode payment
4404  if (!FillBlockPayee(txNew, 0, true)) {
4405  LogPrintf("%s: Cannot fill block payee\n", __func__);
4406  return false;
4407  }
4408 
4409  uint256 hashTxOut = txNew.GetHash();
4410  CTxIn in;
4411  if (!stakeInput->CreateTxIn(this, in, hashTxOut)) {
4412  LogPrintf("%s : failed to create TxIn\n", __func__);
4413  txNew.vin.clear();
4414  txNew.vout.clear();
4415  continue;
4416  }
4417  txNew.vin.push_back(in);
4418 
4419  fKernelFound = true;
4420  break;
4421  }
4422  if (fKernelFound)
4423  break; // if kernel is found stop searching
4424  }
4425  LogPrint(BCLog::STAKING, "%s: attempted staking %d times\n", __func__, nAttempts);
4426  if (!fKernelFound)
4427  return false;
4428 
4429  //Encoding amount
4430  CPubKey sharedSec1;
4431  //In this case, use the transaction pubkey to encode the transactiona amount
4432  //so that every fullnode can verify the exact transaction amount within the transaction
4433  for (size_t i = 1; i < txNew.vout.size(); i++) {
4434  sharedSec1.Set(txNew.vout[i].txPub.begin(), txNew.vout[i].txPub.end());
4435  EncodeTxOutAmount(txNew.vout[i], txNew.vout[i].nValue, sharedSec1.begin());
4436  //create commitment
4437  unsigned char zeroBlind[32];
4438  memset(zeroBlind, 0, 32);
4439  txNew.vout[i].commitment.clear();
4440  CreateCommitment(zeroBlind, txNew.vout[i].nValue, txNew.vout[i].commitment);
4441  }
4442 
4443  // Sign for PRCY
4444  int nIn = 0;
4445  for (CTxIn txIn : txNew.vin) {
4446  const CWalletTx *wtx = GetWalletTx(txIn.prevout.hash);
4447  if (!SignSignature(*this, *wtx, txNew, nIn++))
4448  return error("CreateCoinStake : failed to sign coinstake");
4449  }
4450 
4451  // Successfully generated coinstake
4452  return true;
4453 }
4454 
4458 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand)
4459 {
4460  {
4462  LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
4463  {
4464  // This is only to keep the database open to defeat the auto-flush for the
4465  // duration of this scope. This is the only place where this optimization
4466  // maybe makes sense; please don't do it anywhere else.
4467  CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile, "r+") : NULL;
4468 
4469  // Take key pair from key pool so it won't be used again
4470  reservekey.KeepKey();
4471 
4472  // Add tx to wallet, because if it has change it's also ours,
4473  // otherwise just for transaction history.
4474  AddToWallet(wtxNew, false, pwalletdb);
4475 
4476  // Notify that old coins are spent
4477  {
4478  std::set<uint256> updated_hahes;
4479  for (const CTxIn& txin : wtxNew.vin) {
4480  // notify only once
4481  COutPoint prevout = findMyOutPoint(txin);
4482  if (updated_hahes.find(prevout.hash) != updated_hahes.end()) continue;
4483 
4484  CWalletTx& coin = mapWallet[prevout.hash];
4485  coin.BindWallet(this);
4486  NotifyTransactionChanged(this, prevout.hash, CT_UPDATED);
4487  updated_hahes.insert(prevout.hash);
4488  }
4489  }
4490 
4491  if (fFileBacked)
4492  delete pwalletdb;
4493  }
4494 
4495  // Track how many getdata requests our transaction gets
4496  mapRequestCount[wtxNew.GetHash()] = 0;
4497 
4498  // Broadcast
4499  if (!wtxNew.AcceptToMemoryPool(false)) {
4500  // This must not fail. The transaction has already been signed and recorded.
4501  LogPrintf("CommitTransaction() : Error: Transaction not valid\n");
4502  return false;
4503  }
4504  LogPrintf("CommitTransaction() : hash: %s\n", wtxNew.GetHash().GetHex());
4505  wtxNew.RelayWalletTransaction(strCommand);
4506  }
4507  return true;
4508 }
4509 
4510 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pwalletdb)
4511 {
4512  if (!pwalletdb.WriteAccountingEntry_Backend(acentry))
4513  return false;
4514 
4515  laccentries.push_back(acentry);
4516  CAccountingEntry & entry = laccentries.back();
4517  wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
4518 
4519  return true;
4520 }
4521 
4522 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
4523 {
4524  CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
4525  if (nFeeNeeded >= MAX_FEE) nFeeNeeded = MAX_FEE;
4526  return nFeeNeeded;
4527 }
4528 
4530 {
4531  if (IsLocked()) return;
4533  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
4534  const CWalletTx wtxIn = it->second;
4535  uint256 hash = wtxIn.GetHash();
4536  AddToSpends(hash);
4537  }
4538 }
4539 
4540 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
4541 {
4542  if (!fFileBacked)
4543  return DB_LOAD_OK;
4544  fFirstRunRet = false;
4545  DBErrors nLoadWalletRet = CWalletDB(strWalletFile, "cr+").LoadWallet(this);
4546  if (nLoadWalletRet == DB_NEED_REWRITE) {
4547  if (CDB::Rewrite(strWalletFile, "\x04pool")) {
4548  LOCK(cs_wallet);
4549  setKeyPool.clear();
4550  // Note: can't top-up keypool here, because wallet is locked.
4551  // User will be prompted to unlock wallet the next operation
4552  // the requires a new key.
4553  }
4554  }
4555 
4556  if (nLoadWalletRet != DB_LOAD_OK)
4557  return nLoadWalletRet;
4558  fFirstRunRet = !vchDefaultKey.IsValid();
4559 
4560  uiInterface.LoadWallet(this);
4562 
4563  return DB_LOAD_OK;
4564 }
4565 
4566 
4567 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
4568 {
4569  if (!fFileBacked)
4570  return DB_LOAD_OK;
4571  DBErrors nZapWalletTxRet = CWalletDB(strWalletFile, "cr+").ZapWalletTx(this, vWtx);
4572  if (nZapWalletTxRet == DB_NEED_REWRITE) {
4573  if (CDB::Rewrite(strWalletFile, "\x04pool")) {
4574  LOCK(cs_wallet);
4575  setKeyPool.clear();
4576  // Note: can't top-up keypool here, because wallet is locked.
4577  // User will be prompted to unlock wallet the next operation
4578  // that requires a new key.
4579  }
4580  }
4581 
4582  if (nZapWalletTxRet != DB_LOAD_OK)
4583  return nZapWalletTxRet;
4584 
4585  return DB_LOAD_OK;
4586 }
4587 
4588 
4589 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
4590 {
4591  bool fUpdated = false;
4592  {
4593  LOCK(cs_wallet); // mapAddressBook
4594  std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
4595  fUpdated = mi != mapAddressBook.end();
4596  mapAddressBook[address].name = strName;
4597  if (!strPurpose.empty()) /* update purpose only if requested */
4598  mapAddressBook[address].purpose = strPurpose;
4599  }
4600  NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
4601  strPurpose, (fUpdated ? CT_UPDATED : CT_NEW));
4602  if (!fFileBacked)
4603  return false;
4604  if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
4605  return false;
4606  return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
4607 }
4608 
4610 {
4611  {
4612  LOCK(cs_wallet); // mapAddressBook
4613 
4614  if (fFileBacked) {
4615  // Delete destdata tuples associated with address
4616  std::string strAddress = CBitcoinAddress(address).ToString();
4617  for (const PAIRTYPE(std::string, std::string) & item : mapAddressBook[address].destdata) {
4618  CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
4619  }
4620  }
4621  mapAddressBook.erase(address);
4622  }
4623 
4624  NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
4625 
4626  if (!fFileBacked)
4627  return false;
4628  CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
4629  return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
4630 }
4631 
4632 bool CWallet::SetDefaultKey(const CPubKey& vchPubKey)
4633 {
4634  if (fFileBacked) {
4635  if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
4636  return false;
4637  }
4638  vchDefaultKey = vchPubKey;
4639  return true;
4640 }
4641 
4647 {
4648  {
4649  LOCK(cs_wallet);
4650  CWalletDB walletdb(strWalletFile);
4651  for (int64_t nIndex : setKeyPool)
4652  walletdb.ErasePool(nIndex);
4653  setKeyPool.clear();
4654 
4655  if (IsLocked())
4656  return false;
4657 
4658  int64_t nKeys = std::max(GetArg("-keypool", 1000), (int64_t)0);
4659  for (int i = 0; i < nKeys; i++) {
4660  int64_t nIndex = i + 1;
4661  walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
4662  setKeyPool.insert(nIndex);
4663  }
4664  LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
4665  }
4666  return true;
4667 }
4668 
4669 
4670 void GetAccountAddress(CWallet* pwalletMain, std::string strAccount, int nAccountIndex, bool bForceNew = false)
4671 {
4672  CWalletDB walletdb(pwalletMain->strWalletFile);
4673 
4674  CAccount account;
4675  if (!bForceNew) {
4676  walletdb.ReadAccount(strAccount, account);
4677  }
4678  bool bKeyUsed = false;
4679 
4680  // Check if the current key has been used
4681  if (account.vchPubKey.IsValid()) {
4682  CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
4683  for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
4684  it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
4685  ++it) {
4686  const CWalletTx& wtx = (*it).second;
4687  for (const CTxOut& txout : wtx.vout)
4688  if (txout.scriptPubKey == scriptPubKey)
4689  bKeyUsed = true;
4690  }
4691  }
4692 
4693  // Generate a new key
4694  if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) {
4695  // pwalletMain->GetKeyFromPool(account.vchPubKey);
4696  CKey newKey;
4697  pwalletMain->DeriveNewChildKey(nAccountIndex, newKey);
4698  account.vchPubKey = newKey.GetPubKey();
4699  account.nAccountIndex = nAccountIndex;
4700 
4701  pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
4702  walletdb.WriteAccount(strAccount, account);
4703  }
4704 }
4705 
4706 bool CWallet::TopUpKeyPool(unsigned int kpSize)
4707 {
4708  {
4709  LOCK(cs_wallet);
4710 
4711  if (IsLocked())
4712  return false;
4713 
4714  CWalletDB walletdb(strWalletFile);
4715 
4716  // Top up key pool
4717  unsigned int nTargetSize;
4718  if (kpSize > 0)
4719  nTargetSize = kpSize;
4720  else
4721  nTargetSize = std::max(GetArg("-keypool", 1000), (int64_t)0);
4722 
4723  /*while (setKeyPool.size() < (nTargetSize + 1)) {
4724  int64_t nEnd = 1;
4725  if (!setKeyPool.empty())
4726  nEnd = *(--setKeyPool.end()) + 1;
4727  if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
4728  throw std::runtime_error("TopUpKeyPool() : writing generated key failed");
4729  setKeyPool.insert(nEnd);
4730  LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
4731  double dProgress = 100.f * nEnd / (nTargetSize + 1);
4732  std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress);
4733  uiInterface.InitMessage(strMsg);
4734  }*/
4735  }
4736  return true;
4737 }
4738 
4739 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
4740 {
4741  nIndex = -1;
4742  keypool.vchPubKey = CPubKey();
4743  {
4744  LOCK(cs_wallet);
4745 
4746  if (!IsLocked())
4747  TopUpKeyPool();
4748 
4749  // Get the oldest key
4750  if (setKeyPool.empty())
4751  return;
4752 
4753  CWalletDB walletdb(strWalletFile);
4754 
4755  nIndex = *(setKeyPool.begin());
4756  setKeyPool.erase(setKeyPool.begin());
4757  if (!walletdb.ReadPool(nIndex, keypool))
4758  throw std::runtime_error("ReserveKeyFromKeyPool() : read failed");
4759  if (!HaveKey(keypool.vchPubKey.GetID()))
4760  throw std::runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
4761  assert(keypool.vchPubKey.IsValid());
4762  LogPrintf("keypool reserve %d\n", nIndex);
4763  }
4764 }
4765 
4767 {
4768  {
4769  LOCK(cs_wallet);
4770  if (IsCrypted())
4771  return; //throw std::runtime_error("Wallet is encrypted, please decrypt it");
4772 
4773  CWalletDB walletdb(strWalletFile);
4774  int i = 0;
4775  while (i < 10) {
4776  std::string viewAccountLabel = "viewaccount";
4777  std::string spendAccountLabel = "spendaccount";
4778  CAccount viewAccount;
4779  if (forceNew) {
4780  GetAccountAddress(this, viewAccountLabel, 0, forceNew);
4781  walletdb.ReadAccount(viewAccountLabel, viewAccount);
4782  } else {
4783  walletdb.ReadAccount(viewAccountLabel, viewAccount);
4784  if (!viewAccount.vchPubKey.IsValid()) {
4785  GetAccountAddress(this, viewAccountLabel, 0, forceNew);
4786  }
4787  }
4788  CAccount spendAccount;
4789  if (forceNew) {
4790  GetAccountAddress(this, spendAccountLabel, 1, forceNew);
4791  walletdb.ReadAccount(spendAccountLabel, spendAccount);
4792  } else {
4793  walletdb.ReadAccount(spendAccountLabel, spendAccount);
4794  if (!spendAccount.vchPubKey.IsValid()) {
4795  GetAccountAddress(this, spendAccountLabel, 1, forceNew);
4796  }
4797  }
4798  if (viewAccount.vchPubKey.GetHex() == "" || spendAccount.vchPubKey.GetHex() == "") {
4799  i++;
4800  continue;
4801  }
4802 
4803  walletdb.AppendStealthAccountList("masteraccount");
4804  break;
4805  }
4806  }
4807 }
4808 
4809 void CWallet::KeepKey(int64_t nIndex)
4810 {
4811  // Remove from key pool
4812  if (fFileBacked) {
4813  CWalletDB walletdb(strWalletFile);
4814  walletdb.ErasePool(nIndex);
4815  }
4816  LogPrintf("keypool keep %d\n", nIndex);
4817 }
4818 
4819 void CWallet::ReturnKey(int64_t nIndex)
4820 {
4821  // Return to key pool
4822  {
4823  LOCK(cs_wallet);
4824  setKeyPool.insert(nIndex);
4825  }
4826  LogPrintf("keypool return %d\n", nIndex);
4827 }
4828 
4830 {
4831  int64_t nIndex = 0;
4832  CKeyPool keypool;
4833  {
4834  LOCK(cs_wallet);
4835  ReserveKeyFromKeyPool(nIndex, keypool);
4836  if (nIndex == -1) {
4837  if (IsLocked()) return false;
4838  result = GenerateNewKey();
4839  return true;
4840  }
4841  KeepKey(nIndex);
4842  result = keypool.vchPubKey;
4843  }
4844  return true;
4845 }
4846 
4848 {
4849  int64_t nIndex = 0;
4850  CKeyPool keypool;
4851  ReserveKeyFromKeyPool(nIndex, keypool);
4852  if (nIndex == -1)
4853  return GetTime();
4854  ReturnKey(nIndex);
4855  return keypool.nTime;
4856 }
4857 
4858 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
4859 {
4860  std::map<CTxDestination, CAmount> balances;
4861 
4862  {
4863  LOCK(cs_wallet);
4864  for (PAIRTYPE(uint256, CWalletTx) walletEntry : mapWallet) {
4865  CWalletTx* pcoin = &walletEntry.second;
4866 
4867  if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted())
4868  continue;
4869 
4870  if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
4871  continue;
4872 
4873  int nDepth = pcoin->GetDepthInMainChain();
4874  if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
4875  continue;
4876 
4877  for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
4878  CTxDestination addr;
4879  if (!IsMine(pcoin->vout[i]))
4880  continue;
4881  if (!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
4882  continue;
4883 
4884  CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
4885 
4886  if (!balances.count(addr))
4887  balances[addr] = 0;
4888  balances[addr] += n;
4889  }
4890  }
4891  }
4892 
4893  return balances;
4894 }
4895 
4896 std::set<std::set<CTxDestination> > CWallet::GetAddressGroupings()
4897 {
4898  AssertLockHeld(cs_wallet); // mapWallet
4899  std::set<std::set<CTxDestination> > groupings;
4900  std::set<CTxDestination> grouping;
4901 
4902  for (PAIRTYPE(uint256, CWalletTx) walletEntry : mapWallet) {
4903  CWalletTx* pcoin = &walletEntry.second;
4904 
4905  if (pcoin->vin.size() > 0) {
4906  bool any_mine = false;
4907  // group all input addresses with each other
4908  for (CTxIn txin : pcoin->vin) {
4909  CTxDestination address;
4910  if (!IsMine(txin)) /* If this input isn't mine, ignore it */
4911  continue;
4912  if (!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
4913  continue;
4914  grouping.insert(address);
4915  any_mine = true;
4916  }
4917 
4918  // group change with input addresses
4919  if (any_mine) {
4920  for (CTxOut txout : pcoin->vout)
4921  if (IsChange(txout)) {
4922  CTxDestination txoutAddr;
4923  if (!ExtractDestination(txout.scriptPubKey, txoutAddr))
4924  continue;
4925  grouping.insert(txoutAddr);
4926  }
4927  }
4928  if (grouping.size() > 0) {
4929  groupings.insert(grouping);
4930  grouping.clear();
4931  }
4932  }
4933 
4934  // group lone addrs by themselves
4935  for (unsigned int i = 0; i < pcoin->vout.size(); i++)
4936  if (IsMine(pcoin->vout[i])) {
4937  CTxDestination address;
4938  if (!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
4939  continue;
4940  grouping.insert(address);
4941  groupings.insert(grouping);
4942  grouping.clear();
4943  }
4944  }
4945 
4946  std::set<std::set<CTxDestination>*> uniqueGroupings; // a set of pointers to groups of addresses
4947  std::map<CTxDestination, std::set<CTxDestination>*> setmap; // map addresses to the unique group containing it
4948  for (std::set<CTxDestination> grouping : groupings) {
4949  // make a set of all the groups hit by this new group
4950  std::set<std::set<CTxDestination>*> hits;
4951  std::map<CTxDestination, std::set<CTxDestination>*>::iterator it;
4952  for (CTxDestination address : grouping)
4953  if ((it = setmap.find(address)) != setmap.end())
4954  hits.insert((*it).second);
4955 
4956  // merge all hit groups into a new single group and delete old groups
4957  std::set<CTxDestination>* merged = new std::set<CTxDestination>(grouping);
4958  for (std::set<CTxDestination>* hit : hits) {
4959  merged->insert(hit->begin(), hit->end());
4960  uniqueGroupings.erase(hit);
4961  delete hit;
4962  }
4963  uniqueGroupings.insert(merged);
4964 
4965  // update setmap
4966  for (CTxDestination element : *merged)
4967  setmap[element] = merged;
4968  }
4969 
4970  std::set<std::set<CTxDestination> > ret;
4971  for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings) {
4972  ret.insert(*uniqueGrouping);
4973  delete uniqueGrouping;
4974  }
4975 
4976  return ret;
4977 }
4978 
4979 std::set<CTxDestination> CWallet::GetAccountAddresses(std::string strAccount) const
4980 {
4981  LOCK(cs_wallet);
4982  std::set<CTxDestination> result;
4983  for (const PAIRTYPE(CTxDestination, CAddressBookData) & item : mapAddressBook) {
4984  const CTxDestination& address = item.first;
4985  const std::string& strName = item.second.name;
4986  if (strName == strAccount)
4987  result.insert(address);
4988  }
4989  return result;
4990 }
4991 
4993 {
4994  if (nIndex == -1) {
4995  CKeyPool keypool;
4997  if (nIndex != -1)
4998  vchPubKey = keypool.vchPubKey;
4999  else {
5000  return false;
5001  }
5002  }
5003  assert(vchPubKey.IsValid());
5004  pubkey = vchPubKey;
5005  return true;
5006 }
5007 
5009 {
5010  if (nIndex != -1)
5012  nIndex = -1;
5013  vchPubKey = CPubKey();
5014 }
5015 
5017 {
5018  if (nIndex != -1)
5020  nIndex = -1;
5021  vchPubKey = CPubKey();
5022 }
5023 
5024 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
5025 {
5026  setAddress.clear();
5027 
5028  CWalletDB walletdb(strWalletFile);
5029 
5031  for (const int64_t& id : setKeyPool) {
5032  CKeyPool keypool;
5033  if (!walletdb.ReadPool(id, keypool))
5034  throw std::runtime_error("GetAllReserveKeyHashes() : read failed");
5035  assert(keypool.vchPubKey.IsValid());
5036  CKeyID keyID = keypool.vchPubKey.GetID();
5037  if (!HaveKey(keyID))
5038  throw std::runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
5039  setAddress.insert(keyID);
5040  }
5041 }
5042 
5044 {
5045  {
5046  LOCK(cs_wallet);
5047  // Only notify UI if this transaction is in this wallet
5048  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
5049  if (mi != mapWallet.end()) {
5050  NotifyTransactionChanged(this, hashTx, CT_UPDATED);
5051  return true;
5052  }
5053  }
5054  return false;
5055 }
5056 
5058 {
5059  AssertLockHeld(cs_wallet); // setLockedCoins
5060  setLockedCoins.insert(output);
5061 }
5062 
5064 {
5065  AssertLockHeld(cs_wallet); // setLockedCoins
5066  setLockedCoins.erase(output);
5067 }
5068 
5070 {
5071  AssertLockHeld(cs_wallet); // setLockedCoins
5072  setLockedCoins.clear();
5073 }
5074 
5075 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
5076 {
5077  AssertLockHeld(cs_wallet); // setLockedCoins
5078  COutPoint outpt(hash, n);
5079 
5080  return (setLockedCoins.count(outpt) > 0);
5081 }
5082 
5083 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
5084 {
5085  AssertLockHeld(cs_wallet); // setLockedCoins
5086  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
5087  it != setLockedCoins.end(); it++) {
5088  COutPoint outpt = (*it);
5089  vOutpts.push_back(outpt);
5090  }
5091 }
5092  // end of Actions
5094 
5095 class CAffectedKeysVisitor : public boost::static_visitor<void>
5096 {
5097 private:
5099  std::vector<CKeyID>& vKeys;
5100 
5101 public:
5102  CAffectedKeysVisitor(const CKeyStore& keystoreIn, std::vector<CKeyID>& vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
5103 
5104  void Process(const CScript& script)
5105  {
5106  txnouttype type;
5107  std::vector<CTxDestination> vDest;
5108  int nRequired;
5109  if (ExtractDestinations(script, type, vDest, nRequired)) {
5110  for (const CTxDestination& dest : vDest)
5111  boost::apply_visitor(*this, dest);
5112  }
5113  }
5114 
5115  void operator()(const CKeyID& keyId)
5116  {
5117  if (keystore.HaveKey(keyId))
5118  vKeys.push_back(keyId);
5119  }
5120 
5121  void operator()(const CScriptID& scriptId)
5122  {
5123  CScript script;
5124  if (keystore.GetCScript(scriptId, script))
5125  Process(script);
5126  }
5127 
5128  void operator()(const CNoDestination& none) {}
5129 };
5130 
5131 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const
5132 {
5133  AssertLockHeld(cs_wallet); // mapKeyMetadata
5134  mapKeyBirth.clear();
5135 
5136  // get birth times for keys with metadata
5137  for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
5138  if (it->second.nCreateTime)
5139  mapKeyBirth[it->first] = it->second.nCreateTime;
5140 
5141  // map in which we'll infer heights of other keys
5142  CBlockIndex* pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
5143  std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
5144  std::set<CKeyID> setKeys;
5145  GetKeys(setKeys);
5146  for (const CKeyID& keyid : setKeys) {
5147  if (mapKeyBirth.count(keyid) == 0)
5148  mapKeyFirstBlock[keyid] = pindexMax;
5149  }
5150  setKeys.clear();
5151 
5152  // if there are no such keys, we're done
5153  if (mapKeyFirstBlock.empty())
5154  return;
5155 
5156  // find first block that affects those keys, if there are any left
5157  std::vector<CKeyID> vAffected;
5158  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
5159  // iterate over all wallet transactions...
5160  const CWalletTx& wtx = (*it).second;
5161  BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
5162  if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
5163  // ... which are already in a block
5164  int nHeight = blit->second->nHeight;
5165  for (const CTxOut& txout : wtx.vout) {
5166  // iterate over all their outputs
5167  CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
5168  for (const CKeyID& keyid : vAffected) {
5169  // ... and all their affected keys
5170  std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
5171  if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
5172  rit->second = blit->second;
5173  }
5174  vAffected.clear();
5175  }
5176  }
5177  }
5178 
5179  // Extract block timestamps for those keys
5180  for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
5181  mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
5182 }
5183 
5184 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
5185 {
5186  unsigned int nTimeSmart = wtx.nTimeReceived;
5187  if (!wtx.hashBlock.IsNull()) {
5188  if (mapBlockIndex.count(wtx.hashBlock)) {
5189  int64_t latestNow = wtx.nTimeReceived;
5190  int64_t latestEntry = 0;
5191  {
5192  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
5193  int64_t latestTolerated = latestNow + 300;
5194  TxItems txOrdered = wtxOrdered;
5195  for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
5196  CWalletTx* const pwtx = (*it).second.first;
5197  if (pwtx == &wtx)
5198  continue;
5199  CAccountingEntry* const pacentry = (*it).second.second;
5200  int64_t nSmartTime;
5201  if (pwtx) {
5202  nSmartTime = pwtx->nTimeSmart;
5203  if (!nSmartTime)
5204  nSmartTime = pwtx->nTimeReceived;
5205  } else
5206  nSmartTime = pacentry->nTime;
5207  if (nSmartTime <= latestTolerated) {
5208  latestEntry = nSmartTime;
5209  if (nSmartTime > latestNow)
5210  latestNow = nSmartTime;
5211  break;
5212  }
5213  }
5214  }
5215 
5216  int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
5217  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
5218  } else
5219  LogPrintf("AddToWallet() : found %s in block %s not in index\n",
5220  wtx.GetHash().ToString(),
5221  wtx.hashBlock.ToString());
5222  }
5223  return nTimeSmart;
5224 }
5225 
5226 bool CWallet::AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value)
5227 {
5228  if (boost::get<CNoDestination>(&dest))
5229  return false;
5230 
5231  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
5232  if (!fFileBacked)
5233  return true;
5234  return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
5235 }
5236 
5237 bool CWallet::EraseDestData(const CTxDestination& dest, const std::string& key)
5238 {
5239  if (!mapAddressBook[dest].destdata.erase(key))
5240  return false;
5241  if (!fFileBacked)
5242  return true;
5243  return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
5244 }
5245 
5246 bool CWallet::LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value)
5247 {
5248  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
5249  return true;
5250 }
5251 
5252 bool CWallet::SendAll(std::string des, CWalletTx& wtxNew, bool inclLocked)
5253 {
5254  std::string strFailReason;
5255  if (this->IsLocked()) {
5256  strFailReason = "Wallet is locked! Please unlock it to make transactions.";
5257  LogPrintf("%s: %s\n", __func__, strFailReason);
5258  throw std::runtime_error(strFailReason);
5259  }
5260 
5261  SetRingSize(0);
5262  int estimateTxSize = ComputeTxSize(1, 1, MIN_RING_SIZE);
5263  CAmount nFeeNeeded = GetMinimumFee(estimateTxSize, nTxConfirmTarget, mempool);
5264  if (GetSpendableBalance() <= nFeeNeeded) {
5265  strFailReason = "Not enough balance to pay minimum transaction fee: " + ValueFromAmountToString(nFeeNeeded);
5266  LogPrintf("%s: %s\n", __func__, strFailReason);
5267  throw std::runtime_error(strFailReason);
5268  }
5269 
5270  CAmount total = 0;
5271  std::vector<COutput> vCoins;
5272  vCoins.clear();
5273  bool ret = true;
5274  {
5276  {
5277  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
5278  const uint256& wtxid = it->first;
5279  const CWalletTx* pcoin = &(*it).second;
5280 
5281  int nDepth = pcoin->GetDepthInMainChain(false);
5282  if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
5283  continue;
5284  if (nDepth == 0 && !pcoin->InMempool())
5285  continue;
5286  for (size_t i = 0; i < pcoin->vout.size(); i++) {
5287  if (pcoin->vout[i].IsEmpty()) continue;
5288  isminetype mine = IsMine(pcoin->vout[i]);
5289  if (mine == ISMINE_NO)
5290  continue;
5291  if (mine == ISMINE_WATCH_ONLY)
5292  continue;
5293  CAmount decodedAmount;
5294  CKey decodedBlind;
5295  RevealTxOutAmount(*pcoin, pcoin->vout[i], decodedAmount, decodedBlind);
5296 
5297  std::vector<unsigned char> commitment;
5298  if (!decodedBlind.IsValid()) {
5299  unsigned char blind[32];
5300  CreateCommitmentWithZeroBlind(decodedAmount, blind, commitment);
5301  } else {
5302  CreateCommitment(decodedBlind.begin(), decodedAmount, commitment);
5303  }
5304  if (pcoin->vout[i].commitment != commitment) {
5305  LogPrintf("%s: Commitment not match hash = %s, i = %d, commitment = %s, recomputed = %s, revealed mask = %s\n", __func__, pcoin->GetHash().GetHex(), i, HexStr(&pcoin->vout[i].commitment[0], &pcoin->vout[i].commitment[0] + 33), HexStr(&commitment[0], &commitment[0] + 33), HexStr(decodedBlind.begin(), decodedBlind.begin() + 32));
5306  continue;
5307  }
5308 
5309  if (IsSpent(wtxid, i)) continue;
5310 
5311  {
5312  COutPoint outpoint(wtxid, i);
5313  if (inSpendQueueOutpoints.count(outpoint)) {
5314  continue;
5315  }
5316  if (!inclLocked && IsCollateralized(outpoint)) {
5317  continue;
5318  }
5319  }
5320  vCoins.push_back(COutput(pcoin, i, nDepth, true));
5321  total += decodedAmount;
5322  if (vCoins.size() > MAX_TX_INPUTS) break;
5323  }
5324  if (vCoins.size() > MAX_TX_INPUTS) break;
5325  }
5326 
5327  if (vCoins.size() > MAX_TX_INPUTS) {
5328  strFailReason = "Transaction size too large. Please combine/consolidate UTXOs and try again.";
5329  ret = false;
5330  LogPrintf("%s: %s\n", __func__, strFailReason);
5331  throw std::runtime_error(strFailReason);
5332  }
5333 
5334  if (ret) {
5335  // Generate transaction public key
5336  CKey secret;
5337  secret.MakeNewKey(true);
5339 
5340  unsigned char rand_seed[16];
5341  memcpy(rand_seed, secret.begin(), 16);
5342  secp256k1_rand_seed(rand_seed);
5343  int ringSize = MIN_RING_SIZE + secp256k1_rand32() % (MAX_RING_SIZE - MIN_RING_SIZE + 1);
5344 
5345  estimateTxSize = ComputeTxSize(vCoins.size(), 1, ringSize);
5346  nFeeNeeded = GetMinimumFee(estimateTxSize, nTxConfirmTarget, mempool);
5347  if (total < nFeeNeeded) {
5348  strFailReason = "Not enough balance to pay minimum transaction Fee: " + ValueFromAmountToString(nFeeNeeded);
5349  ret = false;
5350  LogPrintf("%s: %s\n", __func__, strFailReason);
5351  throw std::runtime_error(strFailReason);
5352  } else {
5353  //Parse stealth address
5354  CPubKey pubViewKey, pubSpendKey;
5355  bool hasPaymentID;
5356  uint64_t paymentID;
5357 
5358  if (!CWallet::DecodeStealthAddress(des, pubViewKey, pubSpendKey, hasPaymentID, paymentID)) {
5359  //should never happen
5360  ret = false;
5361  strFailReason = "Invalid Destination Address!";
5362  LogPrintf("%s: %s\n", __func__, strFailReason);
5363  throw std::runtime_error(strFailReason);
5364  } else {
5365  wtxNew.txPrivM.Set(secret.begin(), secret.end(), true);
5366 
5367  wtxNew.hasPaymentID = 0;
5368  if (hasPaymentID) {
5369  wtxNew.hasPaymentID = 1;
5370  wtxNew.paymentID = paymentID;
5371  }
5372 
5373  //Compute stealth destination
5374  CPubKey stealthDes;
5375  CKey spend;
5376  mySpendPrivateKey(spend);
5377  CKey view;
5378  myViewPrivateKey(view);
5379  ComputeStealthDestination(secret, pubViewKey, pubSpendKey, stealthDes);
5380 
5381  CScript scriptPubKey = GetScriptForDestination(stealthDes);
5382 
5383  CAmount nValue = total - nFeeNeeded;
5384 
5385  wtxNew.fTimeReceivedIsTxTime = true;
5386  wtxNew.BindWallet(this);
5387  CMutableTransaction txNew;
5388  txNew.hasPaymentID = wtxNew.hasPaymentID;
5389  txNew.paymentID = wtxNew.paymentID;
5390 
5391  {
5392  while (true) {
5393  txNew.vin.clear();
5394  txNew.vout.clear();
5395  wtxNew.fFromMe = true;
5396 
5397  double dPriority = 0;
5398 
5399  // vouts to the payees
5400  CTxOut txout(nValue, scriptPubKey);
5401  CPubKey txPub = wtxNew.txPrivM.GetPubKey();
5402  txPrivKeys.push_back(wtxNew.txPrivM);
5403  std::copy(txPub.begin(), txPub.end(), std::back_inserter(txout.txPub));
5404 
5405  CPubKey sharedSec;
5406  ECDHInfo::ComputeSharedSec(wtxNew.txPrivM, pubViewKey, sharedSec);
5407  EncodeTxOutAmount(txout, txout.nValue, sharedSec.begin());
5408  txNew.vout.push_back(txout);
5409  txNew.nTxFee = nFeeNeeded;
5410 
5411  //Fill vin
5412  for (size_t i = 0; i < vCoins.size(); i++) {
5413  txNew.vin.push_back(CTxIn(vCoins[i].tx->GetHash(), vCoins[i].i));
5414  }
5415 
5416  // Embed the constructed transaction data in wtxNew.
5417  *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
5418  break;
5419  }
5420 
5421  if (!makeRingCT(wtxNew, ringSize, strFailReason)) {
5422  strFailReason = _("Failed to generate RingCT");
5423  ret = false;
5424  LogPrintf("%s: %s\n", __func__, strFailReason);
5425  throw std::runtime_error(strFailReason);
5426  }
5427 
5428  if (ret && !generateBulletProofAggregate(wtxNew)) {
5429  strFailReason = _("Failed to generate bulletproof");
5430  ret = false;
5431  LogPrintf("%s: %s\n", __func__, strFailReason);
5432  throw std::runtime_error(strFailReason);
5433  }
5434 
5435  if (ret) {
5436  for (size_t i = 0; i < wtxNew.vout.size(); i++) {
5437  wtxNew.vout[i].nValue = 0;
5438  }
5439  CReserveKey reservekey(this);
5440  if (!CommitTransaction(wtxNew, reservekey, "tx")) {
5442  strFailReason = "Internal error! Please try again later!";
5443  ret = false;
5444  LogPrintf("%s: %s\n", __func__, strFailReason);
5445  throw std::runtime_error(strFailReason);
5446  }
5447  if (ret) {
5448  for (size_t i = 0; i < inSpendQueueOutpointsPerSession.size(); i++) {
5450  }
5452 
5453  uint256 hash = wtxNew.GetHash();
5454  int maxTxPrivKeys = txPrivKeys.size() > wtxNew.vout.size() ? wtxNew.vout.size() : txPrivKeys.size();
5455  for (int i = 0; i < maxTxPrivKeys; i++) {
5456  std::string key = hash.GetHex() + std::to_string(i);
5458  }
5459  txPrivKeys.clear();
5460  }
5461  }
5462  }
5463  }
5464  }
5465  }
5466  }
5467  }
5468 
5469  return ret;
5470 }
5471 
5472 bool CWallet::CreateSweepingTransaction(CAmount target, CAmount threshold, uint32_t nTimeBefore)
5473 {
5474  if (this->IsLocked()) {
5475  return true;
5476  }
5477 
5478  if (GetSpendableBalance() < 1 * COIN) {
5479  return false;
5480  }
5481  CAmount total = 0;
5482  std::vector<COutput> vCoins;
5483  COutput lowestLarger(NULL, 0, 0, false);
5484  CAmount currentLowestLargerAmount = 0;
5485  vCoins.clear();
5486  bool ret = true;
5487  bool isReserveUTXOExist = false;
5488  static uint256 reserveHash;
5489  {
5491  {
5492  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
5493  const uint256& wtxid = it->first;
5494  const CWalletTx* pcoin = &(*it).second;
5495 
5496  if (pcoin->GetTxTime() > nTimeBefore) continue;
5497 
5498  int nDepth = pcoin->GetDepthInMainChain(false);
5499  if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
5500  continue;
5501  if (nDepth == 0 && !pcoin->InMempool())
5502  continue;
5503  for (size_t i = 0; i < pcoin->vout.size(); i++) {
5504  if (pcoin->vout[i].IsEmpty()) continue;
5505  isminetype mine = IsMine(pcoin->vout[i]);
5506  if (mine == ISMINE_NO)
5507  continue;
5508  if (mine == ISMINE_WATCH_ONLY)
5509  continue;
5510  CAmount decodedAmount;
5511  CKey decodedBlind;
5512  RevealTxOutAmount(*pcoin, pcoin->vout[i], decodedAmount, decodedBlind);
5513 
5514  std::vector<unsigned char> commitment;
5515  if (!decodedBlind.IsValid()) {
5516  unsigned char blind[32];
5517  CreateCommitmentWithZeroBlind(decodedAmount, blind, commitment);
5518  } else {
5519  CreateCommitment(decodedBlind.begin(), decodedAmount, commitment);
5520  }
5521  if (pcoin->vout[i].commitment != commitment) {
5522  LogPrintf("%s: Commitment not match hash = %s, i = %d, commitment = %s, recomputed = %s, revealed mask = %s\n", __func__, pcoin->GetHash().GetHex(), i, HexStr(&pcoin->vout[i].commitment[0], &pcoin->vout[i].commitment[0] + 33), HexStr(&commitment[0], &commitment[0] + 33), HexStr(decodedBlind.begin(), decodedBlind.begin() + 32));
5523  continue;
5524  }
5525 
5526  if (IsSpent(wtxid, i)) continue;
5527 
5528  {
5529  COutPoint outpoint(wtxid, i);
5530  if (inSpendQueueOutpoints.count(outpoint)) {
5531  continue;
5532  }
5533 
5534  if (IsCollateralized(outpoint)) {
5535  continue;
5536  }
5537  }
5538 
5539  if (nReserveBalance > 0) {
5540  if (decodedAmount == ComputeReserveUTXOAmount()) {
5541  isReserveUTXOExist = true;
5542  reserveHash = wtxid;
5543  //dont select reserve UTXO
5544  continue;
5545  }
5546  }
5547 
5548  if (nDepth <= 5) continue;
5549  if (decodedAmount >= threshold) {
5550  if (lowestLarger.tx == NULL || (lowestLarger.tx != NULL && currentLowestLargerAmount > decodedAmount)) {
5551  lowestLarger.tx = pcoin;
5552  lowestLarger.i = i;
5553  lowestLarger.nDepth = nDepth;
5554  lowestLarger.fSpendable = true;
5555  currentLowestLargerAmount = decodedAmount;
5556  }
5557  continue;
5558  }
5559 
5560  if (vCoins.size() <= MAX_TX_INPUTS - 1) { //reserve 1 input for lowestLarger
5561  vCoins.push_back(COutput(pcoin, i, nDepth, true));
5562  total += decodedAmount;
5563  }
5564  }
5565  }
5566 
5567  if (nReserveBalance > 0) {
5568  if (!isReserveUTXOExist) {
5569  //create transactions that create reserve funds
5570  CWalletTx wtx;
5571  std::string masterAddr;
5572  ComputeStealthPublicAddress("masteraccount", masterAddr);
5573  try {
5574  SendToStealthAddress(masterAddr, ComputeReserveUTXOAmount(), wtx);
5575  } catch (const std::exception& err) {
5576  LogPrintf("Failed to create reserve UTXO\n");
5577  }
5578  return false;
5579  } else {
5580  if (mapWallet.count(reserveHash) < 1) return false;
5581  const CWalletTx reserve = mapWallet[reserveHash];
5582 
5583  if (reserve.GetDepthInMainChain(false) < 10) {
5584  return false;
5585  }
5586  }
5587  }
5588  SetRingSize(0);
5589  int ringSize = MIN_RING_SIZE + secp256k1_rand32() % (MAX_RING_SIZE - MIN_RING_SIZE + 1);
5590  if (vCoins.size() <= 1) return false;
5591  CAmount estimatedFee = ComputeFee(vCoins.size(), 1, ringSize);
5592  if (combineMode != CombineMode::ON && (vCoins.empty() || (vCoins.size() < MIN_TX_INPUTS_FOR_SWEEPING) || (total < target + estimatedFee && vCoins.size() <= MAX_TX_INPUTS))) {
5593  //preconditions to create auto sweeping transactions not satisfied, do nothing here
5594  ret = false;
5595  } else {
5596  LogPrintf("Attempting to create a sweeping transaction\n");
5597  if (combineMode == CombineMode::ON) {
5598  if (total < target + estimatedFee) {
5599  if (lowestLarger.tx != NULL && currentLowestLargerAmount >= threshold) {
5600  vCoins.push_back(lowestLarger);
5601  total += currentLowestLargerAmount;
5602  } else {
5603  LogPrintf("No set of UTXOs to combine into a stakeable coin - autocombine any way if minimum UTXOs satisfied\n");
5604  if (vCoins.size() < MIN_TX_INPUTS_FOR_SWEEPING) return false;
5605  }
5606  }
5607  }
5608  LogPrintf("Generating consolidation transaction, total = %d PRCY\n", total / COIN);
5609  // Generate transaction public key
5610  CWalletTx wtxNew;
5611  CKey secret;
5612  secret.MakeNewKey(true);
5614 
5615  int estimateTxSize = ComputeTxSize(vCoins.size(), 1, ringSize);
5616  CAmount nFeeNeeded = GetMinimumFee(estimateTxSize, nTxConfirmTarget, mempool);
5617  if (total < nFeeNeeded * 2) {
5618  ret = false;
5619  } else {
5620  std::string myAddress;
5621  ComputeStealthPublicAddress("masteraccount", myAddress);
5622  //Parse stealth address
5623  CPubKey pubViewKey, pubSpendKey;
5624  bool hasPaymentID;
5625  uint64_t paymentID;
5626 
5627  if (!CWallet::DecodeStealthAddress(myAddress, pubViewKey, pubSpendKey, hasPaymentID, paymentID)) {
5628  //should never happen
5629  ret = false;
5630  } else {
5631  wtxNew.txPrivM.Set(secret.begin(), secret.end(), true);
5632  wtxNew.hasPaymentID = 0;
5633 
5634  //Compute stealth destination
5635  CPubKey stealthDes;
5636  CKey spend;
5637  mySpendPrivateKey(spend);
5638  CKey view;
5639  myViewPrivateKey(view);
5640  ComputeStealthDestination(secret, pubViewKey, pubSpendKey, stealthDes);
5641 
5642  CScript scriptPubKey = GetScriptForDestination(stealthDes);
5643 
5644  CAmount nValue = total - nFeeNeeded;
5645 
5646  wtxNew.fTimeReceivedIsTxTime = true;
5647  wtxNew.BindWallet(this);
5648  CMutableTransaction txNew;
5649  txNew.hasPaymentID = wtxNew.hasPaymentID;
5650  txNew.paymentID = wtxNew.paymentID;
5651 
5652  {
5653  unsigned int nBytes = 0;
5654  while (true) {
5655  txNew.vin.clear();
5656  txNew.vout.clear();
5657  wtxNew.fFromMe = true;
5658 
5659  double dPriority = 0;
5660  // vouts to the payees
5661  CTxOut txout(nValue, scriptPubKey);
5662  CPubKey txPub = wtxNew.txPrivM.GetPubKey();
5663  txPrivKeys.push_back(wtxNew.txPrivM);
5664  std::copy(txPub.begin(), txPub.end(), std::back_inserter(txout.txPub));
5665 
5666  CPubKey sharedSec;
5667  ECDHInfo::ComputeSharedSec(wtxNew.txPrivM, pubViewKey, sharedSec);
5668  EncodeTxOutAmount(txout, txout.nValue, sharedSec.begin());
5669  txNew.vout.push_back(txout);
5670  //nBytes += ::GetSerializeSize(*(CTxOut*)&txout, SER_NETWORK, PROTOCOL_VERSION);
5671 
5672  txNew.nTxFee = nFeeNeeded;
5673 
5674  //Fill vin
5675  for (size_t i = 0; i < vCoins.size(); i++) {
5676  txNew.vin.push_back(CTxIn(vCoins[i].tx->GetHash(), vCoins[i].i));
5677  }
5678 
5679  // Embed the constructed transaction data in wtxNew.
5680  *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
5681  break;
5682  }
5683 
5684  std::string strFailReason;
5685  if (!makeRingCT(wtxNew, ringSize, strFailReason)) {
5686  ret = false;
5687  }
5688 
5689  if (ret && !generateBulletProofAggregate(wtxNew)) {
5690  strFailReason = _("There is an internal error in generating bulletproofs. Please try again later.");
5691  ret = false;
5692  }
5693 
5694  if (ret) {
5695  for (size_t i = 0; i < wtxNew.vout.size(); i++) {
5696  wtxNew.vout[i].nValue = 0;
5697  }
5698  CReserveKey reservekey(this);
5699  if (!CommitTransaction(wtxNew, reservekey, "tx")) {
5701  ret = false;
5702  }
5703  if (ret) {
5704  for (size_t i = 0; i < inSpendQueueOutpointsPerSession.size(); i++) {
5706  }
5708 
5709  uint256 hash = wtxNew.GetHash();
5710  int maxTxPrivKeys = txPrivKeys.size() > wtxNew.vout.size() ? wtxNew.vout.size() : txPrivKeys.size();
5711  for (int i = 0; i < maxTxPrivKeys; i++) {
5712  std::string key = hash.GetHex() + std::to_string(i);
5714  }
5715  txPrivKeys.clear();
5716  }
5717  }
5718  }
5719  }
5720  }
5721  }
5722  }
5723  }
5724 
5725  return ret;
5726 }
5727 
5729 {
5730  // QT wallet is always locked at startup, return immediately
5731  if (IsLocked()) return;
5732  // Chain is not synced, return
5734  // Tip()->nTime < (GetAdjustedTime() - 300)
5735  if (chainActive.Tip()->nTime < (GetAdjustedTime() - 300)) return;
5736  bool stkStatus = ReadStakingStatus();
5737  if (combineMode == CombineMode::ON && stkStatus) {
5738  //sweeping to create larger UTXO for staking
5741  if (max == 0) {
5742  max = GetBalance();
5743  }
5744  uint32_t nTime = ReadAutoConsolidateSettingTime();
5745  nTime = (nTime == 0)? GetAdjustedTime() : nTime;
5746  LogPrintf("Attempting to create a consolidation transaction for a larger UTXO for staking\n");
5747  // Params().MinimumStakeAmount() already has * COIN, so not used here
5748  CreateSweepingTransaction(Params().MinimumStakeAmount(), max + MAX_FEE, nTime);
5749  return;
5750  }
5751  // nAutoCombineTarget/ nAutoCombineThreshold are not * COIN, so that is used here
5753 }
5754 
5756  //finding all spendable UTXOs < MIN_STAKING
5757  CAmount total = 0;
5758  const CAmount minStakingAmount = Params().MinimumStakeAmount();
5759  std::vector<COutput> vCoins, underStakingThresholdCoins;
5760  {
5762  {
5763  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
5764  const uint256& wtxid = it->first;
5765  const CWalletTx* pcoin = &(*it).second;
5766 
5767  int nDepth = pcoin->GetDepthInMainChain(false);
5768  if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
5769  continue;
5770  if (nDepth == 0 && !pcoin->InMempool())
5771  continue;
5772  for(size_t i = 0; i < pcoin->vout.size(); i++) {
5773  if (pcoin->vout[i].IsEmpty()) continue;
5774  isminetype mine = IsMine(pcoin->vout[i]);
5775  if (mine == ISMINE_NO)
5776  continue;
5777  if (mine == ISMINE_WATCH_ONLY)
5778  continue;
5779  CAmount decodedAmount;
5780  CKey decodedBlind;
5781  RevealTxOutAmount(*pcoin, pcoin->vout[i], decodedAmount, decodedBlind);
5782 
5783  std::vector<unsigned char> commitment;
5784  if (!decodedBlind.IsValid()) {
5785  unsigned char blind[32];
5786  CreateCommitmentWithZeroBlind(decodedAmount, blind, commitment);
5787  } else {
5788  CreateCommitment(decodedBlind.begin(), decodedAmount, commitment);
5789  }
5790  if (pcoin->vout[i].commitment != commitment) {
5791  LogPrintf("%s: Commitment not match hash = %s, i = %d, commitment = %s, recomputed = %s, revealed mask = %s\n", __func__, pcoin->GetHash().GetHex(), i, HexStr(&pcoin->vout[i].commitment[0], &pcoin->vout[i].commitment[0] + 33), HexStr(&commitment[0], &commitment[0] + 33), HexStr(decodedBlind.begin(), decodedBlind.begin() + 32));
5792  continue;
5793  }
5794 
5795  if (IsSpent(wtxid, i)) continue;
5796 
5797  {
5798  COutPoint outpoint(wtxid, i);
5799  if (inSpendQueueOutpoints.count(outpoint)) {
5800  continue;
5801  }
5802  }
5803  vCoins.push_back(COutput(pcoin, i, nDepth, true));
5804  total += decodedAmount;
5805  if (decodedAmount < minStakingAmount) underStakingThresholdCoins.push_back(COutput(pcoin, i, nDepth, true));
5806  }
5807  }
5808  }
5809  }
5810 
5811  minFee = 0;
5812  maxFee = 0;
5813  if (total < minStakingAmount) return false; //no staking sweeping will be created
5814  size_t numUTXOs = vCoins.size();
5815  return true;
5816 }
5817 
5819  return ComputeTxSize(50, 2, 15);
5820 }
5821 
5823 {
5825  // Stop the old blocks from sending multisends
5826  if (chainActive.Tip()->nTime < (GetAdjustedTime() - 300) || IsLocked()) {
5827  return false;
5828  }
5829 
5831  LogPrintf("Multisend: lastmultisendheight is higher than current best height\n");
5832  return false;
5833  }
5834 
5835  std::vector<COutput> vCoins;
5836  AvailableCoins(vCoins);
5837 
5838  bool stakeSent = false;
5839  bool mnSent = false;
5840  for (const COutput& out : vCoins) {
5841  //need output with precise confirm count - this is how we identify which is the output to send
5842  if (out.tx->GetDepthInMainChain() != Params().COINBASE_MATURITY() + 1)
5843  continue;
5844 
5845  COutPoint outpoint(out.tx->GetHash(), out.i);
5846  bool sendMSonMNReward = fMultiSendMasternodeReward && outpoint.IsMasternodeReward(out.tx);
5847  bool sendMSOnStake = fMultiSendStake && out.tx->IsCoinStake() && !sendMSonMNReward; //output is either mnreward or stake reward, not both
5848 
5849  if (!(sendMSOnStake || sendMSonMNReward))
5850  continue;
5851 
5852  CTxDestination destMyAddress;
5853  if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, destMyAddress)) {
5854  LogPrintf("Multisend: failed to extract destination\n");
5855  continue;
5856  }
5857 
5858  //Disabled Addresses won't send MultiSend transactions
5859  if (vDisabledAddresses.size() > 0) {
5860  for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) {
5861  if (vDisabledAddresses[i] == CBitcoinAddress(destMyAddress).ToString()) {
5862  LogPrintf("Multisend: disabled address preventing multisend\n");
5863  return false;
5864  }
5865  }
5866  }
5867 
5868  // create new coin control, populate it with the selected utxo, create sending vector
5869  CCoinControl cControl;
5870  COutPoint outpt(out.tx->GetHash(), out.i);
5871  cControl.Select(outpt);
5872  cControl.destChange = destMyAddress;
5873 
5874  CWalletTx wtx;
5875  CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch
5876  CAmount nFeeRet = 0;
5877  std::vector<std::pair<CScript, CAmount> > vecSend;
5878 
5879  // loop through multisend vector and add amounts and addresses to the sending vector
5880  const isminefilter filter = ISMINE_SPENDABLE;
5881  CAmount nAmount = 0;
5882  for (unsigned int i = 0; i < vMultiSend.size(); i++) {
5883  // MultiSend vector is a pair of 1)Address as a std::string 2) Percent of stake to send as an int
5884  nAmount = ((out.tx->GetCredit(filter) - out.tx->GetDebit(filter)) * vMultiSend[i].second) / 100;
5885  CBitcoinAddress strAddSend(vMultiSend[i].first);
5886  CScript scriptPubKey;
5887  scriptPubKey = GetScriptForDestination(strAddSend.Get());
5888  vecSend.push_back(std::make_pair(scriptPubKey, nAmount));
5889  }
5890 
5891  //get the fee amount
5892  CWalletTx wtxdummy;
5893  std::string strErr;
5894  CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, &cControl, ALL_COINS, false, CAmount(0));
5895  CAmount nLastSendAmount = vecSend[vecSend.size() - 1].second;
5896  if (nLastSendAmount < nFeeRet + 500) {
5897  LogPrintf("%s: fee of %d is too large to insert into last output\n", __func__, nFeeRet + 500);
5898  return false;
5899  }
5900  vecSend[vecSend.size() - 1].second = nLastSendAmount - nFeeRet - 500;
5901 
5902  // Create the transaction and commit it to the network
5903  if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, &cControl, ALL_COINS, false, CAmount(0))) {
5904  LogPrintf("MultiSend createtransaction failed\n");
5905  return false;
5906  }
5907 
5908  if (!CommitTransaction(wtx, keyChange)) {
5909  LogPrintf("MultiSend transaction commit failed\n");
5910  return false;
5911  } else
5912  fMultiSendNotify = true;
5913 
5914  //write nLastMultiSendHeight to DB
5915  CWalletDB walletdb(strWalletFile);
5918  LogPrintf("Failed to write MultiSend setting to DB\n");
5919 
5920  LogPrintf("MultiSend successfully sent\n");
5921 
5922  //set which MultiSend triggered
5923  if (sendMSOnStake)
5924  stakeSent = true;
5925  else
5926  mnSent = true;
5927 
5928  //stop iterating if we have sent out all the MultiSend(s)
5929  if ((stakeSent && mnSent) || (stakeSent && !fMultiSendMasternodeReward) || (mnSent && !fMultiSendStake))
5930  return true;
5931  }
5932 
5933  return true;
5934 }
5935 
5937 {
5938  nTime = GetTime();
5939 }
5940 
5941 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
5942 {
5943  nTime = GetTime();
5944  vchPubKey = vchPubKeyIn;
5945 }
5946 
5947 CWalletKey::CWalletKey(int64_t nExpires)
5948 {
5949  nTimeCreated = (nExpires ? GetTime() : 0);
5950  nTimeExpires = nExpires;
5951 }
5952 
5954 {
5956  CBlock blockTmp;
5957 
5958  // Update the tx's hashBlock
5959  hashBlock = block.GetHash();
5960 
5961  // Locate the transaction
5962  for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
5963  if (block.vtx[nIndex] == *(CTransaction*)this)
5964  break;
5965  if (nIndex == (int)block.vtx.size()) {
5966  nIndex = -1;
5967  LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
5968  return 0;
5969  }
5970 
5971  // Is the tx in a block that's in the main chain
5972  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
5973  if (mi == mapBlockIndex.end())
5974  return 0;
5975  const CBlockIndex* pindex = (*mi).second;
5976  if (!pindex || !chainActive.Contains(pindex))
5977  return 0;
5978 
5979  return chainActive.Height() - pindex->nHeight + 1;
5980 }
5981 
5983 {
5984  if (hashBlock == 0 || nIndex == -1)
5985  return 0;
5987 
5988  // Find the block it claims to be in
5989  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
5990  if (mi == mapBlockIndex.end())
5991  return 0;
5992  CBlockIndex* pindex = (*mi).second;
5993  if (!pindex || !chainActive.Contains(pindex))
5994  return 0;
5995 
5996  pindexRet = pindex;
5997  return chainActive.Height() - pindex->nHeight + 1;
5998 }
5999 
6000 int CMerkleTx::GetDepthInMainChain(bool enableIX) const
6001 {
6002  const CBlockIndex* pindexRet;
6003  return GetDepthInMainChain(pindexRet, enableIX);
6004 }
6005 
6006 int CMerkleTx::GetDepthInMainChain(const CBlockIndex*& pindexRet, bool enableIX) const
6007 {
6009  int nResult = GetDepthInMainChainINTERNAL(pindexRet);
6010  if (nResult == 0 && !mempool.exists(GetHash()))
6011  return -1; // Not in chain, not in mempool
6012 
6013  if (enableIX) {
6014  if (nResult < 6) {
6015  int signatures = GetTransactionLockSignatures();
6016  if (signatures >= SWIFTTX_SIGNATURES_REQUIRED) {
6017  return nSwiftTXDepth + nResult;
6018  }
6019  }
6020  }
6021 
6022  return nResult;
6023 }
6024 
6026 {
6027  LOCK(cs_main);
6028  if (!(IsCoinBase() || IsCoinStake()))
6029  return 0;
6030  return std::max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain());
6031 }
6032 
6034 {
6035  return GetDepthInMainChain(false) > 0;
6036 }
6037 
6039 {
6040  if (!IsCoinBase() && !IsCoinStake()) return false;
6041  const int depth = GetDepthInMainChain(false);
6042  return (depth > 0 && depth <= Params().COINBASE_MATURITY());
6043 }
6044 
6045 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee, bool ignoreFees)
6046 {
6047  CValidationState state;
6048  bool fAccepted = ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee, ignoreFees);
6049  if (!fAccepted)
6050  LogPrintf("%s : %s\n", __func__, state.GetRejectReason());
6051  return fAccepted;
6052 }
6053 
6055 {
6057  if (!fEnableSwiftTX) return -1;
6058 
6059  //compile consessus vote
6060  std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash());
6061  if (i != mapTxLocks.end()) {
6062  return (*i).second.CountSignatures();
6063  }
6064 
6065  return -1;
6066 }
6067 
6069 {
6070  if (!fEnableSwiftTX) return 0;
6071 
6072  //compile consessus vote
6073  std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash());
6074  if (i != mapTxLocks.end()) {
6075  return GetTime() > (*i).second.nTimeout;
6076  }
6077 
6078  return false;
6079 }
6080 
6082 {
6083  std::stringstream ssDateTime;
6084  std::string strWalletBackupName = strprintf("%s", DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime()));
6085  ssDateTime << strWalletBackupName;
6086 
6087  return strprintf("wallet%s.dat%s", "", DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime()));
6088 }
6089 
6091 {
6092  SetNull();
6093 }
6094 
6095 CWallet::CWallet(std::string strWalletFileIn)
6096 {
6097  SetNull();
6098 
6099  strWalletFile = strWalletFileIn;
6100  fFileBacked = true;
6101 }
6102 
6104 {
6105  delete pwalletdbEncryption;
6106 }
6107 
6109 {
6112  fFileBacked = false;
6113  nMasterKeyMaxID = 0;
6114  pwalletdbEncryption = NULL;
6115  nOrderPosNext = 0;
6116  nNextResend = 0;
6117  nLastResend = 0;
6118  nTimeFirstKey = 0;
6119  fWalletUnlockStakingOnly = false;
6120 
6121  // Stake Settings
6122  nHashDrift = 45;
6124  nHashInterval = 22;
6125  nStakeSetUpdateTime = 300; // 5 minutes
6126 
6127  //MultiSend
6128  vMultiSend.clear();
6129  fMultiSendStake = false;
6131  fMultiSendNotify = false;
6134  vDisabledAddresses.clear();
6135 
6136  //Auto Combine Dust
6137  fCombineDust = GetBoolArg("-combinedust", true);
6138  nAutoCombineThreshold = 150;
6139  nAutoCombineTarget = GetArg("-autocombinetarget", 15);
6140 }
6141 
6143 {
6145 }
6146 
6148 {
6150  fMultiSendStake = false;
6151 }
6152 
6154 {
6156  return nWalletMaxVersion >= wf;
6157 }
6158 
6159 bool CWallet::LoadMinVersion(int nVersion)
6160 {
6162  nWalletVersion = nVersion;
6163  nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion);
6164  return true;
6165 }
6166 
6167 isminetype CWallet::IsMine(const CTxOut& txout) const
6168 {
6169  return ::IsMine(*this, txout.scriptPubKey);
6170 }
6171 
6172 CAmount CWallet::GetCredit(const CTransaction& tx, const CTxOut& txout, const isminefilter& filter) const
6173 {
6174  return ((IsMine(txout) & filter) ? getCTxOutValue(tx, txout) : 0);
6175 }
6176 
6177 CAmount CWallet::GetChange(const CTransaction& tx, const CTxOut& txout) const
6178 {
6179  return (IsChange(txout) ? getCTxOutValue(tx, txout) : 0);
6180 }
6181 
6182 bool CWallet::IsMine(const CTransaction& tx) const
6183 {
6184  for (const CTxOut& txout : tx.vout)
6185  if (IsMine(txout))
6186  return true;
6187  return false;
6188 }
6189 
6190 bool CWallet::IsFromMe(const CTransaction& tx) const
6191 {
6192  return (GetDebit(tx, ISMINE_ALL) > 0);
6193 }
6194 
6195 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
6196 {
6197  CAmount nDebit = 0;
6198  for (const CTxIn& txin : tx.vin) {
6199  nDebit += GetDebit(txin, filter);
6200  }
6201  return nDebit;
6202 }
6203 
6204 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
6205 {
6206  CAmount nCredit = 0;
6207  for (const CTxOut& txout : tx.vout) {
6208  nCredit += GetCredit(tx, txout, filter);
6209  }
6210  return nCredit;
6211 }
6212 
6214 {
6215  CAmount nChange = 0;
6216  for (const CTxOut& txout : tx.vout) {
6217  nChange += GetChange(tx, txout);
6218  }
6219  return nChange;
6220 }
6221 
6222 void CWallet::Inventory(const uint256& hash)
6223 {
6224  {
6225  LOCK(cs_wallet);
6226  std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
6227  if (mi != mapRequestCount.end())
6228  (*mi).second++;
6229  }
6230 }
6231 
6233 {
6234  AssertLockHeld(cs_wallet); // setKeyPool
6235  return setKeyPool.size();
6236 }
6237 
6239 {
6240  LOCK(cs_wallet);
6241  return nWalletVersion;
6242 }
6243 
6245 {
6246  Init(NULL);
6247 }
6248 
6250 {
6251  Init(pwalletIn);
6252 }
6253 
6254 CWalletTx::CWalletTx(CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
6255 {
6256  Init(pwalletIn);
6257 }
6258 
6259 CWalletTx::CWalletTx(CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
6260 {
6261  Init(pwalletIn);
6262 }
6263 
6264 void CWalletTx::Init(CWallet* pwalletIn)
6265 {
6266  pwallet = pwalletIn;
6267  mapValue.clear();
6268  vOrderForm.clear();
6269  fTimeReceivedIsTxTime = false;
6270  nTimeReceived = 0;
6271  nTimeSmart = 0;
6272  fFromMe = false;
6273  strFromAccount.clear();
6274  fDebitCached = false;
6275  fCreditCached = false;
6276  fImmatureCreditCached = false;
6277  fAvailableCreditCached = false;
6278  fWatchDebitCached = false;
6279  fWatchCreditCached = false;
6282  fChangeCached = false;
6283  nDebitCached = 0;
6284  nCreditCached = 0;
6287  nWatchDebitCached = 0;
6288  nWatchCreditCached = 0;
6291  nChangeCached = 0;
6292  nOrderPos = -1;
6293 }
6294 
6296 {
6297  // Quick answer in most cases
6298  if (!IsFinalTx(*this))
6299  return false;
6300  int nDepth = GetDepthInMainChain();
6301  if (nDepth >= 1)
6302  return true;
6303  if (nDepth < 0)
6304  return false;
6305  if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
6306  return false;
6307  // Don't trust unconfirmed transactions from us unless they are in the mempool.
6308  {
6309  LOCK(mempool.cs);
6310  if (!mempool.exists(GetHash())) {
6311  return false;
6312  }
6313  }
6314  // Trusted if all inputs are from us and are in the mempool:
6315  for (const CTxIn& txin : vin) {
6316  // Transactions not sent by us: not trusted
6317  COutPoint prevout = pwallet->findMyOutPoint(txin);
6318  const CWalletTx* parent = pwallet->GetWalletTx(prevout.hash);
6319  if (parent == NULL)
6320  return false;
6321  const CTxOut& parentOut = parent->vout[prevout.n];
6322  if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
6323  return false;
6324  }
6325  return true;
6326 }
6327 
6329 {
6330  fCreditCached = false;
6331  fAvailableCreditCached = false;
6332  fWatchDebitCached = false;
6333  fWatchCreditCached = false;
6336  fDebitCached = false;
6337  fChangeCached = false;
6338 }
6339 
6341 {
6342  pwallet = pwalletIn;
6343  MarkDirty();
6344 }
6345 
6347 {
6348  if (fChangeCached)
6349  return nChangeCached;
6350  nChangeCached = pwallet->GetChange(*this);
6351  fChangeCached = true;
6352  return nChangeCached;
6353 }
6354 
6355 bool CWalletTx::IsFromMe(const isminefilter& filter) const
6356 {
6357  return (GetDebit(filter) > 0);
6358 }
6359 
6361 {
6362  if (hashBlock.IsNull()) {
6363  return -1; //not in the chain
6364  } else {
6365  return mapBlockIndex[hashBlock]->nHeight;
6366  }
6367 }
6368 
6369 bool CWallet::ReadAccountList(std::string& accountList)
6370 {
6371  return CWalletDB(strWalletFile).ReadStealthAccountList(accountList);
6372 }
6373 
6374 bool CWallet::ReadStealthAccount(const std::string& strAccount, CStealthAccount& account)
6375 {
6376  return CWalletDB(strWalletFile).ReadStealthAccount(strAccount, account);
6377 }
6378 
6379 bool CWallet::ComputeStealthPublicAddress(const std::string& accountName, std::string& pubAddress)
6380 {
6381  CStealthAccount account;
6382  if (CWalletDB(strWalletFile).ReadStealthAccount(accountName, account)) {
6383  return EncodeStealthPublicAddress(account.viewAccount.vchPubKey, account.spendAccount.vchPubKey, pubAddress);
6384  }
6385  return false;
6386 }
6387 
6388 bool CWallet::ComputeIntegratedPublicAddress(const uint64_t paymentID, const std::string& accountName, std::string& pubAddress)
6389 {
6390  CStealthAccount account;
6391  if (CWalletDB(strWalletFile).ReadStealthAccount(accountName, account)) {
6392  return EncodeIntegratedAddress(account.viewAccount.vchPubKey, account.spendAccount.vchPubKey, paymentID, pubAddress);
6393  }
6394  return false;
6395 }
6396 
6397 void add1s(std::string& s, int wantedSize)
6398 {
6399  int currentLength = s.length();
6400  for (int i = 0; i < wantedSize - currentLength; i++) {
6401  s = "1" + s;
6402  }
6403 }
6404 
6405 
6406 bool CWallet::encodeStealthBase58(const std::vector<unsigned char>& raw, std::string& stealth)
6407 {
6408  if (raw.size() != 71 && raw.size() != 79) {
6409  return false;
6410  }
6411  stealth = "";
6412 
6413  //Encoding Base58 using block=8 bytes
6414  int i = 0;
6415  while (i < (int)raw.size()) {
6416  std::vector<unsigned char> input8;
6417  std::copy(raw.begin() + i, raw.begin() + i + 8, std::back_inserter(input8)); //copy 8 bytes
6418  std::string out = EncodeBase58(input8);
6419  if (out.length() < 11) {
6420  add1s(out, 11);
6421  }
6422  stealth += out;
6423  i += 8;
6424  if (i + 8 > (int)raw.size()) {
6425  //the last block of 7
6426  std::vector<unsigned char> input7;
6427  std::copy(raw.begin() + i, raw.begin() + i + 7, std::back_inserter(input7)); //copy 7 bytes
6428  std::string out11 = EncodeBase58(input7);
6429  add1s(out11, 11);
6430  stealth += out11;
6431  i += 7;
6432  }
6433  }
6434  return true;
6435 }
6436 
6437 bool CWallet::EncodeStealthPublicAddress(const std::vector<unsigned char>& pubViewKey, const std::vector<unsigned char>& pubSpendKey, std::string& pubAddrb58)
6438 {
6439  std::vector<unsigned char> pubAddr;
6440  pubAddr.push_back(Params().StealthPrefix()); //1 byte
6441  std::copy(pubSpendKey.begin(), pubSpendKey.begin() + 33, std::back_inserter(pubAddr)); //copy 33 bytes
6442  std::copy(pubViewKey.begin(), pubViewKey.begin() + 33, std::back_inserter(pubAddr)); //copy 33 bytes
6443  uint256 h = Hash(pubAddr.begin(), pubAddr.end());
6444  unsigned char* begin = h.begin();
6445  pubAddr.push_back(*(begin));
6446  pubAddr.push_back(*(begin + 1));
6447  pubAddr.push_back(*(begin + 2));
6448  pubAddr.push_back(*(begin + 3));
6449 
6450  return encodeStealthBase58(pubAddr, pubAddrb58);
6451 }
6452 
6453 bool CWallet::EncodeIntegratedAddress(const std::vector<unsigned char>& pubViewKey, const std::vector<unsigned char>& pubSpendKey, uint64_t paymentID, std::string& pubAddrb58)
6454 {
6455  std::vector<unsigned char> pubAddr;
6456  pubAddr.push_back(Params().IntegratedPrefix()); //1 byte 19 for integrated address
6457  std::copy(pubSpendKey.begin(), pubSpendKey.begin() + 33, std::back_inserter(pubAddr)); //copy 33 bytes
6458  std::copy(pubViewKey.begin(), pubViewKey.begin() + 33, std::back_inserter(pubAddr)); //copy 33 bytes
6459  std::copy((char*)&paymentID, (char*)&paymentID + sizeof(paymentID), std::back_inserter(pubAddr)); //8 bytes of payment id
6460  uint256 h = Hash(pubAddr.begin(), pubAddr.end());
6461  unsigned char* begin = h.begin();
6462  pubAddr.push_back(*(begin));
6463  pubAddr.push_back(*(begin + 1));
6464  pubAddr.push_back(*(begin + 2));
6465  pubAddr.push_back(*(begin + 3));
6466 
6467  return encodeStealthBase58(pubAddr, pubAddrb58);
6468 }
6469 
6470 bool CWallet::EncodeStealthPublicAddress(const CPubKey& pubViewKey, const CPubKey& pubSpendKey, std::string& pubAddr)
6471 {
6472  if (pubViewKey.IsCompressed() && pubSpendKey.IsCompressed()) {
6473  return EncodeStealthPublicAddress(pubViewKey.Raw(), pubSpendKey.Raw(), pubAddr);
6474  }
6475  return false;
6476 }
6477 
6478 bool CWallet::EncodeIntegratedAddress(const CPubKey& pubViewKey, const CPubKey& pubSpendKey, uint64_t paymentID, std::string& pubAddr)
6479 {
6480  if (pubViewKey.IsCompressed() && pubSpendKey.IsCompressed()) {
6481  return EncodeIntegratedAddress(pubViewKey.Raw(), pubSpendKey.Raw(), paymentID, pubAddr);
6482  }
6483  return false;
6484 }
6485 
6486 bool CWallet::GenerateIntegratedAddress(const std::string& accountName, std::string& pubAddr)
6487 {
6488  CStealthAccount account;
6489  if (CWalletDB(strWalletFile).ReadStealthAccount(accountName, account)) {
6490  return GenerateIntegratedAddress(account.viewAccount.vchPubKey, account.spendAccount.vchPubKey, pubAddr);
6491  }
6492  return false;
6493 }
6494 
6495 bool CWallet::GenerateIntegratedAddress(const CPubKey& pubViewKey, const CPubKey& pubSpendKey, std::string& pubAddr)
6496 {
6497  uint64_t paymentID = GetRand(0xFFFFFFFFFFFFFFFF);
6498  return EncodeIntegratedAddress(pubViewKey, pubSpendKey, paymentID, pubAddr);
6499 }
6500 
6501 std::string CWallet::GenerateIntegratedAddressWithRandomPaymentID(std::string accountName, uint64_t& paymentID) {
6502  CStealthAccount account;
6503  if (CWalletDB(strWalletFile).ReadStealthAccount(accountName, account)) {
6504  std::string pubAddress;
6505  paymentID = GetRand(0xFFFFFFFFFFFFFFFF);
6506  EncodeIntegratedAddress(account.viewAccount.vchPubKey, account.spendAccount.vchPubKey, paymentID, pubAddress);
6507  return pubAddress;
6508  }
6509  return "";
6510 }
6511 
6512 std::string CWallet::GenerateIntegratedAddressWithProvidedPaymentID(std::string accountName, uint64_t paymentID) {
6513  CStealthAccount account;
6514  if (CWalletDB(strWalletFile).ReadStealthAccount(accountName, account)) {
6515  std::string pubAddress;
6516  EncodeIntegratedAddress(account.viewAccount.vchPubKey, account.spendAccount.vchPubKey, paymentID, pubAddress);
6517  return pubAddress;
6518  }
6519  return "";
6520 }
6521 
6522 bool CWallet::DecodeStealthAddress(const std::string& stealth, CPubKey& pubViewKey, CPubKey& pubSpendKey, bool& hasPaymentID, uint64_t& paymentID)
6523 {
6524  if (stealth.length() != 99 && stealth.length() != 110) {
6525  return false;
6526  }
6527  std::vector<unsigned char> raw;
6528  size_t i = 0;
6529  while (i < stealth.length()) {
6530  int npos = 11;
6531  std::string sub = stealth.substr(i, npos);
6532  std::vector<unsigned char> decoded;
6533  if (DecodeBase58(sub, decoded) &&
6534  ((decoded.size() == 8 && i + 11 < stealth.length() - 1) || (decoded.size() == 7 && i + 11 == stealth.length() - 1))) {
6535  std::copy(decoded.begin(), decoded.end(), std::back_inserter(raw));
6536  } else if (sub[0] == '1') {
6537  //find the last padding character
6538  size_t lastPad = 0;
6539  while (lastPad < sub.length() - 1) {
6540  if (sub[lastPad + 1] != '1') {
6541  break;
6542  }
6543  lastPad++;
6544  }
6545  //check whether '1' is padding
6546  int padIdx = lastPad;
6547  while (padIdx >= 0 && sub[padIdx] == '1') {
6548  std::string str_without_pads = sub.substr(padIdx + 1);
6549  decoded.clear();
6550  if (DecodeBase58(str_without_pads, decoded)) {
6551  if ((decoded.size() == 8 && i + 11 < stealth.length()) || (decoded.size() == 7 && i + 11 == stealth.length())) {
6552  std::copy(decoded.begin(), decoded.end(), std::back_inserter(raw));
6553  break;
6554  } else {
6555  decoded.clear();
6556  }
6557  }
6558  padIdx--;
6559  }
6560  if (decoded.size() == 0) {
6561  //cannot decode this block of stealth address
6562  return false;
6563  }
6564  } else {
6565  return false;
6566  }
6567  i = i + npos;
6568  }
6569 
6570  if (raw.size() != 71 && raw.size() != 79) {
6571  return false;
6572  }
6573  hasPaymentID = false;
6574  if (raw.size() == 79) {
6575  hasPaymentID = true;
6576  }
6577 
6578  //Check checksum
6579  uint256 h = Hash(raw.begin(), raw.begin() + raw.size() - 4);
6580  unsigned char* h_begin = h.begin();
6581  unsigned char* p_raw = &raw[raw.size() - 4];
6582  if (memcmp(h_begin, p_raw, 4) != 0) {
6583  return false;
6584  }
6585 
6586  std::vector<unsigned char> vchSpend, vchView;
6587  std::copy(raw.begin() + 1, raw.begin() + 34, std::back_inserter(vchSpend));
6588  std::copy(raw.begin() + 34, raw.begin() + 67, std::back_inserter(vchView));
6589  if (hasPaymentID) {
6590  memcpy((char*)&paymentID, &raw[0] + 67, sizeof(paymentID));
6591  }
6592  pubSpendKey.Set(vchSpend.begin(), vchSpend.end());
6593  pubViewKey.Set(vchView.begin(), vchView.end());
6594 
6595  return true;
6596 }
6597 
6598 bool computeStealthDestination(const CKey& secret, const CPubKey& pubViewKey, const CPubKey& pubSpendKey, CPubKey& des)
6599 {
6600  //generate transaction destination: P = Hs(rA)G+B, A = view pub, B = spend pub, r = secret
6601  //1. Compute rA
6602  unsigned char rA[65];
6603  unsigned char B[65];
6604  memcpy(rA, pubViewKey.begin(), pubViewKey.size());
6605  if (!secp256k1_ec_pubkey_tweak_mul(rA, pubViewKey.size(), secret.begin())) {
6606  return false;
6607  }
6608  uint256 HS = Hash(rA, rA + pubViewKey.size());
6609 
6610  memcpy(B, pubSpendKey.begin(), pubSpendKey.size());
6611 
6612  if (!secp256k1_ec_pubkey_tweak_add(B, pubSpendKey.size(), HS.begin()))
6613  throw std::runtime_error("Cannot compute stealth destination");
6614  des.Set(B, B + pubSpendKey.size());
6615  return true;
6616 }
6617 
6618 bool CWallet::ComputeStealthDestination(const CKey& secret, const CPubKey& pubViewKey, const CPubKey& pubSpendKey, CPubKey& des)
6619 {
6620  return computeStealthDestination(secret, pubViewKey, pubSpendKey, des);
6621 }
6622 
6623 bool CWallet::GenerateAddress(CPubKey& pub, CPubKey& txPub, CKey& txPriv) const
6624 {
6626  {
6627  CKey view, spend;
6628  if (IsLocked()) {
6629  LogPrintf("%s: Wallet is locked\n", __func__);
6630  return false;
6631  }
6632  myViewPrivateKey(view);
6633  mySpendPrivateKey(spend);
6634  txPriv.MakeNewKey(true);
6635  txPub = txPriv.GetPubKey();
6636  return computeStealthDestination(txPriv, view.GetPubKey(), spend.GetPubKey(), pub);
6637  }
6638 }
6639 
6640 bool CWallet::SendToStealthAddress(const std::string& stealthAddr, const CAmount nValue, CWalletTx& wtxNew, bool fUseIX, int ringSize)
6641 {
6643 
6644  std::string strFailReason;
6645  if (this->IsLocked()) {
6646  strFailReason = "Error: Wallet locked, unable to create transaction!";
6647  LogPrintf("%s: %s\n", __func__, strFailReason);
6648  throw std::runtime_error(strFailReason);
6649  }
6650 
6651  std::string myAddress;
6652  ComputeStealthPublicAddress("masteraccount", myAddress);
6653  bool tomyself = (myAddress == stealthAddr);
6654  //Parse stealth address
6655  CPubKey pubViewKey, pubSpendKey;
6656  bool hasPaymentID;
6657  uint64_t paymentID;
6658  if (!CWallet::DecodeStealthAddress(stealthAddr, pubViewKey, pubSpendKey, hasPaymentID, paymentID)) {
6659  throw std::runtime_error("Stealth address mal-formatted");
6660  }
6661 
6662  // Generate transaction public key
6663  CKey secret;
6664  secret.MakeNewKey(true);
6666  wtxNew.txPrivM.Set(secret.begin(), secret.end(), true);
6667 
6668  wtxNew.hasPaymentID = 0;
6669  if (hasPaymentID) {
6670  wtxNew.hasPaymentID = 1;
6671  wtxNew.paymentID = paymentID;
6672  }
6673 
6674  //Compute stealth destination
6675  CPubKey stealthDes;
6676  CKey spend;
6677  mySpendPrivateKey(spend);
6678  computeStealthDestination(secret, pubViewKey, pubSpendKey, stealthDes);
6679 
6680  CScript scriptPubKey = GetScriptForDestination(stealthDes);
6681  CReserveKey reservekey(this);
6682 
6683  CPubKey changeDes;
6684  CKey view;
6685  myViewPrivateKey(view);
6686  CKey secretChange;
6687  secretChange.MakeNewKey(true);
6688  computeStealthDestination(secretChange, view.GetPubKey(), spend.GetPubKey(), changeDes);
6689  CBitcoinAddress changeAddress(changeDes.GetID());
6690  CCoinControl control;
6691  control.destChange = changeAddress.Get();
6692  control.receiver = changeDes;
6693  control.txPriv = secretChange;
6694  CAmount nFeeRequired;
6695  if (!CreateTransactionBulletProof(secret, pubViewKey, scriptPubKey, nValue, wtxNew, reservekey,
6696  nFeeRequired, strFailReason, &control, ALL_COINS, fUseIX, (CAmount)0, 6, tomyself)) {
6697  if (nValue + nFeeRequired > GetBalance())
6698  strFailReason = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!, nfee=%d, nValue=%d", FormatMoney(nFeeRequired), nFeeRequired, nValue);
6699  LogPrintf("%s: %s\n", __func__, strFailReason);
6700  throw std::runtime_error(strFailReason);
6701  }
6702  return true;
6703 }
6704 
6706 {
6707  LOCK(cs_wallet);
6708  {
6709  std::vector<CKey> spends, views;
6710  if (!allMyPrivateKeys(spends, views) || spends.size() != views.size()) {
6711  spends.clear();
6712  views.clear();
6713  CKey spend, view;
6714  if (!mySpendPrivateKey(spend) || !myViewPrivateKey(view)) {
6715  LogPrintf("Failed to find private keys\n");
6716  return false;
6717  }
6718  spends.push_back(spend);
6719  views.push_back(view);
6720  }
6721  for (const CTxOut& out : tx.vout) {
6722  if (out.IsEmpty()) {
6723  continue;
6724  }
6725  CPubKey txPub(out.txPub);
6726  for (size_t i = 0; i < spends.size(); i++) {
6727  CKey& spend = spends[i];
6728  CKey& view = views[i];
6729  const CPubKey& pubSpendKey = spend.GetPubKey();
6730  bool ret = false;
6731 
6732  //compute the tx destination
6733  //P' = Hs(aR)G+B, a = view private, B = spend pub, R = tx public key
6734  unsigned char aR[65];
6735  //copy R into a
6736  memcpy(aR, txPub.begin(), txPub.size());
6737  if (!secp256k1_ec_pubkey_tweak_mul(aR, txPub.size(), view.begin())) {
6738  return false;
6739  }
6740  uint256 HS = Hash(aR, aR + txPub.size());
6741  unsigned char* pHS = HS.begin();
6742  unsigned char expectedDestination[65];
6743  memcpy(expectedDestination, pubSpendKey.begin(), pubSpendKey.size());
6744  if (!secp256k1_ec_pubkey_tweak_add(expectedDestination, pubSpendKey.size(), pHS)) {
6745  continue;
6746  }
6747  CPubKey expectedDes(expectedDestination, expectedDestination + 33);
6748  CScript scriptPubKey = GetScriptForDestination(expectedDes);
6749 
6750  if (scriptPubKey == out.scriptPubKey) {
6751  ret = true;
6752  }
6753 
6754  if (ret) {
6755  //Compute private key to spend
6756  //x = Hs(aR) + b, b = spend private key
6757  unsigned char HStemp[32];
6758  unsigned char spendTemp[32];
6759  memcpy(HStemp, HS.begin(), 32);
6760  memcpy(spendTemp, spend.begin(), 32);
6761  if (!secp256k1_ec_privkey_tweak_add(HStemp, spendTemp))
6762  throw std::runtime_error("Failed to do secp256k1_ec_privkey_tweak_add");
6763  CKey privKey;
6764  privKey.Set(HStemp, HStemp + 32, true);
6765  CPubKey computed = privKey.GetPubKey();
6766 
6767  //put in map from address to txHash used for qt wallet
6768  CKeyID tempKeyID = computed.GetID();
6769  addrToTxHashMap[CBitcoinAddress(tempKeyID).ToString()] = tx.GetHash().GetHex();
6770  AddKey(privKey);
6771  CAmount c;
6772  CKey blind;
6773  RevealTxOutAmount(tx, out, c, blind);
6774  }
6775  }
6776  }
6777  }
6778  return true;
6779 }
6780 
6781 bool CWallet::AllMyPublicAddresses(std::vector<std::string>& addresses, std::vector<std::string>& accountNames)
6782 {
6783  std::string labelList;
6784  if (!ReadAccountList(labelList)) {
6785  std::string masterAddr;
6786  ComputeStealthPublicAddress("masteraccount", masterAddr);
6787  addresses.push_back(masterAddr);
6788  accountNames.push_back("Master Account");
6789  return true;
6790  }
6791 
6792  std::vector<std::string> results;
6793  boost::split(results, labelList, [](char c) { return c == ','; });
6794  std::string masterAddr;
6795  ComputeStealthPublicAddress("masteraccount", masterAddr);
6796  accountNames.push_back("Master Account");
6797  results.push_back(masterAddr);
6798  for (size_t i = 0; i < results.size(); i++) {
6799  std::string& accountName = results[i];
6800  std::string stealthAddr;
6801  if (ComputeStealthPublicAddress(accountName, stealthAddr)) {
6802  addresses.push_back(stealthAddr);
6803  accountNames.push_back(accountName);
6804  }
6805  }
6806  return true;
6807 }
6808 
6809 bool CWallet::allMyPrivateKeys(std::vector<CKey>& spends, std::vector<CKey>& views)
6810 {
6811  if (IsLocked()) {
6812  return false;
6813  }
6814  std::string labelList;
6815  CKey spend, view;
6816  mySpendPrivateKey(spend);
6817  myViewPrivateKey(view);
6818  spends.push_back(spend);
6819  views.push_back(view);
6820 
6821  if (!ReadAccountList(labelList)) {
6822  return false;
6823  }
6824  std::vector<std::string> results;
6825  boost::split(results, labelList, [](char c) { return c == ','; });
6826  for (size_t i = 0; i < results.size(); i++) {
6827  std::string& accountName = results[i];
6828  CStealthAccount stealthAcc;
6829  if (ReadStealthAccount(accountName, stealthAcc)) {
6830  CKey accSpend, accView;
6831  GetKey(stealthAcc.spendAccount.vchPubKey.GetID(), accSpend);
6832  GetKey(stealthAcc.viewAccount.vchPubKey.GetID(), accView);
6833  spends.push_back(accSpend);
6834  views.push_back(accView);
6835  }
6836  }
6837  return true;
6838 }
6839 
6840 CBitcoinAddress GetAccountAddress(uint32_t nAccountIndex, std::string strAccount, CWallet* pwalletMain)
6841 {
6842  CWalletDB walletdb(pwalletMain->strWalletFile);
6843 
6844  CAccount account;
6845 
6846  // Generate a new key
6847  // if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
6848  // throw std::runtime_error("Error: Keypool ran out, please call keypoolrefill first");
6849  CKey newKey;
6850  pwalletMain->DeriveNewChildKey(nAccountIndex, newKey);
6851  account.vchPubKey = newKey.GetPubKey();
6852  account.nAccountIndex = nAccountIndex;
6853 
6854  pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
6855  walletdb.WriteAccount(strAccount, account);
6856 
6857  return CBitcoinAddress(account.vchPubKey.GetID());
6858 }
6859 
6860 void CWallet::DeriveNewChildKey(uint32_t nAccountIndex, CKey& secretRet)
6861 {
6862  CHDChain hdChainTmp;
6863  if (!GetHDChain(hdChainTmp)) {
6864  throw std::runtime_error(std::string(__func__) + ": GetHDChain failed");
6865  }
6866 
6867  if (!DecryptHDChain(hdChainTmp))
6868  throw std::runtime_error(std::string(__func__) + ": DecryptHDChainSeed failed");
6869  // make sure seed matches this chain
6870  if (hdChainTmp.GetID() != hdChainTmp.GetSeedHash())
6871  throw std::runtime_error(std::string(__func__) + ": Wrong HD chain!");
6872 
6873  // derive child key at next index, skip keys already known to the wallet
6874  CExtKey childKey;
6875  uint32_t nChildIndex = 0;
6876  do {
6877  hdChainTmp.DeriveChildExtKey(nAccountIndex, false, nChildIndex, childKey);
6878  // increment childkey index
6879  nChildIndex++;
6880  } while (HaveKey(childKey.key.GetPubKey().GetID()));
6881  secretRet = childKey.key;
6882 
6883  CPubKey pubkey = secretRet.GetPubKey();
6884  assert(secretRet.VerifyPubKey(pubkey));
6885 
6886  // store metadata
6887  int64_t nCreationTime = GetTime();
6888  mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
6889 
6890  if (!AddHDPubKey(childKey.Neuter(), false, nAccountIndex))
6891  throw std::runtime_error(std::string(__func__) + ": AddHDPubKey failed");
6892 }
6893 
6894 bool CWallet::GetPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const
6895 {
6896  LOCK(cs_wallet);
6897  std::map<CKeyID, CHDPubKey>::const_iterator mi = mapHdPubKeys.find(address);
6898  if (mi != mapHdPubKeys.end()) {
6899  const CHDPubKey& hdPubKey = (*mi).second;
6900  vchPubKeyOut = hdPubKey.extPubKey.pubkey;
6901  return true;
6902  } else
6903  return CCryptoKeyStore::GetPubKey(address, vchPubKeyOut);
6904 }
6905 
6906 bool CWallet::GetKey(const CKeyID& address, CKey& keyOut) const
6907 {
6908  LOCK(cs_wallet);
6909  std::map<CKeyID, CHDPubKey>::const_iterator mi = mapHdPubKeys.find(address);
6910  if (mi != mapHdPubKeys.end()) {
6911  // if the key has been found in mapHdPubKeys, derive it on the fly
6912  const CHDPubKey& hdPubKey = (*mi).second;
6913  CHDChain hdChainCurrent;
6914  if (!GetHDChain(hdChainCurrent))
6915  throw std::runtime_error(std::string(__func__) + ": GetHDChain failed");
6916  if (!DecryptHDChain(hdChainCurrent))
6917  throw std::runtime_error(std::string(__func__) + ": DecryptHDChainSeed failed");
6918  // make sure seed matches this chain
6919  if (hdChainCurrent.GetID() != hdChainCurrent.GetSeedHash())
6920  throw std::runtime_error(std::string(__func__) + ": Wrong HD chain!");
6921 
6922  CExtKey extkey;
6923  hdChainCurrent.DeriveChildExtKey(hdPubKey.nAccountIndex, hdPubKey.nChangeIndex != 0, hdPubKey.extPubKey.nChild, extkey);
6924  keyOut = extkey.key;
6925 
6926  return true;
6927  } else {
6928  return CCryptoKeyStore::GetKey(address, keyOut);
6929  }
6930 }
6931 
6932 bool CWallet::HaveKey(const CKeyID& address) const
6933 {
6934  LOCK(cs_wallet);
6935  if (mapHdPubKeys.count(address) > 0)
6936  return true;
6937  return CCryptoKeyStore::HaveKey(address);
6938 }
6939 
6940 bool CWallet::LoadHDPubKey(const CHDPubKey& hdPubKey)
6941 {
6943 
6944  mapHdPubKeys[hdPubKey.extPubKey.pubkey.GetID()] = hdPubKey;
6945  return true;
6946 }
6947 
6948 bool CWallet::AddHDPubKey(const CExtPubKey& extPubKey, bool fInternal, uint32_t nAccountIndex)
6949 {
6951 
6952  CHDChain hdChainCurrent;
6953  GetHDChain(hdChainCurrent);
6954 
6955  CHDPubKey hdPubKey;
6956  hdPubKey.extPubKey = extPubKey;
6957  hdPubKey.nAccountIndex = nAccountIndex;
6958  hdPubKey.hdchainID = hdChainCurrent.GetID();
6959  hdPubKey.nChangeIndex = fInternal ? 1 : 0;
6960  mapHdPubKeys[extPubKey.pubkey.GetID()] = hdPubKey;
6961 
6962  CScript script;
6963  script = GetScriptForDestination(extPubKey.pubkey);
6964  if (HaveWatchOnly(script))
6965  RemoveWatchOnly(script);
6966 
6967  if (!fFileBacked)
6968  return true;
6969 
6970  return CWalletDB(strWalletFile).WriteHDPubKey(hdPubKey, mapKeyMetadata[extPubKey.pubkey.GetID()]);
6971 }
6972 
6974 {
6975  int i = 0;
6976  CWalletDB pDB(strWalletFile);
6977  {
6978  LOCK(cs_wallet);
6979  while (i < 10) {
6980  std::string viewAccountLabel = "viewaccount";
6981  std::string spendAccountLabel = "spendaccount";
6982 
6983  CAccount viewAccount;
6984  pDB.ReadAccount(viewAccountLabel, viewAccount);
6985  if (!viewAccount.vchPubKey.IsValid()) {
6986  std::string viewAccountAddress = GetAccountAddress(0, viewAccountLabel, (CWallet*)this).ToString();
6987  }
6988 
6989  CAccount spendAccount;
6990  pDB.ReadAccount(spendAccountLabel, spendAccount);
6991  if (!spendAccount.vchPubKey.IsValid()) {
6992  std::string spendAccountAddress = GetAccountAddress(1, spendAccountLabel, (CWallet*)this).ToString();
6993  }
6994  if (viewAccount.vchPubKey.GetHex() == "" || spendAccount.vchPubKey.GetHex() == "") {
6995  i++;
6996  continue;
6997  }
6998  LogPrintf("Created master account\n");
6999  break;
7000  }
7001  }
7002 }
7003 
7005 {
7006  {
7008  if (IsLocked()) {
7009  LogPrintf("%s: Wallet is locked\n", __func__);
7010  return false;
7011  }
7012  std::string spendAccountLabel = "spendaccount";
7013  CAccount spendAccount;
7014  CWalletDB pDB(strWalletFile);
7015  if (!pDB.ReadAccount(spendAccountLabel, spendAccount)) {
7016  LogPrintf("Cannot load private Spend key, now creating the master keys\n");
7017  createMasterKey();
7018  pDB.ReadAccount(spendAccountLabel, spendAccount);
7019  }
7020  const CKeyID& keyID = spendAccount.vchPubKey.GetID();
7021  GetKey(keyID, spend);
7022  }
7023  return true;
7024 }
7026 {
7027  {
7029  if (IsLocked()) {
7030  LogPrintf("%s: Wallet is locked\n", __func__);
7031  return false;
7032  }
7033  std::string viewAccountLabel = "viewaccount";
7034  CAccount viewAccount;
7035  CWalletDB pDB(strWalletFile);
7036  if (!pDB.ReadAccount(viewAccountLabel, viewAccount)) {
7037  LogPrintf("Cannot load private View key, now creating the master keys\n");
7038  createMasterKey();
7039  pDB.ReadAccount(viewAccountLabel, viewAccount);
7040  }
7041  const CKeyID& keyID = viewAccount.vchPubKey.GetID();
7042  GetKey(keyID, view);
7043  }
7044  return true;
7045 }
7046 
7047 bool CWallet::RevealTxOutAmount(const CTransaction& tx, const CTxOut& out, CAmount& amount, CKey& blind) const
7048 {
7049  if (IsLocked()) {
7050  return true;
7051  }
7052  if (tx.IsCoinBase()) {
7053  //Coinbase transaction output is not hidden, not need to decrypt
7054  amount = out.nValue;
7055  return true;
7056  }
7057 
7058  if (tx.IsCoinStake()) {
7059  if (out.nValue > 0) {
7060  amount = out.nValue;
7061  return true;
7062  }
7063  }
7064 
7065  if (amountMap.count(out.scriptPubKey) == 1) {
7066  amount = amountMap[out.scriptPubKey];
7067  blind.Set(blindMap[out.scriptPubKey].begin(), blindMap[out.scriptPubKey].end(), true);
7068  return true;
7069  }
7070 
7071  std::set<CKeyID> keyIDs;
7072  GetKeys(keyIDs);
7073  CPubKey sharedSec;
7074  for (const CKeyID& keyID : keyIDs) {
7075  CKey privKey;
7076  GetKey(keyID, privKey);
7077  CScript scriptPubKey = GetScriptForDestination(privKey.GetPubKey());
7078  if (scriptPubKey == out.scriptPubKey) {
7079  CPubKey txPub(&(out.txPub[0]), &(out.txPub[0]) + 33);
7080  CKey view;
7081  if (myViewPrivateKey(view)) {
7082  computeSharedSec(tx, out, sharedSec);
7083  uint256 val = out.maskValue.amount;
7084  uint256 mask = out.maskValue.mask;
7085  CKey decodedMask;
7086  ECDHInfo::Decode(mask.begin(), val.begin(), sharedSec, decodedMask, amount);
7087  std::vector<unsigned char> commitment;
7088  if (CreateCommitment(decodedMask.begin(), amount, commitment)) {
7089  //make sure the amount and commitment are matched
7090  if (commitment == out.commitment) {
7091  amountMap[out.scriptPubKey] = amount;
7092  blindMap[out.scriptPubKey] = decodedMask;
7093  blind.Set(blindMap[out.scriptPubKey].begin(), blindMap[out.scriptPubKey].end(), true);
7094  return true;
7095  } else {
7096  amount = 0;
7097  amountMap[out.scriptPubKey] = amount;
7098  return false;
7099  }
7100  }
7101  }
7102  }
7103  }
7104  amount = 0;
7105  return false;
7106 }
7107 
7109 {
7110  std::set<CKeyID> keyIDs;
7111  GetKeys(keyIDs);
7112  for (const CKeyID& keyID : keyIDs) {
7113  CBitcoinAddress address(keyID);
7114  GetKey(keyID, key);
7115  CPubKey pub = key.GetPubKey();
7116  CScript script = GetScriptForDestination(pub);
7117  if (script == txout.scriptPubKey) {
7118  return true;
7119  }
7120  }
7121  return false;
7122 }
7123 
7124 bool CWallet::generateKeyImage(const CScript& scriptPubKey, CKeyImage& img) const
7125 {
7126  if (IsLocked()) {
7127  return false;
7128  }
7129  std::set<CKeyID> keyIDs;
7130  GetKeys(keyIDs);
7131  CKey key;
7132  unsigned char pubData[65];
7133  for (const CKeyID& keyID : keyIDs) {
7134  CBitcoinAddress address(keyID);
7135  GetKey(keyID, key);
7136  CPubKey pub = key.GetPubKey();
7137  CScript script = GetScriptForDestination(pub);
7138  if (script == scriptPubKey) {
7139  uint256 hash = pub.GetHash();
7140  pubData[0] = *(pub.begin());
7141  memcpy(pubData + 1, hash.begin(), 32);
7142  CPubKey newPubKey(pubData, pubData + 33);
7143  //P' = Hs(aR)G+B, a = view private, B = spend pub, R = tx public key
7144  unsigned char ki[65];
7145  //copy newPubKey into ki
7146  memcpy(ki, newPubKey.begin(), newPubKey.size());
7147  while (!secp256k1_ec_pubkey_tweak_mul(ki, newPubKey.size(), key.begin())) {
7148  hash = newPubKey.GetHash();
7149  pubData[0] = *(newPubKey.begin());
7150  memcpy(pubData + 1, hash.begin(), 32);
7151  newPubKey.Set(pubData, pubData + 33);
7152  memcpy(ki, newPubKey.begin(), newPubKey.size());
7153  }
7154 
7155  img = CKeyImage(ki, ki + 33);
7156  return true;
7157  }
7158  }
7159  return false;
7160 }
7161 
7162 bool CWallet::generateKeyImage(const CPubKey& pub, CKeyImage& img) const
7163 {
7164  CScript script = GetScriptForDestination(pub);
7165  return generateKeyImage(script, img);
7166 }
7167 
7168 bool CWallet::EncodeTxOutAmount(CTxOut& out, const CAmount& amount, const unsigned char* sharedSec, bool isCoinstake)
7169 {
7170  if (amount < 0) {
7171  return false;
7172  }
7173  //generate random mask
7174  if (!isCoinstake) {
7177  uint256 tempAmount((uint64_t)amount);
7178  memcpy(out.maskValue.amount.begin(), tempAmount.begin(), 32);
7179  CPubKey sharedPub(sharedSec, sharedSec + 33);
7180  ECDHInfo::Encode(out.maskValue.inMemoryRawBind, amount, sharedPub, out.maskValue.mask, out.maskValue.amount);
7181  out.maskValue.hashOfKey = Hash(sharedSec, sharedSec + 33);
7182  } else {
7183  uint256 tempAmount((uint64_t)amount);
7184  out.maskValue.amount.SetNull();
7185  memcpy(out.maskValue.amount.begin(), tempAmount.begin(), 32);
7186  CPubKey sharedPub(sharedSec, sharedSec + 33);
7187  ecdhEncode(out.maskValue.mask.begin(), out.maskValue.amount.begin(), sharedPub.begin(), sharedPub.size());
7188  out.maskValue.hashOfKey = Hash(sharedSec, sharedSec + 33);
7189  }
7190  return true;
7191 }
7192 
7194 {
7195  const CTxOut& out = output.tx->vout[output.i];
7196  CAmount amount = 0;
7197  CKey blind;
7198  RevealTxOutAmount((const CTransaction&)(*output.tx), out, amount, blind);
7199  return amount;
7200 }
7201 
7203 {
7204  CAmount amount = 0;
7205  CKey blind;
7206  RevealTxOutAmount(tx, out, amount, blind);
7207  return amount;
7208 }
CWallet::GetUnlockedCoins
CAmount GetUnlockedCoins() const
Definition: wallet.cpp:2282
CTransaction::IsCoinAudit
bool IsCoinAudit() const
Definition: transaction.h:364
kernel.h
TX_TYPE_REVEAL_BOTH
@ TX_TYPE_REVEAL_BOTH
Definition: transaction.h:263
CWalletDB::WriteBestBlock
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:172
CWallet::LockCoin
void LockCoin(COutPoint &output)
Definition: wallet.cpp:5057
secp256k1_pedersen_commit
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commit(const secp256k1_context2 *ctx, secp256k1_pedersen_commitment *commit, const unsigned char *blind, uint64_t value, const secp256k1_generator *value_gen, const secp256k1_generator *blind_gen) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(6)
Generate a Pedersen commitment.
Definition: main_impl.h:93
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: chain.h:364
CCoinControl::receiver
CPubKey receiver
Definition: coincontrol.h:19
CHDChain::GetID
uint256 GetID() const
Definition: hdchain.h:85
CTxIn
An input of a transaction.
Definition: transaction.h:83
CKeyStore
A virtual base class for key stores.
Definition: keystore.h:21
CCoinControl::Select
void Select(const COutPoint &output)
Definition: coincontrol.h:59
CCoinControl::fAllowOtherInputs
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:25
CWalletDB::ListAccountCreditDebit
void ListAccountCreditDebit(const std::string &strAccount, std::list< CAccountingEntry > &acentries)
Definition: walletdb.cpp:425
CWallet::checkPassPhraseRule
bool checkPassPhraseRule(const char *pass)
Definition: wallet.cpp:187
CWallet::txPrivKeys
std::vector< CKey > txPrivKeys
Definition: wallet.h:356
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:183
CCoinControl::IsSelected
bool IsSelected(const uint256 &hash, unsigned int n) const
Definition: coincontrol.h:53
CMasterKey::vchSalt
std::vector< unsigned char > vchSalt
Definition: crypter.h:38
CWallet::AddToWalletIfInvolvingMe
bool AddToWalletIfInvolvingMe(const CTransaction &tx, const CBlock *pblock, bool fUpdate)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1272
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:387
CWallet::ComputeTimeSmart
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Definition: wallet.cpp:5184
isminefilter
uint8_t isminefilter
used for bitflags of isminetype
Definition: wallet_ismine.h:24
UINT256_ZERO
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:129
fImporting
std::atomic< bool > fImporting
Definition: main.cpp:80
CWallet::pendingKeyImages
std::list< std::string > pendingKeyImages
Definition: wallet.h:371
CAccountingEntry
Internal transfers.
Definition: wallet.h:982
CWallet::GetVinAndKeysFromOutput
bool GetVinAndKeysFromOutput(COutput out, CTxIn &txinRet, CPubKey &pubKeyRet, CKey &keyRet)
Extract txin information and keys from output.
Definition: wallet.cpp:970
UNSTAKABLE_BALANCE_TOO_LOW
@ UNSTAKABLE_BALANCE_TOO_LOW
Definition: wallet.h:226
IsMine
isminetype IsMine(const CKeyStore &keystore, const CTxDestination &dest)
Definition: wallet_ismine.cpp:30
CWallet::nMasterKeyMaxID
unsigned int nMasterKeyMaxID
Definition: wallet.h:312
CBlockIndex::IsProofOfStake
bool IsProofOfStake() const
Definition: chain.h:390
CWalletDB::WriteOrderPosNext
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:185
CHDPubKey::extPubKey
CExtPubKey extPubKey
Definition: hdchain.h:99
CWallet::NotifyAddressBookChanged
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:601
CWallet::IncOrderPosNext
int64_t IncOrderPosNext(CWalletDB *pwalletdb=NULL)
Increment the next transaction order id.
Definition: wallet.cpp:1150
CWalletDB::WriteKeyImage
bool WriteKeyImage(const std::string &outpointKey, const CKeyImage &k)
Definition: walletdb.cpp:1281
CWallet::nWalletMaxVersion
int nWalletMaxVersion
the maximum wallet format version: memory-only variable that specifies to what version this wallet ma...
Definition: wallet.h:257
CWallet::minTxFee
static CFeeRate minTxFee
Fees smaller than this (in duffs) are considered zero fee (for transaction creation) We are ~100 time...
Definition: wallet.h:536
WALLET_CRYPTO_KEY_SIZE
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:14
GetRandInt
int GetRandInt(int nMax)
Definition: random.cpp:366
CCryptoKeyStore::EncryptHDChain
bool EncryptHDChain(const CKeyingMaterial &vMasterKeyIn)
Definition: crypter.cpp:234
CWallet::GenerateAddress
bool GenerateAddress(CPubKey &pub, CPubKey &txPub, CKey &txPriv) const
Definition: wallet.cpp:6623
CWallet::EncodeStealthPublicAddress
bool EncodeStealthPublicAddress(const std::vector< unsigned char > &pubViewKey, const std::vector< unsigned char > &pubSpendKey, std::string &pubAddr)
Definition: wallet.cpp:6437
CTxIn::encryptionKey
std::vector< unsigned char > encryptionKey
Definition: transaction.h:96
base_uint::end
unsigned char * end()
Definition: arith_uint256.h:245
CWallet::GetAddressGroupings
std::set< std::set< CTxDestination > > GetAddressGroupings()
Definition: wallet.cpp:4896
CCryptoKeyStore::SetCrypted
bool SetCrypted()
Definition: crypter.cpp:127
CWallet::SelectCoinsMinConf
bool SelectCoinsMinConf(bool needFee, CAmount &estimatedFee, int ringSize, int numOut, const CAmount &nTargetValue, int nConfMine, int nConfTheirs, std::vector< COutput > vCoins, std::set< std::pair< const CWalletTx *, unsigned int > > &setCoinsRet, CAmount &nValueRet)
Definition: wallet.cpp:2861
CWallet::MintableCoins
bool MintableCoins()
Definition: wallet.cpp:2674
minRelayTxFee
CFeeRate minRelayTxFee
Fees smaller than this (in duffs) are considered zero fee (for relaying and mining) We are ~100 times...
Definition: main.cpp:100
CBlockIndex::GetAncestor
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: main.cpp:4856
CWallet::estimateStakingConsolidationFees
bool estimateStakingConsolidationFees(CAmount &min, CAmount &max)
Definition: wallet.cpp:5755
FEATURE_COMPRPUBKEY
@ FEATURE_COMPRPUBKEY
Definition: wallet.h:104
CWallet::mapTxSpends
TxSpends mapTxSpends
Definition: wallet.h:268
CReserveKey::pwallet
CWallet * pwallet
Definition: wallet.h:682
CWallet::fWalletUnlockStakingOnly
bool fWalletUnlockStakingOnly
Definition: wallet.h:304
CWallet::MakeShnorrSignature
bool MakeShnorrSignature(CTransaction &)
Definition: wallet.cpp:3993
fDeleteTransactionsAfterNBlocks
unsigned int fDeleteTransactionsAfterNBlocks
Definition: wallet.cpp:63
ShutdownRequested
bool ShutdownRequested()
Definition: init.cpp:135
CWallet::ResendWalletTransactions
void ResendWalletTransactions()
Definition: wallet.cpp:2199
CWallet::ComputeReserveUTXOAmount
CAmount ComputeReserveUTXOAmount()
Definition: wallet.cpp:3133
CT_DELETED
@ CT_DELETED
Definition: guiinterface.h:24
GetTime
int64_t GetTime()
For unit testing.
Definition: utiltime.cpp:19
CWallet::mapWallet
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:344
CHDChain::DeriveChildExtKey
void DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_t nChildIndex, CExtKey &extKeyRet)
Definition: hdchain.cpp:144
CDB::TxnCommit
bool TxnCommit()
Definition: db.h:296
CWallet::SendAll
bool SendAll(std::string des, CWalletTx &wtxNew, bool inclLocked)
Definition: wallet.cpp:5252
GetAccountAddress
void GetAccountAddress(CWallet *pwalletMain, std::string strAccount, int nAccountIndex, bool bForceNew=false)
Definition: wallet.cpp:4670
CWallet::addrToTxHashMap
std::map< std::string, std::string > addrToTxHashMap
Definition: wallet.h:355
ECDHInfo::Encode
static void Encode(const CKey &mask, const CAmount &amount, const CPubKey &sharedSec, uint256 &encodedMask, uint256 &encodedAmount)
Definition: wallet.cpp:119
ValidOutPoint
bool ValidOutPoint(const COutPoint out, int nHeight)
Definition: main.cpp:2741
CWallet::fFileBacked
bool fFileBacked
Definition: wallet.h:303
CWallet::ReadStakingStatus
bool ReadStakingStatus()
Definition: wallet.cpp:370
CWalletDB::WriteAutoConsolidateSettingTime
bool WriteAutoConsolidateSettingTime(uint32_t settingTime)
Definition: walletdb.cpp:368
transaction.h
CWallet::createMasterKey
void createMasterKey() const
Definition: wallet.cpp:6973
CKey::MakeNewKey
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:40
CWalletDB::Write2FAPeriod
bool Write2FAPeriod(int period)
Definition: walletdb.cpp:338
CWallet::ScanForWalletTransactions
int ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate=false, bool fromStartup=false, int height=-1)
Scan the block chain (starting in pindexStart) for transactions from or to us.
Definition: wallet.cpp:2062
CKeyPool
A key pool entry.
Definition: wallet.h:126
CHDChain::GetSeedHash
uint256 GetSeedHash()
Definition: hdchain.cpp:139
AvailableCoinsType
AvailableCoinsType
Definition: wallet.h:109
RelayTransactionLockReq
void RelayTransactionLockReq(const CTransaction &tx, bool relayToAll)
Definition: net.cpp:2063
CWalletDB::WriteCryptedHDChain
bool WriteCryptedHDChain(const CHDChain &chain)
Definition: walletdb.cpp:1303
CWallet::RemoveFromSpends
void RemoveFromSpends(const uint256 &wtxid)
Definition: wallet.cpp:1768
CWallet::nLastResend
int64_t nLastResend
Definition: wallet.h:260
CWallet::GetImmatureBalance
CAmount GetImmatureBalance() const
Definition: wallet.cpp:2333
b
void const uint64_t * b
Definition: field_5x52_asm_impl.h:10
CWallet::DeriveNewChildKey
void DeriveNewChildKey(uint32_t nAccountIndex, CKey &secretRet)
Definition: wallet.cpp:6860
CWallet::CommitTransaction
bool CommitTransaction(CWalletTx &wtxNew, CReserveKey &reservekey, std::string strCommand=NetMsgType::TX)
Call after CreateTransaction unless you want to abort.
Definition: wallet.cpp:4458
CWalletTx::fWatchCreditCached
bool fWatchCreditCached
Definition: wallet.h:814
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:52
CWalletDB::ReadStakingStatus
bool ReadStakingStatus()
Definition: walletdb.cpp:296
CHDChain::IsNull
bool IsNull() const
Definition: hdchain.cpp:23
CWallet::GetOldestKeyPoolTime
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:4847
CWallet::RevealTxOutAmount
bool RevealTxOutAmount(const CTransaction &tx, const CTxOut &out, CAmount &amount, CKey &) const
Definition: wallet.cpp:7047
CWallet::nStakeSplitThreshold
uint64_t nStakeSplitThreshold
Definition: wallet.h:317
CBitcoinAddress::GetKeyID
bool GetKeyID(CKeyID &keyID) const
Definition: base58.cpp:281
CWalletDB::ZapWalletTx
DBErrors ZapWalletTx(CWallet *pwallet, std::vector< CWalletTx > &vWtx)
Definition: walletdb.cpp:967
CWalletTx::fTimeReceivedIsTxTime
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:800
CWallet::IsMine
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1333
CCryptoKeyStore::cryptedHDChain
CHDChain cryptedHDChain
Definition: crypter.h:149
ISMINE_NO
@ ISMINE_NO
Definition: wallet_ismine.h:17
CWalletTx::nImmatureCreditCached
CAmount nImmatureCreditCached
Definition: wallet.h:821
CWallet::TxItems
std::multimap< int64_t, TxPair > TxItems
Definition: wallet.h:348
base_uint::GetHex
std::string GetHex() const
Definition: arith_uint256.cpp:155
CWallet::CWallet
CWallet()
Definition: wallet.cpp:6090
secp256k1_ec_privkey_tweak_mul
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_mul(unsigned char *seckey, const unsigned char *tweak) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2)
Tweak a private key by multiplying it with tweak.
Definition: secp256k1.c:262
base_uint::begin
unsigned char * begin()
Definition: arith_uint256.h:240
AllowFree
bool AllowFree(double dPriority)
Definition: txmempool.h:26
CWalletDB::ErasePurpose
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:70
ALL_COINS
@ ALL_COINS
Definition: wallet.h:110
CTransaction::S
std::vector< std::vector< uint256 > > S
Definition: transaction.h:301
chainActive
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:70
CWalletDB::WriteAccountingEntry_Backend
bool WriteAccountingEntry_Backend(const CAccountingEntry &acentry)
This writes directly to the database, and will not update the CWallet's cached accounting entries!...
Definition: walletdb.cpp:408
timedata.h
CWalletDB::EraseTx
bool EraseTx(uint256 hash)
Definition: walletdb.cpp:82
uiInterface
CClientUIInterface uiInterface
Definition: init.cpp:101
CWallet::CreateCoinStake
bool CreateCoinStake(const CKeyStore &keystore, unsigned int nBits, int64_t nSearchInterval, CMutableTransaction &txNew, unsigned int &nTxNewTime)
Definition: wallet.cpp:4302
COutPoint::hash
uint256 hash
Definition: transaction.h:39
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:285
CWallet::isMatchMyKeyImage
bool isMatchMyKeyImage(const CKeyImage &ki, const COutPoint &out)
Definition: wallet.cpp:961
CCrypter::Encrypt
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
Definition: crypter.cpp:74
CCryptoKeyStore::SetHDChain
bool SetHDChain(const CHDChain &chain)
Definition: crypter.cpp:334
CWallet::GetKeyFromPool
bool GetKeyFromPool(CPubKey &key)
Definition: wallet.cpp:4829
CWalletTx::mapValue
mapValue_t mapValue
Definition: wallet.h:798
ecdhDecode
void ecdhDecode(unsigned char *masked, unsigned char *amount, const unsigned char *sharedSec, int size)
Definition: wallet.cpp:83
CWallet::GetConflicts
std::set< uint256 > GetConflicts(const uint256 &txid) const
Get wallet transactions that conflict with given transaction (spend same outputs)
Definition: wallet.cpp:754
CCryptoKeyStore::GetKeys
void GetKeys(std::set< CKeyID > &setAddress) const
Definition: crypter.h:185
CWallet::AddHDPubKey
bool AddHDPubKey(const CExtPubKey &extPubKey, bool fInternal, uint32_t nAccountIndex)
Adds a HDPubKey into the wallet(database)
Definition: wallet.cpp:6948
CWalletTx::CWalletTx
CWalletTx()
Definition: wallet.cpp:6244
CBitcoinAddress
base58-encoded PRCY addresses.
Definition: base58.h:109
secp256k1_pedersen_commitment_parse
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commitment_parse(const secp256k1_context2 *ctx, secp256k1_pedersen_commitment *commit, const unsigned char *input) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Parse a 33-byte commitment into a commitment object.
Definition: main_impl.h:56
CWallet::Write2FALastTime
bool Write2FALastTime(uint64_t lastTime)
Definition: wallet.cpp:402
CWallet::Read2FALastTime
uint64_t Read2FALastTime()
Definition: wallet.cpp:406
CCryptoKeyStore::GetKey
bool GetKey(const CKeyID &address, CKey &keyOut) const
Definition: crypter.cpp:172
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:97
CKey::GetPrivKey
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:66
fTxConflictDeleteEnabled
bool fTxConflictDeleteEnabled
Definition: wallet.cpp:61
uint256.h
mapArgs
std::map< std::string, std::string > mapArgs
Definition: util.cpp:111
CPubKey::Set
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
Definition: pubkey.h:71
CTxMemPool::exists
bool exists(uint256 hash)
Definition: txmempool.h:179
CMasternodeSync::IsBlockchainSynced
bool IsBlockchainSynced()
Definition: masternode-sync.cpp:32
CKeyingMaterial
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:69
CWallet::mapRequestCount
std::map< uint256, int > mapRequestCount
Definition: wallet.h:352
CKey::Set
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:83
CWalletDB::ReadAccount
bool ReadAccount(const std::string &strAccount, CAccount &account)
Definition: walletdb.cpp:362
FEATURE_LATEST
@ FEATURE_LATEST
Definition: wallet.h:106
CMutableTransaction::nTxFee
CAmount nTxFee
Definition: transaction.h:397
CCoinControl
Coin Control Features.
Definition: coincontrol.h:15
CWallet::Unlock
bool Unlock(const SecureString &strWalletPassphrase, bool anonimizeOnly=false)
Definition: wallet.cpp:552
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:181
STAKABLE_NEED_CONSOLIDATION_WITH_RESERVE_BALANCE
@ STAKABLE_NEED_CONSOLIDATION_WITH_RESERVE_BALANCE
Definition: wallet.h:231
CWallet::IsFromMe
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:6190
CReserveKey
A key allocated from the key pool.
Definition: wallet.h:679
CWallet::AddAccountingEntry
bool AddAccountingEntry(const CAccountingEntry &, CWalletDB &pwalletdb)
Definition: wallet.cpp:4510
CTransaction::nLockTime
const uint32_t nLockTime
Definition: transaction.h:287
wallet.h
CWallet::inSpendQueueOutpointsPerSession
std::vector< COutPoint > inSpendQueueOutpointsPerSession
Definition: wallet.h:373
CWalletDB::Read2FASecret
std::string Read2FASecret()
Definition: walletdb.cpp:330
fSendFreeTransactions
bool fSendFreeTransactions
Definition: wallet.cpp:56
CWallet::SetMaxVersion
bool SetMaxVersion(int nVersion)
change which version we're allowed to upgrade to (note that this does not immediately imply upgrading...
Definition: wallet.cpp:742
CReserveKey::vchPubKey
CPubKey vchPubKey
Definition: wallet.h:684
NetMsgType::IX
const char * IX
The ix message transmits a single SwiftX transaction.
Definition: protocol.cpp:48
CWalletDB::WriteCScript
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:131
CWallet::GetSpendableBalance
CAmount GetSpendableBalance()
Definition: wallet.cpp:2260
CTxOut::IsEmpty
bool IsEmpty() const
Definition: transaction.h:220
CWallet::inSpendQueueOutpoints
std::map< COutPoint, bool > inSpendQueueOutpoints
Definition: wallet.h:372
CWallet::nAutoCombineThreshold
CAmount nAutoCombineThreshold
Definition: wallet.h:332
DB_LOAD_OK
@ DB_LOAD_OK
Definition: walletdb.h:37
CWalletTx::nWatchCreditCached
CAmount nWatchCreditCached
Definition: wallet.h:824
ToByteVector
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:32
masternode-sync.h
CWalletTx::GetAvailableWatchOnlyCredit
CAmount GetAvailableWatchOnlyCredit(const bool &fUseCache=true) const
Definition: wallet.cpp:1656
CWallet::generateBulletProofAggregate
bool generateBulletProofAggregate(CTransaction &tx)
Definition: wallet.cpp:3564
CMasterKey::vchCryptedKey
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:37
CWallet::LoadCryptedKey
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:440
CWalletTx::GetComputedTxTime
int64_t GetComputedTxTime() const
Definition: wallet.cpp:1439
Hash160
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:237
CWallet::StakingCoinStatus
StakingStatusError StakingCoinStatus(CAmount &minFee, CAmount &maxFee)
Definition: wallet.cpp:2712
CWallet::ComputeFee
int ComputeFee(size_t numIn, size_t numOut, size_t ringSize)
Definition: wallet.cpp:3139
CTxOut::IsDust
bool IsDust(CFeeRate minRelayTxFee) const
Definition: transaction.h:227
CWallet::NotifyWatchonlyChanged
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:613
CWalletTx::fAvailableWatchCreditCached
bool fAvailableWatchCreditCached
Definition: wallet.h:816
fLargeWorkInvalidChainFound
bool fLargeWorkInvalidChainFound
Definition: main.cpp:2517
CWalletDB::Write2FALastTime
bool Write2FALastTime(uint64_t lastTime)
Definition: walletdb.cpp:350
CCrypter::Decrypt
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:91
UNSTAKABLE_BALANCE_RESERVE_TOO_HIGH
@ UNSTAKABLE_BALANCE_RESERVE_TOO_HIGH
Definition: wallet.h:228
CWallet::strMultiSendChangeAddress
std::string strMultiSendChangeAddress
Definition: wallet.h:326
CAffectedKeysVisitor::CAffectedKeysVisitor
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector< CKeyID > &vKeysIn)
Definition: wallet.cpp:5102
CWallet::GetChange
CAmount GetChange(const CTransaction &tx, const CTxOut &txout) const
Definition: wallet.cpp:6177
CWallet::ReadStealthAccount
bool ReadStealthAccount(const std::string &strAccount, CStealthAccount &account)
Definition: wallet.cpp:6374
memcpy
void * memcpy(void *a, const void *b, size_t c)
Definition: glibc_compat.cpp:15
CWallet::IsSpent
bool IsSpent(const uint256 &hash, unsigned int n)
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:860
CWallet::CreateTransaction
bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx &wtxNew, CReserveKey &reservekey, int64_t &nFeeRet, std::string &strFailReason, const CCoinControl *coinControl)
UNSTAKABLE_BALANCE_RESERVE_TOO_HIGH_CONSOLIDATION_FAILED
@ UNSTAKABLE_BALANCE_RESERVE_TOO_HIGH_CONSOLIDATION_FAILED
Definition: wallet.h:229
CReserveKey::nIndex
int64_t nIndex
Definition: wallet.h:683
CMasterKey
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
Definition: crypter.h:34
CWallet::CreateTransactionBulletProof
bool CreateTransactionBulletProof(const CKey &txPrivDes, const CPubKey &recipientViewKey, const std::vector< std::pair< CScript, CAmount > > &vecSend, CWalletTx &wtxNew, CReserveKey &reservekey, CAmount &nFeeRet, std::string &strFailReason, const CCoinControl *coinControl=NULL, AvailableCoinsType coin_type=ALL_COINS, bool useIX=false, CAmount nFeePay=0, int ringSize=6, bool tomyself=false)
Definition: wallet.cpp:3171
CWallet::getWalletTxs
std::vector< CWalletTx > getWalletTxs()
Definition: wallet.cpp:176
isminetype
isminetype
IsMine() return codes.
Definition: wallet_ismine.h:16
CWallet::WriteAutoConsolidateSettingTime
bool WriteAutoConsolidateSettingTime(uint32_t settingTime)
Definition: wallet.cpp:3156
CWallet::GetMinimumFee
static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool &pool)
Definition: wallet.cpp:4522
CWallet::GetAccountAddresses
std::set< CTxDestination > GetAccountAddresses(std::string strAccount) const
Definition: wallet.cpp:4979
GetSerializeSize
unsigned int GetSerializeSize(char a, int, int=0)
Definition: serialize.h:194
CHDPubKey::hdchainID
uint256 hdchainID
Definition: hdchain.h:100
mapTxLockReq
std::map< uint256, CTransaction > mapTxLockReq
Definition: swifttx.cpp:24
CKeyID
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:29
MIN_TX_INPUTS_FOR_SWEEPING
const int MIN_TX_INPUTS_FOR_SWEEPING
Definition: main.cpp:94
EncodeBase58
std::string EncodeBase58(const unsigned char *pbegin, const unsigned char *pend)
Why base-58 instead of standard base-64 encoding?
Definition: base58.cpp:83
DateTimeStrFormat
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:50
CWallet::makeRingCT
bool makeRingCT(CTransaction &wtxNew, int ringSize, std::string &strFailReason)
Definition: wallet.cpp:3587
CWallet::ComputeStealthPublicAddress
bool ComputeStealthPublicAddress(const std::string &accountName, std::string &pubAddress)
Definition: wallet.cpp:6379
CWalletDB::ReadScannedBlockHeight
bool ReadScannedBlockHeight(int &height)
Definition: walletdb.cpp:308
CReserveKey::GetReservedKey
bool GetReservedKey(CPubKey &pubkey)
Definition: wallet.cpp:4992
CKeyPool::nTime
int64_t nTime
Definition: wallet.h:129
guiinterfaceutil.h
CWalletTx::nAvailableCreditCached
CAmount nAvailableCreditCached
Definition: wallet.h:822
DecodeBase58
bool DecodeBase58(const char *psz, std::vector< unsigned char > &vch)
Decode a base58-encoded string (psz) into a byte vector (vchRet).
Definition: base58.cpp:22
CMutableTransaction::txType
uint32_t txType
Definition: transaction.h:394
MAX_TX_INPUTS
const int MAX_TX_INPUTS
Definition: main.cpp:93
CValidationState::GetRejectReason
std::string GetRejectReason() const
Definition: validation.h:87
GetContext
secp256k1_context2 * GetContext()
Definition: main.cpp:348
FormatMoney
std::string FormatMoney(const CAmount &n, bool fPlus)
Money parsing/formatting utilities.
Definition: utilmoneystr.cpp:13
CKeyStore::cs_KeyStore
RecursiveMutex cs_KeyStore
Definition: keystore.h:24
DecryptSecret
bool DecryptSecret(const CKeyingMaterial &vMasterKey, const std::vector< unsigned char > &vchCiphertext, const uint256 &nIV, CKeyingMaterial &vchPlaintext)
Definition: crypter.cpp:117
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:159
CWallet::nAutoCombineTarget
CAmount nAutoCombineTarget
Definition: wallet.h:333
CCoinControl::HasSelected
bool HasSelected() const
Definition: coincontrol.h:48
IsFinalTx
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: tx_verify.cpp:12
fPayAtLeastCustomFee
bool fPayAtLeastCustomFee
Definition: wallet.cpp:57
CWallet::keyImagesSpends
std::map< std::string, bool > keyImagesSpends
Definition: wallet.h:369
CScript::clear
void clear()
Definition: script.h:634
CMerkleTx::GetDepthInMainChainINTERNAL
int GetDepthInMainChainINTERNAL(const CBlockIndex *&pindexRet) const
Definition: wallet.cpp:5982
CHDChain::SetMnemonic
bool SetMnemonic(const SecureVector &vchMnemonic, const SecureVector &vchMnemonicPassphrase, bool fUpdateID)
Definition: hdchain.cpp:65
MaskValue::hashOfKey
uint256 hashOfKey
Definition: transaction.h:153
nSwiftTXDepth
int nSwiftTXDepth
Definition: util.cpp:103
CBase58Data::ToString
std::string ToString() const
Definition: base58.cpp:200
CStealthAccount
Definition: wallet.h:195
CDB::Rewrite
static bool Rewrite(const std::string &strFile, const char *pszSkip=NULL)
Definition: db.cpp:387
CWallet::TxPair
std::pair< CWalletTx *, CAccountingEntry * > TxPair
Definition: wallet.h:347
CWallet::nOrderPosNext
int64_t nOrderPosNext
Definition: wallet.h:351
CWallet::GetAddressBalances
std::map< CTxDestination, CAmount > GetAddressBalances()
Definition: wallet.cpp:4858
CWallet::AddToSpends
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid)
Definition: wallet.cpp:901
CPrcyStake
Definition: stakeinput.h:32
GetTxSignatureHash
uint256 GetTxSignatureHash(const CTransaction &tx)
Definition: main.cpp:681
payTxFee
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
Transaction fee set by the user.
CWallet::blindMap
std::map< CScript, CKey > blindMap
Definition: wallet.h:375
CFeeRate
Fee rate in PRCY per kilobyte: CAmount / kB.
Definition: amount.h:39
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:80
fMasterNode
bool fMasterNode
Definition: util.cpp:97
CWallet::AddKeyPubKey
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, and saves it to disk.
Definition: wallet.cpp:240
CWallet::UnlockCoin
void UnlockCoin(COutPoint &output)
Definition: wallet.cpp:5063
CWallet::DecoyConfirmationMinimum
int64_t DecoyConfirmationMinimum
Definition: wallet.h:366
DB_NEED_REWRITE
@ DB_NEED_REWRITE
Definition: walletdb.h:42
CWallet::coinbaseDecoysPool
std::map< COutPoint, uint256 > coinbaseDecoysPool
Definition: wallet.h:377
COutPoint::IsMasternodeReward
bool IsMasternodeReward(const CTransaction *tx) const
Definition: transaction.cpp:72
CAffectedKeysVisitor::operator()
void operator()(const CKeyID &keyId)
Definition: wallet.cpp:5115
CWalletTx::nAvailableWatchCreditCached
CAmount nAvailableWatchCreditCached
Definition: wallet.h:826
CWalletDB::WriteCryptedKey
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:105
UNSTAKABLE_BALANCE_TOO_LOW_CONSOLIDATION_FAILED
@ UNSTAKABLE_BALANCE_TOO_LOW_CONSOLIDATION_FAILED
Definition: wallet.h:227
CWalletDB::ReadKeyImage
bool ReadKeyImage(const std::string &outpointKey, CKeyImage &k)
Definition: walletdb.cpp:1285
CWalletTx::nChangeCached
CAmount nChangeCached
Definition: wallet.h:827
CWalletTx::nTimeSmart
unsigned int nTimeSmart
time received by this node
Definition: wallet.h:802
CWallet::AddDestData
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:5226
CPubKey::GetHex
std::string GetHex() const
Definition: pubkey.h:193
CTxIn::masternodeStealthAddress
std::vector< unsigned char > masternodeStealthAddress
Definition: transaction.h:99
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:269
CWalletTx::fImmatureWatchCreditCached
bool fImmatureWatchCreditCached
Definition: wallet.h:815
CCryptoKeyStore::AddKeyPubKey
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
Add a key to the store.
Definition: crypter.cpp:138
CKey::end
const unsigned char * end() const
Definition: key.h:101
CBitcoinSecret
A base58-encoded secret key.
Definition: base58.h:131
CWalletDB::ReadAutoConsolidateSettingTime
uint32_t ReadAutoConsolidateSettingTime()
Definition: walletdb.cpp:373
CWallet::GetKeyBirthTimes
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const
Definition: wallet.cpp:5131
CWallet::ComputeTxSize
static int ComputeTxSize(size_t numIn, size_t numOut, size_t ringSize)
Definition: wallet.cpp:3123
CTransaction::txType
uint32_t txType
Definition: transaction.h:294
CWallet::AddCScript
bool AddCScript(const CScript &redeemScript)
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: wallet.cpp:445
MaskValue::mask
uint256 mask
Definition: transaction.h:151
CHDPubKey
Definition: hdchain.h:92
CWallet::nHashDrift
unsigned int nHashDrift
Definition: wallet.h:315
CWallet::Write2FASecret
bool Write2FASecret(std::string secret)
Definition: wallet.cpp:384
CWallet::KeepKey
void KeepKey(int64_t nIndex)
Definition: wallet.cpp:4809
CWallet::UpdateWalletTransactionOrder
void UpdateWalletTransactionOrder(std::map< std::pair< int, int >, CWalletTx * > &mapSorted, bool resetOrder)
Update the nOrderPos with passed in ordered map.
Definition: wallet.cpp:1825
COutPoint::IsNull
bool IsNull() const
Definition: transaction.h:54
CWallet::vDisabledAddresses
std::vector< std::string > vDisabledAddresses
Definition: wallet.h:328
Stake
bool Stake(CStakeInput *stakeInput, unsigned int nBits, unsigned int nTimeBlockFrom, unsigned int &nTimeTx, uint256 &hashProofOfStake)
Definition: kernel.cpp:301
masternodeSync
CMasternodeSync masternodeSync
Definition: masternode-sync.cpp:19
CWallet::nWalletVersion
int nWalletVersion
the current wallet version: clients below this version are not able to load the wallet
Definition: wallet.h:254
CWalletTx::fWatchDebitCached
bool fWatchDebitCached
Definition: wallet.h:813
r
void const uint64_t uint64_t * r
Definition: field_5x52_asm_impl.h:10
CWallet::GetMasternodeVinAndKeys
bool GetMasternodeVinAndKeys(CTxIn &txinRet, CPubKey &pubKeyRet, CKey &keyRet, std::string strTxHash, std::string strOutputIndex, std::string &strError)
Get 5000 PRCY output and keys which can be used for the Masternode.
Definition: wallet.cpp:2409
CWallet::SetAddressBook
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:4589
CAffectedKeysVisitor::vKeys
std::vector< CKeyID > & vKeys
Definition: wallet.cpp:5099
CBlockIndex::nTime
unsigned int nTime
Definition: chain.h:228
CWallet::fDecryptionThoroughlyChecked
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
Definition: wallet.h:251
CExtPubKey::nChild
unsigned int nChild
Definition: pubkey.h:208
CTxOut::nValue
CAmount nValue
Definition: transaction.h:167
CWallet::MarkDirty
void MarkDirty()
Definition: wallet.cpp:1162
CAffectedKeysVisitor
Definition: wallet.cpp:5095
CWallet::SetBestChain
void SetBestChain(const CBlockLocator &loc)
Definition: wallet.cpp:710
GetRand
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:351
CPubKey::begin
const unsigned char * begin() const
Definition: pubkey.h:95
CWallet::DelAddressBook
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:4609
CWallet::EncodeIntegratedAddress
bool EncodeIntegratedAddress(const CPubKey &pubViewKey, const CPubKey &pubSpendKey, uint64_t paymentID, std::string &pubAddr)
Definition: wallet.cpp:6478
CWallet::AddComputedPrivateKey
void AddComputedPrivateKey(const CTxOut &out)
Definition: wallet.cpp:4264
CT_NEW
@ CT_NEW
Definition: guiinterface.h:22
CCryptoKeyStore::NotifyStatusChanged
boost::signals2::signal< void(CCryptoKeyStore *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: crypter.h:203
cs_main
RecursiveMutex cs_main
Global state.
Definition: main.cpp:65
CKey::begin
const unsigned char * begin() const
Definition: key.h:100
CBlockIndex::GetBlockHeader
CBlockHeader GetBlockHeader() const
Definition: chain.h:340
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:359
CAffectedKeysVisitor::keystore
const CKeyStore & keystore
Definition: wallet.cpp:5098
pblocktree
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: main.cpp:1131
fLargeWorkForkFound
bool fLargeWorkForkFound
Definition: main.cpp:2516
CWallet::GetBudgetSystemCollateralTX
bool GetBudgetSystemCollateralTX(CTransaction &tx, uint256 hash, bool useIX)
Definition: wallet.cpp:3063
CWallet::ComputeStealthDestination
static bool ComputeStealthDestination(const CKey &secret, const CPubKey &pubViewKey, const CPubKey &pubSpendKey, CPubKey &des)
Definition: wallet.cpp:6618
CWallet::GetUnconfirmedWatchOnlyBalance
CAmount GetUnconfirmedWatchOnlyBalance() const
Definition: wallet.cpp:2361
CWallet::SetMinVersion
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:716
CMerkleTx::nIndex
int nIndex
Definition: wallet.h:738
CWalletTx::nTimeReceived
unsigned int nTimeReceived
Definition: wallet.h:801
fDeleteInterval
int fDeleteInterval
Definition: wallet.cpp:62
CWallet::MAX_DECOY_POOL
static const int32_t MAX_DECOY_POOL
Definition: wallet.h:276
StakingStatusError
StakingStatusError
Definition: wallet.h:223
COutput::ToString
std::string ToString() const
Definition: wallet.cpp:162
CMerkleTx
A transaction with a merkle branch linking it to the block chain.
Definition: wallet.h:731
CWallet::fMultiSendNotify
bool fMultiSendNotify
Definition: wallet.h:325
OP_RETURN
@ OP_RETURN
Definition: script.h:76
SWIFTTX_SIGNATURES_REQUIRED
#define SWIFTTX_SIGNATURES_REQUIRED
Definition: swifttx.h:26
IsInitialBlockDownload
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network)
Definition: main.cpp:2500
MAX_RING_SIZE
int MAX_RING_SIZE
Definition: main.cpp:92
CTxMemPool::cs
RecursiveMutex cs
sum of all mempool tx' byte sizes
Definition: txmempool.h:135
CompareValueOnly
Definition: wallet.cpp:154
CWalletKey::nTimeCreated
int64_t nTimeCreated
Definition: wallet.h:952
secp256k1_bulletproof_rangeproof_prove
SECP256K1_WARN_UNUSED_RESULT SECP256K1_API int secp256k1_bulletproof_rangeproof_prove(const secp256k1_context2 *ctx, secp256k1_scratch_space2 *scratch, const secp256k1_bulletproof_generators *gens, unsigned char *proof, size_t *plen, const uint64_t *value, const uint64_t *min_value, const unsigned char *const *blind, size_t n_commits, const secp256k1_generator *value_gen, size_t nbits, const unsigned char *nonce, const unsigned char *extra_commit, size_t extra_commit_len) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(6) SECP256K1_ARG_NONNULL(8) SECP256K1_ARG_NONNULL(10) SECP256K1_ARG_NONNULL(12)
Produces an aggregate Bulletproof rangeproof for a set of Pedersen commitments Returns: 1: rangeproof...
Definition: main_impl.h:582
CKeyStore::GetCScript
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const =0
CWallet::resetPendingOutPoints
void resetPendingOutPoints()
Definition: wallet.cpp:2998
CBasicKeyStore::RemoveWatchOnly
virtual bool RemoveWatchOnly(const CScript &dest)
Definition: keystore.cpp:68
secp256k1.h
CCryptoKeyStore::SetCryptedHDChain
bool SetCryptedHDChain(const CHDChain &chain)
Definition: crypter.cpp:346
nTxConfirmTarget
unsigned int nTxConfirmTarget
Definition: wallet.cpp:53
fEnableSwiftTX
bool fEnableSwiftTX
Definition: util.cpp:102
CWallet::nStakeSetUpdateTime
int nStakeSetUpdateTime
Definition: wallet.h:318
CWalletDB::WritePool
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:275
CWallet::ReserveKeyFromKeyPool
void ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool)
Definition: wallet.cpp:4739
bdisableSystemnotifications
bool bdisableSystemnotifications
Definition: wallet.cpp:55
CWalletTx::GetCredit
CAmount GetCredit(const isminefilter &filter) const
Definition: wallet.cpp:1505
CWallet::GenerateNewHDChain
void GenerateNewHDChain(std::string *phrase=NULL)
Definition: wallet.cpp:317
CWalletTx::nOrderPos
int64_t nOrderPos
Definition: wallet.h:805
CTxOut
An output of a transaction.
Definition: transaction.h:164
CWallet::AvailableCoinsByAddress
std::map< CBitcoinAddress, std::vector< COutput > > AvailableCoinsByAddress(bool fConfirmed=true, CAmount maxCoinValue=0)
Definition: wallet.cpp:2562
_
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
Definition: guiinterface.h:119
GetRandBytes
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
Definition: random.cpp:273
CWallet::ComputeIntegratedPublicAddress
bool ComputeIntegratedPublicAddress(const uint64_t paymentID, const std::string &accountName, std::string &pubAddress)
Definition: wallet.cpp:6388
STAKABLE_NEED_CONSOLIDATION
@ STAKABLE_NEED_CONSOLIDATION
Definition: wallet.h:230
CExtKey
Definition: key.h:161
CBlockHeader::GetBlockTime
int64_t GetBlockTime() const
Definition: block.h:135
ecdhutil.h
CMutableTransaction::paymentID
uint64_t paymentID
Definition: transaction.h:393
CWalletDB::Read2FAPeriod
int Read2FAPeriod()
Definition: walletdb.cpp:342
GetTransaction
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock.
Definition: main.cpp:2010
fTxDeleteEnabled
bool fTxDeleteEnabled
Definition: wallet.cpp:60
CWallet::vchDefaultKey
CPubKey vchDefaultKey
Definition: wallet.h:358
CWallet::GenerateIntegratedAddress
bool GenerateIntegratedAddress(const std::string &accountName, std::string &pubAddr)
Definition: wallet.cpp:6486
CWallet::GenerateIntegratedAddressWithProvidedPaymentID
std::string GenerateIntegratedAddressWithProvidedPaymentID(std::string accountName, uint64_t paymentID)
Definition: wallet.cpp:6512
CMutableTransaction::hasPaymentID
char hasPaymentID
Definition: transaction.h:392
CWalletTx::fChangeCached
bool fChangeCached
Definition: wallet.h:817
CBlockIndex::GetMedianTimePast
int64_t GetMedianTimePast() const
Definition: chain.h:371
CWalletDB::LoadWallet
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:811
CTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:286
CWallet::vMultiSend
std::vector< std::pair< std::string, int > > vMultiSend
Definition: wallet.h:322
ExtractPubKey
bool ExtractPubKey(const CScript &scriptPubKey, CPubKey &out)
Definition: standard.cpp:185
CWallet::MakeShnorrSignatureTxIn
bool MakeShnorrSignatureTxIn(CTxIn &txin, uint256)
Definition: wallet.cpp:4008
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:168
CWallet::GetCredit
CAmount GetCredit(const CTransaction &tx, const CTxOut &txout, const isminefilter &filter) const
Definition: wallet.cpp:6172
CWallet::IsLockedCoin
bool IsLockedCoin(uint256 hash, unsigned int n) const
Definition: wallet.cpp:5075
ISMINE_ALL
@ ISMINE_ALL
Definition: wallet_ismine.h:21
CWallet::nLastMultiSendHeight
int nLastMultiSendHeight
Definition: wallet.h:327
fLiteMode
bool fLiteMode
Definition: util.cpp:100
CWallet::mySpendPrivateKey
bool mySpendPrivateKey(CKey &spend) const
Definition: wallet.cpp:7004
CWallet::GetUniqueWalletBackupName
std::string GetUniqueWalletBackupName() const
Definition: wallet.cpp:6081
CChainParams::MinimumStakeAmount
CAmount MinimumStakeAmount() const
Definition: chainparams.h:87
CWalletDB::Write2FA
bool Write2FA(bool status)
Definition: walletdb.cpp:313
CPubKey::end
const unsigned char * end() const
Definition: pubkey.h:96
CWallet::userDecoysPool
std::map< COutPoint, uint256 > userDecoysPool
Definition: wallet.h:376
secp256k1_bulletproofs.h
CWalletTx::GetDebit
CAmount GetDebit(const isminefilter &filter) const
Definition: wallet.cpp:1478
CreateNewLock
int64_t CreateNewLock(CTransaction tx)
Definition: swifttx.cpp:217
CWalletTx::nDebitCached
CAmount nDebitCached
Definition: wallet.h:819
CWallet::IsMasternodeController
bool IsMasternodeController()
Definition: wallet.cpp:3058
CHDChain::GetMnemonic
bool GetMnemonic(SecureVector &vchMnemonicRet, SecureVector &vchMnemonicPassphraseRet) const
Definition: hdchain.cpp:100
CWalletDB::WriteMasterKey
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:125
CAddressBookData
Address book data.
Definition: wallet.h:148
CPubKey::GetHash
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition: pubkey.h:149
STAKING_OK
@ STAKING_OK
Definition: wallet.h:225
CWallet::computeSharedSec
bool computeSharedSec(const CTransaction &tx, const CTxOut &out, CPubKey &sharedSec) const
Definition: wallet.cpp:4252
CWallet::IsChange
bool IsChange(const CTxOut &txout) const
Definition: wallet.cpp:1419
CWallet::nNextResend
int64_t nNextResend
Definition: wallet.h:259
CWallet::GetLockedCoins
CAmount GetLockedCoins() const
Definition: wallet.cpp:2300
CWallet::wtxOrdered
TxItems wtxOrdered
Definition: wallet.h:349
SecureString
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: allocators.h:262
CWallet::mapHdPubKeys
std::map< CKeyID, CHDPubKey > mapHdPubKeys
Definition: wallet.h:361
CWallet::GetWalletTx
const CWalletTx * GetWalletTx(const uint256 &hash) const
Definition: wallet.cpp:167
nStartupTime
int64_t nStartupTime
Definition: wallet.cpp:58
CWallet::AddToWallet
bool AddToWallet(const CWalletTx &wtxIn, bool fFromLoadWallet, CWalletDB *pwalletdb)
Definition: wallet.cpp:1171
CWallet::LoadMinVersion
bool LoadMinVersion(int nVersion)
Definition: wallet.cpp:6159
CWallet::IsHDEnabled
bool IsHDEnabled()
Definition: wallet.cpp:345
HexStr
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
Definition: utilstrencodings.h:85
CTransaction::ntxFeeKeyImage
CKeyImage ntxFeeKeyImage
Definition: transaction.h:304
GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:255
PAIRTYPE
#define PAIRTYPE(t1, t2)
This is needed because the foreach macro can't get over the comma in pair<t1, t2>
Definition: utilstrencodings.h:24
CKey::IsValid
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:104
CWallet::ShowProgress
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:610
CWallet::NewKeyPool
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
Definition: wallet.cpp:4646
CWalletTx::RelayWalletTransaction
void RelayWalletTransaction(std::string strCommand=NetMsgType::TX)
Definition: wallet.cpp:2169
CWalletDB
Access to the wallet database (wallet.dat)
Definition: walletdb.h:80
CWalletDB::Read2FALastTime
uint64_t Read2FALastTime()
Definition: walletdb.cpp:354
secp256k1_ec_pubkey_tweak_mul
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_mul(unsigned char *pubkey, int pubkeylen, const unsigned char *tweak) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3)
Tweak a public key by multiplying it with tweak.
Definition: secp256k1.c:281
COutputEntry
Definition: wallet.h:724
sign.h
CWallet::LoadHDPubKey
bool LoadHDPubKey(const CHDPubKey &hdPubKey)
loads a HDPubKey into the wallets memory
Definition: wallet.cpp:6940
CWallet::GetVersion
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.cpp:6238
computeStealthDestination
bool computeStealthDestination(const CKey &secret, const CPubKey &pubViewKey, const CPubKey &pubSpendKey, CPubKey &des)
Definition: wallet.cpp:6598
CWallet::outpointToKeyImages
std::map< std::string, CKeyImage > outpointToKeyImages
Definition: wallet.h:368
CWallet::LoadWallet
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:4540
LogPrintf
#define LogPrintf(...)
Definition: logging.h:147
CAmount
int64_t CAmount
Amount in PRCY (Can be negative)
Definition: amount.h:17
CWalletDB::ReadPool
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:270
CTxIn::R
std::vector< unsigned char > R
Definition: transaction.h:91
CTransaction::nTxFee
CAmount nTxFee
Definition: transaction.h:298
CMerkleTx::AcceptToMemoryPool
bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectInsaneFee=true, bool ignoreFees=false)
Definition: wallet.cpp:6045
CWallet::GetAllReserveKeys
void GetAllReserveKeys(std::set< CKeyID > &setAddress) const
Definition: wallet.cpp:5024
CWallet::getCOutPutValue
CAmount getCOutPutValue(const COutput &output) const
Definition: wallet.cpp:7193
CAffectedKeysVisitor::operator()
void operator()(const CNoDestination &none)
Definition: wallet.cpp:5128
PointHashingSuccessively
bool PointHashingSuccessively(const CPubKey &pk, const unsigned char *tweak, unsigned char *out)
Definition: util.cpp:619
bSpendZeroConfChange
bool bSpendZeroConfChange
Definition: wallet.cpp:54
mempool
CTxMemPool mempool(::minRelayTxFee)
CKeyPool::vchPubKey
CPubKey vchPubKey
Definition: wallet.h:130
CWalletTx::fAvailableCreditCached
bool fAvailableCreditCached
Definition: wallet.h:812
CStealthAccount::spendAccount
CAccount spendAccount
Definition: wallet.h:198
CBasicKeyStore::AddCScript
virtual bool AddCScript(const CScript &redeemScript)
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:34
CWallet::~CWallet
~CWallet()
Definition: wallet.cpp:6103
secp256k1_pedersen_commitment_serialize
SECP256K1_API int secp256k1_pedersen_commitment_serialize(const secp256k1_context2 *ctx, unsigned char *output, const secp256k1_pedersen_commitment *commit) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Serialize a commitment object into a serialized byte sequence.
Definition: main_impl.h:77
CTxIn::decoys
std::vector< COutPoint > decoys
Definition: transaction.h:98
CWallet::ReorderWalletTransactions
void ReorderWalletTransactions(std::map< std::pair< int, int >, CWalletTx * > &mapSorted, int64_t &maxOrderPos)
Reorder the transactions based on block hieght and block index.
Definition: wallet.cpp:1792
CWallet::amountMap
std::map< CScript, CAmount > amountMap
Definition: wallet.h:374
CWallet::Read2FAPeriod
int Read2FAPeriod()
Definition: wallet.cpp:397
ISMINE_SPENDABLE
@ ISMINE_SPENDABLE
Definition: wallet_ismine.h:20
AssertLockHeld
#define AssertLockHeld(cs)
Definition: sync.h:71
CWalletDB::ErasePool
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:281
CWallet::mapMasterKeys
MasterKeyMap mapMasterKeys
Definition: wallet.h:311
CWallet::selectDecoysAndRealIndex
bool selectDecoysAndRealIndex(CTransaction &tx, int &myIndex, int ringSize)
Definition: wallet.cpp:4039
CPubKey::size
unsigned int size() const
Simple read-only vector-like interface to the pubkey data.
Definition: pubkey.h:94
CAccount
Account information.
Definition: wallet.h:167
masternode-payments.h
CWallet::GetBalance
CAmount GetBalance()
Definition: wallet.cpp:2243
CWalletTx::vOrderForm
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:799
uint256
256-bit unsigned big integer.
Definition: uint256.h:38
uint256S
uint256 uint256S(const char *str)
Definition: uint256.h:99
CheckFinalTx
bool CheckFinalTx(const CTransaction &tx, int flags)
Check if transaction will be final in the next block to be created.
Definition: main.cpp:1465
CWalletDB::WriteKey
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:88
CWallet::GetUnconfirmedBalance
CAmount GetUnconfirmedBalance() const
Definition: wallet.cpp:2319
CWalletTx::BindWallet
void BindWallet(CWallet *pwalletIn)
Definition: wallet.cpp:6340
GetScratch
secp256k1_scratch_space2 * GetScratch()
Definition: main.cpp:355
CWalletTx::pwallet
CWallet * pwallet
Definition: wallet.h:795
CKeyStore::HaveKey
virtual bool HaveKey(const CKeyID &address) const =0
Check whether a key corresponding to a given address is present in the store.
CWallet::CreateCommitment
static bool CreateCommitment(const CAmount val, CKey &blind, std::vector< unsigned char > &commitment)
Definition: wallet.cpp:3096
CWallet::IsAutoConsolidateOn
bool IsAutoConsolidateOn()
Definition: wallet.cpp:3166
CKey::GetPubKey
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:79
CPubKey::Raw
std::vector< unsigned char > Raw() const
Definition: pubkey.h:188
CWalletDB::Read2FA
bool Read2FA()
Definition: walletdb.cpp:317
CWalletDB::WriteWatchOnly
bool WriteWatchOnly(const CScript &script)
Definition: walletdb.cpp:137
LogPrint
#define LogPrint(category,...)
Definition: logging.h:162
MaskValue::amount
uint256 amount
Definition: transaction.h:150
MASTERNODE_MIN_CONFIRMATIONS
#define MASTERNODE_MIN_CONFIRMATIONS
Definition: masternode.h:18
CWalletTx::GetTxTime
int64_t GetTxTime() const
Definition: wallet.cpp:1433
CHDPubKey::nChangeIndex
uint32_t nChangeIndex
Definition: hdchain.h:102
CWalletTx::nCreditCached
CAmount nCreditCached
Definition: wallet.h:820
CheckTXAvailability
bool CheckTXAvailability(const CWalletTx *pcoin, bool fOnlyConfirmed, bool fUseIX, int &nDepth)
Test if the transaction is spendable.
Definition: wallet.cpp:2391
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:363
CWallet::DeleteWalletTransactions
bool DeleteWalletTransactions(const CBlockIndex *pindex, bool fRescan=false)
Definition: wallet.cpp:1909
base_uint::IsNull
bool IsNull() const
Definition: arith_uint256.h:312
CWalletTx::GetUnlockedCredit
CAmount GetUnlockedCredit() const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:1586
CWalletTx::strFromAccount
std::string strFromAccount
Definition: wallet.h:804
ExtractDestination
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Definition: standard.cpp:199
CWallet::SendToStealthAddress
bool SendToStealthAddress(const std::string &stealthAddr, CAmount nValue, CWalletTx &wtxNew, bool fUseIX=false, int ringSize=5)
Definition: wallet.cpp:6640
ONLY_5000
@ ONLY_5000
Definition: wallet.h:111
ISMINE_WATCH_ONLY
@ ISMINE_WATCH_ONLY
Indicates that we dont know how to create a scriptSig that would solve this if we were given the appr...
Definition: wallet_ismine.h:19
COutput::fSpendable
bool fSpendable
Definition: wallet.h:928
CWallet::generateKeyImage
bool generateKeyImage(const CPubKey &pub, CKeyImage &img) const
Definition: wallet.cpp:7162
secp256k1_pedersen_commitment_to_serialized_pubkey
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commitment_to_serialized_pubkey(secp256k1_pedersen_commitment *commit, unsigned char *pubkey, size_t *length) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Definition: main_impl.h:44
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:359
COutput::nDepth
int nDepth
Definition: wallet.h:927
CWallet::GetDebit
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Definition: wallet.cpp:1402
CNoDestination
Definition: standard.h:68
CWalletTx::GetLockedCredit
CAmount GetLockedCredit() const
Definition: wallet.cpp:1610
CWalletKey::CWalletKey
CWalletKey(int64_t nExpires=0)
Definition: wallet.cpp:5947
ECDHInfo::ComputeSharedSec
static void ComputeSharedSec(const CKey &priv, const CPubKey &pubKey, CPubKey &sharedSec)
Definition: wallet.cpp:109
CWalletTx::InMempool
bool InMempool() const
Definition: wallet.cpp:2160
CWallet::GetWatchOnlyBalance
CAmount GetWatchOnlyBalance() const
Definition: wallet.cpp:2346
CWallet::GetImmatureWatchOnlyBalance
CAmount GetImmatureWatchOnlyBalance() const
Definition: wallet.cpp:2375
maxTxFee
CAmount maxTxFee
Definition: wallet.cpp:52
CWallet::encodeStealthBase58
bool encodeStealthBase58(const std::vector< unsigned char > &raw, std::string &stealth)
Definition: wallet.cpp:6406
CWallet::SelectCoins
bool SelectCoins(bool needFee, CAmount &estimatedFee, int ringSize, int numOut, const CAmount &nTargetValue, std::set< std::pair< const CWalletTx *, unsigned int > > &setCoinsRet, CAmount &nValueRet, const CCoinControl *coinControl=NULL, AvailableCoinsType coin_type=ALL_COINS, bool useIX=true)
Definition: wallet.cpp:3023
fKeepLastNTransactions
unsigned int fKeepLastNTransactions
Definition: wallet.cpp:64
CWallet::LoadWatchOnly
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
Definition: wallet.cpp:494
CTxDestination
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:81
CMerkleTx::GetDepthInMainChain
int GetDepthInMainChain(const CBlockIndex *&pindexRet, bool enableIX=true) const
Return depth of transaction in blockchain: -1 : not in blockchain, and not in memory pool (conflicted...
Definition: wallet.cpp:6006
CWallet::IsCollateralized
bool IsCollateralized(const COutPoint &outpoint)
Definition: wallet.cpp:3048
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:641
CCoinControl::txPriv
CKey txPriv
Definition: coincontrol.h:20
checkpoints.h
CWallet::AddCryptedKey
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:411
SetRingSize
void SetRingSize(int nHeight)
Definition: main.cpp:2466
CCryptoKeyStore::AddCryptedKey
virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Definition: crypter.cpp:160
CWalletTx::GetBlockHeight
int GetBlockHeight() const
Definition: wallet.cpp:6360
CWallet::Lock
bool Lock()
Lock Wallet.
Definition: wallet.cpp:582
CWallet::laccentries
std::list< CAccountingEntry > laccentries
Definition: wallet.h:345
CWallet::setMultiSendDisabled
void setMultiSendDisabled()
Definition: wallet.cpp:6147
CT_UPDATED
@ CT_UPDATED
Definition: guiinterface.h:23
CAccountingEntry::nTime
int64_t nTime
Definition: wallet.h:987
CWallet::SetHDChain
bool SetHDChain(const CHDChain &chain, bool memonly)
Definition: wallet.cpp:260
masternodeConfig
CMasternodeConfig masternodeConfig
Definition: masternodeconfig.cpp:13
RelayTransaction
void RelayTransaction(const CTransaction &tx)
Definition: net.cpp:2028
CPubKey::IsCompressed
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:168
CKeyPool::CKeyPool
CKeyPool()
Definition: wallet.cpp:5936
CWallet::EncryptWallet
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:1049
CCoinControl::fSplitBlock
bool fSplitBlock
Definition: coincontrol.h:22
base_uint::SetNull
void SetNull()
Definition: arith_uint256.h:308
CWallet::PROBABILITY_NEW_COIN_SELECTED
static const int32_t PROBABILITY_NEW_COIN_SELECTED
Definition: wallet.h:277
CBlock::vtx
std::vector< CTransaction > vtx
Definition: block.h:146
GetTimeMillis
int64_t GetTimeMillis()
Definition: utiltime.cpp:31
CWalletTx::GetImmatureCredit
CAmount GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.cpp:1534
R
#define R(a, b)
MaskValue::inMemoryRawBind
CKey inMemoryRawBind
Definition: transaction.h:152
CWallet::findCorrespondingPrivateKey
bool findCorrespondingPrivateKey(const CTxOut &txout, CKey &key) const
Definition: wallet.cpp:7108
stakeinput.h
invalid.h
CWallet::SyncTransaction
void SyncTransaction(const CTransaction &tx, const CBlock *pblock)
Definition: wallet.cpp:1303
CompareValueOnly::operator()
bool operator()(const std::pair< CAmount, std::pair< const CWalletTx *, unsigned int > > &t1, const std::pair< CAmount, std::pair< const CWalletTx *, unsigned int > > &t2) const
Definition: wallet.cpp:155
CBlock
Definition: block.h:142
COutput::tx
const CWalletTx * tx
Definition: wallet.h:925
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:388
CWallet::DecodeStealthAddress
static bool DecodeStealthAddress(const std::string &stealth, CPubKey &pubViewKey, CPubKey &pubSpendKey, bool &hasPaymentID, uint64_t &paymentID)
Definition: wallet.cpp:6522
FEATURE_BASE
@ FEATURE_BASE
Definition: wallet.h:101
strprintf
#define strprintf
Definition: tinyformat.h:1056
CWallet::fCombineDust
bool fCombineDust
Definition: wallet.h:331
CWallet::ScanWalletKeyImages
void ScanWalletKeyImages()
Definition: wallet.cpp:4529
CWalletDB::WriteAccount
bool WriteAccount(const std::string &strAccount, const CAccount &account)
Definition: walletdb.cpp:383
DBErrors
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:36
CMerkleTx::SetMerkleBranch
int SetMerkleBranch(const CBlock &block)
Definition: wallet.cpp:5953
Checkpoints::GuessVerificationProgress
double GuessVerificationProgress(const CBlockIndex *pindex, bool fSigchecks)
Guess how far we are in the verification process at the given block index.
Definition: checkpoints.cpp:45
CWallet::AutoCombineDust
void AutoCombineDust()
Definition: wallet.cpp:5728
CPubKey
An encapsulated public key.
Definition: pubkey.h:37
CWallet::Inventory
void Inventory(const uint256 &hash)
Definition: wallet.cpp:6222
GetAdjustedTime
int64_t GetAdjustedTime()
Definition: timedata.cpp:30
CWallet::CreateSweepingTransaction
bool CreateSweepingTransaction(CAmount target, CAmount threshold, uint32_t nTimeBefore)
Definition: wallet.cpp:5472
CWallet::AvailableCoins
bool AvailableCoins(std::vector< COutput > &vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL, bool fIncludeZeroValue=false, AvailableCoinsType nCoinType=ALL_COINS, bool fUseIX=false)
populate vCoins with vector of available COutputs.
Definition: wallet.cpp:2490
CTransaction::ToString
std::string ToString() const
Definition: transaction.cpp:217
CWallet::DeleteTransactions
bool DeleteTransactions(std::vector< uint256 > &removeTxs, bool fRescan=false)
Delete transactions from the Wallet.
Definition: wallet.cpp:1877
CAccount::vchPubKey
CPubKey vchPubKey
Definition: wallet.h:170
SecureVector
std::vector< unsigned char, secure_allocator< unsigned char > > SecureVector
Definition: allocators.h:267
CWallet::SetDefaultKey
bool SetDefaultKey(const CPubKey &vchPubKey)
Definition: wallet.cpp:4632
CWallet::SetCryptedHDChain
bool SetCryptedHDChain(const CHDChain &chain, bool memonly)
Definition: wallet.cpp:273
CTransaction::bulletproofs
std::vector< unsigned char > bulletproofs
Definition: transaction.h:296
CWalletTx::GetAmounts
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, std::string &strSentAccount, const isminefilter &filter) const
Definition: wallet.cpp:1681
CMerkleTx::GetBlocksToMaturity
int GetBlocksToMaturity() const
Definition: wallet.cpp:6025
NetMsgType::TX
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:25
CWallet::GetTransactionType
std::string GetTransactionType(const CTransaction &tx)
Definition: wallet.cpp:910
CWallet::IsTransactionForMe
bool IsTransactionForMe(const CTransaction &tx)
Definition: wallet.cpp:6705
secp256k1_context_struct2
Definition: secp256k1_types.h:15
CKey
An encapsulated private key.
Definition: key.h:39
CTxOut::maskValue
MaskValue maskValue
Definition: transaction.h:176
CReserveKey::KeepKey
void KeepKey()
Definition: wallet.cpp:5008
CAffectedKeysVisitor::Process
void Process(const CScript &script)
Definition: wallet.cpp:5104
CWallet::TopUpKeyPool
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:4706
CCrypter
Encryption/decryption context with key information.
Definition: crypter.h:77
CKey::VerifyPubKey
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:111
ON
@ ON
Definition: wallet.h:236
CKeyStore::AddKey
virtual bool AddKey(const CKey &key)
Definition: keystore.cpp:22
utilmoneystr.h
CClientUIInterface::LoadWallet
boost::signals2::signal< void(CWallet *wallet)> LoadWallet
A wallet has been loaded.
Definition: guiinterface.h:98
CAccountingEntry::nOrderPos
int64_t nOrderPos
Definition: wallet.h:991
CWallet::HaveKey
bool HaveKey(const CKeyID &address) const
Check whether a key corresponding to a given address is present in the store.
Definition: wallet.cpp:6932
secp256k1_pedersen_commitment
Opaque data structure that stores a Pedersen commitment.
Definition: secp256k1_commitment.h:22
fReindex
std::atomic< bool > fReindex
Definition: main.cpp:81
CHDChain
Definition: hdchain.h:11
CWalletTx::GetChange
CAmount GetChange() const
Definition: wallet.cpp:6346
CWallet::setKeyPool
std::set< int64_t > setKeyPool
Definition: wallet.h:307
COutPoint::n
uint32_t n
Definition: transaction.h:40
CWallet::CreateCommitmentWithZeroBlind
static bool CreateCommitmentWithZeroBlind(const CAmount val, unsigned char *pBlind, std::vector< unsigned char > &commitment)
Definition: wallet.cpp:3102
CTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:285
CCoinControl::nSplitBlock
int nSplitBlock
Definition: coincontrol.h:23
CStealthAccount::viewAccount
CAccount viewAccount
Definition: wallet.h:199
CTxMemPool::mapTx
std::map< uint256, CTxMemPoolEntry > mapTx
Definition: txmempool.h:136
swifttx.h
secp256k1_generator_const_g
const SECP256K1_API secp256k1_generator secp256k1_generator_const_g
Standard secp256k1 generator G.
Definition: main_impl.h:18
LOCK
#define LOCK(cs)
Definition: sync.h:182
CWallet::MultiSend
bool MultiSend()
Definition: wallet.cpp:5822
CTransaction::txPrivM
CKey txPrivM
Definition: transaction.h:290
CWalletDB::WriteMSettings
bool WriteMSettings(bool fMultiSendStake, bool fMultiSendMasternode, int nLastMultiSendHeight)
Definition: walletdb.cpp:225
CCryptoKeyStore::DecryptHDChain
bool DecryptHDChain(CHDChain &hdChainRet) const
Definition: crypter.cpp:287
CTxIn::s
std::vector< unsigned char > s
Definition: transaction.h:90
CWalletTx::WriteToDisk
bool WriteToDisk(CWalletDB *pwalletdb)
Definition: wallet.cpp:1761
key
CKey key
Definition: bip38tooldialog.cpp:173
CWalletDB::WriteTx
bool WriteTx(uint256 hash, const CWalletTx &wtx)
Definition: walletdb.cpp:76
CWallet
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,...
Definition: wallet.h:243
CCryptoKeyStore::GetHDChain
bool GetHDChain(CHDChain &hdChainRet) const
Definition: crypter.cpp:358
CKeyImage
CPubKey CKeyImage
Definition: pubkey.h:203
MIN_RING_SIZE
int MIN_RING_SIZE
Definition: main.cpp:91
CWallet::ReturnKey
void ReturnKey(int64_t nIndex)
Definition: wallet.cpp:4819
CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:792
CMasternodeConfig::CMasternodeEntry
Definition: masternodeconfig.h:22
CWallet::NotifyTransactionChanged
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:607
CAffectedKeysVisitor::operator()
void operator()(const CScriptID &scriptId)
Definition: wallet.cpp:5121
secp256k1_generator_const_h
const SECP256K1_API secp256k1_generator secp256k1_generator_const_h
Alternate secp256k1 generator from Elements Alpha.
Definition: main_impl.h:32
BCLog::STAKING
@ STAKING
Definition: logging.h:61
GetStrongRandBytes
void GetStrongRandBytes(unsigned char *out, int num)
Function to gather random data from multiple sources, failing whenever any of those source fail to pr...
Definition: random.cpp:316
ReadBlockFromDisk
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
Definition: main.cpp:2101
CCryptoKeyStore::mapCryptedKeys
CryptedKeyMap mapCryptedKeys
Definition: crypter.h:148
secp256k1_ec_privkey_tweak_add
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_add(unsigned char *seckey, const unsigned char *tweak) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2)
Tweak a private key by adding tweak to it.
Definition: secp256k1.c:217
secp256k1_generator.h
CWalletDB::Write2FASecret
bool Write2FASecret(std::string secret)
Definition: walletdb.cpp:326
CWallet::SetNull
void SetNull()
Definition: wallet.cpp:6108
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:86
CWallet::GetPubKey
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
GetPubKey implementation that also checks the mapHdPubKeys.
Definition: wallet.cpp:6894
CTransaction::paymentID
uint64_t paymentID
Definition: transaction.h:292
pwalletMain
CWallet * pwalletMain
Definition: wallet.cpp:49
CWallet::RescanAfterUnlock
bool RescanAfterUnlock(int fromHeight)
Definition: wallet.cpp:499
SignSignature
bool SignSignature(const CKeyStore &keystore, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, int nHashType)
Definition: sign.cpp:96
CBasicKeyStore::AddWatchOnly
virtual bool AddWatchOnly(const CScript &dest)
Support for Watch-only addresses.
Definition: keystore.cpp:61
CWallet::ZapWalletTx
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:4567
prevector::size
size_type size() const
Definition: prevector.h:282
CWalletDB::Compact
static bool Compact(CDBEnv &dbenv, const std::string &strFile)
Definition: walletdb.cpp:1180
CReserveKey::ReturnKey
void ReturnKey()
Definition: wallet.cpp:5016
CWalletTx::fCreditCached
bool fCreditCached
Definition: wallet.h:810
CHDPubKey::nAccountIndex
uint32_t nAccountIndex
Definition: hdchain.h:101
CMerkleTx::GetTransactionLockSignatures
int GetTransactionLockSignatures() const
Definition: wallet.cpp:6054
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:463
CWalletDB::WriteDestData
bool WriteDestData(const std::string &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
Definition: walletdb.cpp:1265
masternode-budget.h
CWallet::mapKeyMetadata
std::map< CKeyID, CKeyMetadata > mapKeyMetadata
Definition: wallet.h:308
CCrypter::SetKeyFromPassphrase
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:43
CWallet::pwalletdbEncryption
CWalletDB * pwalletdbEncryption
Definition: wallet.h:249
CMerkleTx::IsInMainChain
bool IsInMainChain() const
Definition: wallet.cpp:6033
CPubKey::IsFullyValid
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:54
CChain::Contains
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:626
WalletFeature
WalletFeature
(client) version numbers for particular wallet features
Definition: wallet.h:100
secp256k1_ec_pubkey_tweak_add
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_add(unsigned char *pubkey, int pubkeylen, const unsigned char *tweak) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3)
Tweak a public key by adding tweak times the generator to it.
Definition: secp256k1.c:237
MilliSleep
void MilliSleep(int64_t n)
Definition: utiltime.cpp:45
CWallet::GetSeedPhrase
bool GetSeedPhrase(std::string &phrase)
Definition: wallet.cpp:351
CMerkleTx::IsTransactionLockTimedOut
bool IsTransactionLockTimedOut() const
Definition: wallet.cpp:6068
CMasterKey::nDerivationMethod
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:41
CWallet::nHashInterval
unsigned int nHashInterval
Definition: wallet.h:316
CWallet::cs_wallet
RecursiveMutex cs_wallet
Definition: wallet.h:301
secp256k1_pedersen_serialized_pubkey_to_commitment
SECP256K1_API void secp256k1_pedersen_serialized_pubkey_to_commitment(const unsigned char *pubkey, size_t length, secp256k1_pedersen_commitment *commit) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3)
Definition: main_impl.h:50
CFeeRate::ToString
std::string ToString() const
Definition: amount.cpp:30
VerifyShnorrKeyImageTxIn
bool VerifyShnorrKeyImageTxIn(const CTxIn &txin, uint256 ctsHash)
Definition: main.cpp:1407
GetBlockValue
CAmount GetBlockValue(int nHeight)
Definition: main.cpp:2158
CWallet::findMyOutPoint
COutPoint findMyOutPoint(const CTxIn &txin) const
Definition: wallet.cpp:1348
CWallet::MaxTxSizePerTx
static int MaxTxSizePerTx()
Definition: wallet.cpp:5818
CWalletTx::IsTrusted
bool IsTrusted() const
Definition: wallet.cpp:6295
CWalletTx::nWatchDebitCached
CAmount nWatchDebitCached
Definition: wallet.h:823
CKeyMetadata::nCreateTime
int64_t nCreateTime
Definition: walletdb.h:50
CWalletKey::nTimeExpires
int64_t nTimeExpires
Definition: wallet.h:953
CWallet::dirtyCachedBalance
CAmount dirtyCachedBalance
Definition: wallet.h:379
CWallet::LoadKeyMetadata
bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
Definition: wallet.cpp:430
CCryptoKeyStore::GetPubKey
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
Definition: crypter.cpp:195
base58.h
CWalletTx::MarkDirty
void MarkDirty()
make sure balances are recalculated
Definition: wallet.cpp:6328
CDB::TxnBegin
bool TxnBegin()
Definition: db.h:285
CWallet::Read2FASecret
std::string Read2FASecret()
Definition: wallet.cpp:388
CWallet::setLockedCoins
std::set< COutPoint > setLockedCoins
Definition: wallet.h:360
CWallet::combineMode
CombineMode combineMode
Definition: wallet.h:365
runCommand
void runCommand(std::string strCommand)
Definition: util.cpp:593
CCryptoKeyStore::IsCrypted
bool IsCrypted() const
Definition: crypter.h:154
CWallet::UpdatedTransaction
bool UpdatedTransaction(const uint256 &hashTx)
Definition: wallet.cpp:5043
script.h
nReserveBalance
int64_t nReserveBalance
Definition: wallet.cpp:59
CTxOut::commitment
std::vector< unsigned char > commitment
Definition: transaction.h:178
WALLET_CRYPTO_SALT_SIZE
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:15
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:342
CMerkleTx::hashBlock
uint256 hashBlock
Definition: wallet.h:737
COutput::i
int i
Definition: wallet.h:926
CWallet::GetKeyPoolSize
unsigned int GetKeyPoolSize()
Definition: wallet.cpp:6232
CAccount::nAccountIndex
uint32_t nAccountIndex
Definition: wallet.h:171
CWallet::AddWatchOnly
bool AddWatchOnly(const CScript &dest)
Adds a watch-only address to the store, and saves it to disk.
Definition: wallet.cpp:469
CWallet::SyncMetaData
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >)
Definition: wallet.cpp:777
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
CWallet::GetSpendDepth
unsigned int GetSpendDepth(const uint256 &hash, unsigned int n) const
Definition: wallet.cpp:885
BCLog::DELETETX
@ DELETETX
Definition: logging.h:67
CChain::Tip
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:596
txnouttype
txnouttype
Definition: standard.h:57
CWalletDB::EraseDestData
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:1291
CPubKey::IsValid
bool IsValid() const
Definition: pubkey.h:159
CWallet::GetDecryptedHDChain
bool GetDecryptedHDChain(CHDChain &hdChainRet)
Definition: wallet.cpp:295
CMutableTransaction::GetHash
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:93
CWallet::EraseDestData
bool EraseDestData(const CTxDestination &dest, const std::string &key)
Erases a destination data tuple in the store and on disk.
Definition: wallet.cpp:5237
CWallet::ReacceptWalletTransactions
void ReacceptWalletTransactions()
Definition: wallet.cpp:2132
CWalletTx::GetRequestCount
int GetRequestCount() const
Definition: wallet.cpp:1445
CMerkleTx::IsInMainChainImmature
bool IsInMainChainImmature() const
Definition: wallet.cpp:6038
CWallet::WriteStakingStatus
bool WriteStakingStatus(bool status)
Definition: wallet.cpp:366
FastRandomContext::randbool
bool randbool()
Generate a random boolean.
Definition: random.h:131
nTimeBestReceived
int64_t nTimeBestReceived
Definition: main.cpp:72
CExtPubKey::pubkey
CPubKey pubkey
Definition: pubkey.h:210
CTransaction::hasPaymentID
char hasPaymentID
Definition: transaction.h:291
CWallet::ChangeWalletPassphrase
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:656
Hash
std::string Hash(std::string input)
Compute the 256-bit hash of a std::string.
Definition: hash.h:122
secp256k1_pedersen_commitment_sum_pos
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commitment_sum_pos(const secp256k1_context2 *ctx, const secp256k1_pedersen_commitment *const *pos, size_t n_pos, secp256k1_pedersen_commitment *out) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4)
Definition: main_impl.h:205
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:384
CBasicKeyStore::HaveWatchOnly
virtual bool HaveWatchOnly() const
Definition: keystore.cpp:81
CBlockLocator
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:249
GetGenerator
secp256k1_bulletproof_generators * GetGenerator()
Definition: main.cpp:362
add1s
void add1s(std::string &s, int wantedSize)
Definition: wallet.cpp:6397
coincontrol.h
CFeeRate::GetFee
CAmount GetFee(size_t size) const
Definition: amount.cpp:20
CTransaction::ComputePriority
double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const
Definition: transaction.cpp:191
CWalletTx::GetAccountAmounts
void GetAccountAmounts(const std::string &strAccount, CAmount &nReceived, CAmount &nSent, CAmount &nFee, const isminefilter &filter) const
Definition: wallet.cpp:1731
CTxIn::keyImage
CKeyImage keyImage
Definition: transaction.h:97
CWalletTx::nImmatureWatchCreditCached
CAmount nImmatureWatchCreditCached
Definition: wallet.h:825
CWallet::fMultiSendStake
bool fMultiSendStake
Definition: wallet.h:323
CWallet::EraseFromWallet
bool EraseFromWallet(const uint256 &hash)
Definition: wallet.cpp:1320
net.h
ExtractDestinations
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Definition: standard.cpp:223
CWallet::Read2FA
bool Read2FA()
Definition: wallet.cpp:379
CExtKey::Neuter
CExtPubKey Neuter() const
Definition: key.cpp:205
GetTxInSignatureHash
uint256 GetTxInSignatureHash(const CTxIn &txin)
Definition: main.cpp:687
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:162
CWalletTx::GetConflicts
std::set< uint256 > GetConflicts() const
Definition: wallet.cpp:2188
CScriptID
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:20
secp256k1_pedersen_commitment_sum
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commitment_sum(const secp256k1_context2 *ctx, const secp256k1_pedersen_commitment *const *pos, size_t n_pos, const secp256k1_pedersen_commitment *const *neg, size_t n_neg, secp256k1_pedersen_commitment *out) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(6)
Definition: main_impl.h:175
CWalletDB::WriteHDPubKey
bool WriteHDPubKey(const CHDPubKey &hdPubKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:1316
CBitcoinAddress::Get
CTxDestination Get() const
Definition: base58.cpp:267
CWalletDB::ReadStealthAccount
bool ReadStealthAccount(const std::string &strAccount, CStealthAccount &account)
Definition: walletdb.cpp:388
CWallet::ListLockedCoins
void ListLockedCoins(std::vector< COutPoint > &vOutpts)
Definition: wallet.cpp:5083
CWallet::RemoveWatchOnly
bool RemoveWatchOnly(const CScript &dest)
Definition: wallet.cpp:480
GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:241
CWalletTx::fFromMe
char fFromMe
Definition: wallet.h:803
CWallet::isMultiSendEnabled
bool isMultiSendEnabled()
Definition: wallet.cpp:6142
CWallet::strWalletFile
std::string strWalletFile
Definition: wallet.h:305
COutput
Definition: wallet.h:922
CWallet::GetKey
bool GetKey(const CKeyID &address, CKey &keyOut) const
GetKey implementation that can derive a HD private key on the fly.
Definition: wallet.cpp:6906
amount.h
CTransaction::c
uint256 c
Definition: transaction.h:300
CCryptoKeyStore::vMasterKey
CKeyingMaterial vMasterKey
Definition: crypter.h:136
bitdb
CDBEnv bitdb
Definition: db.cpp:29
CWallet::EncodeTxOutAmount
bool EncodeTxOutAmount(CTxOut &out, const CAmount &amount, const unsigned char *sharedSec, bool isCoinstake=false)
Definition: wallet.cpp:7168
CValidationState
Capture information about block/transaction validation.
Definition: validation.h:23
CWallet::CanSupportFeature
bool CanSupportFeature(enum WalletFeature wf)
check whether we are allowed to upgrade (or already support) to the named feature
Definition: wallet.cpp:6153
CChainParams::MNCollateralAmt
CAmount MNCollateralAmt() const
Definition: chainparams.h:86
CWalletDB::ReadStealthAccountList
bool ReadStealthAccountList(std::string &accountList)
Definition: walletdb.cpp:46
secp256k1_pedersen_blind_sum
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_blind_sum(const secp256k1_context2 *ctx, unsigned char *blind_out, const unsigned char *const *blinds, size_t n, size_t npositive) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Computes the sum of multiple positive and negative blinding factors.
Definition: main_impl.h:126
CWalletDB::WriteScannedBlockHeight
bool WriteScannedBlockHeight(int height)
Definition: walletdb.cpp:304
CWallet::Write2FAPeriod
bool Write2FAPeriod(int period)
Definition: wallet.cpp:393
CExtPubKey
Definition: pubkey.h:205
CWallet::CreatePrivacyAccount
void CreatePrivacyAccount(bool force=false)
Definition: wallet.cpp:4766
masternodeconfig.h
CWallet::nTimeFirstKey
int64_t nTimeFirstKey
Definition: wallet.h:363
CWallet::allMyPrivateKeys
bool allMyPrivateKeys(std::vector< CKey > &spends, std::vector< CKey > &views)
Definition: wallet.cpp:6809
CMerkleTx::Init
void Init()
Definition: wallet.h:750
CWallet::GenerateNewKey
CPubKey GenerateNewKey()
Definition: wallet.cpp:215
ecdhEncode
void ecdhEncode(unsigned char *unmasked, unsigned char *amount, const unsigned char *sharedSec, int size)
Definition: wallet.cpp:69
CExtKey::key
CKey key
Definition: key.h:166
CMasterKey::nDeriveIterations
unsigned int nDeriveIterations
Definition: crypter.h:42
CTxMemPool::estimatePriority
double estimatePriority(int nBlocks) const
Estimate priority needed to get into the next nBlocks.
Definition: txmempool.cpp:638
CWallet::LoadDestData
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:5246
CKeyMetadata
Definition: walletdb.h:45
CWalletTx::fDebitCached
bool fDebitCached
Definition: wallet.h:809
CWallet::AllMyPublicAddresses
bool AllMyPublicAddresses(std::vector< std::string > &addresses, std::vector< std::string > &accountNames)
Definition: wallet.cpp:6781
CChain::Next
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or NULL if the given index is not found or is the tip.
Definition: chain.h:632
secp256k1_commitment.h
CWallet::getCTxOutValue
CAmount getCTxOutValue(const CTransaction &tx, const CTxOut &out) const
Definition: wallet.cpp:7202
CWallet::LoadCScript
bool LoadCScript(const CScript &redeemScript)
Definition: wallet.cpp:454
CTransaction::hash
const uint256 hash
Memory only.
Definition: transaction.h:273
CChain::Genesis
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
Definition: chain.h:590
CBlockTreeDB::WriteKeyImage
bool WriteKeyImage(const std::string &keyImage, const uint256 &height)
Definition: txdb.cpp:201
txdb.h
CWallet::mapAddressBook
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:354
CWalletTx::fImmatureCreditCached
bool fImmatureCreditCached
Definition: wallet.h:811
FastRandomContext
Fast randomness source.
Definition: random.h:44
CWalletDB::AppendStealthAccountList
bool AppendStealthAccountList(const std::string &accountName)
Definition: walletdb.cpp:33
CWallet::ParameterInteraction
static bool ParameterInteraction()
Definition: wallet.cpp:812
CWallet::GenerateIntegratedAddressWithRandomPaymentID
std::string GenerateIntegratedAddressWithRandomPaymentID(std::string accountName, uint64_t &paymentID)
Definition: wallet.cpp:6501
IsSpentKeyImage
bool IsSpentKeyImage(const std::string &kiHex, const uint256 &againsHash)
Definition: main.cpp:283
CCryptoKeyStore::IsLocked
bool IsLocked() const
Definition: crypter.h:159
FillBlockPayee
bool FillBlockPayee(CMutableTransaction &txNew, CAmount nFees, bool fProofOfStake)
Definition: masternode-payments.cpp:214
error
bool error(const char *fmt, const Args &... args)
Definition: util.h:61
CPubKey::GetID
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:143
CWallet::Write2FA
bool Write2FA(bool status)
Definition: wallet.cpp:375
CWalletDB::WriteStakingStatus
bool WriteStakingStatus(bool status)
Definition: walletdb.cpp:292
CWallet::myViewPrivateKey
bool myViewPrivateKey(CKey &view) const
Definition: wallet.cpp:7025
CWalletDB::WriteMinVersion
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:287
TX_TYPE_REVEAL_AMOUNT
@ TX_TYPE_REVEAL_AMOUNT
Definition: transaction.h:261
CWalletDB::WriteTxPrivateKey
bool WriteTxPrivateKey(const std::string &outpointKey, const std::string &k)
Definition: walletdb.cpp:1271
mapTxLocks
std::map< uint256, CTransactionLock > mapTxLocks
Definition: swifttx.cpp:27
CWalletDB::WriteName
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:50
ParseMoney
bool ParseMoney(const std::string &str, CAmount &nRet)
Definition: utilmoneystr.cpp:37
mapBlockIndex
BlockMap mapBlockIndex
Definition: main.cpp:67
STAKABLE_COINS
@ STAKABLE_COINS
Definition: wallet.h:112
CWallet::fMultiSendMasternodeReward
bool fMultiSendMasternodeReward
Definition: wallet.h:324
CTxOut::txPub
std::vector< unsigned char > txPub
Definition: transaction.h:173
CDB::TxnAbort
bool TxnAbort()
Definition: db.h:305
CWallet::walletUnlockCountStatus
int walletUnlockCountStatus
Definition: wallet.h:319
CWalletTx::IsFromMe
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.cpp:6355
CWallet::ReadAutoConsolidateSettingTime
uint32_t ReadAutoConsolidateSettingTime()
Definition: wallet.cpp:3161
CCryptoKeyStore::EncryptKeys
bool EncryptKeys(CKeyingMaterial &vMasterKeyIn)
will encrypt previously unencrypted keys
Definition: crypter.cpp:211
CCryptoKeyStore::HaveKey
bool HaveKey(const CKeyID &address) const
Check whether a key corresponding to a given address is present in the store.
Definition: crypter.h:173
FEATURE_WALLETCRYPT
@ FEATURE_WALLETCRYPT
Definition: wallet.h:103
CWallet::ReadAccountList
bool ReadAccountList(std::string &accountList)
Definition: wallet.cpp:6369
CMasternodeConfig::getEntries
std::vector< CMasternodeEntry > & getEntries()
Definition: masternodeconfig.h:103
ECDHInfo::Decode
static void Decode(unsigned char *encodedMask, unsigned char *encodedAmount, const CPubKey &sharedSec, CKey &decodedMask, CAmount &decodedAmount)
Definition: wallet.cpp:126
CWalletDB::EraseName
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:56
CWalletTx::GetImmatureWatchOnlyCredit
CAmount GetImmatureWatchOnlyCredit(const bool &fUseCache=true) const
Definition: wallet.cpp:1642
CCoinControl::destChange
CTxDestination destChange
Definition: coincontrol.h:18
CTransaction::IsCoinStake
bool IsCoinStake() const
Definition: transaction.cpp:143
base_uint::ToString
std::string ToString() const
Definition: arith_uint256.cpp:199
CWallet::SelectStakeCoins
bool SelectStakeCoins(std::list< std::unique_ptr< CStakeInput > > &listInputs, CAmount nTargetAmount)
Definition: wallet.cpp:2629
CWallet::UnlockAllCoins
void UnlockAllCoins()
Definition: wallet.cpp:5069
CWalletTx::GetAvailableCredit
CAmount GetAvailableCredit(bool fUseCache=true) const
Definition: wallet.cpp:1547