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.
12 #include "ui_interface.h"
15 #include "coincontrol.h"
18 #include <openssl/bio.h>
23 extern int64_t nReserveBalance;
25 //////////////////////////////////////////////////////////////////////////////
35 CWallet::CWallet(std::string strWalletFileIn)
39 strWalletFile = strWalletFileIn;
43 void CWallet::SetNull()
45 nWalletVersion = FEATURE_BASE;
46 nWalletMaxVersion = FEATURE_BASE;
49 pwalletdbEncryption = NULL;
50 pwalletdbDecryption = NULL;
59 struct CompareValueOnly
61 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
62 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
64 return t1.first < t2.first;
68 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
71 auto it = mapWallet.find(hash);
72 if (it == mapWallet.end())
77 CPubKey CWallet::GenerateNewKey()
79 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
83 key.MakeNewKey(fCompressed);
85 // Compressed public keys were introduced in version 0.6.0
87 SetMinVersion(FEATURE_COMPRPUBKEY);
89 auto pubkey = key.GetPubKey();
91 // Create new metadata
92 auto nCreationTime = GetTime();
93 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = CKeyMetadata(nCreationTime);
94 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
95 nTimeFirstKey = nCreationTime;
98 throw runtime_error("CWallet::GenerateNewKey() : AddKey failed");
99 return key.GetPubKey();
102 CMalleableKeyView CWallet::GenerateNewMalleableKey()
104 RandAddSeedPerfmon();
106 // Compressed public keys were introduced in version 0.6.0
107 SetMinVersion(FEATURE_MALLKEY);
111 const CMalleableKeyView &keyView(mKey);
113 // Create new metadata
114 auto nCreationTime = GetTime();
115 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = CKeyMetadata(nCreationTime);
116 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
117 nTimeFirstKey = nCreationTime;
120 throw runtime_error("CWallet::GenerateNewMalleableKey() : AddKey failed");
121 return CMalleableKeyView(mKey);
124 bool CWallet::AddKey(const CKey& key)
126 auto pubkey = key.GetPubKey();
127 if (!CCryptoKeyStore::AddKey(key))
132 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(pubkey.GetID())]);
136 bool CWallet::AddKey(const CMalleableKey& mKey)
138 auto keyView = CMalleableKeyView(mKey);
139 auto vchSecretH = mKey.GetSecretH();
140 if (!CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH))
145 return CWalletDB(strWalletFile).WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
149 bool CWallet::AddCryptedMalleableKey(const CMalleableKeyView& keyView, const vector<unsigned char> &vchCryptedSecretH)
151 if (!CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH))
159 CBitcoinAddress addr(keyView.GetMalleablePubKey());
160 if (pwalletdbEncryption)
161 return pwalletdbEncryption->WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
163 return CWalletDB(strWalletFile).WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
169 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
171 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
174 // check if we need to remove from watch-only
176 script.SetDestination(vchPubKey.GetID());
177 if (HaveWatchOnly(script))
178 RemoveWatchOnly(script);
184 CBitcoinAddress addr(vchPubKey.GetID());
185 if (pwalletdbEncryption)
186 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
188 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
193 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
195 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
196 nTimeFirstKey = meta.nCreateTime;
198 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = meta;
202 bool CWallet::LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
204 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
205 nTimeFirstKey = metadata.nCreateTime;
207 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = metadata;
211 bool CWallet::LoadMinVersion(int nVersion)
213 nWalletVersion = nVersion;
214 nWalletMaxVersion = max(nWalletMaxVersion, nVersion);
218 bool CWallet::AddCScript(const CScript& redeemScript)
220 if (!CCryptoKeyStore::AddCScript(redeemScript))
224 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
227 bool CWallet::LoadCScript(const CScript& redeemScript)
229 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
230 * that never can be redeemed. However, old wallets may still contain
231 * these. Do not add them to the wallet and warn. */
232 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
234 auto strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
235 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",
236 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
240 return CCryptoKeyStore::AddCScript(redeemScript);
244 bool CWallet::AddWatchOnly(const CScript &dest)
246 if (!CCryptoKeyStore::AddWatchOnly(dest))
248 nTimeFirstKey = 1; // No birthday information for watch-only keys.
249 NotifyWatchonlyChanged(true);
252 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
255 bool CWallet::RemoveWatchOnly(const CScript &dest)
258 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
260 if (!HaveWatchOnly())
261 NotifyWatchonlyChanged(false);
263 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
269 bool CWallet::LoadWatchOnly(const CScript &dest)
271 return CCryptoKeyStore::AddWatchOnly(dest);
274 // ppcoin: optional setting to unlock wallet for block minting only;
275 // serves to disable the trivial sendmoney when OS account compromised
276 bool fWalletUnlockMintOnly = false;
278 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
284 CKeyingMaterial vMasterKey;
288 for(const auto& pMasterKey : mapMasterKeys)
290 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
292 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
294 if (CCryptoKeyStore::Unlock(vMasterKey))
301 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
303 bool fWasLocked = IsLocked();
310 CKeyingMaterial vMasterKey;
311 for(auto& pMasterKey : mapMasterKeys)
313 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
315 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
317 if (CCryptoKeyStore::Unlock(vMasterKey))
319 auto nStartTime = GetTimeMillis();
320 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
321 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
322 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
324 nStartTime = GetTimeMillis();
325 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
326 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
327 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
329 if (pMasterKey.second.nDeriveIterations < 25000)
330 pMasterKey.second.nDeriveIterations = 25000;
332 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
334 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
336 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
338 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
349 void CWallet::SetBestChain(const CBlockLocator& loc)
351 CWalletDB walletdb(strWalletFile);
352 walletdb.WriteBestBlock(loc);
355 // This class implements an addrIncoming entry that causes pre-0.4
356 // clients to crash on startup if reading a private-key-encrypted wallet.
357 class CCorruptAddress
362 if (nType & SER_DISK)
367 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
369 if (nWalletVersion >= nVersion)
372 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
373 if (fExplicit && nVersion > nWalletMaxVersion)
374 nVersion = FEATURE_LATEST;
376 nWalletVersion = nVersion;
378 if (nVersion > nWalletMaxVersion)
379 nWalletMaxVersion = nVersion;
383 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
384 if (nWalletVersion > 40000)
385 pwalletdb->WriteMinVersion(nWalletVersion);
393 bool CWallet::SetMaxVersion(int nVersion)
395 // cannot downgrade below current version
396 if (nWalletVersion > nVersion)
399 nWalletMaxVersion = nVersion;
404 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
409 CKeyingMaterial vMasterKey;
410 RandAddSeedPerfmon();
412 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
413 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
415 CMasterKey kMasterKey;
417 RandAddSeedPerfmon();
418 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
419 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
422 auto nStartTime = GetTimeMillis();
423 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
424 auto nDivider = GetTimeMillis() - nStartTime;
425 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
427 nStartTime = GetTimeMillis();
428 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
429 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
430 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
432 if (kMasterKey.nDeriveIterations < 25000)
433 kMasterKey.nDeriveIterations = 25000;
435 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
437 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
439 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
444 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
447 pwalletdbEncryption = new CWalletDB(strWalletFile);
448 if (!pwalletdbEncryption->TxnBegin())
450 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
453 if (!EncryptKeys(vMasterKey))
456 pwalletdbEncryption->TxnAbort();
457 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.
460 // Encryption was introduced in version 0.4.0
461 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
465 if (!pwalletdbEncryption->TxnCommit())
466 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.
468 delete pwalletdbEncryption;
469 pwalletdbEncryption = NULL;
473 Unlock(strWalletPassphrase);
477 // Need to completely rewrite the wallet file; if we don't, bdb might keep
478 // bits of the unencrypted private key in slack space in the database file.
479 CDB::Rewrite(strWalletFile);
482 NotifyStatusChanged(this);
487 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
493 CKeyingMaterial vMasterKey;
497 for(const auto& pMasterKey : mapMasterKeys)
499 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
501 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
503 if (!CCryptoKeyStore::Unlock(vMasterKey))
509 pwalletdbDecryption = new CWalletDB(strWalletFile);
510 if (!pwalletdbDecryption->TxnBegin())
514 if (!DecryptKeys(vMasterKey))
517 pwalletdbDecryption->TxnAbort();
518 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.
523 // Overwrite crypted keys
524 auto mi = mapKeys.begin();
525 while (mi != mapKeys.end())
528 key.SetSecret((*mi).second.first, (*mi).second.second);
529 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
530 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(mi->first)]);
534 auto mi2 = mapMalleableKeys.begin();
535 while (mi2 != mapMalleableKeys.end())
537 const auto &vchSecretH = mi2->second;
538 const auto &keyView = mi2->first;
539 pwalletdbDecryption->EraseCryptedMalleableKey(keyView);
540 pwalletdbDecryption->WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
545 auto mk = mapMasterKeys.begin();
546 while (mk != mapMasterKeys.end())
548 pwalletdbDecryption->EraseMasterKey((*mk).first);
552 if (!pwalletdbDecryption->TxnCommit())
553 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.
555 delete pwalletdbDecryption;
556 pwalletdbDecryption = NULL;
559 // Need to completely rewrite the wallet file; if we don't, bdb might keep
560 // encrypted private keys in the database file which can be a reason of consistency issues.
561 CDB::Rewrite(strWalletFile);
563 NotifyStatusChanged(this);
568 bool CWallet::GetPEM(const CKeyID &keyID, const string &fileName, const SecureString &strPassKey) const
570 BIO *pemOut = BIO_new_file(fileName.c_str(), "w");
572 return error("GetPEM() : failed to create file %s\n", fileName.c_str());
574 if (!GetKey(keyID, key))
575 return error("GetPEM() : failed to get key for address=%s\n", CBitcoinAddress(keyID).ToString().c_str());
576 bool result = key.WritePEM(pemOut, strPassKey);
581 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
583 int64_t nRet = nOrderPosNext++;
585 pwalletdb->WriteOrderPosNext(nOrderPosNext);
587 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
592 CWallet::TxItems CWallet::OrderedTxItems(list<CAccountingEntry>& acentries, string strAccount)
594 CWalletDB walletdb(strWalletFile);
596 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
599 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
600 // would make this much faster for applications that do this a lot.
601 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
603 CWalletTx* wtx = &((*it).second);
604 txOrdered.insert({ wtx->nOrderPos, { wtx, (CAccountingEntry*)0 } });
607 walletdb.ListAccountCreditDebit(strAccount, acentries);
608 for(auto& entry : acentries)
610 txOrdered.insert({ entry.nOrderPos, { (CWalletTx*)0, &entry } });
616 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
618 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
619 // Update the wallet spent flag if it doesn't know due to wallet.dat being
620 // restored from backup or the user making copies of wallet.dat.
623 for(const auto& txin : tx.vin)
625 auto mi = mapWallet.find(txin.prevout.hash);
626 if (mi != mapWallet.end())
628 auto& wtx = (*mi).second;
629 if (txin.prevout.n >= wtx.vout.size())
630 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
631 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
633 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
634 wtx.MarkSpent(txin.prevout.n);
636 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
637 vMintingWalletUpdated.push_back(txin.prevout.hash);
644 auto hash = tx.GetHash();
645 auto mi = mapWallet.find(hash);
646 auto& wtx = (*mi).second;
648 for(const CTxOut& txout : tx.vout)
652 wtx.MarkUnspent(&txout - &tx.vout[0]);
654 NotifyTransactionChanged(this, hash, CT_UPDATED);
655 vMintingWalletUpdated.push_back(hash);
663 void CWallet::MarkDirty()
667 for(auto& item : mapWallet)
668 item.second.MarkDirty();
672 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
674 auto hash = wtxIn.GetHash();
677 // Inserts only if not already there, returns tx inserted or tx found
678 auto ret = mapWallet.insert({ hash, wtxIn });
679 auto& wtx = (*ret.first).second;
680 wtx.BindWallet(this);
681 bool fInsertedNew = ret.second;
684 wtx.nTimeReceived = GetAdjustedTime();
685 wtx.nOrderPos = IncOrderPosNext();
687 wtx.nTimeSmart = wtx.nTimeReceived;
688 if (wtxIn.hashBlock != 0)
690 if (mapBlockIndex.count(wtxIn.hashBlock))
692 unsigned int latestNow = wtx.nTimeReceived;
693 unsigned int latestEntry = 0;
695 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
696 int64_t latestTolerated = latestNow + 300;
697 list<CAccountingEntry> acentries;
698 auto txOrdered = OrderedTxItems(acentries);
699 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
701 CWalletTx *const pwtx = (*it).second.first;
704 CAccountingEntry *const pacentry = (*it).second.second;
708 nSmartTime = pwtx->nTimeSmart;
710 nSmartTime = pwtx->nTimeReceived;
713 nSmartTime = pacentry->nTime;
714 if (nSmartTime <= latestTolerated)
716 latestEntry = nSmartTime;
717 if (nSmartTime > latestNow)
718 latestNow = nSmartTime;
724 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
725 wtx.nTimeSmart = max(latestEntry, min(blocktime, latestNow));
728 printf("AddToWallet() : found %s in block %s not in index\n",
729 wtxIn.GetHash().ToString().substr(0,10).c_str(),
730 wtxIn.hashBlock.ToString().c_str());
734 bool fUpdated = false;
738 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
740 wtx.hashBlock = wtxIn.hashBlock;
743 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
745 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
746 wtx.nIndex = wtxIn.nIndex;
749 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
751 wtx.fFromMe = wtxIn.fFromMe;
754 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
758 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
761 if (fInsertedNew || fUpdated)
762 if (!wtx.WriteToDisk())
765 // If default receiving address gets used, replace it with a new one
766 CScript scriptDefaultKey;
767 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
768 for(const CTxOut& txout : wtx.vout)
770 if (txout.scriptPubKey == scriptDefaultKey)
772 CPubKey newDefaultKey;
773 if (GetKeyFromPool(newDefaultKey, false))
775 SetDefaultKey(newDefaultKey);
776 SetAddressBookName(vchDefaultKey.GetID(), "");
781 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
782 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
784 // Notify UI of new or updated transaction
785 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
786 vMintingWalletUpdated.push_back(hash);
787 // notify an external script when a wallet transaction comes in or is updated
788 auto strCmd = GetArg("-walletnotify", "");
792 boost::thread t(runCommand, regex_replace(strCmd, static_cast<regex>("%s"), wtxIn.GetHash().GetHex()));
798 // Add a transaction to the wallet, or update it.
799 // pblock is optional, but should be provided if the transaction is known to be in a block.
800 // If fUpdate is true, existing transactions will be updated.
801 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
803 auto hash = tx.GetHash();
806 bool fExisted = mapWallet.count(hash) != 0;
807 if (fExisted && !fUpdate) return false;
808 if (fExisted || IsMine(tx) || IsFromMe(tx))
810 CWalletTx wtx(this,tx);
811 // Get merkle branch if transaction was found in a block
813 wtx.SetMerkleBranch(pblock);
814 return AddToWallet(wtx);
817 WalletUpdateSpent(tx);
822 bool CWallet::EraseFromWallet(uint256 hash)
828 if (mapWallet.erase(hash))
829 CWalletDB(strWalletFile).EraseTx(hash);
835 isminetype CWallet::IsMine(const CTxIn &txin) const
839 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
840 if (mi != mapWallet.end())
842 const CWalletTx& prev = (*mi).second;
843 if (txin.prevout.n < prev.vout.size())
844 return IsMine(prev.vout[txin.prevout.n]);
851 CWalletTx::CWalletTx()
856 CWalletTx::CWalletTx(const CWallet* pwalletIn)
861 CWalletTx::CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
866 CWalletTx::CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
871 void CWalletTx::Init(const CWallet* pwalletIn)
877 fTimeReceivedIsTxTime = false;
881 strFromAccount.clear();
883 fDebitCached = false;
884 fWatchDebitCached = false;
885 fCreditCached = false;
886 fWatchCreditCached = false;
887 fAvailableCreditCached = false;
888 fAvailableWatchCreditCached = false;
889 fImmatureCreditCached = false;
890 fImmatureWatchCreditCached = false;
891 fChangeCached = false;
893 nWatchDebitCached = 0;
895 nWatchCreditCached = 0;
896 nAvailableCreditCached = 0;
897 nAvailableWatchCreditCached = 0;
898 nImmatureCreditCached = 0;
899 nImmatureWatchCreditCached = 0;
904 // marks certain txout's as spent
905 // returns true if any update took place
906 bool CWalletTx::UpdateSpent(const vector<char>& vfNewSpent)
908 bool fReturn = false;
909 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
911 if (i == vfSpent.size())
914 if (vfNewSpent[i] && !vfSpent[i])
918 fAvailableCreditCached = fAvailableWatchCreditCached = false;
924 // make sure balances are recalculated
925 void CWalletTx::MarkDirty()
927 fCreditCached = false;
928 fAvailableCreditCached = fAvailableWatchCreditCached = false;
929 fDebitCached = fWatchDebitCached = false;
930 fChangeCached = false;
933 void CWalletTx::BindWallet(CWallet *pwalletIn)
939 void CWalletTx::MarkSpent(unsigned int nOut)
941 if (nOut >= vout.size())
942 throw runtime_error("CWalletTx::MarkSpent() : nOut out of range");
943 vfSpent.resize(vout.size());
946 vfSpent[nOut] = true;
947 fAvailableCreditCached = fAvailableWatchCreditCached = false;
951 void CWalletTx::MarkUnspent(unsigned int nOut)
953 if (nOut >= vout.size())
954 throw runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
955 vfSpent.resize(vout.size());
958 vfSpent[nOut] = false;
959 fAvailableCreditCached = fAvailableWatchCreditCached = false;
963 bool CWalletTx::IsSpent(unsigned int nOut) const
965 if (nOut >= vout.size())
966 throw runtime_error("CWalletTx::IsSpent() : nOut out of range");
967 if (nOut >= vfSpent.size())
969 return (!!vfSpent[nOut]);
972 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
976 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
977 if (mi != mapWallet.end())
979 const CWalletTx& prev = (*mi).second;
980 if (txin.prevout.n < prev.vout.size())
981 if (IsMine(prev.vout[txin.prevout.n]) & filter)
982 return prev.vout[txin.prevout.n].nValue;
988 isminetype CWallet::IsMine(const CTxOut& txout) const
990 return ::IsMine(*this, txout.scriptPubKey);
993 int64_t CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
995 if (!MoneyRange(txout.nValue))
996 throw runtime_error("CWallet::GetCredit() : value out of range");
997 return (IsMine(txout) & filter ? txout.nValue : 0);
1000 bool CWallet::IsChange(const CTxOut& txout) const
1002 // TODO: fix handling of 'change' outputs. The assumption is that any
1003 // payment to a script that is ours, but isn't in the address book
1004 // is change. That assumption is likely to break when we implement multisignature
1005 // wallets that return change back into a multi-signature-protected address;
1006 // a better way of identifying which outputs are 'the send' and which are
1007 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1008 // which output, if any, was change).
1009 if (::IsMine(*this, txout.scriptPubKey))
1011 CTxDestination address;
1012 if (!ExtractDestination(txout.scriptPubKey, address))
1016 if (!mapAddressBook.count(address))
1022 int64_t CWallet::GetChange(const CTxOut& txout) const
1024 if (!MoneyRange(txout.nValue))
1025 throw runtime_error("CWallet::GetChange() : value out of range");
1026 return (IsChange(txout) ? txout.nValue : 0);
1029 bool CWallet::IsMine(const CTransaction& tx) const
1031 for(const CTxOut& txout : tx.vout)
1032 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
1037 bool CWallet::IsFromMe(const CTransaction& tx) const
1039 return (GetDebit(tx, MINE_ALL) > 0);
1042 int64_t CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1045 for(const CTxIn& txin : tx.vin)
1047 auto nValue = GetDebit(txin, filter);
1049 if (!MoneyRange(nValue) || !MoneyRange(nDebit))
1050 throw runtime_error("CWallet::GetDebit() : value out of range");
1052 return nDebit.getint64();
1055 int64_t CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1057 CBigNum nCredit = 0;
1058 for(const CTxOut& txout : tx.vout)
1060 auto nValue = GetCredit(txout, filter);
1062 if (!MoneyRange(nValue) || !MoneyRange(nCredit))
1063 throw runtime_error("CWallet::GetCredit() : value out of range");
1065 return nCredit.getint64();
1068 int64_t CWallet::GetChange(const CTransaction& tx) const
1070 CBigNum nChange = 0;
1071 for(const CTxOut& txout : tx.vout)
1073 int64_t nValue = GetChange(txout);
1075 if (!MoneyRange(nValue) || !MoneyRange(nChange))
1076 throw runtime_error("CWallet::GetChange() : value out of range");
1078 return nChange.getint64();
1081 int64_t CWalletTx::GetTxTime() const
1086 int CWalletTx::GetRequestCount() const
1088 // Returns -1 if it wasn't being tracked
1091 LOCK(pwallet->cs_wallet);
1092 if (IsCoinBase() || IsCoinStake())
1097 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1098 if (mi != pwallet->mapRequestCount.end())
1099 nRequests = (*mi).second;
1104 // Did anyone request this transaction?
1105 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1106 if (mi != pwallet->mapRequestCount.end())
1108 nRequests = (*mi).second;
1110 // How about the block it's in?
1111 if (nRequests == 0 && hashBlock != 0)
1113 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1114 if (mi != pwallet->mapRequestCount.end())
1115 nRequests = (*mi).second;
1117 nRequests = 1; // If it's in someone else's block it must have got out
1125 bool CWalletTx::InMempool() const
1128 if (mempool.exists(GetHash())) {
1134 bool CWalletTx::IsTrusted() const
1136 // Quick answer in most cases
1139 int nDepth = GetDepthInMainChain();
1144 if (!fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
1147 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1151 // Trusted if all inputs are from us and are in the mempool:
1152 for(const CTxIn& txin : vin)
1154 // Transactions not sent by us: not trusted
1155 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1158 const CTxOut& parentOut = parent->vout[txin.prevout.n];
1159 if (pwallet->IsMine(parentOut) != MINE_SPENDABLE)
1165 int64_t CWalletTx::GetDebit(const isminefilter& filter) const
1171 if (filter & MINE_SPENDABLE)
1174 nDebit += nDebitCached;
1177 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
1178 fDebitCached = true;
1179 nDebit += nDebitCached;
1182 if (filter & MINE_WATCH_ONLY)
1184 if (fWatchDebitCached)
1185 nDebit += nWatchDebitCached;
1188 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
1189 fWatchDebitCached = true;
1190 nDebit += nWatchDebitCached;
1196 int64_t CWalletTx::GetCredit(const isminefilter& filter) const
1198 // Must wait until coinbase is safely deep enough in the chain before valuing it
1199 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1203 if (filter & MINE_SPENDABLE)
1205 // GetBalance can assume transactions in mapWallet won't change
1207 credit += nCreditCached;
1210 nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1211 fCreditCached = true;
1212 credit += nCreditCached;
1215 if (filter & MINE_WATCH_ONLY)
1217 if (fWatchCreditCached)
1218 credit += nWatchCreditCached;
1221 nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1222 fWatchCreditCached = true;
1223 credit += nWatchCreditCached;
1229 int64_t CWalletTx::GetImmatureCredit(bool fUseCache) const
1231 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1233 if (fUseCache && fImmatureCreditCached)
1234 return nImmatureCreditCached;
1235 nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1236 fImmatureCreditCached = true;
1237 return nImmatureCreditCached;
1243 int64_t CWalletTx::GetImmatureWatchOnlyCredit(bool fUseCache) const
1245 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1247 if (fUseCache && fImmatureWatchCreditCached)
1248 return nImmatureWatchCreditCached;
1249 nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1250 fImmatureWatchCreditCached = true;
1251 return nImmatureWatchCreditCached;
1258 int64_t CWalletTx::GetAvailableCredit(bool fUseCache) const
1260 // Must wait until coinbase is safely deep enough in the chain before valuing it
1261 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1265 if (fAvailableCreditCached)
1266 return nAvailableCreditCached;
1269 CBigNum nCredit = 0;
1270 for (uint32_t i = 0; i < vout.size(); i++)
1274 const CTxOut &txout = vout[i];
1275 int64_t nValue = pwallet->GetCredit(txout, MINE_SPENDABLE);
1277 if (!MoneyRange(nValue) || !MoneyRange(nCredit))
1278 throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1282 nAvailableCreditCached = nCredit.getint64();
1283 fAvailableCreditCached = true;
1285 return nCredit.getint64();
1288 int64_t CWalletTx::GetAvailableWatchCredit(bool fUseCache) const
1290 // Must wait until coinbase is safely deep enough in the chain before valuing it
1291 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1295 if (fAvailableWatchCreditCached)
1296 return nAvailableWatchCreditCached;
1299 CBigNum nCredit = 0;
1300 for (unsigned int i = 0; i < vout.size(); i++)
1304 const CTxOut &txout = vout[i];
1305 int64_t nValue = pwallet->GetCredit(txout, MINE_WATCH_ONLY);
1307 if (!MoneyRange(nValue) || !MoneyRange(nCredit))
1308 throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1312 nAvailableWatchCreditCached = nCredit.getint64();
1313 fAvailableWatchCreditCached = true;
1315 return nCredit.getint64();
1318 int64_t CWalletTx::GetChange() const
1321 return nChangeCached;
1322 nChangeCached = pwallet->GetChange(*this);
1323 fChangeCached = true;
1324 return nChangeCached;
1327 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
1328 list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
1330 nGeneratedImmature = nGeneratedMature = nFee = 0;
1331 listReceived.clear();
1333 strSentAccount = strFromAccount;
1335 if (IsCoinBase() || IsCoinStake())
1337 if (GetBlocksToMaturity() > 0)
1338 nGeneratedImmature = pwallet->GetCredit(*this, filter);
1340 nGeneratedMature = GetCredit(filter);
1345 auto nDebit = GetDebit(filter);
1346 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1348 auto nValueOut = GetValueOut();
1349 nFee = nDebit - nValueOut;
1353 for(const CTxOut& txout : vout)
1355 auto fIsMine = pwallet->IsMine(txout);
1356 // Only need to handle txouts if AT LEAST one of these is true:
1357 // 1) they debit from us (sent)
1358 // 2) the output is to us (received)
1361 // Don't report 'change' txouts
1362 if (pwallet->IsChange(txout))
1365 else if (!(fIsMine & filter))
1368 // In either case, we need to get the destination address
1369 CBitcoinAddress address;
1370 if (!ExtractAddress(*pwallet, txout.scriptPubKey, address))
1372 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1373 this->GetHash().ToString().c_str());
1374 address = CBitcoinAddress();
1377 // If we are debited by the transaction, add the output as a "sent" entry
1379 listSent.push_back({ address, txout.nValue });
1381 // If we are receiving the output, add it as a "received" entry
1382 if (fIsMine & filter)
1383 listReceived.push_back({ address, txout.nValue });
1388 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
1389 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
1391 nGenerated = nReceived = nSent = nFee = 0;
1393 int64_t allGeneratedImmature, allGeneratedMature, allFee;
1394 allGeneratedImmature = allGeneratedMature = allFee = 0;
1395 string strSentAccount;
1396 list<pair<CBitcoinAddress, int64_t> > listReceived;
1397 list<pair<CBitcoinAddress, int64_t> > listSent;
1398 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
1400 if (strAccount.empty())
1401 nGenerated = allGeneratedMature;
1402 if (strAccount == strSentAccount)
1404 for(const auto& s : listSent)
1409 LOCK(pwallet->cs_wallet);
1410 for(const auto& r : listReceived)
1412 if (pwallet->mapAddressBook.count(r.first))
1414 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
1415 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
1416 nReceived += r.second;
1418 else if (strAccount.empty())
1420 nReceived += r.second;
1426 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
1430 const int COPY_DEPTH = 3;
1431 if (SetMerkleBranch() < COPY_DEPTH)
1433 vector<uint256> vWorkQueue;
1434 for(const CTxIn& txin : vin)
1435 vWorkQueue.push_back(txin.prevout.hash);
1437 // This critsect is OK because txdb is already open
1439 LOCK(pwallet->cs_wallet);
1440 map<uint256, const CMerkleTx*> mapWalletPrev;
1441 set<uint256> setAlreadyDone;
1442 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1444 auto hash = vWorkQueue[i];
1445 if (setAlreadyDone.count(hash))
1447 setAlreadyDone.insert(hash);
1450 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
1451 if (mi != pwallet->mapWallet.end())
1454 for(const CMerkleTx& txWalletPrev : (*mi).second.vtxPrev)
1455 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1457 else if (mapWalletPrev.count(hash))
1459 tx = *mapWalletPrev[hash];
1461 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1467 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1471 int nDepth = tx.SetMerkleBranch();
1472 vtxPrev.push_back(tx);
1474 if (nDepth < COPY_DEPTH)
1476 for(const CTxIn& txin : tx.vin)
1477 vWorkQueue.push_back(txin.prevout.hash);
1483 reverse(vtxPrev.begin(), vtxPrev.end());
1486 bool CWalletTx::WriteToDisk()
1488 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1491 // Scan the block chain (starting in pindexStart) for transactions
1492 // from or to us. If fUpdate is true, found transactions that already
1493 // exist in the wallet will be updated.
1494 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1498 CBlockIndex* pindex = pindexStart;
1504 block.ReadFromDisk(pindex, true);
1505 for(CTransaction& tx : block.vtx)
1507 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1510 pindex = pindex->pnext;
1516 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1519 tx.ReadFromDisk(COutPoint(hashTx, 0));
1520 if (AddToWalletIfInvolvingMe(tx, NULL, true))
1525 void CWallet::ReacceptWalletTransactions()
1528 bool fRepeat = true;
1533 vector<CDiskTxPos> vMissingTx;
1534 for(auto& item : mapWallet)
1536 auto& wtx = item.second;
1537 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1541 bool fUpdated = false;
1542 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1544 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1545 if (txindex.vSpent.size() != wtx.vout.size())
1547 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1550 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1554 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1558 vMissingTx.push_back(txindex.vSpent[i]);
1563 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1570 // Re-accept any txes of ours that aren't already in a block
1571 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1572 wtx.AcceptWalletTransaction(txdb, false);
1575 if (!vMissingTx.empty())
1577 // TODO: optimize this to scan just part of the block chain?
1578 if (ScanForWalletTransactions(pindexGenesisBlock))
1579 fRepeat = true; // Found missing transactions: re-do re-accept.
1584 bool CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1586 auto hash = GetHash();
1587 if (IsCoinBase() || IsCoinStake() || txdb.ContainsTx(hash) || !InMempool())
1590 for(auto it = vtxPrev.begin(); it != vtxPrev.end(); it++)
1592 const CMerkleTx& tx = *it;
1593 auto hash = tx.GetHash();
1595 if (tx.IsCoinBase() || tx.IsCoinStake())
1598 if (!txdb.ContainsTx(hash))
1599 RelayTransaction((CTransaction)tx, hash);
1602 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1603 RelayTransaction((CTransaction)*this, hash);
1607 bool CWalletTx::RelayWalletTransaction()
1610 return RelayWalletTransaction(txdb);
1613 vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1615 vector<uint256> result;
1618 // Sort them in chronological order
1619 map<unsigned int, CWalletTx*> mapSorted;
1620 for(auto& item : mapWallet)
1622 auto& wtx = item.second;
1623 // Don't rebroadcast if newer than nTime:
1624 if (wtx.nTimeReceived > nTime)
1626 mapSorted.insert({ wtx.nTimeReceived, &wtx });
1628 for(auto& item : mapSorted)
1630 auto& wtx = *item.second;
1631 if (wtx.RelayWalletTransaction())
1632 result.push_back(wtx.GetHash());
1637 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
1639 auto nNow = GetTime();
1641 // Do this infrequently and randomly to avoid giving away
1642 // that these are our transactions.
1643 if (nNow < nNextResend)
1645 bool fFirst = (nNextResend == 0);
1646 nNextResend = PoissonNextSend(nNow, 5*60);
1650 // Only do it if there's been a new block since last time
1651 if (nBestBlockTime < nLastResend)
1655 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1657 auto relayed = ResendWalletTransactionsBefore(nBestBlockTime - 5*60);
1658 if (!relayed.empty())
1659 printf("CWallet::ResendWalletTransactions: rebroadcast %" PRIszu " unconfirmed transactions\n", relayed.size());
1663 //////////////////////////////////////////////////////////////////////////////
1669 int64_t CWallet::GetBalance() const
1674 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1676 const CWalletTx* pcoin = &(*it).second;
1677 if (pcoin->IsTrusted())
1678 nTotal += pcoin->GetAvailableCredit();
1685 int64_t CWallet::GetWatchOnlyBalance() const
1690 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1692 const CWalletTx* pcoin = &(*it).second;
1693 if (pcoin->IsTrusted())
1694 nTotal += pcoin->GetAvailableWatchCredit();
1701 int64_t CWallet::GetUnconfirmedBalance() const
1706 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1708 const CWalletTx* pcoin = &(*it).second;
1709 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1710 nTotal += pcoin->GetAvailableCredit();
1716 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1721 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1723 const CWalletTx* pcoin = &(*it).second;
1724 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1725 nTotal += pcoin->GetAvailableWatchCredit();
1731 int64_t CWallet::GetImmatureBalance() const
1736 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1738 const CWalletTx* pcoin = &(*it).second;
1739 nTotal += pcoin->GetImmatureCredit();
1745 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1750 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1752 const CWalletTx* pcoin = &(*it).second;
1753 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1759 // populate vCoins with vector of spendable COutputs
1760 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1766 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1768 const CWalletTx* pcoin = &(*it).second;
1770 if (!pcoin->IsFinal())
1773 if (fOnlyConfirmed && !pcoin->IsTrusted())
1776 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1779 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1782 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1783 auto mine = IsMine(pcoin->vout[i]);
1784 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1785 pcoin->vout[i].nValue >= nMinimumInputValue &&
1786 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1788 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1795 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1801 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1803 const CWalletTx* pcoin = &(*it).second;
1805 if (!pcoin->IsFinal())
1808 if(pcoin->GetDepthInMainChain() < nConf)
1811 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1812 auto mine = IsMine(pcoin->vout[i]);
1814 // ignore coin if it was already spent or we don't own it
1815 if (pcoin->IsSpent(i) || mine == MINE_NO)
1818 // if coin value is between required limits then add new item to vector
1819 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1820 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1826 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1827 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1829 vector<char> vfIncluded;
1831 vfBest.assign(vValue.size(), true);
1832 nBest = nTotalLower;
1834 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1836 vfIncluded.assign(vValue.size(), false);
1838 bool fReachedTarget = false;
1839 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1841 for (unsigned int i = 0; i < vValue.size(); i++)
1843 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1845 nTotal += vValue[i].first;
1846 vfIncluded[i] = true;
1847 if (nTotal >= nTargetValue)
1849 fReachedTarget = true;
1853 vfBest = vfIncluded;
1855 nTotal -= vValue[i].first;
1856 vfIncluded[i] = false;
1864 int64_t CWallet::GetStake() const
1868 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1870 const CWalletTx* pcoin = &(*it).second;
1871 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1872 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1877 int64_t CWallet::GetWatchOnlyStake() const
1881 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1883 const CWalletTx* pcoin = &(*it).second;
1884 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1885 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1890 int64_t CWallet::GetNewMint() const
1894 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1896 const CWalletTx* pcoin = &(*it).second;
1897 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1898 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1903 int64_t CWallet::GetWatchOnlyNewMint() const
1907 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
1909 const CWalletTx* pcoin = &(*it).second;
1910 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1911 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1916 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
1918 setCoinsRet.clear();
1921 // List of values less than target
1922 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1923 coinLowestLarger.first = numeric_limits<int64_t>::max();
1924 coinLowestLarger.second.first = NULL;
1925 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1926 int64_t nTotalLower = 0;
1928 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1930 for(const COutput &output : vCoins)
1932 if (!output.fSpendable)
1935 const CWalletTx *pcoin = output.tx;
1937 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1942 // Follow the timestamp rules
1943 if (pcoin->nTime > nSpendTime)
1946 auto n = pcoin->vout[i].nValue;
1947 auto coin = make_pair(n, make_pair(pcoin, i));
1949 if (n == nTargetValue)
1951 setCoinsRet.insert(coin.second);
1952 nValueRet += coin.first;
1955 else if (n < nTargetValue + CENT)
1957 vValue.push_back(coin);
1960 else if (n < coinLowestLarger.first)
1962 coinLowestLarger = coin;
1966 if (nTotalLower == nTargetValue)
1968 for (unsigned int i = 0; i < vValue.size(); ++i)
1970 setCoinsRet.insert(vValue[i].second);
1971 nValueRet += vValue[i].first;
1976 if (nTotalLower < nTargetValue)
1978 if (coinLowestLarger.second.first == NULL)
1980 setCoinsRet.insert(coinLowestLarger.second);
1981 nValueRet += coinLowestLarger.first;
1985 // Solve subset sum by stochastic approximation
1986 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1987 vector<char> vfBest;
1990 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1991 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1992 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1994 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1995 // or the next bigger coin is closer), return the bigger coin
1996 if (coinLowestLarger.second.first &&
1997 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1999 setCoinsRet.insert(coinLowestLarger.second);
2000 nValueRet += coinLowestLarger.first;
2003 for (unsigned int i = 0; i < vValue.size(); i++)
2006 setCoinsRet.insert(vValue[i].second);
2007 nValueRet += vValue[i].first;
2010 if (fDebug && GetBoolArg("-printpriority"))
2013 printf("SelectCoins() best subset: ");
2014 for (unsigned int i = 0; i < vValue.size(); i++)
2016 printf("%s ", FormatMoney(vValue[i].first).c_str());
2017 printf("total %s\n", FormatMoney(nBest).c_str());
2024 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
2026 vector<COutput> vCoins;
2027 AvailableCoins(vCoins, true, coinControl);
2029 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2030 if (coinControl && coinControl->HasSelected())
2032 for(const COutput& out : vCoins)
2036 nValueRet += out.tx->vout[out.i].nValue;
2037 setCoinsRet.insert({ out.tx, out.i });
2039 return (nValueRet >= nTargetValue);
2042 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2043 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2044 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
2047 // Select some coins without random shuffle or best subset approximation
2048 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
2050 vector<COutput> vCoins;
2051 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
2053 setCoinsRet.clear();
2056 for(COutput output : vCoins)
2058 if(!output.fSpendable)
2060 const CWalletTx *pcoin = output.tx;
2063 // Ignore immature coins
2064 if (pcoin->GetBlocksToMaturity() > 0)
2067 // Stop if we've chosen enough inputs
2068 if (nValueRet >= nTargetValue)
2071 // Follow the timestamp rules
2072 if (pcoin->nTime > nSpendTime)
2075 auto n = pcoin->vout[i].nValue;
2076 auto coin = make_pair(n, make_pair(pcoin, i));
2078 if (n >= nTargetValue)
2080 // If input value is greater or equal to target then simply insert
2081 // it into the current subset and exit
2082 setCoinsRet.insert(coin.second);
2083 nValueRet += coin.first;
2086 else if (n < nTargetValue + CENT)
2088 setCoinsRet.insert(coin.second);
2089 nValueRet += coin.first;
2096 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2099 for(auto& s : vecSend)
2105 if (vecSend.empty() || nValue < 0)
2108 wtxNew.BindWallet(this);
2111 LOCK2(cs_main, cs_wallet);
2112 // txdb must be opened before the mapWallet lock
2115 nFeeRet = nTransactionFee;
2119 wtxNew.vout.clear();
2120 wtxNew.fFromMe = true;
2122 auto nTotalValue = nValue + nFeeRet;
2123 double dPriority = 0;
2124 // vouts to the payees
2125 for(const auto& s : vecSend)
2126 wtxNew.vout.push_back(CTxOut(s.second, s.first));
2128 // Choose coins to use
2129 set<pair<const CWalletTx*,unsigned int> > setCoins;
2130 int64_t nValueIn = 0;
2131 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
2133 for(auto& pcoin : setCoins)
2135 auto nCredit = pcoin.first->vout[pcoin.second].nValue;
2136 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
2139 auto nChange = nValueIn - nValue - nFeeRet;
2142 // Fill a vout to ourself
2143 // TODO: pass in scriptChange instead of reservekey so
2144 // change transaction isn't always pay-to-bitcoin-address
2145 CScript scriptChange;
2147 // coin control: send change to custom address
2148 if (coinControl && coinControl->destChange.IsValid())
2149 scriptChange.SetAddress(coinControl->destChange);
2151 // no coin control: send change to newly generated address
2154 // Note: We use a new key here to keep it from being obvious which side is the change.
2155 // The drawback is that by not reusing a previous key, the change may be lost if a
2156 // backup is restored, if the backup doesn't have the new private key for the change.
2157 // If we reused the old key, it would be possible to add code to look for and
2158 // rediscover unknown transactions that were written with keys of ours to recover
2159 // post-backup change.
2161 // Reserve a new key pair from key pool
2162 auto vchPubKey = reservekey.GetReservedKey();
2164 scriptChange.SetDestination(vchPubKey.GetID());
2167 // Insert change txn at random position:
2168 auto position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
2169 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
2172 reservekey.ReturnKey();
2175 for(const auto& coin : setCoins)
2176 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
2180 for(const auto& coin : setCoins)
2181 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
2185 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
2186 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2188 dPriority /= nBytes;
2190 // Check that enough fee is included
2191 bool fAllowFree = CTransaction::AllowFree(dPriority);
2192 auto nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
2193 auto nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2195 if (nFeeRet < max(nPayFee, nMinFee))
2197 nFeeRet = max(nPayFee, nMinFee);
2201 // Fill vtxPrev by copying from previous transactions vtxPrev
2202 wtxNew.AddSupportingTransactions(txdb);
2203 wtxNew.fTimeReceivedIsTxTime = true;
2212 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2214 vector< pair<CScript, int64_t> > vecSend;
2215 vecSend.push_back({ scriptPubKey, nValue });
2216 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
2219 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
2221 auto nTimeWeight = GetWeight(nTime, GetTime());
2223 // If time weight is lower or equal to zero then weight is zero.
2224 if (nTimeWeight <= 0)
2230 auto bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
2231 nWeight = bnCoinDayWeight.getuint64();
2234 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
2236 auto nBalance = GetBalance();
2238 if (nAmount > nBalance)
2242 int64_t nValueIn = 0;
2243 set<pair<const CWalletTx*,unsigned int> > setCoins;
2245 // Simple coins selection - no randomization
2246 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
2249 if (setCoins.empty())
2253 vector<const CWalletTx*> vwtxPrev;
2255 // Reserve a new key pair from key pool
2256 CReserveKey reservekey(this);
2257 auto vchPubKey = reservekey.GetReservedKey();
2260 CScript scriptOutput;
2261 scriptOutput.SetDestination(vchPubKey.GetID());
2264 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2267 for(auto& pcoin : setCoins)
2269 auto nCredit = pcoin.first->vout[pcoin.second].nValue;
2271 // Add current coin to inputs list and add its credit to transaction output
2272 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2273 wtxNew.vout[0].nValue += nCredit;
2274 vwtxPrev.push_back(pcoin.first);
2277 // Replaced with estimation for performance purposes
2279 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2280 const CWalletTx *txin = vwtxPrev[i];
2282 // Sign scripts to get actual transaction size for fee calculation
2283 if (!SignSignature(*this, *txin, wtxNew, i))
2288 // Assuming that average scriptsig size is 110 bytes
2289 auto nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2290 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
2292 double dFinalPriority = dWeight /= nBytes;
2293 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2295 // Get actual transaction fee according to its estimated size and priority
2296 auto nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2298 // Prepare transaction for commit if sum is enough ot its size is too big
2299 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
2301 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2303 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2304 const CWalletTx *txin = vwtxPrev[i];
2307 if (!SignSignature(*this, *txin, wtxNew, i))
2311 // Try to commit, return false on failure
2312 if (!CommitTransaction(wtxNew, reservekey))
2315 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2317 dWeight = 0; // Reset all temporary values
2320 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2324 // Create transactions if there are some unhandled coins left
2325 if (wtxNew.vout[0].nValue > 0) {
2326 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2328 double dFinalPriority = dWeight /= nBytes;
2329 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2331 // Get actual transaction fee according to its size and priority
2332 auto nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2334 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2336 if (wtxNew.vout[0].nValue <= 0)
2339 for (uint32_t i = 0; i < wtxNew.vin.size(); i++) {
2340 const CWalletTx *txin = vwtxPrev[i];
2342 // Sign all scripts again
2343 if (!SignSignature(*this, *txin, wtxNew, i))
2347 // Try to commit, return false on failure
2348 if (!CommitTransaction(wtxNew, reservekey))
2351 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2357 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
2360 if (!GetTransaction(hashTx, wtx))
2361 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
2363 vector<valtype> vSolutions;
2364 txnouttype whichType;
2365 CScript scriptPubKeyOut;
2366 auto scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
2367 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
2368 return error("CreateCoinStake : failed to parse kernel\n");
2370 if (fDebug && GetBoolArg("-printcoinstake"))
2371 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
2373 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
2374 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
2376 if (whichType == TX_PUBKEYHASH) // pay to address type
2378 // convert to pay to public key type
2379 if (!GetKey(uint160(vSolutions[0]), key))
2380 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2382 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
2384 if (whichType == TX_PUBKEY)
2386 auto& vchPubKey = vSolutions[0];
2387 if (!GetKey(Hash160(vchPubKey), key))
2388 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2389 if (key.GetPubKey() != vchPubKey)
2390 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
2391 scriptPubKeyOut = scriptPubKeyKernel;
2394 // The following combine threshold is important to security
2395 // Should not be adjusted if you don't understand the consequences
2396 auto nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
2398 auto nBalance = GetBalance();
2399 auto nCredit = wtx.vout[nOut].nValue;
2404 // List of constake dependencies
2405 vector<const CWalletTx*> vwtxPrev;
2406 vwtxPrev.push_back(&wtx);
2408 // Set generation time, and kernel input
2409 txNew.nTime = nGenerationTime;
2410 txNew.vin.push_back(CTxIn(hashTx, nOut));
2412 // Mark coin stake transaction with empty vout[0]
2413 CScript scriptEmpty;
2414 scriptEmpty.clear();
2415 txNew.vout.push_back(CTxOut(0, scriptEmpty));
2417 if (fDebug && GetBoolArg("-printcoinstake"))
2418 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2420 int64_t nValueIn = 0;
2422 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
2425 if (setCoins.empty())
2428 bool fDontSplitCoins = false;
2429 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
2431 // Only one output for old kernel inputs
2432 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2434 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
2436 // * Value is higher than 0.01 NVC;
2437 // * Only add inputs of the same key/address as kernel;
2438 // * Input hash and kernel parent hash should be different.
2439 for(auto pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
2441 // Stop adding more inputs if already too many inputs
2442 if (txNew.vin.size() >= 100)
2444 // Stop adding more inputs if value is already pretty significant
2445 if (nCredit > nCombineThreshold)
2447 // Stop adding inputs if reached reserve limit
2448 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
2451 auto nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
2453 // Do not add input that is still too young
2454 if (nTimeWeight < nStakeMaxAge)
2456 // Do not add input if key/address is not the same as kernel
2457 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2459 // Do not add input if parents are the same
2460 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2462 // Do not add additional significant input
2463 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2466 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2467 nCredit += pcoin->first->vout[pcoin->second].nValue;
2468 vwtxPrev.push_back(pcoin->first);
2471 fDontSplitCoins = true;
2475 auto nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2477 if (fDebug && GetBoolArg("-printcoinstake"))
2478 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2480 if (nCredit > nSplitThreshold)
2482 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2483 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2484 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2486 if (fDebug && GetBoolArg("-printcoinstake"))
2487 printf("CreateCoinStake : splitting coinstake\n");
2491 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2492 fDontSplitCoins = true;
2496 // Calculate coin age reward
2499 if (!txNew.GetCoinAge(txdb, nCoinAge))
2500 return error("CreateCoinStake : failed to calculate coin age\n");
2501 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2503 int64_t nMinFee = 0;
2506 // Set output amount
2507 if (fDontSplitCoins)
2508 txNew.vout[1].nValue = nCredit - nMinFee;
2511 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2512 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2517 for(const CWalletTx* pcoin : vwtxPrev)
2519 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2520 return error("CreateCoinStake : failed to sign coinstake\n");
2524 auto nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2525 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2526 return error("CreateCoinStake : exceeded coinstake size limit\n");
2528 // Check enough fee is paid
2529 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2531 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2532 continue; // try signing again
2536 if (fDebug && GetBoolArg("-printfee"))
2537 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2542 // Successfully created coinstake
2546 // Call after CreateTransaction unless you want to abort
2547 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2550 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2552 // Track how many getdata requests our transaction gets
2553 mapRequestCount[wtxNew.GetHash()] = 0;
2555 // Try to broadcast before saving
2556 if (!wtxNew.AcceptToMemoryPool())
2558 // This must not fail. The transaction has already been signed.
2559 printf("CommitTransaction() : Error: Transaction not valid");
2563 wtxNew.RelayWalletTransaction();
2566 LOCK2(cs_main, cs_wallet);
2568 // This is only to keep the database open to defeat the auto-flush for the
2569 // duration of this scope. This is the only place where this optimization
2570 // maybe makes sense; please don't do it anywhere else.
2571 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2573 // Take key pair from key pool so it won't be used again
2574 reservekey.KeepKey();
2576 // Add tx to wallet, because if it has change it's also ours,
2577 // otherwise just for transaction history.
2578 AddToWallet(wtxNew);
2580 // Mark old coins as spent
2581 for(const CTxIn& txin : wtxNew.vin)
2583 CWalletTx &coin = mapWallet[txin.prevout.hash];
2584 coin.BindWallet(this);
2585 coin.MarkSpent(txin.prevout.n);
2587 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2588 vMintingWalletUpdated.push_back(coin.GetHash());
2601 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2605 return "Invalid amount";
2606 if (nValue + nTransactionFee > GetBalance())
2607 return "Insufficient funds";
2609 CReserveKey reservekey(this);
2610 int64_t nFeeRequired;
2614 string strError("Error: Wallet locked, unable to create transaction ");
2615 printf("SendMoney() : %s", strError.c_str());
2618 if (fWalletUnlockMintOnly)
2620 string strError("Error: Wallet unlocked for block minting only, unable to create transaction.");
2621 printf("SendMoney() : %s", strError.c_str());
2624 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2627 if (nValue + nFeeRequired > GetBalance())
2628 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());
2630 strError = _("Error: Transaction creation failed ");
2631 printf("SendMoney() : %s", strError.c_str());
2635 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2638 if (!CommitTransaction(wtxNew, reservekey))
2639 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.";
2644 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2648 fFirstRunRet = false;
2649 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2650 if (nLoadWalletRet == DB_NEED_REWRITE)
2652 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2655 // Note: can't top-up keypool here, because wallet is locked.
2656 // User will be prompted to unlock wallet the next operation
2657 // the requires a new key.
2661 if (nLoadWalletRet != DB_LOAD_OK)
2662 return nLoadWalletRet;
2663 fFirstRunRet = !vchDefaultKey.IsValid();
2665 NewThread(ThreadFlushWalletDB, &strWalletFile);
2669 DBErrors CWallet::ZapWalletTx()
2673 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2674 if (nZapWalletTxRet == DB_NEED_REWRITE)
2676 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2680 // Note: can't top-up keypool here, because wallet is locked.
2681 // User will be prompted to unlock wallet the next operation
2682 // the requires a new key.
2686 if (nZapWalletTxRet != DB_LOAD_OK)
2687 return nZapWalletTxRet;
2692 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2694 return SetAddressBookName(CBitcoinAddress(address), strName);
2697 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
2699 auto mi = mapAddressBook.find(address);
2700 mapAddressBook[address] = strName;
2701 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2704 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
2707 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
2709 mapAddressBook.erase(address);
2710 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2713 return CWalletDB(strWalletFile).EraseName(address.ToString());
2717 void CWallet::PrintWallet(const CBlock& block)
2721 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2723 auto& wtx = mapWallet[block.vtx[1].GetHash()];
2724 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2726 else if (mapWallet.count(block.vtx[0].GetHash()))
2728 auto& wtx = mapWallet[block.vtx[0].GetHash()];
2729 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2735 void CWallet::Inventory(const uint256 &hash)
2739 auto mi = mapRequestCount.find(hash);
2740 if (mi != mapRequestCount.end())
2745 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2749 auto mi = mapWallet.find(hashTx);
2750 if (mi != mapWallet.end())
2759 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2763 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2766 vchDefaultKey = vchPubKey;
2770 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2772 if (!pwallet->fFileBacked)
2774 strWalletFileOut = pwallet->strWalletFile;
2779 // Mark old keypool keys as used,
2780 // and generate all new keys
2782 bool CWallet::NewKeyPool(unsigned int nSize)
2786 CWalletDB walletdb(strWalletFile);
2787 for(int64_t nIndex : setKeyPool)
2788 walletdb.ErasePool(nIndex);
2798 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2800 for (uint64_t i = 0; i < nKeys; i++)
2803 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2804 setKeyPool.insert(nIndex);
2806 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2811 bool CWallet::TopUpKeyPool(unsigned int nSize)
2819 CWalletDB walletdb(strWalletFile);
2822 uint64_t nTargetSize;
2824 nTargetSize = nSize;
2826 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2828 while (setKeyPool.size() < (nTargetSize + 1))
2831 if (!setKeyPool.empty())
2832 nEnd = *(--setKeyPool.end()) + 1;
2833 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2834 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2835 setKeyPool.insert(nEnd);
2836 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2842 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2845 keypool.vchPubKey = CPubKey();
2852 // Get the oldest key
2853 if(setKeyPool.empty())
2856 CWalletDB walletdb(strWalletFile);
2858 nIndex = *(setKeyPool.begin());
2859 setKeyPool.erase(setKeyPool.begin());
2860 if (!walletdb.ReadPool(nIndex, keypool))
2861 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2862 if (!HaveKey(keypool.vchPubKey.GetID()))
2863 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2864 assert(keypool.vchPubKey.IsValid());
2865 if (fDebug && GetBoolArg("-printkeypool"))
2866 printf("keypool reserve %" PRId64 "\n", nIndex);
2870 void CWallet::KeepKey(int64_t nIndex)
2872 // Remove from key pool
2875 CWalletDB walletdb(strWalletFile);
2876 walletdb.ErasePool(nIndex);
2879 printf("keypool keep %" PRId64 "\n", nIndex);
2882 void CWallet::ReturnKey(int64_t nIndex)
2884 // Return to key pool
2887 setKeyPool.insert(nIndex);
2890 printf("keypool return %" PRId64 "\n", nIndex);
2893 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2899 ReserveKeyFromKeyPool(nIndex, keypool);
2902 if (fAllowReuse && vchDefaultKey.IsValid())
2904 result = vchDefaultKey;
2907 if (IsLocked()) return false;
2908 result = GenerateNewKey();
2912 result = keypool.vchPubKey;
2917 int64_t CWallet::GetOldestKeyPoolTime()
2921 ReserveKeyFromKeyPool(nIndex, keypool);
2925 return keypool.nTime;
2928 map<CBitcoinAddress, int64_t> CWallet::GetAddressBalances()
2930 map<CBitcoinAddress, int64_t> balances;
2934 for(auto& walletEntry : mapWallet)
2936 CWalletTx *pcoin = &walletEntry.second;
2938 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2941 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2944 int nDepth = pcoin->GetDepthInMainChain();
2945 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2948 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2950 CBitcoinAddress addr;
2951 if (!IsMine(pcoin->vout[i]))
2953 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, addr))
2956 auto n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2958 if (!balances.count(addr))
2960 balances[addr] += n;
2968 set< set<CBitcoinAddress> > CWallet::GetAddressGroupings()
2970 set< set<CBitcoinAddress> > groupings;
2971 set<CBitcoinAddress> grouping;
2973 for(auto& walletEntry : mapWallet)
2975 CWalletTx *pcoin = &walletEntry.second;
2977 if (pcoin->vin.size() > 0)
2979 bool any_mine = false;
2980 // group all input addresses with each other
2981 for(CTxIn txin : pcoin->vin)
2983 CBitcoinAddress address;
2984 if(!IsMine(txin)) // If this input isn't mine, ignore it
2986 if(!ExtractAddress(*this, mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2988 grouping.insert(address);
2992 // group change with input addresses
2995 for(CTxOut txout : pcoin->vout)
2996 if (IsChange(txout))
2998 CBitcoinAddress txoutAddr;
2999 if(!ExtractAddress(*this, txout.scriptPubKey, txoutAddr))
3001 grouping.insert(txoutAddr);
3004 if (!grouping.empty())
3006 groupings.insert(grouping);
3011 // group lone addrs by themselves
3012 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3013 if (IsMine(pcoin->vout[i]))
3015 CBitcoinAddress address;
3016 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, address))
3018 grouping.insert(address);
3019 groupings.insert(grouping);
3024 set< set<CBitcoinAddress>* > uniqueGroupings; // a set of pointers to groups of addresses
3025 map< CBitcoinAddress, set<CBitcoinAddress>* > setmap; // map addresses to the unique group containing it
3026 for(auto& grouping : groupings)
3028 // make a set of all the groups hit by this new group
3029 set< set<CBitcoinAddress>* > hits;
3030 map< CBitcoinAddress, set<CBitcoinAddress>* >::iterator it;
3031 for(auto& address : grouping)
3032 if ((it = setmap.find(address)) != setmap.end())
3033 hits.insert((*it).second);
3035 // merge all hit groups into a new single group and delete old groups
3036 set<CBitcoinAddress>* merged = new set<CBitcoinAddress>(grouping);
3037 for(auto hit : hits)
3039 merged->insert(hit->begin(), hit->end());
3040 uniqueGroupings.erase(hit);
3043 uniqueGroupings.insert(merged);
3046 for(CBitcoinAddress element : *merged)
3047 setmap[element] = merged;
3050 set< set<CBitcoinAddress> > ret;
3051 for(auto uniqueGrouping : uniqueGroupings)
3053 ret.insert(*uniqueGrouping);
3054 delete uniqueGrouping;
3060 // ppcoin: check 'spent' consistency between wallet and txindex
3061 // ppcoin: fix wallet spent state according to txindex
3062 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
3065 nBalanceInQuestion = 0;
3068 vector<CWalletTx*> vCoins;
3069 vCoins.reserve(mapWallet.size());
3070 for (auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
3071 vCoins.push_back(&(*it).second);
3074 for(auto pcoin : vCoins)
3076 // Find the corresponding transaction index
3078 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
3080 for (unsigned int n=0; n < pcoin->vout.size(); n++)
3082 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
3084 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
3085 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3087 nBalanceInQuestion += pcoin->vout[n].nValue;
3090 pcoin->MarkUnspent(n);
3091 pcoin->WriteToDisk();
3094 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
3096 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
3097 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3099 nBalanceInQuestion += pcoin->vout[n].nValue;
3102 pcoin->MarkSpent(n);
3103 pcoin->WriteToDisk();
3109 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
3111 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
3114 EraseFromWallet(pcoin->GetHash());
3120 // ppcoin: disable transaction (only for coinstake)
3121 void CWallet::DisableTransaction(const CTransaction &tx)
3123 if (!tx.IsCoinStake() || !IsFromMe(tx))
3124 return; // only disconnecting coinstake requires marking input unspent
3127 for(const auto& txin : tx.vin)
3129 auto mi = mapWallet.find(txin.prevout.hash);
3130 if (mi != mapWallet.end())
3132 auto& prev = (*mi).second;
3133 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
3135 prev.MarkUnspent(txin.prevout.n);
3142 CPubKey CReserveKey::GetReservedKey()
3147 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3149 vchPubKey = keypool.vchPubKey;
3152 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
3153 vchPubKey = pwallet->vchDefaultKey;
3156 assert(vchPubKey.IsValid());
3160 void CReserveKey::KeepKey()
3163 pwallet->KeepKey(nIndex);
3165 vchPubKey = CPubKey();
3168 void CReserveKey::ReturnKey()
3171 pwallet->ReturnKey(nIndex);
3173 vchPubKey = CPubKey();
3176 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3180 CWalletDB walletdb(strWalletFile);
3182 LOCK2(cs_main, cs_wallet);
3183 for(const int64_t& id : setKeyPool)
3186 if (!walletdb.ReadPool(id, keypool))
3187 throw runtime_error("GetAllReserveKeyHashes() : read failed");
3188 assert(keypool.vchPubKey.IsValid());
3189 auto keyID = keypool.vchPubKey.GetID();
3190 if (!HaveKey(keyID))
3191 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
3192 setAddress.insert(keyID);
3196 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3200 // Only notify UI if this transaction is in this wallet
3201 auto mi = mapWallet.find(hashTx);
3202 if (mi != mapWallet.end())
3204 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3205 vMintingWalletUpdated.push_back(hashTx);
3210 void CWallet::GetAddresses(map<CBitcoinAddress, int64_t> &mapAddresses) const {
3211 mapAddresses.clear();
3213 // get birth times for keys with metadata
3214 for (auto it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
3215 mapAddresses[it->first] = it->second.nCreateTime ? it->second.nCreateTime : 0;
3218 for (auto it = mapWallet.begin(); it != mapWallet.end(); it++) {
3219 // iterate over all wallet transactions...
3220 const auto &wtx = (*it).second;
3221 if (wtx.hashBlock == 0)
3222 continue; // skip unconfirmed transactions
3224 for(auto it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
3225 const CTxOut &out = (*it2);
3226 // iterate over all their outputs
3227 CBitcoinAddress addressRet;
3228 if (ExtractAddress(*this, out.scriptPubKey, addressRet)) {
3229 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
3230 mapAddresses[addressRet] = wtx.nTime;
3233 // multisig output affects more than one key
3234 vector<CKeyID> vAffected;
3235 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
3237 for(auto it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
3238 CBitcoinAddress addrAffected(*it3);
3239 if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
3240 mapAddresses[addrAffected] = wtx.nTime;
3248 void CWallet::ClearOrphans()
3250 list<uint256> orphans;
3253 for(auto it = mapWallet.begin(); it != mapWallet.end(); ++it)
3255 const CWalletTx *wtx = &(*it).second;
3256 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
3258 orphans.push_back(wtx->GetHash());
3262 for(auto it = orphans.begin(); it != orphans.end(); ++it)
3263 EraseFromWallet(*it);