1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <openssl/bio.h>
20 extern int64_t nReserveBalance;
22 //////////////////////////////////////////////////////////////////////////////
32 CWallet::CWallet(std::string strWalletFileIn)
36 strWalletFile = strWalletFileIn;
40 void CWallet::SetNull()
42 nWalletVersion = FEATURE_BASE;
43 nWalletMaxVersion = FEATURE_BASE;
46 pwalletdbEncryption = NULL;
47 pwalletdbDecryption = NULL;
56 struct CompareValueOnly
58 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
59 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
61 return t1.first < t2.first;
65 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
68 auto it = mapWallet.find(hash);
69 if (it == mapWallet.end())
74 CPubKey CWallet::GenerateNewKey()
76 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
80 key.MakeNewKey(fCompressed);
82 // Compressed public keys were introduced in version 0.6.0
84 SetMinVersion(FEATURE_COMPRPUBKEY);
86 auto pubkey = key.GetPubKey();
88 // Create new metadata
89 auto nCreationTime = GetTime();
90 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = CKeyMetadata(nCreationTime);
91 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
92 nTimeFirstKey = nCreationTime;
95 throw runtime_error("CWallet::GenerateNewKey() : AddKey failed");
96 return key.GetPubKey();
99 CMalleableKeyView CWallet::GenerateNewMalleableKey()
101 RandAddSeedPerfmon();
103 // Compressed public keys were introduced in version 0.6.0
104 SetMinVersion(FEATURE_MALLKEY);
108 const CMalleableKeyView &keyView(mKey);
110 // Create new metadata
111 auto nCreationTime = GetTime();
112 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = CKeyMetadata(nCreationTime);
113 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
114 nTimeFirstKey = nCreationTime;
117 throw runtime_error("CWallet::GenerateNewMalleableKey() : AddKey failed");
118 return CMalleableKeyView(mKey);
121 bool CWallet::AddKey(const CKey& key)
123 auto pubkey = key.GetPubKey();
124 if (!CCryptoKeyStore::AddKey(key))
129 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(pubkey.GetID())]);
133 bool CWallet::AddKey(const CMalleableKey& mKey)
135 auto keyView = CMalleableKeyView(mKey);
136 auto vchSecretH = mKey.GetSecretH();
137 if (!CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH))
142 return CWalletDB(strWalletFile).WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
146 bool CWallet::AddCryptedMalleableKey(const CMalleableKeyView& keyView, const vector<unsigned char> &vchCryptedSecretH)
148 if (!CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH))
156 CBitcoinAddress addr(keyView.GetMalleablePubKey());
157 if (pwalletdbEncryption)
158 return pwalletdbEncryption->WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
160 return CWalletDB(strWalletFile).WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
166 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
168 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
171 // check if we need to remove from watch-only
173 script.SetDestination(vchPubKey.GetID());
174 if (HaveWatchOnly(script))
175 RemoveWatchOnly(script);
181 CBitcoinAddress addr(vchPubKey.GetID());
182 if (pwalletdbEncryption)
183 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
185 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
190 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
192 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
193 nTimeFirstKey = meta.nCreateTime;
195 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = meta;
199 bool CWallet::LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
201 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
202 nTimeFirstKey = metadata.nCreateTime;
204 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = metadata;
208 bool CWallet::AddCScript(const CScript& redeemScript)
210 if (!CCryptoKeyStore::AddCScript(redeemScript))
214 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
217 bool CWallet::LoadCScript(const CScript& redeemScript)
219 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
220 * that never can be redeemed. However, old wallets may still contain
221 * these. Do not add them to the wallet and warn. */
222 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
224 auto strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
225 printf("LoadCScript() : Warning: This wallet contains a redeemScript of size %" PRIszu " which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
226 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
230 return CCryptoKeyStore::AddCScript(redeemScript);
234 bool CWallet::AddWatchOnly(const CScript &dest)
236 if (!CCryptoKeyStore::AddWatchOnly(dest))
238 nTimeFirstKey = 1; // No birthday information for watch-only keys.
239 NotifyWatchonlyChanged(true);
242 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
245 bool CWallet::RemoveWatchOnly(const CScript &dest)
248 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
250 if (!HaveWatchOnly())
251 NotifyWatchonlyChanged(false);
253 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
259 bool CWallet::LoadWatchOnly(const CScript &dest)
261 return CCryptoKeyStore::AddWatchOnly(dest);
264 // ppcoin: optional setting to unlock wallet for block minting only;
265 // serves to disable the trivial sendmoney when OS account compromised
266 bool fWalletUnlockMintOnly = false;
268 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
274 CKeyingMaterial vMasterKey;
278 for(const auto& pMasterKey : mapMasterKeys)
280 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
282 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
284 if (CCryptoKeyStore::Unlock(vMasterKey))
291 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
293 bool fWasLocked = IsLocked();
300 CKeyingMaterial vMasterKey;
301 for(auto& pMasterKey : mapMasterKeys)
303 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
305 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
307 if (CCryptoKeyStore::Unlock(vMasterKey))
309 auto nStartTime = GetTimeMillis();
310 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
311 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
312 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
314 nStartTime = GetTimeMillis();
315 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
316 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
317 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
319 if (pMasterKey.second.nDeriveIterations < 25000)
320 pMasterKey.second.nDeriveIterations = 25000;
322 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
324 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
326 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
328 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
339 void CWallet::SetBestChain(const CBlockLocator& loc)
341 CWalletDB walletdb(strWalletFile);
342 walletdb.WriteBestBlock(loc);
345 // This class implements an addrIncoming entry that causes pre-0.4
346 // clients to crash on startup if reading a private-key-encrypted wallet.
347 class CCorruptAddress
352 if (nType & SER_DISK)
357 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
359 if (nWalletVersion >= nVersion)
362 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
363 if (fExplicit && nVersion > nWalletMaxVersion)
364 nVersion = FEATURE_LATEST;
366 nWalletVersion = nVersion;
368 if (nVersion > nWalletMaxVersion)
369 nWalletMaxVersion = nVersion;
373 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
374 if (nWalletVersion > 40000)
375 pwalletdb->WriteMinVersion(nWalletVersion);
383 bool CWallet::SetMaxVersion(int nVersion)
385 // cannot downgrade below current version
386 if (nWalletVersion > nVersion)
389 nWalletMaxVersion = nVersion;
394 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
399 CKeyingMaterial vMasterKey;
400 RandAddSeedPerfmon();
402 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
403 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
405 CMasterKey kMasterKey;
407 RandAddSeedPerfmon();
408 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
409 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
412 auto nStartTime = GetTimeMillis();
413 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
414 auto nDivider = GetTimeMillis() - nStartTime;
415 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
417 nStartTime = GetTimeMillis();
418 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
419 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
420 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
422 if (kMasterKey.nDeriveIterations < 25000)
423 kMasterKey.nDeriveIterations = 25000;
425 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
427 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
429 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
434 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
437 pwalletdbEncryption = new CWalletDB(strWalletFile);
438 if (!pwalletdbEncryption->TxnBegin())
440 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
443 if (!EncryptKeys(vMasterKey))
446 pwalletdbEncryption->TxnAbort();
447 exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
450 // Encryption was introduced in version 0.4.0
451 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
455 if (!pwalletdbEncryption->TxnCommit())
456 exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
458 delete pwalletdbEncryption;
459 pwalletdbEncryption = NULL;
463 Unlock(strWalletPassphrase);
467 // Need to completely rewrite the wallet file; if we don't, bdb might keep
468 // bits of the unencrypted private key in slack space in the database file.
469 CDB::Rewrite(strWalletFile);
472 NotifyStatusChanged(this);
477 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
483 CKeyingMaterial vMasterKey;
487 for(const auto& pMasterKey : mapMasterKeys)
489 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
491 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
493 if (!CCryptoKeyStore::Unlock(vMasterKey))
499 pwalletdbDecryption = new CWalletDB(strWalletFile);
500 if (!pwalletdbDecryption->TxnBegin())
504 if (!DecryptKeys(vMasterKey))
507 pwalletdbDecryption->TxnAbort();
508 exit(1); //We now probably have half of our keys decrypted in memory, and half not...die and let the user reload their encrypted wallet.
513 // Overwrite crypted keys
514 auto mi = mapKeys.begin();
515 while (mi != mapKeys.end())
518 key.SetSecret((*mi).second.first, (*mi).second.second);
519 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
520 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(mi->first)]);
524 auto mi2 = mapMalleableKeys.begin();
525 while (mi2 != mapMalleableKeys.end())
527 const auto &vchSecretH = mi2->second;
528 const auto &keyView = mi2->first;
529 pwalletdbDecryption->EraseCryptedMalleableKey(keyView);
530 pwalletdbDecryption->WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
535 auto mk = mapMasterKeys.begin();
536 while (mk != mapMasterKeys.end())
538 pwalletdbDecryption->EraseMasterKey((*mk).first);
542 if (!pwalletdbDecryption->TxnCommit())
543 exit(1); //We now have keys decrypted in memory, but no on disk...die to avoid confusion and let the user reload their encrypted wallet.
545 delete pwalletdbDecryption;
546 pwalletdbDecryption = NULL;
549 // Need to completely rewrite the wallet file; if we don't, bdb might keep
550 // encrypted private keys in the database file which can be a reason of consistency issues.
551 CDB::Rewrite(strWalletFile);
553 NotifyStatusChanged(this);
558 bool CWallet::GetPEM(const CKeyID &keyID, const string &fileName, const SecureString &strPassKey) const
560 BIO *pemOut = BIO_new_file(fileName.c_str(), "w");
562 return error("GetPEM() : failed to create file %s\n", fileName.c_str());
564 if (!GetKey(keyID, key))
565 return error("GetPEM() : failed to get key for address=%s\n", CBitcoinAddress(keyID).ToString().c_str());
566 bool result = key.WritePEM(pemOut, strPassKey);
571 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
573 int64_t nRet = nOrderPosNext++;
575 pwalletdb->WriteOrderPosNext(nOrderPosNext);
577 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
582 CWallet::TxItems CWallet::OrderedTxItems(list<CAccountingEntry>& acentries, string strAccount)
584 CWalletDB walletdb(strWalletFile);
586 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
589 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
590 // would make this much faster for applications that do this a lot.
591 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
593 CWalletTx* wtx = &((*it).second);
594 txOrdered.insert({ wtx->nOrderPos, { wtx, (CAccountingEntry*)0 } });
597 walletdb.ListAccountCreditDebit(strAccount, acentries);
598 for(auto& entry : acentries)
600 txOrdered.insert({ entry.nOrderPos, { (CWalletTx*)0, &entry } });
606 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
608 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
609 // Update the wallet spent flag if it doesn't know due to wallet.dat being
610 // restored from backup or the user making copies of wallet.dat.
613 for(const auto& txin : tx.vin)
615 auto mi = mapWallet.find(txin.prevout.hash);
616 if (mi != mapWallet.end())
618 auto& wtx = (*mi).second;
619 if (txin.prevout.n >= wtx.vout.size())
620 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
621 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
623 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
624 wtx.MarkSpent(txin.prevout.n);
626 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
627 vMintingWalletUpdated.push_back(txin.prevout.hash);
634 auto hash = tx.GetHash();
635 auto mi = mapWallet.find(hash);
636 auto& wtx = (*mi).second;
638 for(const CTxOut& txout : tx.vout)
642 wtx.MarkUnspent(&txout - &tx.vout[0]);
644 NotifyTransactionChanged(this, hash, CT_UPDATED);
645 vMintingWalletUpdated.push_back(hash);
653 void CWallet::MarkDirty()
657 for(auto& item : mapWallet)
658 item.second.MarkDirty();
662 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
664 auto hash = wtxIn.GetHash();
667 // Inserts only if not already there, returns tx inserted or tx found
668 auto ret = mapWallet.insert({ hash, wtxIn });
669 auto& wtx = (*ret.first).second;
670 wtx.BindWallet(this);
671 bool fInsertedNew = ret.second;
674 wtx.nTimeReceived = GetAdjustedTime();
675 wtx.nOrderPos = IncOrderPosNext();
677 wtx.nTimeSmart = wtx.nTimeReceived;
678 if (wtxIn.hashBlock != 0)
680 if (mapBlockIndex.count(wtxIn.hashBlock))
682 unsigned int latestNow = wtx.nTimeReceived;
683 unsigned int latestEntry = 0;
685 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
686 int64_t latestTolerated = latestNow + 300;
687 list<CAccountingEntry> acentries;
688 auto txOrdered = OrderedTxItems(acentries);
689 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
691 CWalletTx *const pwtx = (*it).second.first;
694 CAccountingEntry *const pacentry = (*it).second.second;
698 nSmartTime = pwtx->nTimeSmart;
700 nSmartTime = pwtx->nTimeReceived;
703 nSmartTime = pacentry->nTime;
704 if (nSmartTime <= latestTolerated)
706 latestEntry = nSmartTime;
707 if (nSmartTime > latestNow)
708 latestNow = nSmartTime;
714 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
715 wtx.nTimeSmart = max(latestEntry, min(blocktime, latestNow));
718 printf("AddToWallet() : found %s in block %s not in index\n",
719 wtxIn.GetHash().ToString().substr(0,10).c_str(),
720 wtxIn.hashBlock.ToString().c_str());
724 bool fUpdated = false;
728 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
730 wtx.hashBlock = wtxIn.hashBlock;
733 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
735 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
736 wtx.nIndex = wtxIn.nIndex;
739 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
741 wtx.fFromMe = wtxIn.fFromMe;
744 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
748 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
751 if (fInsertedNew || fUpdated)
752 if (!wtx.WriteToDisk())
755 // If default receiving address gets used, replace it with a new one
756 CScript scriptDefaultKey;
757 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
758 for(const CTxOut& txout : wtx.vout)
760 if (txout.scriptPubKey == scriptDefaultKey)
762 CPubKey newDefaultKey;
763 if (GetKeyFromPool(newDefaultKey, false))
765 SetDefaultKey(newDefaultKey);
766 SetAddressBookName(vchDefaultKey.GetID(), "");
771 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
772 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
774 // Notify UI of new or updated transaction
775 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
776 vMintingWalletUpdated.push_back(hash);
777 // notify an external script when a wallet transaction comes in or is updated
778 auto strCmd = GetArg("-walletnotify", "");
780 if ( !strCmd.empty())
782 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
783 boost::thread t(runCommand, strCmd); // thread runs free
790 // Add a transaction to the wallet, or update it.
791 // pblock is optional, but should be provided if the transaction is known to be in a block.
792 // If fUpdate is true, existing transactions will be updated.
793 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
795 auto hash = tx.GetHash();
798 bool fExisted = mapWallet.count(hash) != 0;
799 if (fExisted && !fUpdate) return false;
800 if (fExisted || IsMine(tx) || IsFromMe(tx))
802 CWalletTx wtx(this,tx);
803 // Get merkle branch if transaction was found in a block
805 wtx.SetMerkleBranch(pblock);
806 return AddToWallet(wtx);
809 WalletUpdateSpent(tx);
814 bool CWallet::EraseFromWallet(uint256 hash)
820 if (mapWallet.erase(hash))
821 CWalletDB(strWalletFile).EraseTx(hash);
827 isminetype CWallet::IsMine(const CTxIn &txin) const
831 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
832 if (mi != mapWallet.end())
834 const CWalletTx& prev = (*mi).second;
835 if (txin.prevout.n < prev.vout.size())
836 return IsMine(prev.vout[txin.prevout.n]);
842 CWalletTx::CWalletTx()
847 CWalletTx::CWalletTx(const CWallet* pwalletIn)
852 CWalletTx::CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
857 CWalletTx::CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
862 void CWalletTx::Init(const CWallet* pwalletIn)
868 fTimeReceivedIsTxTime = false;
872 strFromAccount.clear();
874 fDebitCached = false;
875 fWatchDebitCached = false;
876 fCreditCached = false;
877 fWatchCreditCached = false;
878 fAvailableCreditCached = false;
879 fAvailableWatchCreditCached = false;
880 fImmatureCreditCached = false;
881 fImmatureWatchCreditCached = false;
882 fChangeCached = false;
884 nWatchDebitCached = 0;
886 nWatchCreditCached = 0;
887 nAvailableCreditCached = 0;
888 nAvailableWatchCreditCached = 0;
889 nImmatureCreditCached = 0;
890 nImmatureWatchCreditCached = 0;
895 // marks certain txout's as spent
896 // returns true if any update took place
897 bool CWalletTx::UpdateSpent(const vector<char>& vfNewSpent)
899 bool fReturn = false;
900 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
902 if (i == vfSpent.size())
905 if (vfNewSpent[i] && !vfSpent[i])
909 fAvailableCreditCached = fAvailableWatchCreditCached = false;
915 // make sure balances are recalculated
916 void CWalletTx::MarkDirty()
918 fCreditCached = false;
919 fAvailableCreditCached = fAvailableWatchCreditCached = false;
920 fDebitCached = fWatchDebitCached = false;
921 fChangeCached = false;
924 void CWalletTx::BindWallet(CWallet *pwalletIn)
930 void CWalletTx::MarkSpent(unsigned int nOut)
932 if (nOut >= vout.size())
933 throw runtime_error("CWalletTx::MarkSpent() : nOut out of range");
934 vfSpent.resize(vout.size());
937 vfSpent[nOut] = true;
938 fAvailableCreditCached = fAvailableWatchCreditCached = false;
942 void CWalletTx::MarkUnspent(unsigned int nOut)
944 if (nOut >= vout.size())
945 throw runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
946 vfSpent.resize(vout.size());
949 vfSpent[nOut] = false;
950 fAvailableCreditCached = fAvailableWatchCreditCached = false;
954 bool CWalletTx::IsSpent(unsigned int nOut) const
956 if (nOut >= vout.size())
957 throw runtime_error("CWalletTx::IsSpent() : nOut out of range");
958 if (nOut >= vfSpent.size())
960 return (!!vfSpent[nOut]);
963 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
967 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
968 if (mi != mapWallet.end())
970 const CWalletTx& prev = (*mi).second;
971 if (txin.prevout.n < prev.vout.size())
972 if (IsMine(prev.vout[txin.prevout.n]) & filter)
973 return prev.vout[txin.prevout.n].nValue;
979 isminetype CWallet::IsMine(const CTxOut& txout) const
981 return ::IsMine(*this, txout.scriptPubKey);
984 int64_t CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
986 if (!MoneyRange(txout.nValue))
987 throw runtime_error("CWallet::GetCredit() : value out of range");
988 return (IsMine(txout) & filter ? txout.nValue : 0);
991 bool CWallet::IsChange(const CTxOut& txout) const
993 // TODO: fix handling of 'change' outputs. The assumption is that any
994 // payment to a script that is ours, but isn't in the address book
995 // is change. That assumption is likely to break when we implement multisignature
996 // wallets that return change back into a multi-signature-protected address;
997 // a better way of identifying which outputs are 'the send' and which are
998 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
999 // which output, if any, was change).
1000 if (::IsMine(*this, txout.scriptPubKey))
1002 CTxDestination address;
1003 if (!ExtractDestination(txout.scriptPubKey, address))
1007 if (!mapAddressBook.count(address))
1013 int64_t CWallet::GetChange(const CTxOut& txout) const
1015 if (!MoneyRange(txout.nValue))
1016 throw runtime_error("CWallet::GetChange() : value out of range");
1017 return (IsChange(txout) ? txout.nValue : 0);
1020 bool CWallet::IsMine(const CTransaction& tx) const
1022 for(const CTxOut& txout : tx.vout)
1023 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
1028 bool CWallet::IsFromMe(const CTransaction& tx) const
1030 return (GetDebit(tx, MINE_ALL) > 0);
1033 int64_t CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1036 for(const CTxIn& txin : tx.vin)
1038 auto nValue = GetDebit(txin, filter);
1040 if (!MoneyRange(nValue) || !MoneyRange(nDebit))
1041 throw runtime_error("CWallet::GetDebit() : value out of range");
1043 return nDebit.getint64();
1046 int64_t CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1048 CBigNum nCredit = 0;
1049 for(const CTxOut& txout : tx.vout)
1051 auto nValue = GetCredit(txout, filter);
1053 if (!MoneyRange(nValue) || !MoneyRange(nCredit))
1054 throw runtime_error("CWallet::GetCredit() : value out of range");
1056 return nCredit.getint64();
1059 int64_t CWallet::GetChange(const CTransaction& tx) const
1061 CBigNum nChange = 0;
1062 for(const CTxOut& txout : tx.vout)
1064 int64_t nValue = GetChange(txout);
1066 if (!MoneyRange(nValue) || !MoneyRange(nChange))
1067 throw runtime_error("CWallet::GetChange() : value out of range");
1069 return nChange.getint64();
1072 int64_t CWalletTx::GetTxTime() const
1077 int CWalletTx::GetRequestCount() const
1079 // Returns -1 if it wasn't being tracked
1082 LOCK(pwallet->cs_wallet);
1083 if (IsCoinBase() || IsCoinStake())
1088 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1089 if (mi != pwallet->mapRequestCount.end())
1090 nRequests = (*mi).second;
1095 // Did anyone request this transaction?
1096 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1097 if (mi != pwallet->mapRequestCount.end())
1099 nRequests = (*mi).second;
1101 // How about the block it's in?
1102 if (nRequests == 0 && hashBlock != 0)
1104 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1105 if (mi != pwallet->mapRequestCount.end())
1106 nRequests = (*mi).second;
1108 nRequests = 1; // If it's in someone else's block it must have got out
1116 bool CWalletTx::InMempool() const
1119 if (mempool.exists(GetHash())) {
1125 bool CWalletTx::IsTrusted() const
1127 // Quick answer in most cases
1130 int nDepth = GetDepthInMainChain();
1135 if (!fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
1138 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1142 // Trusted if all inputs are from us and are in the mempool:
1143 for(const CTxIn& txin : vin)
1145 // Transactions not sent by us: not trusted
1146 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1149 const CTxOut& parentOut = parent->vout[txin.prevout.n];
1150 if (pwallet->IsMine(parentOut) != MINE_SPENDABLE)
1156 int64_t CWalletTx::GetDebit(const isminefilter& filter) const
1162 if (filter & MINE_SPENDABLE)
1165 nDebit += nDebitCached;
1168 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
1169 fDebitCached = true;
1170 nDebit += nDebitCached;
1173 if (filter & MINE_WATCH_ONLY)
1175 if (fWatchDebitCached)
1176 nDebit += nWatchDebitCached;
1179 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
1180 fWatchDebitCached = true;
1181 nDebit += nWatchDebitCached;
1187 int64_t CWalletTx::GetCredit(const isminefilter& filter) const
1189 // Must wait until coinbase is safely deep enough in the chain before valuing it
1190 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1194 if (filter & MINE_SPENDABLE)
1196 // GetBalance can assume transactions in mapWallet won't change
1198 credit += nCreditCached;
1201 nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1202 fCreditCached = true;
1203 credit += nCreditCached;
1206 if (filter & MINE_WATCH_ONLY)
1208 if (fWatchCreditCached)
1209 credit += nWatchCreditCached;
1212 nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1213 fWatchCreditCached = true;
1214 credit += nWatchCreditCached;
1220 int64_t CWalletTx::GetImmatureCredit(bool fUseCache) const
1222 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1224 if (fUseCache && fImmatureCreditCached)
1225 return nImmatureCreditCached;
1226 nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1227 fImmatureCreditCached = true;
1228 return nImmatureCreditCached;
1234 int64_t CWalletTx::GetImmatureWatchOnlyCredit(bool fUseCache) const
1236 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1238 if (fUseCache && fImmatureWatchCreditCached)
1239 return nImmatureWatchCreditCached;
1240 nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1241 fImmatureWatchCreditCached = true;
1242 return nImmatureWatchCreditCached;
1249 int64_t CWalletTx::GetAvailableCredit(bool fUseCache) const
1251 // Must wait until coinbase is safely deep enough in the chain before valuing it
1252 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1256 if (fAvailableCreditCached)
1257 return nAvailableCreditCached;
1260 CBigNum nCredit = 0;
1261 for (uint32_t i = 0; i < vout.size(); i++)
1265 const CTxOut &txout = vout[i];
1266 int64_t nValue = pwallet->GetCredit(txout, MINE_SPENDABLE);
1268 if (!MoneyRange(nValue) || !MoneyRange(nCredit))
1269 throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1273 nAvailableCreditCached = nCredit.getint64();
1274 fAvailableCreditCached = true;
1276 return nCredit.getint64();
1279 int64_t CWalletTx::GetAvailableWatchCredit(bool fUseCache) const
1281 // Must wait until coinbase is safely deep enough in the chain before valuing it
1282 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1286 if (fAvailableWatchCreditCached)
1287 return nAvailableWatchCreditCached;
1290 CBigNum nCredit = 0;
1291 for (unsigned int i = 0; i < vout.size(); i++)
1295 const CTxOut &txout = vout[i];
1296 int64_t nValue = pwallet->GetCredit(txout, MINE_WATCH_ONLY);
1298 if (!MoneyRange(nValue) || !MoneyRange(nCredit))
1299 throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1303 nAvailableWatchCreditCached = nCredit.getint64();
1304 fAvailableWatchCreditCached = true;
1306 return nCredit.getint64();
1309 int64_t CWalletTx::GetChange() const
1312 return nChangeCached;
1313 nChangeCached = pwallet->GetChange(*this);
1314 fChangeCached = true;
1315 return nChangeCached;
1318 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
1319 list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
1321 nGeneratedImmature = nGeneratedMature = nFee = 0;
1322 listReceived.clear();
1324 strSentAccount = strFromAccount;
1326 if (IsCoinBase() || IsCoinStake())
1328 if (GetBlocksToMaturity() > 0)
1329 nGeneratedImmature = pwallet->GetCredit(*this, filter);
1331 nGeneratedMature = GetCredit(filter);
1336 auto nDebit = GetDebit(filter);
1337 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1339 auto nValueOut = GetValueOut();
1340 nFee = nDebit - nValueOut;
1344 for(const CTxOut& txout : vout)
1346 auto fIsMine = pwallet->IsMine(txout);
1347 // Only need to handle txouts if AT LEAST one of these is true:
1348 // 1) they debit from us (sent)
1349 // 2) the output is to us (received)
1352 // Don't report 'change' txouts
1353 if (pwallet->IsChange(txout))
1356 else if (!(fIsMine & filter))
1359 // In either case, we need to get the destination address
1360 CBitcoinAddress address;
1361 if (!ExtractAddress(*pwallet, txout.scriptPubKey, address))
1363 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1364 this->GetHash().ToString().c_str());
1365 address = CBitcoinAddress();
1368 // If we are debited by the transaction, add the output as a "sent" entry
1370 listSent.push_back({ address, txout.nValue });
1372 // If we are receiving the output, add it as a "received" entry
1373 if (fIsMine & filter)
1374 listReceived.push_back({ address, txout.nValue });
1379 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
1380 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
1382 nGenerated = nReceived = nSent = nFee = 0;
1384 int64_t allGeneratedImmature, allGeneratedMature, allFee;
1385 allGeneratedImmature = allGeneratedMature = allFee = 0;
1386 string strSentAccount;
1387 list<pair<CBitcoinAddress, int64_t> > listReceived;
1388 list<pair<CBitcoinAddress, int64_t> > listSent;
1389 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
1391 if (strAccount.empty())
1392 nGenerated = allGeneratedMature;
1393 if (strAccount == strSentAccount)
1395 for(const auto& s : listSent)
1400 LOCK(pwallet->cs_wallet);
1401 for(const auto& r : listReceived)
1403 if (pwallet->mapAddressBook.count(r.first))
1405 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
1406 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
1407 nReceived += r.second;
1409 else if (strAccount.empty())
1411 nReceived += r.second;
1417 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
1421 const int COPY_DEPTH = 3;
1422 if (SetMerkleBranch() < COPY_DEPTH)
1424 vector<uint256> vWorkQueue;
1425 for(const CTxIn& txin : vin)
1426 vWorkQueue.push_back(txin.prevout.hash);
1428 // This critsect is OK because txdb is already open
1430 LOCK(pwallet->cs_wallet);
1431 map<uint256, const CMerkleTx*> mapWalletPrev;
1432 set<uint256> setAlreadyDone;
1433 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1435 auto hash = vWorkQueue[i];
1436 if (setAlreadyDone.count(hash))
1438 setAlreadyDone.insert(hash);
1441 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
1442 if (mi != pwallet->mapWallet.end())
1445 for(const CMerkleTx& txWalletPrev : (*mi).second.vtxPrev)
1446 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1448 else if (mapWalletPrev.count(hash))
1450 tx = *mapWalletPrev[hash];
1452 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1458 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1462 int nDepth = tx.SetMerkleBranch();
1463 vtxPrev.push_back(tx);
1465 if (nDepth < COPY_DEPTH)
1467 for(const CTxIn& txin : tx.vin)
1468 vWorkQueue.push_back(txin.prevout.hash);
1474 reverse(vtxPrev.begin(), vtxPrev.end());
1477 bool CWalletTx::WriteToDisk()
1479 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1482 // Scan the block chain (starting in pindexStart) for transactions
1483 // from or to us. If fUpdate is true, found transactions that already
1484 // exist in the wallet will be updated.
1485 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1489 CBlockIndex* pindex = pindexStart;
1495 block.ReadFromDisk(pindex, true);
1496 for(CTransaction& tx : block.vtx)
1498 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1501 pindex = pindex->pnext;
1507 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1510 tx.ReadFromDisk(COutPoint(hashTx, 0));
1511 if (AddToWalletIfInvolvingMe(tx, NULL, true))
1516 void CWallet::ReacceptWalletTransactions()
1519 bool fRepeat = true;
1524 vector<CDiskTxPos> vMissingTx;
1525 for(auto& item : mapWallet)
1527 auto& wtx = item.second;
1528 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1532 bool fUpdated = false;
1533 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1535 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1536 if (txindex.vSpent.size() != wtx.vout.size())
1538 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1541 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1545 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1549 vMissingTx.push_back(txindex.vSpent[i]);
1554 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1561 // Re-accept any txes of ours that aren't already in a block
1562 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1563 wtx.AcceptWalletTransaction(txdb, false);
1566 if (!vMissingTx.empty())
1568 // TODO: optimize this to scan just part of the block chain?
1569 if (ScanForWalletTransactions(pindexGenesisBlock))
1570 fRepeat = true; // Found missing transactions: re-do re-accept.
1575 bool CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1577 auto hash = GetHash();
1578 if (IsCoinBase() || IsCoinStake() || txdb.ContainsTx(hash) || !InMempool())
1581 for(auto it = vtxPrev.begin(); it != vtxPrev.end(); it++)
1583 const CMerkleTx& tx = *it;
1584 auto hash = tx.GetHash();
1586 if (tx.IsCoinBase() || tx.IsCoinStake())
1589 if (!txdb.ContainsTx(hash))
1590 RelayTransaction((CTransaction)tx, hash);
1593 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1594 RelayTransaction((CTransaction)*this, hash);
1598 bool CWalletTx::RelayWalletTransaction()
1601 return RelayWalletTransaction(txdb);
1604 vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1606 vector<uint256> result;
1609 // Sort them in chronological order
1610 map<unsigned int, CWalletTx*> mapSorted;
1611 for(auto& item : mapWallet)
1613 auto& wtx = item.second;
1614 // Don't rebroadcast if newer than nTime:
1615 if (wtx.nTimeReceived > nTime)
1617 mapSorted.insert({ wtx.nTimeReceived, &wtx });
1619 for(auto& item : mapSorted)
1621 auto& wtx = *item.second;
1622 if (wtx.RelayWalletTransaction())
1623 result.push_back(wtx.GetHash());
1628 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
1630 auto nNow = GetTime();
1632 // Do this infrequently and randomly to avoid giving away
1633 // that these are our transactions.
1634 if (nNow < nNextResend)
1636 bool fFirst = (nNextResend == 0);
1637 nNextResend = PoissonNextSend(nNow, 5*60);
1641 // Only do it if there's been a new block since last time
1642 if (nBestBlockTime < nLastResend)
1646 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1648 auto relayed = ResendWalletTransactionsBefore(nBestBlockTime - 5*60);
1649 if (!relayed.empty())
1650 printf("CWallet::ResendWalletTransactions: rebroadcast %" PRIszu " unconfirmed transactions\n", relayed.size());
1654 //////////////////////////////////////////////////////////////////////////////
1660 int64_t CWallet::GetBalance() const
1665 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1667 const CWalletTx* pcoin = &(*it).second;
1668 if (pcoin->IsTrusted())
1669 nTotal += pcoin->GetAvailableCredit();
1676 int64_t CWallet::GetWatchOnlyBalance() const
1681 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1683 const CWalletTx* pcoin = &(*it).second;
1684 if (pcoin->IsTrusted())
1685 nTotal += pcoin->GetAvailableWatchCredit();
1692 int64_t CWallet::GetUnconfirmedBalance() const
1697 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1699 const CWalletTx* pcoin = &(*it).second;
1700 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1701 nTotal += pcoin->GetAvailableCredit();
1707 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1712 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1714 const CWalletTx* pcoin = &(*it).second;
1715 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1716 nTotal += pcoin->GetAvailableWatchCredit();
1722 int64_t CWallet::GetImmatureBalance() const
1727 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1729 const CWalletTx* pcoin = &(*it).second;
1730 nTotal += pcoin->GetImmatureCredit();
1736 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1741 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1743 const CWalletTx* pcoin = &(*it).second;
1744 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1750 // populate vCoins with vector of spendable COutputs
1751 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1757 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1759 const CWalletTx* pcoin = &(*it).second;
1761 if (!pcoin->IsFinal())
1764 if (fOnlyConfirmed && !pcoin->IsTrusted())
1767 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1770 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1773 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1774 auto mine = IsMine(pcoin->vout[i]);
1775 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1776 pcoin->vout[i].nValue >= nMinimumInputValue &&
1777 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1779 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1786 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1792 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1794 const CWalletTx* pcoin = &(*it).second;
1796 if (!pcoin->IsFinal())
1799 if(pcoin->GetDepthInMainChain() < nConf)
1802 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1803 auto mine = IsMine(pcoin->vout[i]);
1805 // ignore coin if it was already spent or we don't own it
1806 if (pcoin->IsSpent(i) || mine == MINE_NO)
1809 // if coin value is between required limits then add new item to vector
1810 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1811 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1817 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1818 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1820 vector<char> vfIncluded;
1822 vfBest.assign(vValue.size(), true);
1823 nBest = nTotalLower;
1825 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1827 vfIncluded.assign(vValue.size(), false);
1829 bool fReachedTarget = false;
1830 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1832 for (unsigned int i = 0; i < vValue.size(); i++)
1834 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1836 nTotal += vValue[i].first;
1837 vfIncluded[i] = true;
1838 if (nTotal >= nTargetValue)
1840 fReachedTarget = true;
1844 vfBest = vfIncluded;
1846 nTotal -= vValue[i].first;
1847 vfIncluded[i] = false;
1855 int64_t CWallet::GetStake() const
1859 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1861 const CWalletTx* pcoin = &(*it).second;
1862 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1863 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1868 int64_t CWallet::GetWatchOnlyStake() const
1872 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1874 const CWalletTx* pcoin = &(*it).second;
1875 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1876 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1881 int64_t CWallet::GetNewMint() const
1885 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1887 const CWalletTx* pcoin = &(*it).second;
1888 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1889 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1894 int64_t CWallet::GetWatchOnlyNewMint() const
1898 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1900 const CWalletTx* pcoin = &(*it).second;
1901 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1902 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1907 bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
1909 setCoinsRet.clear();
1912 // List of values less than target
1913 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1914 coinLowestLarger.first = numeric_limits<int64_t>::max();
1915 coinLowestLarger.second.first = NULL;
1916 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1917 int64_t nTotalLower = 0;
1919 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1921 for(const COutput &output : vCoins)
1923 if (!output.fSpendable)
1926 const CWalletTx *pcoin = output.tx;
1928 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1933 // Follow the timestamp rules
1934 if (pcoin->nTime > nSpendTime)
1937 auto n = pcoin->vout[i].nValue;
1938 auto coin = make_pair(n, make_pair(pcoin, i));
1940 if (n == nTargetValue)
1942 setCoinsRet.insert(coin.second);
1943 nValueRet += coin.first;
1946 else if (n < nTargetValue + CENT)
1948 vValue.push_back(coin);
1951 else if (n < coinLowestLarger.first)
1953 coinLowestLarger = coin;
1957 if (nTotalLower == nTargetValue)
1959 for (unsigned int i = 0; i < vValue.size(); ++i)
1961 setCoinsRet.insert(vValue[i].second);
1962 nValueRet += vValue[i].first;
1967 if (nTotalLower < nTargetValue)
1969 if (coinLowestLarger.second.first == NULL)
1971 setCoinsRet.insert(coinLowestLarger.second);
1972 nValueRet += coinLowestLarger.first;
1976 // Solve subset sum by stochastic approximation
1977 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1978 vector<char> vfBest;
1981 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1982 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1983 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1985 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1986 // or the next bigger coin is closer), return the bigger coin
1987 if (coinLowestLarger.second.first &&
1988 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1990 setCoinsRet.insert(coinLowestLarger.second);
1991 nValueRet += coinLowestLarger.first;
1994 for (unsigned int i = 0; i < vValue.size(); i++)
1997 setCoinsRet.insert(vValue[i].second);
1998 nValueRet += vValue[i].first;
2001 if (fDebug && GetBoolArg("-printpriority"))
2004 printf("SelectCoins() best subset: ");
2005 for (unsigned int i = 0; i < vValue.size(); i++)
2007 printf("%s ", FormatMoney(vValue[i].first).c_str());
2008 printf("total %s\n", FormatMoney(nBest).c_str());
2015 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
2017 vector<COutput> vCoins;
2018 AvailableCoins(vCoins, true, coinControl);
2020 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2021 if (coinControl && coinControl->HasSelected())
2023 for(const COutput& out : vCoins)
2027 nValueRet += out.tx->vout[out.i].nValue;
2028 setCoinsRet.insert({ out.tx, out.i });
2030 return (nValueRet >= nTargetValue);
2033 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2034 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2035 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
2038 // Select some coins without random shuffle or best subset approximation
2039 bool CWallet::SelectCoinsSimple(int64_t nTargetValue, int64_t nMinValue, int64_t nMaxValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
2041 vector<COutput> vCoins;
2042 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
2044 setCoinsRet.clear();
2047 for(COutput output : vCoins)
2049 if(!output.fSpendable)
2051 const CWalletTx *pcoin = output.tx;
2054 // Ignore immature coins
2055 if (pcoin->GetBlocksToMaturity() > 0)
2058 // Stop if we've chosen enough inputs
2059 if (nValueRet >= nTargetValue)
2062 // Follow the timestamp rules
2063 if (pcoin->nTime > nSpendTime)
2066 auto n = pcoin->vout[i].nValue;
2067 auto coin = make_pair(n, make_pair(pcoin, i));
2069 if (n >= nTargetValue)
2071 // If input value is greater or equal to target then simply insert
2072 // it into the current subset and exit
2073 setCoinsRet.insert(coin.second);
2074 nValueRet += coin.first;
2077 else if (n < nTargetValue + CENT)
2079 setCoinsRet.insert(coin.second);
2080 nValueRet += coin.first;
2087 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2090 for(auto& s : vecSend)
2096 if (vecSend.empty() || nValue < 0)
2099 wtxNew.BindWallet(this);
2102 LOCK2(cs_main, cs_wallet);
2103 // txdb must be opened before the mapWallet lock
2106 nFeeRet = nTransactionFee;
2110 wtxNew.vout.clear();
2111 wtxNew.fFromMe = true;
2113 auto nTotalValue = nValue + nFeeRet;
2114 double dPriority = 0;
2115 // vouts to the payees
2116 for(const auto& s : vecSend)
2117 wtxNew.vout.push_back(CTxOut(s.second, s.first));
2119 // Choose coins to use
2120 set<pair<const CWalletTx*,unsigned int> > setCoins;
2121 int64_t nValueIn = 0;
2122 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
2124 for(auto& pcoin : setCoins)
2126 auto nCredit = pcoin.first->vout[pcoin.second].nValue;
2127 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
2130 auto nChange = nValueIn - nValue - nFeeRet;
2133 // Fill a vout to ourself
2134 // TODO: pass in scriptChange instead of reservekey so
2135 // change transaction isn't always pay-to-bitcoin-address
2136 CScript scriptChange;
2138 // coin control: send change to custom address
2139 if (coinControl && coinControl->destChange.IsValid())
2140 scriptChange.SetAddress(coinControl->destChange);
2142 // no coin control: send change to newly generated address
2145 // Note: We use a new key here to keep it from being obvious which side is the change.
2146 // The drawback is that by not reusing a previous key, the change may be lost if a
2147 // backup is restored, if the backup doesn't have the new private key for the change.
2148 // If we reused the old key, it would be possible to add code to look for and
2149 // rediscover unknown transactions that were written with keys of ours to recover
2150 // post-backup change.
2152 // Reserve a new key pair from key pool
2153 auto vchPubKey = reservekey.GetReservedKey();
2155 scriptChange.SetDestination(vchPubKey.GetID());
2158 // Insert change txn at random position:
2159 auto position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
2160 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
2163 reservekey.ReturnKey();
2166 for(const auto& coin : setCoins)
2167 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
2171 for(const auto& coin : setCoins)
2172 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
2176 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
2177 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2179 dPriority /= nBytes;
2181 // Check that enough fee is included
2182 bool fAllowFree = CTransaction::AllowFree(dPriority);
2183 auto nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
2184 auto nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2186 if (nFeeRet < max(nPayFee, nMinFee))
2188 nFeeRet = max(nPayFee, nMinFee);
2192 // Fill vtxPrev by copying from previous transactions vtxPrev
2193 wtxNew.AddSupportingTransactions(txdb);
2194 wtxNew.fTimeReceivedIsTxTime = true;
2203 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2205 vector< pair<CScript, int64_t> > vecSend;
2206 vecSend.push_back({ scriptPubKey, nValue });
2207 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
2210 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
2212 auto nTimeWeight = GetWeight(nTime, GetTime());
2214 // If time weight is lower or equal to zero then weight is zero.
2215 if (nTimeWeight <= 0)
2221 auto bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
2222 nWeight = bnCoinDayWeight.getuint64();
2225 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
2227 auto nBalance = GetBalance();
2229 if (nAmount > nBalance)
2233 int64_t nValueIn = 0;
2234 set<pair<const CWalletTx*,unsigned int> > setCoins;
2236 // Simple coins selection - no randomization
2237 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
2240 if (setCoins.empty())
2244 vector<const CWalletTx*> vwtxPrev;
2246 // Reserve a new key pair from key pool
2247 CReserveKey reservekey(this);
2248 auto vchPubKey = reservekey.GetReservedKey();
2251 CScript scriptOutput;
2252 scriptOutput.SetDestination(vchPubKey.GetID());
2255 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2258 for(auto& pcoin : setCoins)
2260 auto nCredit = pcoin.first->vout[pcoin.second].nValue;
2262 // Add current coin to inputs list and add its credit to transaction output
2263 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2264 wtxNew.vout[0].nValue += nCredit;
2265 vwtxPrev.push_back(pcoin.first);
2268 // Replaced with estimation for performance purposes
2270 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2271 const CWalletTx *txin = vwtxPrev[i];
2273 // Sign scripts to get actual transaction size for fee calculation
2274 if (!SignSignature(*this, *txin, wtxNew, i))
2279 // Assuming that average scriptsig size is 110 bytes
2280 auto nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2281 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
2283 double dFinalPriority = dWeight /= nBytes;
2284 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2286 // Get actual transaction fee according to its estimated size and priority
2287 auto nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2289 // Prepare transaction for commit if sum is enough ot its size is too big
2290 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
2292 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2294 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2295 const CWalletTx *txin = vwtxPrev[i];
2298 if (!SignSignature(*this, *txin, wtxNew, i))
2302 // Try to commit, return false on failure
2303 if (!CommitTransaction(wtxNew, reservekey))
2306 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2308 dWeight = 0; // Reset all temporary values
2311 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2315 // Create transactions if there are some unhandled coins left
2316 if (wtxNew.vout[0].nValue > 0) {
2317 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2319 double dFinalPriority = dWeight /= nBytes;
2320 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2322 // Get actual transaction fee according to its size and priority
2323 auto nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2325 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2327 if (wtxNew.vout[0].nValue <= 0)
2330 for (uint32_t i = 0; i < wtxNew.vin.size(); i++) {
2331 const CWalletTx *txin = vwtxPrev[i];
2333 // Sign all scripts again
2334 if (!SignSignature(*this, *txin, wtxNew, i))
2338 // Try to commit, return false on failure
2339 if (!CommitTransaction(wtxNew, reservekey))
2342 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2348 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
2351 if (!GetTransaction(hashTx, wtx))
2352 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
2354 vector<valtype> vSolutions;
2355 txnouttype whichType;
2356 CScript scriptPubKeyOut;
2357 auto scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
2358 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
2359 return error("CreateCoinStake : failed to parse kernel\n");
2361 if (fDebug && GetBoolArg("-printcoinstake"))
2362 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
2364 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
2365 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
2367 if (whichType == TX_PUBKEYHASH) // pay to address type
2369 // convert to pay to public key type
2370 if (!GetKey(uint160(vSolutions[0]), key))
2371 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2373 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
2375 if (whichType == TX_PUBKEY)
2377 auto& vchPubKey = vSolutions[0];
2378 if (!GetKey(Hash160(vchPubKey), key))
2379 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2380 if (key.GetPubKey() != vchPubKey)
2381 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
2382 scriptPubKeyOut = scriptPubKeyKernel;
2385 // The following combine threshold is important to security
2386 // Should not be adjusted if you don't understand the consequences
2387 auto nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
2389 auto nBalance = GetBalance();
2390 auto nCredit = wtx.vout[nOut].nValue;
2395 // List of constake dependencies
2396 vector<const CWalletTx*> vwtxPrev;
2397 vwtxPrev.push_back(&wtx);
2399 // Set generation time, and kernel input
2400 txNew.nTime = nGenerationTime;
2401 txNew.vin.push_back(CTxIn(hashTx, nOut));
2403 // Mark coin stake transaction with empty vout[0]
2404 CScript scriptEmpty;
2405 scriptEmpty.clear();
2406 txNew.vout.push_back(CTxOut(0, scriptEmpty));
2408 if (fDebug && GetBoolArg("-printcoinstake"))
2409 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2411 int64_t nValueIn = 0;
2413 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
2416 if (setCoins.empty())
2419 bool fDontSplitCoins = false;
2420 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
2422 // Only one output for old kernel inputs
2423 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2425 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
2427 // * Value is higher than 0.01 NVC;
2428 // * Only add inputs of the same key/address as kernel;
2429 // * Input hash and kernel parent hash should be different.
2430 for(auto pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
2432 // Stop adding more inputs if already too many inputs
2433 if (txNew.vin.size() >= 100)
2435 // Stop adding more inputs if value is already pretty significant
2436 if (nCredit > nCombineThreshold)
2438 // Stop adding inputs if reached reserve limit
2439 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
2442 auto nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
2444 // Do not add input that is still too young
2445 if (nTimeWeight < nStakeMaxAge)
2447 // Do not add input if key/address is not the same as kernel
2448 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2450 // Do not add input if parents are the same
2451 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2453 // Do not add additional significant input
2454 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2457 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2458 nCredit += pcoin->first->vout[pcoin->second].nValue;
2459 vwtxPrev.push_back(pcoin->first);
2462 fDontSplitCoins = true;
2466 auto nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2468 if (fDebug && GetBoolArg("-printcoinstake"))
2469 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2471 if (nCredit > nSplitThreshold)
2473 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2474 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2475 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2477 if (fDebug && GetBoolArg("-printcoinstake"))
2478 printf("CreateCoinStake : splitting coinstake\n");
2482 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2483 fDontSplitCoins = true;
2487 // Calculate coin age reward
2490 if (!txNew.GetCoinAge(txdb, nCoinAge))
2491 return error("CreateCoinStake : failed to calculate coin age\n");
2492 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2494 int64_t nMinFee = 0;
2497 // Set output amount
2498 if (fDontSplitCoins)
2499 txNew.vout[1].nValue = nCredit - nMinFee;
2502 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2503 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2508 for(const CWalletTx* pcoin : vwtxPrev)
2510 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2511 return error("CreateCoinStake : failed to sign coinstake\n");
2515 auto nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2516 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2517 return error("CreateCoinStake : exceeded coinstake size limit\n");
2519 // Check enough fee is paid
2520 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2522 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2523 continue; // try signing again
2527 if (fDebug && GetBoolArg("-printfee"))
2528 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2533 // Successfully created coinstake
2537 // Call after CreateTransaction unless you want to abort
2538 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2541 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2543 // Track how many getdata requests our transaction gets
2544 mapRequestCount[wtxNew.GetHash()] = 0;
2546 // Try to broadcast before saving
2547 if (!wtxNew.AcceptToMemoryPool())
2549 // This must not fail. The transaction has already been signed.
2550 printf("CommitTransaction() : Error: Transaction not valid");
2554 wtxNew.RelayWalletTransaction();
2557 LOCK2(cs_main, cs_wallet);
2559 // This is only to keep the database open to defeat the auto-flush for the
2560 // duration of this scope. This is the only place where this optimization
2561 // maybe makes sense; please don't do it anywhere else.
2562 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2564 // Take key pair from key pool so it won't be used again
2565 reservekey.KeepKey();
2567 // Add tx to wallet, because if it has change it's also ours,
2568 // otherwise just for transaction history.
2569 AddToWallet(wtxNew);
2571 // Mark old coins as spent
2572 for(const CTxIn& txin : wtxNew.vin)
2574 CWalletTx &coin = mapWallet[txin.prevout.hash];
2575 coin.BindWallet(this);
2576 coin.MarkSpent(txin.prevout.n);
2578 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2579 vMintingWalletUpdated.push_back(coin.GetHash());
2592 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2596 return _("Invalid amount");
2597 if (nValue + nTransactionFee > GetBalance())
2598 return _("Insufficient funds");
2600 CReserveKey reservekey(this);
2601 int64_t nFeeRequired;
2605 string strError = _("Error: Wallet locked, unable to create transaction ");
2606 printf("SendMoney() : %s", strError.c_str());
2609 if (fWalletUnlockMintOnly)
2611 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2612 printf("SendMoney() : %s", strError.c_str());
2615 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2618 if (nValue + nFeeRequired > GetBalance())
2619 strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
2621 strError = _("Error: Transaction creation failed ");
2622 printf("SendMoney() : %s", strError.c_str());
2626 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2629 if (!CommitTransaction(wtxNew, reservekey))
2630 return _("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.");
2635 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2639 fFirstRunRet = false;
2640 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2641 if (nLoadWalletRet == DB_NEED_REWRITE)
2643 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2646 // Note: can't top-up keypool here, because wallet is locked.
2647 // User will be prompted to unlock wallet the next operation
2648 // the requires a new key.
2652 if (nLoadWalletRet != DB_LOAD_OK)
2653 return nLoadWalletRet;
2654 fFirstRunRet = !vchDefaultKey.IsValid();
2656 NewThread(ThreadFlushWalletDB, &strWalletFile);
2660 DBErrors CWallet::ZapWalletTx()
2664 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2665 if (nZapWalletTxRet == DB_NEED_REWRITE)
2667 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2671 // Note: can't top-up keypool here, because wallet is locked.
2672 // User will be prompted to unlock wallet the next operation
2673 // the requires a new key.
2677 if (nZapWalletTxRet != DB_LOAD_OK)
2678 return nZapWalletTxRet;
2683 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2685 return SetAddressBookName(CBitcoinAddress(address), strName);
2688 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
2690 auto mi = mapAddressBook.find(address);
2691 mapAddressBook[address] = strName;
2692 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2695 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
2698 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
2700 mapAddressBook.erase(address);
2701 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2704 return CWalletDB(strWalletFile).EraseName(address.ToString());
2708 void CWallet::PrintWallet(const CBlock& block)
2712 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2714 auto& wtx = mapWallet[block.vtx[1].GetHash()];
2715 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2717 else if (mapWallet.count(block.vtx[0].GetHash()))
2719 auto& wtx = mapWallet[block.vtx[0].GetHash()];
2720 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2726 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2730 auto mi = mapWallet.find(hashTx);
2731 if (mi != mapWallet.end())
2740 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2744 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2747 vchDefaultKey = vchPubKey;
2751 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2753 if (!pwallet->fFileBacked)
2755 strWalletFileOut = pwallet->strWalletFile;
2760 // Mark old keypool keys as used,
2761 // and generate all new keys
2763 bool CWallet::NewKeyPool(unsigned int nSize)
2767 CWalletDB walletdb(strWalletFile);
2768 for(int64_t nIndex : setKeyPool)
2769 walletdb.ErasePool(nIndex);
2779 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2781 for (uint64_t i = 0; i < nKeys; i++)
2784 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2785 setKeyPool.insert(nIndex);
2787 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2792 bool CWallet::TopUpKeyPool(unsigned int nSize)
2800 CWalletDB walletdb(strWalletFile);
2803 uint64_t nTargetSize;
2805 nTargetSize = nSize;
2807 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2809 while (setKeyPool.size() < (nTargetSize + 1))
2812 if (!setKeyPool.empty())
2813 nEnd = *(--setKeyPool.end()) + 1;
2814 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2815 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2816 setKeyPool.insert(nEnd);
2817 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2823 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2826 keypool.vchPubKey = CPubKey();
2833 // Get the oldest key
2834 if(setKeyPool.empty())
2837 CWalletDB walletdb(strWalletFile);
2839 nIndex = *(setKeyPool.begin());
2840 setKeyPool.erase(setKeyPool.begin());
2841 if (!walletdb.ReadPool(nIndex, keypool))
2842 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2843 if (!HaveKey(keypool.vchPubKey.GetID()))
2844 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2845 assert(keypool.vchPubKey.IsValid());
2846 if (fDebug && GetBoolArg("-printkeypool"))
2847 printf("keypool reserve %" PRId64 "\n", nIndex);
2851 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2854 LOCK2(cs_main, cs_wallet);
2855 CWalletDB walletdb(strWalletFile);
2857 int64_t nIndex = 1 + *(--setKeyPool.end());
2858 if (!walletdb.WritePool(nIndex, keypool))
2859 throw runtime_error("AddReserveKey() : writing added key failed");
2860 setKeyPool.insert(nIndex);
2866 void CWallet::KeepKey(int64_t nIndex)
2868 // Remove from key pool
2871 CWalletDB walletdb(strWalletFile);
2872 walletdb.ErasePool(nIndex);
2875 printf("keypool keep %" PRId64 "\n", nIndex);
2878 void CWallet::ReturnKey(int64_t nIndex)
2880 // Return to key pool
2883 setKeyPool.insert(nIndex);
2886 printf("keypool return %" PRId64 "\n", nIndex);
2889 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2895 ReserveKeyFromKeyPool(nIndex, keypool);
2898 if (fAllowReuse && vchDefaultKey.IsValid())
2900 result = vchDefaultKey;
2903 if (IsLocked()) return false;
2904 result = GenerateNewKey();
2908 result = keypool.vchPubKey;
2913 int64_t CWallet::GetOldestKeyPoolTime()
2917 ReserveKeyFromKeyPool(nIndex, keypool);
2921 return keypool.nTime;
2924 map<CBitcoinAddress, int64_t> CWallet::GetAddressBalances()
2926 map<CBitcoinAddress, int64_t> balances;
2930 for(auto& walletEntry : mapWallet)
2932 CWalletTx *pcoin = &walletEntry.second;
2934 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2937 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2940 int nDepth = pcoin->GetDepthInMainChain();
2941 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2944 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2946 CBitcoinAddress addr;
2947 if (!IsMine(pcoin->vout[i]))
2949 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, addr))
2952 auto n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2954 if (!balances.count(addr))
2956 balances[addr] += n;
2964 set< set<CBitcoinAddress> > CWallet::GetAddressGroupings()
2966 set< set<CBitcoinAddress> > groupings;
2967 set<CBitcoinAddress> grouping;
2969 for(auto& walletEntry : mapWallet)
2971 CWalletTx *pcoin = &walletEntry.second;
2973 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2975 // group all input addresses with each other
2976 for(CTxIn txin : pcoin->vin)
2978 CBitcoinAddress address;
2979 if(!ExtractAddress(*this, mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2981 grouping.insert(address);
2984 // group change with input addresses
2985 for(CTxOut txout : pcoin->vout)
2986 if (IsChange(txout))
2988 auto tx = mapWallet[pcoin->vin[0].prevout.hash];
2989 CBitcoinAddress txoutAddr;
2990 if(!ExtractAddress(*this, txout.scriptPubKey, txoutAddr))
2992 grouping.insert(txoutAddr);
2994 groupings.insert(grouping);
2998 // group lone addrs by themselves
2999 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3000 if (IsMine(pcoin->vout[i]))
3002 CBitcoinAddress address;
3003 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, address))
3005 grouping.insert(address);
3006 groupings.insert(grouping);
3011 set< set<CBitcoinAddress>* > uniqueGroupings; // a set of pointers to groups of addresses
3012 map< CBitcoinAddress, set<CBitcoinAddress>* > setmap; // map addresses to the unique group containing it
3013 for(auto& grouping : groupings)
3015 // make a set of all the groups hit by this new group
3016 set< set<CBitcoinAddress>* > hits;
3017 map< CBitcoinAddress, set<CBitcoinAddress>* >::iterator it;
3018 for(auto& address : grouping)
3019 if ((it = setmap.find(address)) != setmap.end())
3020 hits.insert((*it).second);
3022 // merge all hit groups into a new single group and delete old groups
3023 set<CBitcoinAddress>* merged = new set<CBitcoinAddress>(grouping);
3024 for(auto hit : hits)
3026 merged->insert(hit->begin(), hit->end());
3027 uniqueGroupings.erase(hit);
3030 uniqueGroupings.insert(merged);
3033 for(CBitcoinAddress element : *merged)
3034 setmap[element] = merged;
3037 set< set<CBitcoinAddress> > ret;
3038 for(auto uniqueGrouping : uniqueGroupings)
3040 ret.insert(*uniqueGrouping);
3041 delete uniqueGrouping;
3047 // ppcoin: check 'spent' consistency between wallet and txindex
3048 // ppcoin: fix wallet spent state according to txindex
3049 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
3052 nBalanceInQuestion = 0;
3055 vector<CWalletTx*> vCoins;
3056 vCoins.reserve(mapWallet.size());
3057 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
3058 vCoins.push_back(&(*it).second);
3061 for(auto pcoin : vCoins)
3063 // Find the corresponding transaction index
3065 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
3067 for (unsigned int n=0; n < pcoin->vout.size(); n++)
3069 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
3071 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
3072 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3074 nBalanceInQuestion += pcoin->vout[n].nValue;
3077 pcoin->MarkUnspent(n);
3078 pcoin->WriteToDisk();
3081 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
3083 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
3084 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3086 nBalanceInQuestion += pcoin->vout[n].nValue;
3089 pcoin->MarkSpent(n);
3090 pcoin->WriteToDisk();
3096 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
3098 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
3101 EraseFromWallet(pcoin->GetHash());
3107 // ppcoin: disable transaction (only for coinstake)
3108 void CWallet::DisableTransaction(const CTransaction &tx)
3110 if (!tx.IsCoinStake() || !IsFromMe(tx))
3111 return; // only disconnecting coinstake requires marking input unspent
3114 for(const auto& txin : tx.vin)
3116 auto mi = mapWallet.find(txin.prevout.hash);
3117 if (mi != mapWallet.end())
3119 auto& prev = (*mi).second;
3120 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
3122 prev.MarkUnspent(txin.prevout.n);
3129 CPubKey CReserveKey::GetReservedKey()
3134 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3136 vchPubKey = keypool.vchPubKey;
3139 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
3140 vchPubKey = pwallet->vchDefaultKey;
3143 assert(vchPubKey.IsValid());
3147 void CReserveKey::KeepKey()
3150 pwallet->KeepKey(nIndex);
3152 vchPubKey = CPubKey();
3155 void CReserveKey::ReturnKey()
3158 pwallet->ReturnKey(nIndex);
3160 vchPubKey = CPubKey();
3163 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3167 CWalletDB walletdb(strWalletFile);
3169 LOCK2(cs_main, cs_wallet);
3170 for(const int64_t& id : setKeyPool)
3173 if (!walletdb.ReadPool(id, keypool))
3174 throw runtime_error("GetAllReserveKeyHashes() : read failed");
3175 assert(keypool.vchPubKey.IsValid());
3176 auto keyID = keypool.vchPubKey.GetID();
3177 if (!HaveKey(keyID))
3178 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
3179 setAddress.insert(keyID);
3183 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3187 // Only notify UI if this transaction is in this wallet
3188 auto mi = mapWallet.find(hashTx);
3189 if (mi != mapWallet.end())
3191 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3192 vMintingWalletUpdated.push_back(hashTx);
3197 void CWallet::GetAddresses(map<CBitcoinAddress, int64_t> &mapAddresses) const {
3198 mapAddresses.clear();
3200 // get birth times for keys with metadata
3201 for (auto it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
3202 mapAddresses[it->first] = it->second.nCreateTime ? it->second.nCreateTime : 0;
3205 for (auto it = mapWallet.begin(); it != mapWallet.end(); it++) {
3206 // iterate over all wallet transactions...
3207 const auto &wtx = (*it).second;
3208 if (wtx.hashBlock == 0)
3209 continue; // skip unconfirmed transactions
3211 for(auto it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
3212 const CTxOut &out = (*it2);
3213 // iterate over all their outputs
3214 CBitcoinAddress addressRet;
3215 if (ExtractAddress(*this, out.scriptPubKey, addressRet)) {
3216 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
3217 mapAddresses[addressRet] = wtx.nTime;
3220 // multisig output affects more than one key
3221 vector<CKeyID> vAffected;
3222 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
3224 for(auto it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
3225 CBitcoinAddress addrAffected(*it3);
3226 if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
3227 mapAddresses[addrAffected] = wtx.nTime;
3235 void CWallet::ClearOrphans()
3237 list<uint256> orphans;
3240 for(auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
3242 const CWalletTx *wtx = &(*it).second;
3243 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
3245 orphans.push_back(wtx->GetHash());
3249 for(auto it = orphans.begin(); it != orphans.end(); ++it)
3250 EraseFromWallet(*it);