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.
7 #include "txdb-leveldb.h"
9 #include "coincontrol.h"
15 #include <openssl/bio.h>
21 extern int64_t nReserveBalance;
23 //////////////////////////////////////////////////////////////////////////////
28 struct CompareValueOnly
30 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
31 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
33 return t1.first < t2.first;
37 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
40 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
41 if (it == mapWallet.end())
46 CPubKey CWallet::GenerateNewKey()
48 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
52 key.MakeNewKey(fCompressed);
54 // Compressed public keys were introduced in version 0.6.0
56 SetMinVersion(FEATURE_COMPRPUBKEY);
58 CPubKey pubkey = key.GetPubKey();
60 // Create new metadata
61 int64_t nCreationTime = GetTime();
62 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = CKeyMetadata(nCreationTime);
63 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
64 nTimeFirstKey = nCreationTime;
67 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
68 return key.GetPubKey();
71 CMalleableKeyView CWallet::GenerateNewMalleableKey()
75 // Compressed public keys were introduced in version 0.6.0
76 SetMinVersion(FEATURE_MALLKEY);
80 const CMalleableKeyView &keyView(mKey);
82 // Create new metadata
83 int64_t nCreationTime = GetTime();
84 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = CKeyMetadata(nCreationTime);
85 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
86 nTimeFirstKey = nCreationTime;
89 throw std::runtime_error("CWallet::GenerateNewMalleableKey() : AddKey failed");
90 return CMalleableKeyView(mKey);
93 bool CWallet::AddKey(const CKey& key)
95 CPubKey pubkey = key.GetPubKey();
96 if (!CCryptoKeyStore::AddKey(key))
101 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(pubkey.GetID())]);
105 bool CWallet::AddKey(const CMalleableKey& mKey)
107 CMalleableKeyView keyView = CMalleableKeyView(mKey);
108 CSecret vchSecretH = mKey.GetSecretH();
109 if (!CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH))
114 return CWalletDB(strWalletFile).WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
118 bool CWallet::AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH)
120 if (!CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH))
128 CBitcoinAddress addr(keyView.GetMalleablePubKey());
129 if (pwalletdbEncryption)
130 return pwalletdbEncryption->WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
132 return CWalletDB(strWalletFile).WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
138 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
140 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
142 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
145 // check if we need to remove from watch-only
147 script.SetDestination(vchPubKey.GetID());
148 if (HaveWatchOnly(script))
149 RemoveWatchOnly(script);
155 CBitcoinAddress addr(vchPubKey.GetID());
156 if (pwalletdbEncryption)
157 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
159 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
164 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
166 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
167 nTimeFirstKey = meta.nCreateTime;
169 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = meta;
173 bool CWallet::LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
175 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
176 nTimeFirstKey = metadata.nCreateTime;
178 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = metadata;
182 bool CWallet::LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
184 bool CWallet::LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH) { return CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH); }
186 bool CWallet::LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
188 bool CWallet::AddCScript(const CScript& redeemScript)
190 if (!CCryptoKeyStore::AddCScript(redeemScript))
194 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
197 bool CWallet::LoadCScript(const CScript& redeemScript)
199 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
200 * that never can be redeemed. However, old wallets may still contain
201 * these. Do not add them to the wallet and warn. */
202 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
204 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
205 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",
206 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
210 return CCryptoKeyStore::AddCScript(redeemScript);
214 bool CWallet::AddWatchOnly(const CScript &dest)
216 if (!CCryptoKeyStore::AddWatchOnly(dest))
218 nTimeFirstKey = 1; // No birthday information for watch-only keys.
219 NotifyWatchonlyChanged(true);
222 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
225 bool CWallet::RemoveWatchOnly(const CScript &dest)
228 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
230 if (!HaveWatchOnly())
231 NotifyWatchonlyChanged(false);
233 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
239 bool CWallet::LoadWatchOnly(const CScript &dest)
241 return CCryptoKeyStore::AddWatchOnly(dest);
244 // ppcoin: optional setting to unlock wallet for block minting only;
245 // serves to disable the trivial sendmoney when OS account compromised
246 bool fWalletUnlockMintOnly = false;
248 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
254 CKeyingMaterial vMasterKey;
258 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
260 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
262 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
264 if (CCryptoKeyStore::Unlock(vMasterKey))
271 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
273 bool fWasLocked = IsLocked();
280 CKeyingMaterial vMasterKey;
281 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
283 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
285 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
287 if (CCryptoKeyStore::Unlock(vMasterKey))
289 int64_t nStartTime = GetTimeMillis();
290 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
291 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
292 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
294 nStartTime = GetTimeMillis();
295 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
296 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
297 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
299 if (pMasterKey.second.nDeriveIterations < 25000)
300 pMasterKey.second.nDeriveIterations = 25000;
302 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
304 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
306 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
308 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
319 void CWallet::SetBestChain(const CBlockLocator& loc)
321 CWalletDB walletdb(strWalletFile);
322 walletdb.WriteBestBlock(loc);
325 // This class implements an addrIncoming entry that causes pre-0.4
326 // clients to crash on startup if reading a private-key-encrypted wallet.
327 class CCorruptAddress
332 if (nType & SER_DISK)
337 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
339 if (nWalletVersion >= nVersion)
342 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
343 if (fExplicit && nVersion > nWalletMaxVersion)
344 nVersion = FEATURE_LATEST;
346 nWalletVersion = nVersion;
348 if (nVersion > nWalletMaxVersion)
349 nWalletMaxVersion = nVersion;
353 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
354 if (nWalletVersion > 40000)
355 pwalletdb->WriteMinVersion(nWalletVersion);
363 bool CWallet::SetMaxVersion(int nVersion)
365 // cannot downgrade below current version
366 if (nWalletVersion > nVersion)
369 nWalletMaxVersion = nVersion;
374 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
379 CKeyingMaterial vMasterKey;
380 RandAddSeedPerfmon();
382 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
383 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
385 CMasterKey kMasterKey;
387 RandAddSeedPerfmon();
388 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
389 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
392 int64_t nStartTime = GetTimeMillis();
393 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
394 int64_t nDivider = GetTimeMillis() - nStartTime;
395 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
397 nStartTime = GetTimeMillis();
398 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
399 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
400 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
402 if (kMasterKey.nDeriveIterations < 25000)
403 kMasterKey.nDeriveIterations = 25000;
405 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
407 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
409 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
414 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
417 pwalletdbEncryption = new CWalletDB(strWalletFile);
418 if (!pwalletdbEncryption->TxnBegin())
420 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
423 if (!EncryptKeys(vMasterKey))
426 pwalletdbEncryption->TxnAbort();
427 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.
430 // Encryption was introduced in version 0.4.0
431 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
435 if (!pwalletdbEncryption->TxnCommit())
436 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.
438 delete pwalletdbEncryption;
439 pwalletdbEncryption = NULL;
443 Unlock(strWalletPassphrase);
447 // Need to completely rewrite the wallet file; if we don't, bdb might keep
448 // bits of the unencrypted private key in slack space in the database file.
449 CDB::Rewrite(strWalletFile);
452 NotifyStatusChanged(this);
457 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
463 CKeyingMaterial vMasterKey;
467 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
469 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
471 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
473 if (!CCryptoKeyStore::Unlock(vMasterKey))
479 pwalletdbDecryption = new CWalletDB(strWalletFile);
480 if (!pwalletdbDecryption->TxnBegin())
484 if (!DecryptKeys(vMasterKey))
487 pwalletdbDecryption->TxnAbort();
488 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.
493 // Overwrite crypted keys
494 KeyMap::const_iterator mi = mapKeys.begin();
495 while (mi != mapKeys.end())
498 key.SetSecret((*mi).second.first, (*mi).second.second);
499 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
500 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(mi->first)]);
504 MalleableKeyMap::const_iterator mi2 = mapMalleableKeys.begin();
505 while (mi2 != mapMalleableKeys.end())
507 const CSecret &vchSecretH = mi2->second;
508 const CMalleableKeyView &keyView = mi2->first;
509 pwalletdbDecryption->EraseCryptedMalleableKey(keyView);
510 pwalletdbDecryption->WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
515 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
516 while (mk != mapMasterKeys.end())
518 pwalletdbDecryption->EraseMasterKey((*mk).first);
522 if (!pwalletdbDecryption->TxnCommit())
523 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.
525 delete pwalletdbDecryption;
526 pwalletdbDecryption = NULL;
529 // Need to completely rewrite the wallet file; if we don't, bdb might keep
530 // encrypted private keys in the database file which can be a reason of consistency issues.
531 CDB::Rewrite(strWalletFile);
533 NotifyStatusChanged(this);
538 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
540 int64_t nRet = nOrderPosNext++;
542 pwalletdb->WriteOrderPosNext(nOrderPosNext);
544 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
549 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
551 CWalletDB walletdb(strWalletFile);
553 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
556 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
557 // would make this much faster for applications that do this a lot.
558 for (auto & it : mapWallet)
560 CWalletTx* wtx = &(it.second);
561 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)nullptr)));
564 walletdb.ListAccountCreditDebit(strAccount, acentries);
565 for (CAccountingEntry& entry : acentries)
567 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)nullptr, &entry)));
573 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
575 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
576 // Update the wallet spent flag if it doesn't know due to wallet.dat being
577 // restored from backup or the user making copies of wallet.dat.
580 for (const CTxIn& txin : tx.vin)
582 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
583 if (mi != mapWallet.end())
585 CWalletTx& wtx = (*mi).second;
586 if (txin.prevout.n >= wtx.vout.size())
587 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
588 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
590 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
591 wtx.MarkSpent(txin.prevout.n);
593 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
594 vMintingWalletUpdated.push_back(txin.prevout.hash);
601 uint256 hash = tx.GetHash();
602 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
603 CWalletTx& wtx = (*mi).second;
605 for (const CTxOut& txout : tx.vout)
609 wtx.MarkUnspent(&txout - &tx.vout[0]);
611 NotifyTransactionChanged(this, hash, CT_UPDATED);
612 vMintingWalletUpdated.push_back(hash);
620 void CWallet::MarkDirty()
624 for (auto& item : mapWallet)
625 item.second.MarkDirty();
629 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
631 uint256 hash = wtxIn.GetHash();
634 // Inserts only if not already there, returns tx inserted or tx found
635 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
636 CWalletTx& wtx = (*ret.first).second;
637 wtx.BindWallet(this);
638 bool fInsertedNew = ret.second;
641 wtx.nTimeReceived = GetAdjustedTime();
642 wtx.nOrderPos = IncOrderPosNext();
644 wtx.nTimeSmart = wtx.nTimeReceived;
645 if (wtxIn.hashBlock != 0)
647 if (mapBlockIndex.count(wtxIn.hashBlock))
649 unsigned int latestNow = wtx.nTimeReceived;
650 unsigned int latestEntry = 0;
652 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
653 int64_t latestTolerated = latestNow + 300;
654 std::list<CAccountingEntry> acentries;
655 TxItems txOrdered = OrderedTxItems(acentries);
656 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
658 CWalletTx *const pwtx = (*it).second.first;
661 CAccountingEntry *const pacentry = (*it).second.second;
665 nSmartTime = pwtx->nTimeSmart;
667 nSmartTime = pwtx->nTimeReceived;
670 nSmartTime = pacentry->nTime;
671 if (nSmartTime <= latestTolerated)
673 latestEntry = nSmartTime;
674 if (nSmartTime > latestNow)
675 latestNow = nSmartTime;
681 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
682 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
685 printf("AddToWallet() : found %s in block %s not in index\n",
686 wtxIn.GetHash().ToString().substr(0,10).c_str(),
687 wtxIn.hashBlock.ToString().c_str());
691 bool fUpdated = false;
695 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
697 wtx.hashBlock = wtxIn.hashBlock;
700 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
702 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
703 wtx.nIndex = wtxIn.nIndex;
706 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
708 wtx.fFromMe = wtxIn.fFromMe;
711 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
715 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
718 if (fInsertedNew || fUpdated)
719 if (!wtx.WriteToDisk())
722 // If default receiving address gets used, replace it with a new one
723 CScript scriptDefaultKey;
724 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
725 for (const CTxOut& txout : wtx.vout)
727 if (txout.scriptPubKey == scriptDefaultKey)
729 CPubKey newDefaultKey;
730 if (GetKeyFromPool(newDefaultKey, false))
732 SetDefaultKey(newDefaultKey);
733 SetAddressBookName(vchDefaultKey.GetID(), "");
738 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
739 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
741 // Notify UI of new or updated transaction
742 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
743 vMintingWalletUpdated.push_back(hash);
744 // notify an external script when a wallet transaction comes in or is updated
745 std::string strCmd = GetArg("-walletnotify", "");
747 if ( !strCmd.empty())
749 boost::thread t(runCommand, regex_replace(strCmd, static_cast<std::regex>("%s"), wtxIn.GetHash().GetHex()));
755 // Add a transaction to the wallet, or update it.
756 // pblock is optional, but should be provided if the transaction is known to be in a block.
757 // If fUpdate is true, existing transactions will be updated.
758 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
760 uint256 hash = tx.GetHash();
763 bool fExisted = mapWallet.count(hash) != 0;
764 if (fExisted && !fUpdate) return false;
765 if (fExisted || IsMine(tx) || IsFromMe(tx))
767 CWalletTx wtx(this,tx);
768 // Get merkle branch if transaction was found in a block
770 wtx.SetMerkleBranch(pblock);
771 return AddToWallet(wtx);
774 WalletUpdateSpent(tx);
779 bool CWallet::EraseFromWallet(uint256 hash)
785 if (mapWallet.erase(hash))
786 CWalletDB(strWalletFile).EraseTx(hash);
792 isminetype CWallet::IsMine(const CTxIn &txin) const
796 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
797 if (mi != mapWallet.end())
799 const CWalletTx& prev = (*mi).second;
800 if (txin.prevout.n < prev.vout.size())
801 return IsMine(prev.vout[txin.prevout.n]);
807 // marks certain txout's as spent
808 // returns true if any update took place
809 bool CWalletTx::UpdateSpent(const std::vector<char>& vfNewSpent)
811 bool fReturn = false;
812 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
814 if (i == vfSpent.size())
817 if (vfNewSpent[i] && !vfSpent[i])
821 fAvailableCreditCached = fAvailableWatchCreditCached = false;
827 // make sure balances are recalculated
828 void CWalletTx::MarkDirty()
830 fCreditCached = false;
831 fAvailableCreditCached = fAvailableWatchCreditCached = false;
832 fDebitCached = fWatchDebitCached = false;
833 fChangeCached = false;
836 void CWalletTx::BindWallet(CWallet *pwalletIn)
842 void CWalletTx::MarkSpent(unsigned int nOut)
844 if (nOut >= vout.size())
845 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
846 vfSpent.resize(vout.size());
849 vfSpent[nOut] = true;
850 fAvailableCreditCached = fAvailableWatchCreditCached = false;
854 void CWalletTx::MarkUnspent(unsigned int nOut)
856 if (nOut >= vout.size())
857 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
858 vfSpent.resize(vout.size());
861 vfSpent[nOut] = false;
862 fAvailableCreditCached = fAvailableWatchCreditCached = false;
866 bool CWalletTx::IsSpent(unsigned int nOut) const
868 if (nOut >= vout.size())
869 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
870 if (nOut >= vfSpent.size())
872 return (!!vfSpent[nOut]);
875 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
879 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
880 if (mi != mapWallet.end())
882 const CWalletTx& prev = (*mi).second;
883 if (txin.prevout.n < prev.vout.size())
884 if (IsMine(prev.vout[txin.prevout.n]) & filter)
885 return prev.vout[txin.prevout.n].nValue;
891 isminetype CWallet::IsMine(const CTxOut& txout) const
893 return ::IsMine(*this, txout.scriptPubKey);
896 int64_t CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
898 if (!MoneyRange(txout.nValue))
899 throw std::runtime_error("CWallet::GetCredit() : value out of range");
900 return (IsMine(txout) & filter ? txout.nValue : 0);
903 bool CWallet::IsChange(const CTxOut& txout) const
905 // TODO: fix handling of 'change' outputs. The assumption is that any
906 // payment to a script that is ours, but isn't in the address book
907 // is change. That assumption is likely to break when we implement multisignature
908 // wallets that return change back into a multi-signature-protected address;
909 // a better way of identifying which outputs are 'the send' and which are
910 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
911 // which output, if any, was change).
912 if (::IsMine(*this, txout.scriptPubKey))
914 CTxDestination address;
915 if (!ExtractDestination(txout.scriptPubKey, address))
919 if (!mapAddressBook.count(address))
925 int64_t CWallet::GetChange(const CTxOut& txout) const
927 if (!MoneyRange(txout.nValue))
928 throw std::runtime_error("CWallet::GetChange() : value out of range");
929 return (IsChange(txout) ? txout.nValue : 0);
932 bool CWallet::IsMine(const CTransaction& tx) const
934 for (const CTxOut& txout : tx.vout)
935 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
940 bool CWallet::IsFromMe(const CTransaction& tx) const
942 return (GetDebit(tx, MINE_ALL) > 0);
945 int64_t CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
948 for (const CTxIn& txin : tx.vin)
950 nDebit += GetDebit(txin, filter);
951 if (!MoneyRange(nDebit))
952 throw std::runtime_error("CWallet::GetDebit() : value out of range");
957 int64_t CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
960 for (const CTxOut& txout : tx.vout)
962 nCredit += GetCredit(txout, filter);
963 if (!MoneyRange(nCredit))
964 throw std::runtime_error("CWallet::GetCredit() : value out of range");
969 int64_t CWallet::GetChange(const CTransaction& tx) const
972 for (const CTxOut& txout : tx.vout)
974 nChange += GetChange(txout);
975 if (!MoneyRange(nChange))
976 throw std::runtime_error("CWallet::GetChange() : value out of range");
981 int64_t CWalletTx::GetTxTime() const
986 int CWalletTx::GetRequestCount() const
988 // Returns -1 if it wasn't being tracked
991 LOCK(pwallet->cs_wallet);
992 if (IsCoinBase() || IsCoinStake())
997 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
998 if (mi != pwallet->mapRequestCount.end())
999 nRequests = (*mi).second;
1004 // Did anyone request this transaction?
1005 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1006 if (mi != pwallet->mapRequestCount.end())
1008 nRequests = (*mi).second;
1010 // How about the block it's in?
1011 if (nRequests == 0 && hashBlock != 0)
1013 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1014 if (mi != pwallet->mapRequestCount.end())
1015 nRequests = (*mi).second;
1017 nRequests = 1; // If it's in someone else's block it must have got out
1025 bool CWalletTx::InMempool() const
1028 if (mempool.exists(GetHash())) {
1034 bool CWalletTx::IsTrusted() const
1036 // Quick answer in most cases
1039 int nDepth = GetDepthInMainChain();
1044 if (!fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
1047 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1051 // Trusted if all inputs are from us and are in the mempool:
1052 for (const CTxIn& txin : vin)
1054 // Transactions not sent by us: not trusted
1055 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1058 const CTxOut& parentOut = parent->vout[txin.prevout.n];
1059 if (pwallet->IsMine(parentOut) != MINE_SPENDABLE)
1065 int64_t CWalletTx::GetDebit(const isminefilter& filter) const
1071 if (filter & MINE_SPENDABLE)
1074 nDebit += nDebitCached;
1077 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
1078 fDebitCached = true;
1079 nDebit += nDebitCached;
1082 if (filter & MINE_WATCH_ONLY)
1084 if (fWatchDebitCached)
1085 nDebit += nWatchDebitCached;
1088 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
1089 fWatchDebitCached = true;
1090 nDebit += nWatchDebitCached;
1096 int64_t CWalletTx::GetCredit(const isminefilter& filter) const
1098 // Must wait until coinbase is safely deep enough in the chain before valuing it
1099 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1103 if (filter & MINE_SPENDABLE)
1105 // GetBalance can assume transactions in mapWallet won't change
1107 credit += nCreditCached;
1110 nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1111 fCreditCached = true;
1112 credit += nCreditCached;
1115 if (filter & MINE_WATCH_ONLY)
1117 if (fWatchCreditCached)
1118 credit += nWatchCreditCached;
1121 nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1122 fWatchCreditCached = true;
1123 credit += nWatchCreditCached;
1129 int64_t CWalletTx::GetImmatureCredit(bool fUseCache) const
1131 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1133 if (fUseCache && fImmatureCreditCached)
1134 return nImmatureCreditCached;
1135 nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1136 fImmatureCreditCached = true;
1137 return nImmatureCreditCached;
1143 int64_t CWalletTx::GetImmatureWatchOnlyCredit(bool fUseCache) const
1145 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1147 if (fUseCache && fImmatureWatchCreditCached)
1148 return nImmatureWatchCreditCached;
1149 nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1150 fImmatureWatchCreditCached = true;
1151 return nImmatureWatchCreditCached;
1158 int64_t CWalletTx::GetAvailableCredit(bool fUseCache) const
1160 // Must wait until coinbase is safely deep enough in the chain before valuing it
1161 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1165 if (fAvailableCreditCached)
1166 return nAvailableCreditCached;
1169 int64_t nCredit = 0;
1170 for (unsigned int i = 0; i < vout.size(); i++)
1174 const CTxOut &txout = vout[i];
1175 nCredit += pwallet->GetCredit(txout, MINE_SPENDABLE);
1176 if (!MoneyRange(nCredit))
1177 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1181 nAvailableCreditCached = nCredit;
1182 fAvailableCreditCached = true;
1187 int64_t CWalletTx::GetAvailableWatchCredit(bool fUseCache) const
1189 // Must wait until coinbase is safely deep enough in the chain before valuing it
1190 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1194 if (fAvailableWatchCreditCached)
1195 return nAvailableWatchCreditCached;
1198 int64_t nCredit = 0;
1199 for (unsigned int i = 0; i < vout.size(); i++)
1203 const CTxOut &txout = vout[i];
1204 nCredit += pwallet->GetCredit(txout, MINE_WATCH_ONLY);
1205 if (!MoneyRange(nCredit))
1206 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1210 nAvailableWatchCreditCached = nCredit;
1211 fAvailableWatchCreditCached = true;
1216 int64_t CWalletTx::GetChange() const
1219 return nChangeCached;
1220 nChangeCached = pwallet->GetChange(*this);
1221 fChangeCached = true;
1222 return nChangeCached;
1225 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
1226 list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
1228 nGeneratedImmature = nGeneratedMature = nFee = 0;
1229 listReceived.clear();
1231 strSentAccount = strFromAccount;
1233 if (IsCoinBase() || IsCoinStake())
1235 if (GetBlocksToMaturity() > 0)
1236 nGeneratedImmature = pwallet->GetCredit(*this, filter);
1238 nGeneratedMature = GetCredit(filter);
1243 int64_t nDebit = GetDebit(filter);
1244 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1246 int64_t nValueOut = GetValueOut();
1247 nFee = nDebit - nValueOut;
1251 for (const CTxOut& txout : vout)
1253 isminetype fIsMine = pwallet->IsMine(txout);
1254 // Only need to handle txouts if AT LEAST one of these is true:
1255 // 1) they debit from us (sent)
1256 // 2) the output is to us (received)
1259 // Don't report 'change' txouts
1260 if (pwallet->IsChange(txout))
1263 else if (!(fIsMine & filter))
1266 // In either case, we need to get the destination address
1267 CBitcoinAddress address;
1268 if (!ExtractAddress(*pwallet, txout.scriptPubKey, address))
1270 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1271 this->GetHash().ToString().c_str());
1272 address = CBitcoinAddress();
1275 // If we are debited by the transaction, add the output as a "sent" entry
1277 listSent.push_back(make_pair(address, txout.nValue));
1279 // If we are receiving the output, add it as a "received" entry
1280 if (fIsMine & filter)
1281 listReceived.push_back(make_pair(address, txout.nValue));
1286 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
1287 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
1289 nGenerated = nReceived = nSent = nFee = 0;
1291 int64_t allGeneratedImmature, allGeneratedMature, allFee;
1292 allGeneratedImmature = allGeneratedMature = allFee = 0;
1293 string strSentAccount;
1294 list<pair<CBitcoinAddress, int64_t> > listReceived;
1295 list<pair<CBitcoinAddress, int64_t> > listSent;
1296 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
1298 if (strAccount.empty())
1299 nGenerated = allGeneratedMature;
1300 if (strAccount == strSentAccount)
1302 for (const auto& s : listSent)
1307 LOCK(pwallet->cs_wallet);
1308 for (const auto& r : listReceived)
1310 if (pwallet->mapAddressBook.count(r.first))
1312 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
1313 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
1314 nReceived += r.second;
1316 else if (strAccount.empty())
1318 nReceived += r.second;
1324 bool CWalletTx::IsFromMe(const isminefilter &filter) const
1326 return (GetDebit(filter) > 0);
1329 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
1333 const int COPY_DEPTH = 3;
1334 if (SetMerkleBranch() < COPY_DEPTH)
1336 vector<uint256> vWorkQueue;
1337 for (const CTxIn& txin : vin)
1338 vWorkQueue.push_back(txin.prevout.hash);
1340 // This critsect is OK because txdb is already open
1342 LOCK(pwallet->cs_wallet);
1343 map<uint256, const CMerkleTx*> mapWalletPrev;
1344 set<uint256> setAlreadyDone;
1345 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1347 uint256 hash = vWorkQueue[i];
1348 if (setAlreadyDone.count(hash))
1350 setAlreadyDone.insert(hash);
1353 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
1354 if (mi != pwallet->mapWallet.end())
1357 for (const CMerkleTx& txWalletPrev : (*mi).second.vtxPrev)
1358 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1360 else if (mapWalletPrev.count(hash))
1362 tx = *mapWalletPrev[hash];
1364 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1370 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1374 int nDepth = tx.SetMerkleBranch();
1375 vtxPrev.push_back(tx);
1377 if (nDepth < COPY_DEPTH)
1379 for (const CTxIn& txin : tx.vin)
1380 vWorkQueue.push_back(txin.prevout.hash);
1386 reverse(vtxPrev.begin(), vtxPrev.end());
1389 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
1394 // Add previous supporting transactions first
1395 for (CMerkleTx& tx : vtxPrev)
1397 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1399 uint256 hash = tx.GetHash();
1400 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
1401 tx.AcceptToMemoryPool(txdb, fCheckInputs);
1404 return AcceptToMemoryPool(txdb, fCheckInputs);
1409 bool CWalletTx::AcceptWalletTransaction()
1412 return AcceptWalletTransaction(txdb);
1415 bool CWalletTx::WriteToDisk()
1417 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1420 // Scan the block chain (starting in pindexStart) for transactions
1421 // from or to us. If fUpdate is true, found transactions that already
1422 // exist in the wallet will be updated.
1423 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1427 CBlockIndex* pindex = pindexStart;
1433 block.ReadFromDisk(pindex, true);
1434 for (CTransaction& tx : block.vtx)
1436 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1439 pindex = pindex->pnext;
1445 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1448 tx.ReadFromDisk(COutPoint(hashTx, 0));
1449 if (AddToWalletIfInvolvingMe(tx, NULL, true))
1454 void CWallet::ReacceptWalletTransactions()
1457 bool fRepeat = true;
1462 vector<CDiskTxPos> vMissingTx;
1463 for (auto& item : mapWallet)
1465 CWalletTx& wtx = item.second;
1466 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1470 bool fUpdated = false;
1471 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1473 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1474 if (txindex.vSpent.size() != wtx.vout.size())
1476 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1479 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1483 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1487 vMissingTx.push_back(txindex.vSpent[i]);
1492 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1499 // Re-accept any txes of ours that aren't already in a block
1500 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1501 wtx.AcceptWalletTransaction(txdb, false);
1504 if (!vMissingTx.empty())
1506 // TODO: optimize this to scan just part of the block chain?
1507 if (ScanForWalletTransactions(pindexGenesisBlock))
1508 fRepeat = true; // Found missing transactions: re-do re-accept.
1513 bool CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1515 uint256 hash = GetHash();
1516 if (IsCoinBase() || IsCoinStake() || txdb.ContainsTx(hash) || !InMempool())
1519 for(std::vector<CMerkleTx>::const_iterator it = vtxPrev.begin(); it != vtxPrev.end(); it++)
1521 const CMerkleTx& tx = *it;
1522 uint256 hash = tx.GetHash();
1524 if (tx.IsCoinBase() || tx.IsCoinStake())
1527 if (!txdb.ContainsTx(hash))
1528 RelayTransaction((CTransaction)tx, hash);
1531 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1532 RelayTransaction((CTransaction)*this, hash);
1536 bool CWalletTx::RelayWalletTransaction()
1539 return RelayWalletTransaction(txdb);
1542 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1544 std::vector<uint256> result;
1547 // Sort them in chronological order
1548 map<unsigned int, CWalletTx*> mapSorted;
1549 for (auto& item : mapWallet)
1551 CWalletTx& wtx = item.second;
1552 // Don't rebroadcast if newer than nTime:
1553 if (wtx.nTimeReceived > nTime)
1555 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1557 for (auto& item : mapSorted)
1559 CWalletTx& wtx = *item.second;
1560 if (wtx.RelayWalletTransaction())
1561 result.push_back(wtx.GetHash());
1566 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
1568 int64_t nNow = GetTime();
1570 // Do this infrequently and randomly to avoid giving away
1571 // that these are our transactions.
1572 if (nNow < nNextResend)
1574 bool fFirst = (nNextResend == 0);
1575 nNextResend = PoissonNextSend(nNow, 5*60);
1579 // Only do it if there's been a new block since last time
1580 if (nBestBlockTime < nLastResend)
1584 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1586 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime - 5*60);
1587 if (!relayed.empty())
1588 printf("CWallet::ResendWalletTransactions: rebroadcast %" PRIszu " unconfirmed transactions\n", relayed.size());
1592 //////////////////////////////////////////////////////////////////////////////
1598 int64_t CWallet::GetBalance() const
1603 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1605 const CWalletTx* pcoin = &(*it).second;
1606 if (pcoin->IsTrusted())
1607 nTotal += pcoin->GetAvailableCredit();
1614 int64_t CWallet::GetWatchOnlyBalance() const
1619 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1621 const CWalletTx* pcoin = &(*it).second;
1622 if (pcoin->IsTrusted())
1623 nTotal += pcoin->GetAvailableWatchCredit();
1630 int64_t CWallet::GetUnconfirmedBalance() const
1635 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1637 const CWalletTx* pcoin = &(*it).second;
1638 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1639 nTotal += pcoin->GetAvailableCredit();
1645 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1650 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1652 const CWalletTx* pcoin = &(*it).second;
1653 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1654 nTotal += pcoin->GetAvailableWatchCredit();
1660 int64_t CWallet::GetImmatureBalance() const
1665 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1667 const CWalletTx* pcoin = &(*it).second;
1668 nTotal += pcoin->GetImmatureCredit();
1674 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1679 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1681 const CWalletTx* pcoin = &(*it).second;
1682 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1688 // populate vCoins with vector of spendable COutputs
1689 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1695 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1697 const CWalletTx* pcoin = &(*it).second;
1699 if (!pcoin->IsFinal())
1702 if (fOnlyConfirmed && !pcoin->IsTrusted())
1705 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1708 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1711 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1712 isminetype mine = IsMine(pcoin->vout[i]);
1713 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1714 pcoin->vout[i].nValue >= nMinimumInputValue &&
1715 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1717 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1724 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1730 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1732 const CWalletTx* pcoin = &(*it).second;
1734 if (!pcoin->IsFinal())
1737 if(pcoin->GetDepthInMainChain() < nConf)
1740 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1741 isminetype mine = IsMine(pcoin->vout[i]);
1743 // ignore coin if it was already spent or we don't own it
1744 if (pcoin->IsSpent(i) || mine == MINE_NO)
1747 // if coin value is between required limits then add new item to vector
1748 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1749 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1755 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1756 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1758 vector<char> vfIncluded;
1760 vfBest.assign(vValue.size(), true);
1761 nBest = nTotalLower;
1763 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1765 vfIncluded.assign(vValue.size(), false);
1767 bool fReachedTarget = false;
1768 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1770 for (unsigned int i = 0; i < vValue.size(); i++)
1772 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1774 nTotal += vValue[i].first;
1775 vfIncluded[i] = true;
1776 if (nTotal >= nTargetValue)
1778 fReachedTarget = true;
1782 vfBest = vfIncluded;
1784 nTotal -= vValue[i].first;
1785 vfIncluded[i] = false;
1793 int64_t CWallet::GetStake() const
1797 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1799 const CWalletTx* pcoin = &(*it).second;
1800 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1801 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1806 int64_t CWallet::GetWatchOnlyStake() const
1810 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1812 const CWalletTx* pcoin = &(*it).second;
1813 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1814 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1819 int64_t CWallet::GetNewMint() const
1823 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1825 const CWalletTx* pcoin = &(*it).second;
1826 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1827 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1832 int64_t CWallet::GetWatchOnlyNewMint() const
1836 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1838 const CWalletTx* pcoin = &(*it).second;
1839 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1840 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1845 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
1847 setCoinsRet.clear();
1850 // List of values less than target
1851 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1852 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1853 coinLowestLarger.second.first = NULL;
1854 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1855 int64_t nTotalLower = 0;
1857 std::random_device rd;
1858 std::mt19937 g(rd());
1859 shuffle(vCoins.begin(), vCoins.end(), g);
1861 for (const COutput &output : vCoins)
1863 if (!output.fSpendable)
1866 const CWalletTx *pcoin = output.tx;
1868 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1873 // Follow the timestamp rules
1874 if (pcoin->nTime > nSpendTime)
1877 int64_t n = pcoin->vout[i].nValue;
1879 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1881 if (n == nTargetValue)
1883 setCoinsRet.insert(coin.second);
1884 nValueRet += coin.first;
1887 else if (n < nTargetValue + CENT)
1889 vValue.push_back(coin);
1892 else if (n < coinLowestLarger.first)
1894 coinLowestLarger = coin;
1898 if (nTotalLower == nTargetValue)
1900 for (unsigned int i = 0; i < vValue.size(); ++i)
1902 setCoinsRet.insert(vValue[i].second);
1903 nValueRet += vValue[i].first;
1908 if (nTotalLower < nTargetValue)
1910 if (coinLowestLarger.second.first == NULL)
1912 setCoinsRet.insert(coinLowestLarger.second);
1913 nValueRet += coinLowestLarger.first;
1917 // Solve subset sum by stochastic approximation
1918 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
1919 std::reverse(vValue.begin(), vValue.end());
1920 vector<char> vfBest;
1923 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1924 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1925 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1927 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1928 // or the next bigger coin is closer), return the bigger coin
1929 if (coinLowestLarger.second.first &&
1930 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1932 setCoinsRet.insert(coinLowestLarger.second);
1933 nValueRet += coinLowestLarger.first;
1936 for (unsigned int i = 0; i < vValue.size(); i++)
1939 setCoinsRet.insert(vValue[i].second);
1940 nValueRet += vValue[i].first;
1943 if (fDebug && GetBoolArg("-printpriority"))
1946 printf("SelectCoins() best subset: ");
1947 for (unsigned int i = 0; i < vValue.size(); i++)
1949 printf("%s ", FormatMoney(vValue[i].first).c_str());
1950 printf("total %s\n", FormatMoney(nBest).c_str());
1957 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1959 vector<COutput> vCoins;
1960 AvailableCoins(vCoins, true, coinControl);
1962 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1963 if (coinControl && coinControl->HasSelected())
1965 for (const COutput& out : vCoins)
1969 nValueRet += out.tx->vout[out.i].nValue;
1970 setCoinsRet.insert(make_pair(out.tx, out.i));
1972 return (nValueRet >= nTargetValue);
1975 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1976 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1977 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1985 CWallet::CWallet(std::string strWalletFileIn)
1989 strWalletFile = strWalletFileIn;
1993 void CWallet::SetNull()
1995 nWalletVersion = FEATURE_BASE;
1996 nWalletMaxVersion = FEATURE_BASE;
1997 fFileBacked = false;
1998 nMasterKeyMaxID = 0;
1999 pwalletdbEncryption = NULL;
2000 pwalletdbDecryption = NULL;
2009 // Select some coins without random shuffle or best subset approximation
2010 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
2012 vector<COutput> vCoins;
2013 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
2015 setCoinsRet.clear();
2018 for (COutput output : vCoins)
2020 if(!output.fSpendable)
2022 const CWalletTx *pcoin = output.tx;
2025 // Ignore immature coins
2026 if (pcoin->GetBlocksToMaturity() > 0)
2029 // Stop if we've chosen enough inputs
2030 if (nValueRet >= nTargetValue)
2033 // Follow the timestamp rules
2034 if (pcoin->nTime > nSpendTime)
2037 int64_t n = pcoin->vout[i].nValue;
2039 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2041 if (n >= nTargetValue)
2043 // If input value is greater or equal to target then simply insert
2044 // it into the current subset and exit
2045 setCoinsRet.insert(coin.second);
2046 nValueRet += coin.first;
2049 else if (n < nTargetValue + CENT)
2051 setCoinsRet.insert(coin.second);
2052 nValueRet += coin.first;
2059 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2062 for (const auto& s : vecSend)
2068 if (vecSend.empty() || nValue < 0)
2071 wtxNew.BindWallet(this);
2074 LOCK2(cs_main, cs_wallet);
2075 // txdb must be opened before the mapWallet lock
2078 nFeeRet = nTransactionFee;
2082 wtxNew.vout.clear();
2083 wtxNew.fFromMe = true;
2085 int64_t nTotalValue = nValue + nFeeRet;
2086 double dPriority = 0;
2087 // vouts to the payees
2088 for (const auto& s : vecSend)
2089 wtxNew.vout.push_back(CTxOut(s.second, s.first));
2091 // Choose coins to use
2092 set<pair<const CWalletTx*,unsigned int> > setCoins;
2093 int64_t nValueIn = 0;
2094 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
2096 for (auto pcoin : setCoins)
2098 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
2099 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
2102 int64_t nChange = nValueIn - nValue - nFeeRet;
2105 // Fill a vout to ourself
2106 // TODO: pass in scriptChange instead of reservekey so
2107 // change transaction isn't always pay-to-bitcoin-address
2108 CScript scriptChange;
2110 // coin control: send change to custom address
2111 if (coinControl && coinControl->destChange.IsValid())
2112 scriptChange.SetAddress(coinControl->destChange);
2114 // no coin control: send change to newly generated address
2117 // Note: We use a new key here to keep it from being obvious which side is the change.
2118 // The drawback is that by not reusing a previous key, the change may be lost if a
2119 // backup is restored, if the backup doesn't have the new private key for the change.
2120 // If we reused the old key, it would be possible to add code to look for and
2121 // rediscover unknown transactions that were written with keys of ours to recover
2122 // post-backup change.
2124 // Reserve a new key pair from key pool
2125 CPubKey vchPubKey = reservekey.GetReservedKey();
2127 scriptChange.SetDestination(vchPubKey.GetID());
2130 // Insert change txn at random position:
2131 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
2132 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
2135 reservekey.ReturnKey();
2138 for (const auto& coin : setCoins)
2139 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
2143 for (const auto& coin : setCoins)
2144 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
2148 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
2149 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2151 dPriority /= nBytes;
2153 // Check that enough fee is included
2154 bool fAllowFree = CTransaction::AllowFree(dPriority);
2155 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
2156 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2158 if (nFeeRet < max(nPayFee, nMinFee))
2160 nFeeRet = max(nPayFee, nMinFee);
2164 // Fill vtxPrev by copying from previous transactions vtxPrev
2165 wtxNew.AddSupportingTransactions(txdb);
2166 wtxNew.fTimeReceivedIsTxTime = true;
2175 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2177 vector< pair<CScript, int64_t> > vecSend;
2178 vecSend.push_back(make_pair(scriptPubKey, nValue));
2179 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
2182 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
2184 int64_t nTimeWeight = GetWeight(nTime, GetTime());
2186 // If time weight is lower or equal to zero then weight is zero.
2187 if (nTimeWeight <= 0)
2193 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
2194 nWeight = bnCoinDayWeight.getuint64();
2197 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
2199 int64_t nBalance = GetBalance();
2201 if (nAmount > nBalance)
2205 int64_t nValueIn = 0;
2206 set<pair<const CWalletTx*,unsigned int> > setCoins;
2208 // Simple coins selection - no randomization
2209 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
2212 if (setCoins.empty())
2216 vector<const CWalletTx*> vwtxPrev;
2218 // Reserve a new key pair from key pool
2219 CReserveKey reservekey(this);
2220 CPubKey vchPubKey = reservekey.GetReservedKey();
2223 CScript scriptOutput;
2224 scriptOutput.SetDestination(vchPubKey.GetID());
2227 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2230 for (auto pcoin : setCoins)
2232 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
2234 // Add current coin to inputs list and add its credit to transaction output
2235 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2236 wtxNew.vout[0].nValue += nCredit;
2237 vwtxPrev.push_back(pcoin.first);
2240 // Replaced with estimation for performance purposes
2242 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2243 const CWalletTx *txin = vwtxPrev[i];
2245 // Sign scripts to get actual transaction size for fee calculation
2246 if (!SignSignature(*this, *txin, wtxNew, i))
2251 // Assuming that average scriptsig size is 110 bytes
2252 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2253 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
2255 double dFinalPriority = dWeight /= nBytes;
2256 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2258 // Get actual transaction fee according to its estimated size and priority
2259 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2261 // Prepare transaction for commit if sum is enough ot its size is too big
2262 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
2264 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2266 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2267 const CWalletTx *txin = vwtxPrev[i];
2270 if (!SignSignature(*this, *txin, wtxNew, i))
2274 // Try to commit, return false on failure
2275 if (!CommitTransaction(wtxNew, reservekey))
2278 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2280 dWeight = 0; // Reset all temporary values
2283 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2287 // Create transactions if there are some unhandled coins left
2288 if (wtxNew.vout[0].nValue > 0) {
2289 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2291 double dFinalPriority = dWeight / nBytes;
2292 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2294 // Get actual transaction fee according to its size and priority
2295 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2297 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2299 if (wtxNew.vout[0].nValue <= 0)
2302 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2303 const CWalletTx *txin = vwtxPrev[i];
2305 // Sign all scripts again
2306 if (!SignSignature(*this, *txin, wtxNew, i))
2310 // Try to commit, return false on failure
2311 if (!CommitTransaction(wtxNew, reservekey))
2314 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2320 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
2323 if (!GetTransaction(hashTx, wtx))
2324 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
2326 vector<valtype> vSolutions;
2327 txnouttype whichType;
2328 CScript scriptPubKeyOut;
2329 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
2330 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
2331 return error("CreateCoinStake : failed to parse kernel\n");
2333 if (fDebug && GetBoolArg("-printcoinstake"))
2334 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
2336 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
2337 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
2339 if (whichType == TX_PUBKEYHASH) // pay to address type
2341 // convert to pay to public key type
2342 if (!GetKey(uint160(vSolutions[0]), key))
2343 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2345 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
2347 if (whichType == TX_PUBKEY)
2349 valtype& vchPubKey = vSolutions[0];
2350 if (!GetKey(Hash160(vchPubKey), key))
2351 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2352 if (key.GetPubKey() != vchPubKey)
2353 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
2354 scriptPubKeyOut = scriptPubKeyKernel;
2357 // The following combine threshold is important to security
2358 // Should not be adjusted if you don't understand the consequences
2359 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
2361 int64_t nBalance = GetBalance();
2362 int64_t nCredit = wtx.vout[nOut].nValue;
2367 // List of constake dependencies
2368 vector<const CWalletTx*> vwtxPrev;
2369 vwtxPrev.push_back(&wtx);
2371 // Set generation time, and kernel input
2372 txNew.nTime = nGenerationTime;
2373 txNew.vin.push_back(CTxIn(hashTx, nOut));
2375 // Mark coin stake transaction with empty vout[0]
2376 CScript scriptEmpty;
2377 scriptEmpty.clear();
2378 txNew.vout.push_back(CTxOut(0, scriptEmpty));
2380 if (fDebug && GetBoolArg("-printcoinstake"))
2381 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2383 int64_t nValueIn = 0;
2385 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
2388 if (setCoins.empty())
2391 bool fDontSplitCoins = false;
2392 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
2394 // Only one output for old kernel inputs
2395 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2397 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
2399 // * Value is higher than 0.01 NVC;
2400 // * Only add inputs of the same key/address as kernel;
2401 // * Input hash and kernel parent hash should be different.
2402 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
2404 // Stop adding more inputs if already too many inputs
2405 if (txNew.vin.size() >= 100)
2407 // Stop adding more inputs if value is already pretty significant
2408 if (nCredit > nCombineThreshold)
2410 // Stop adding inputs if reached reserve limit
2411 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
2414 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
2416 // Do not add input that is still too young
2417 if (nTimeWeight < nStakeMaxAge)
2419 // Do not add input if key/address is not the same as kernel
2420 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2422 // Do not add input if parents are the same
2423 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2425 // Do not add additional significant input
2426 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2429 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2430 nCredit += pcoin->first->vout[pcoin->second].nValue;
2431 vwtxPrev.push_back(pcoin->first);
2434 fDontSplitCoins = true;
2438 int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2440 if (fDebug && GetBoolArg("-printcoinstake"))
2441 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2443 if (nCredit > nSplitThreshold)
2445 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2446 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2447 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2449 if (fDebug && GetBoolArg("-printcoinstake"))
2450 printf("CreateCoinStake : splitting coinstake\n");
2454 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2455 fDontSplitCoins = true;
2459 // Calculate coin age reward
2462 if (!txNew.GetCoinAge(txdb, nCoinAge))
2463 return error("CreateCoinStake : failed to calculate coin age\n");
2464 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2466 int64_t nMinFee = 0;
2469 // Set output amount
2470 if (fDontSplitCoins)
2471 txNew.vout[1].nValue = nCredit - nMinFee;
2474 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2475 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2480 for (const CWalletTx* pcoin : vwtxPrev)
2482 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2483 return error("CreateCoinStake : failed to sign coinstake\n");
2487 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2488 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2489 return error("CreateCoinStake : exceeded coinstake size limit\n");
2491 // Check enough fee is paid
2492 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2494 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2495 continue; // try signing again
2499 if (fDebug && GetBoolArg("-printfee"))
2500 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2505 // Successfully created coinstake
2509 // Call after CreateTransaction unless you want to abort
2510 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2513 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2515 // Track how many getdata requests our transaction gets
2516 mapRequestCount[wtxNew.GetHash()] = 0;
2518 // Try to broadcast before saving
2519 if (!wtxNew.AcceptToMemoryPool())
2521 // This must not fail. The transaction has already been signed.
2522 printf("CommitTransaction() : Error: Transaction not valid");
2526 wtxNew.RelayWalletTransaction();
2529 LOCK2(cs_main, cs_wallet);
2531 // This is only to keep the database open to defeat the auto-flush for the
2532 // duration of this scope. This is the only place where this optimization
2533 // maybe makes sense; please don't do it anywhere else.
2534 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2536 // Take key pair from key pool so it won't be used again
2537 reservekey.KeepKey();
2539 // Add tx to wallet, because if it has change it's also ours,
2540 // otherwise just for transaction history.
2541 AddToWallet(wtxNew);
2543 // Mark old coins as spent
2544 for (const CTxIn& txin : wtxNew.vin)
2546 CWalletTx &coin = mapWallet[txin.prevout.hash];
2547 coin.BindWallet(this);
2548 coin.MarkSpent(txin.prevout.n);
2550 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2551 vMintingWalletUpdated.push_back(coin.GetHash());
2564 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2568 return _("Invalid amount");
2569 if (nValue + nTransactionFee > GetBalance())
2570 return _("Insufficient funds");
2572 CReserveKey reservekey(this);
2573 int64_t nFeeRequired;
2577 string strError = _("Error: Wallet locked, unable to create transaction ");
2578 printf("SendMoney() : %s", strError.c_str());
2581 if (fWalletUnlockMintOnly)
2583 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2584 printf("SendMoney() : %s", strError.c_str());
2587 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2590 if (nValue + nFeeRequired > GetBalance())
2591 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());
2593 strError = _("Error: Transaction creation failed ");
2594 printf("SendMoney() : %s", strError.c_str());
2598 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2601 if (!CommitTransaction(wtxNew, reservekey))
2602 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.");
2607 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2611 fFirstRunRet = false;
2612 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2613 if (nLoadWalletRet == DB_NEED_REWRITE)
2615 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2618 // Note: can't top-up keypool here, because wallet is locked.
2619 // User will be prompted to unlock wallet the next operation
2620 // the requires a new key.
2624 if (nLoadWalletRet != DB_LOAD_OK)
2625 return nLoadWalletRet;
2626 fFirstRunRet = !vchDefaultKey.IsValid();
2628 NewThread(ThreadFlushWalletDB, &strWalletFile);
2632 DBErrors CWallet::ZapWalletTx()
2636 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2637 if (nZapWalletTxRet == DB_NEED_REWRITE)
2639 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2643 // Note: can't top-up keypool here, because wallet is locked.
2644 // User will be prompted to unlock wallet the next operation
2645 // the requires a new key.
2649 if (nZapWalletTxRet != DB_LOAD_OK)
2650 return nZapWalletTxRet;
2655 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2657 return SetAddressBookName(CBitcoinAddress(address), strName);
2660 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
2662 std::map<CBitcoinAddress, string>::iterator mi = mapAddressBook.find(address);
2663 mapAddressBook[address] = strName;
2664 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2667 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
2670 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
2672 mapAddressBook.erase(address);
2673 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2676 return CWalletDB(strWalletFile).EraseName(address.ToString());
2680 void CWallet::PrintWallet(const CBlock& block)
2684 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2686 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2687 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2689 else if (mapWallet.count(block.vtx[0].GetHash()))
2691 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2692 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2698 void CWallet::Inventory(const uint256 &hash)
2702 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
2703 if (mi != mapRequestCount.end())
2708 unsigned int CWallet::GetKeyPoolSize()
2710 return (unsigned int)(setKeyPool.size());
2713 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2717 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2718 if (mi != mapWallet.end())
2727 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2731 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2734 vchDefaultKey = vchPubKey;
2738 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2740 if (!pwallet->fFileBacked)
2742 strWalletFileOut = pwallet->strWalletFile;
2747 // Mark old keypool keys as used,
2748 // and generate all new keys
2750 bool CWallet::NewKeyPool(unsigned int nSize)
2754 CWalletDB walletdb(strWalletFile);
2755 for (int64_t nIndex : setKeyPool)
2756 walletdb.ErasePool(nIndex);
2766 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2768 for (uint64_t i = 0; i < nKeys; i++)
2770 uint64_t nIndex = i+1;
2771 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2772 setKeyPool.insert(nIndex);
2774 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2779 bool CWallet::TopUpKeyPool(unsigned int nSize)
2787 CWalletDB walletdb(strWalletFile);
2790 uint64_t nTargetSize;
2792 nTargetSize = nSize;
2794 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2796 while (setKeyPool.size() < (nTargetSize + 1))
2799 if (!setKeyPool.empty())
2800 nEnd = *(--setKeyPool.end()) + 1;
2801 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2802 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2803 setKeyPool.insert(nEnd);
2804 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2810 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2813 keypool.vchPubKey = CPubKey();
2820 // Get the oldest key
2821 if(setKeyPool.empty())
2824 CWalletDB walletdb(strWalletFile);
2826 nIndex = *(setKeyPool.begin());
2827 setKeyPool.erase(setKeyPool.begin());
2828 if (!walletdb.ReadPool(nIndex, keypool))
2829 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2830 if (!HaveKey(keypool.vchPubKey.GetID()))
2831 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2832 assert(keypool.vchPubKey.IsValid());
2833 if (fDebug && GetBoolArg("-printkeypool"))
2834 printf("keypool reserve %" PRId64 "\n", nIndex);
2838 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2841 LOCK2(cs_main, cs_wallet);
2842 CWalletDB walletdb(strWalletFile);
2844 int64_t nIndex = 1 + *(--setKeyPool.end());
2845 if (!walletdb.WritePool(nIndex, keypool))
2846 throw runtime_error("AddReserveKey() : writing added key failed");
2847 setKeyPool.insert(nIndex);
2853 void CWallet::KeepKey(int64_t nIndex)
2855 // Remove from key pool
2858 CWalletDB walletdb(strWalletFile);
2859 walletdb.ErasePool(nIndex);
2862 printf("keypool keep %" PRId64 "\n", nIndex);
2865 void CWallet::ReturnKey(int64_t nIndex)
2867 // Return to key pool
2870 setKeyPool.insert(nIndex);
2873 printf("keypool return %" PRId64 "\n", nIndex);
2876 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2882 ReserveKeyFromKeyPool(nIndex, keypool);
2885 if (fAllowReuse && vchDefaultKey.IsValid())
2887 result = vchDefaultKey;
2890 if (IsLocked()) return false;
2891 result = GenerateNewKey();
2895 result = keypool.vchPubKey;
2900 int64_t CWallet::GetOldestKeyPoolTime()
2904 ReserveKeyFromKeyPool(nIndex, keypool);
2908 return keypool.nTime;
2911 std::map<CBitcoinAddress, int64_t> CWallet::GetAddressBalances()
2913 map<CBitcoinAddress, int64_t> balances;
2917 for (auto walletEntry : mapWallet)
2919 CWalletTx *pcoin = &walletEntry.second;
2921 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2924 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2927 int nDepth = pcoin->GetDepthInMainChain();
2928 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2931 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2933 CBitcoinAddress addr;
2934 if (!IsMine(pcoin->vout[i]))
2936 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, addr))
2939 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2941 if (!balances.count(addr))
2943 balances[addr] += n;
2951 set< set<CBitcoinAddress> > CWallet::GetAddressGroupings()
2953 set< set<CBitcoinAddress> > groupings;
2954 set<CBitcoinAddress> grouping;
2956 for (auto& walletEntry : mapWallet)
2958 CWalletTx *pcoin = &walletEntry.second;
2960 if (pcoin->vin.size() > 0)
2962 bool any_mine = false;
2963 // group all input addresses with each other
2964 for (CTxIn txin : pcoin->vin)
2966 CBitcoinAddress address;
2967 if(!IsMine(txin)) // If this input isn't mine, ignore it
2969 if(!ExtractAddress(*this, mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2971 grouping.insert(address);
2975 // group change with input addresses
2978 for (CTxOut txout : pcoin->vout)
2979 if (IsChange(txout))
2981 CBitcoinAddress txoutAddr;
2982 if(!ExtractAddress(*this, txout.scriptPubKey, txoutAddr))
2984 grouping.insert(txoutAddr);
2987 if (!grouping.empty())
2989 groupings.insert(grouping);
2994 // group lone addrs by themselves
2995 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2996 if (IsMine(pcoin->vout[i]))
2998 CBitcoinAddress address;
2999 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, address))
3001 grouping.insert(address);
3002 groupings.insert(grouping);
3007 set< set<CBitcoinAddress>* > uniqueGroupings; // a set of pointers to groups of addresses
3008 map< CBitcoinAddress, set<CBitcoinAddress>* > setmap; // map addresses to the unique group containing it
3009 for (set<CBitcoinAddress> grouping : groupings)
3011 // make a set of all the groups hit by this new group
3012 set< set<CBitcoinAddress>* > hits;
3013 map< CBitcoinAddress, set<CBitcoinAddress>* >::iterator it;
3014 for (CBitcoinAddress address : grouping)
3015 if ((it = setmap.find(address)) != setmap.end())
3016 hits.insert((*it).second);
3018 // merge all hit groups into a new single group and delete old groups
3019 set<CBitcoinAddress>* merged = new set<CBitcoinAddress>(grouping);
3020 for (set<CBitcoinAddress>* hit : hits)
3022 merged->insert(hit->begin(), hit->end());
3023 uniqueGroupings.erase(hit);
3026 uniqueGroupings.insert(merged);
3029 for (CBitcoinAddress element : *merged)
3030 setmap[element] = merged;
3033 set< set<CBitcoinAddress> > ret;
3034 for (set<CBitcoinAddress>* uniqueGrouping : uniqueGroupings)
3036 ret.insert(*uniqueGrouping);
3037 delete uniqueGrouping;
3043 // ppcoin: check 'spent' consistency between wallet and txindex
3044 // ppcoin: fix wallet spent state according to txindex
3045 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
3048 nBalanceInQuestion = 0;
3051 vector<CWalletTx*> vCoins;
3052 vCoins.reserve(mapWallet.size());
3053 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3054 vCoins.push_back(&(*it).second);
3057 for (CWalletTx* pcoin : vCoins)
3059 // Find the corresponding transaction index
3061 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
3063 for (unsigned int n=0; n < pcoin->vout.size(); n++)
3065 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
3067 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
3068 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3070 nBalanceInQuestion += pcoin->vout[n].nValue;
3073 pcoin->MarkUnspent(n);
3074 pcoin->WriteToDisk();
3077 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
3079 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
3080 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3082 nBalanceInQuestion += pcoin->vout[n].nValue;
3085 pcoin->MarkSpent(n);
3086 pcoin->WriteToDisk();
3092 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
3094 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
3097 EraseFromWallet(pcoin->GetHash());
3103 // ppcoin: disable transaction (only for coinstake)
3104 void CWallet::DisableTransaction(const CTransaction &tx)
3106 if (!tx.IsCoinStake() || !IsFromMe(tx))
3107 return; // only disconnecting coinstake requires marking input unspent
3110 for (const CTxIn& txin : tx.vin)
3112 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
3113 if (mi != mapWallet.end())
3115 CWalletTx& prev = (*mi).second;
3116 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
3118 prev.MarkUnspent(txin.prevout.n);
3125 CPubKey CReserveKey::GetReservedKey()
3130 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3132 vchPubKey = keypool.vchPubKey;
3135 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
3136 vchPubKey = pwallet->vchDefaultKey;
3139 assert(vchPubKey.IsValid());
3143 void CReserveKey::KeepKey()
3146 pwallet->KeepKey(nIndex);
3148 vchPubKey = CPubKey();
3151 CReserveKey::CReserveKey(CWallet *pwalletIn)
3154 pwallet = pwalletIn;
3157 CReserveKey::~CReserveKey()
3163 void CReserveKey::ReturnKey()
3166 pwallet->ReturnKey(nIndex);
3168 vchPubKey = CPubKey();
3171 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3175 CWalletDB walletdb(strWalletFile);
3177 LOCK2(cs_main, cs_wallet);
3178 for (const int64_t& id : setKeyPool)
3181 if (!walletdb.ReadPool(id, keypool))
3182 throw runtime_error("GetAllReserveKeyHashes() : read failed");
3183 assert(keypool.vchPubKey.IsValid());
3184 CKeyID keyID = keypool.vchPubKey.GetID();
3185 if (!HaveKey(keyID))
3186 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
3187 setAddress.insert(keyID);
3191 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3195 // Only notify UI if this transaction is in this wallet
3196 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3197 if (mi != mapWallet.end())
3199 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3200 vMintingWalletUpdated.push_back(hashTx);
3205 void CWallet::GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const {
3206 mapAddresses.clear();
3208 // get birth times for keys with metadata
3209 for (std::map<CBitcoinAddress, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
3210 mapAddresses[it->first] = it->second.nCreateTime ? it->second.nCreateTime : 0;
3213 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3214 // iterate over all wallet transactions...
3215 const CWalletTx &wtx = (*it).second;
3216 if (wtx.hashBlock == 0)
3217 continue; // skip unconfirmed transactions
3219 for(std::vector<CTxOut>::const_iterator it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
3220 const CTxOut &out = (*it2);
3221 // iterate over all their outputs
3222 CBitcoinAddress addressRet;
3223 if (ExtractAddress(*this, out.scriptPubKey, addressRet)) {
3224 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
3225 mapAddresses[addressRet] = wtx.nTime;
3228 // multisig output affects more than one key
3229 std::vector<CKeyID> vAffected;
3230 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
3232 for(std::vector<CKeyID>::const_iterator it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
3233 CBitcoinAddress addrAffected(*it3);
3234 if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
3235 mapAddresses[addrAffected] = wtx.nTime;
3243 void CWallet::ClearOrphans()
3245 list<uint256> orphans;
3248 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3250 const CWalletTx *wtx = &(*it).second;
3251 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
3253 orphans.push_back(wtx->GetHash());
3257 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
3258 EraseFromWallet(*it);
3262 CWalletTx::CWalletTx()
3267 CWalletTx::CWalletTx(const CWallet *pwalletIn)
3272 CWalletTx::CWalletTx(const CWallet *pwalletIn, const CMerkleTx &txIn) : CMerkleTx(txIn)
3277 CWalletTx::CWalletTx(const CWallet *pwalletIn, const CTransaction &txIn) : CMerkleTx(txIn)
3282 void CWalletTx::Init(const CWallet *pwalletIn)
3284 pwallet = pwalletIn;
3288 fTimeReceivedIsTxTime = false;
3292 strFromAccount.clear();
3294 fDebitCached = false;
3295 fWatchDebitCached = false;
3296 fCreditCached = false;
3297 fWatchCreditCached = false;
3298 fAvailableCreditCached = false;
3299 fAvailableWatchCreditCached = false;
3300 fImmatureCreditCached = false;
3301 fImmatureWatchCreditCached = false;
3302 fChangeCached = false;
3304 nWatchDebitCached = 0;
3306 nWatchCreditCached = 0;
3307 nAvailableCreditCached = 0;
3308 nAvailableWatchCreditCached = 0;
3309 nImmatureCreditCached = 0;
3310 nImmatureWatchCreditCached = 0;
3315 COutput::COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
3317 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
3320 string COutput::ToString() const
3322 return strprintf("COutput(%s, %d, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, fSpendable, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
3325 CAccount::CAccount()
3330 void CAccount::SetNull()
3332 vchPubKey = CPubKey();
3335 CAccountingEntry::CAccountingEntry()
3340 void CAccountingEntry::SetNull()
3345 strOtherAccount.clear();
3350 CWalletKey::CWalletKey(int64_t nExpires)
3352 nTimeCreated = (nExpires ? GetTime() : 0);
3353 nTimeExpires = nExpires;
3356 CKeyPool::CKeyPool()
3361 CKeyPool::CKeyPool(const CPubKey &vchPubKeyIn)
3364 vchPubKey = vchPubKeyIn;