1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <openssl/bio.h>
20 extern int64_t nReserveBalance;
22 //////////////////////////////////////////////////////////////////////////////
27 struct CompareValueOnly
29 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
30 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
32 return t1.first < t2.first;
36 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
39 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
40 if (it == mapWallet.end())
45 CPubKey CWallet::GenerateNewKey()
47 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
51 key.MakeNewKey(fCompressed);
53 // Compressed public keys were introduced in version 0.6.0
55 SetMinVersion(FEATURE_COMPRPUBKEY);
57 CPubKey pubkey = key.GetPubKey();
59 // Create new metadata
60 int64_t nCreationTime = GetTime();
61 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = CKeyMetadata(nCreationTime);
62 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
63 nTimeFirstKey = nCreationTime;
66 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
67 return key.GetPubKey();
70 CMalleableKeyView CWallet::GenerateNewMalleableKey()
74 // Compressed public keys were introduced in version 0.6.0
75 SetMinVersion(FEATURE_MALLKEY);
79 const CMalleableKeyView &keyView(mKey);
81 // Create new metadata
82 int64_t nCreationTime = GetTime();
83 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = CKeyMetadata(nCreationTime);
84 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
85 nTimeFirstKey = nCreationTime;
88 throw std::runtime_error("CWallet::GenerateNewMalleableKey() : AddKey failed");
89 return CMalleableKeyView(mKey);
92 bool CWallet::AddKey(const CKey& key)
94 CPubKey pubkey = key.GetPubKey();
95 if (!CCryptoKeyStore::AddKey(key))
100 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(pubkey.GetID())]);
104 bool CWallet::AddKey(const CMalleableKey& mKey)
106 CMalleableKeyView keyView = CMalleableKeyView(mKey);
107 CSecret vchSecretH = mKey.GetSecretH();
108 if (!CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH))
113 return CWalletDB(strWalletFile).WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
117 bool CWallet::AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH)
119 if (!CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH))
127 CBitcoinAddress addr(keyView.GetMalleablePubKey());
128 if (pwalletdbEncryption)
129 return pwalletdbEncryption->WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
131 return CWalletDB(strWalletFile).WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
137 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
139 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
142 // check if we need to remove from watch-only
144 script.SetDestination(vchPubKey.GetID());
145 if (HaveWatchOnly(script))
146 RemoveWatchOnly(script);
152 CBitcoinAddress addr(vchPubKey.GetID());
153 if (pwalletdbEncryption)
154 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
156 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
161 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
163 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
164 nTimeFirstKey = meta.nCreateTime;
166 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = meta;
170 bool CWallet::LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
172 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
173 nTimeFirstKey = metadata.nCreateTime;
175 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = metadata;
179 bool CWallet::AddCScript(const CScript& redeemScript)
181 if (!CCryptoKeyStore::AddCScript(redeemScript))
185 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
188 bool CWallet::LoadCScript(const CScript& redeemScript)
190 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
191 * that never can be redeemed. However, old wallets may still contain
192 * these. Do not add them to the wallet and warn. */
193 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
195 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
196 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",
197 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
201 return CCryptoKeyStore::AddCScript(redeemScript);
205 bool CWallet::AddWatchOnly(const CScript &dest)
207 if (!CCryptoKeyStore::AddWatchOnly(dest))
209 nTimeFirstKey = 1; // No birthday information for watch-only keys.
210 NotifyWatchonlyChanged(true);
213 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
216 bool CWallet::RemoveWatchOnly(const CScript &dest)
219 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
221 if (!HaveWatchOnly())
222 NotifyWatchonlyChanged(false);
224 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
230 bool CWallet::LoadWatchOnly(const CScript &dest)
232 return CCryptoKeyStore::AddWatchOnly(dest);
235 // ppcoin: optional setting to unlock wallet for block minting only;
236 // serves to disable the trivial sendmoney when OS account compromised
237 bool fWalletUnlockMintOnly = false;
239 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
245 CKeyingMaterial vMasterKey;
249 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
251 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
253 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
255 if (CCryptoKeyStore::Unlock(vMasterKey))
262 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
264 bool fWasLocked = IsLocked();
271 CKeyingMaterial vMasterKey;
272 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
274 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
276 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
278 if (CCryptoKeyStore::Unlock(vMasterKey))
280 int64_t nStartTime = GetTimeMillis();
281 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
282 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
283 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
285 nStartTime = GetTimeMillis();
286 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
287 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
288 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
290 if (pMasterKey.second.nDeriveIterations < 25000)
291 pMasterKey.second.nDeriveIterations = 25000;
293 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
295 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
297 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
299 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
310 void CWallet::SetBestChain(const CBlockLocator& loc)
312 CWalletDB walletdb(strWalletFile);
313 walletdb.WriteBestBlock(loc);
316 // This class implements an addrIncoming entry that causes pre-0.4
317 // clients to crash on startup if reading a private-key-encrypted wallet.
318 class CCorruptAddress
323 if (nType & SER_DISK)
328 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
330 if (nWalletVersion >= nVersion)
333 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
334 if (fExplicit && nVersion > nWalletMaxVersion)
335 nVersion = FEATURE_LATEST;
337 nWalletVersion = nVersion;
339 if (nVersion > nWalletMaxVersion)
340 nWalletMaxVersion = nVersion;
344 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
345 if (nWalletVersion > 40000)
346 pwalletdb->WriteMinVersion(nWalletVersion);
354 bool CWallet::SetMaxVersion(int nVersion)
356 // cannot downgrade below current version
357 if (nWalletVersion > nVersion)
360 nWalletMaxVersion = nVersion;
365 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
370 CKeyingMaterial vMasterKey;
371 RandAddSeedPerfmon();
373 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
374 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
376 CMasterKey kMasterKey;
378 RandAddSeedPerfmon();
379 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
380 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
383 int64_t nStartTime = GetTimeMillis();
384 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
385 int64_t nDivider = GetTimeMillis() - nStartTime;
386 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
388 nStartTime = GetTimeMillis();
389 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
390 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
391 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
393 if (kMasterKey.nDeriveIterations < 25000)
394 kMasterKey.nDeriveIterations = 25000;
396 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
398 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
400 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
405 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
408 pwalletdbEncryption = new CWalletDB(strWalletFile);
409 if (!pwalletdbEncryption->TxnBegin())
411 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
414 if (!EncryptKeys(vMasterKey))
417 pwalletdbEncryption->TxnAbort();
418 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.
421 // Encryption was introduced in version 0.4.0
422 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
426 if (!pwalletdbEncryption->TxnCommit())
427 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.
429 delete pwalletdbEncryption;
430 pwalletdbEncryption = NULL;
434 Unlock(strWalletPassphrase);
438 // Need to completely rewrite the wallet file; if we don't, bdb might keep
439 // bits of the unencrypted private key in slack space in the database file.
440 CDB::Rewrite(strWalletFile);
443 NotifyStatusChanged(this);
448 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
454 CKeyingMaterial vMasterKey;
458 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
460 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
462 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
464 if (!CCryptoKeyStore::Unlock(vMasterKey))
470 pwalletdbDecryption = new CWalletDB(strWalletFile);
471 if (!pwalletdbDecryption->TxnBegin())
475 if (!DecryptKeys(vMasterKey))
478 pwalletdbDecryption->TxnAbort();
479 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.
484 // Overwrite crypted keys
485 KeyMap::const_iterator mi = mapKeys.begin();
486 while (mi != mapKeys.end())
489 key.SetSecret((*mi).second.first, (*mi).second.second);
490 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
491 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(mi->first)]);
495 MalleableKeyMap::const_iterator mi2 = mapMalleableKeys.begin();
496 while (mi2 != mapMalleableKeys.end())
498 const CSecret &vchSecretH = mi2->second;
499 const CMalleableKeyView &keyView = mi2->first;
500 pwalletdbDecryption->EraseCryptedMalleableKey(keyView);
501 pwalletdbDecryption->WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
506 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
507 while (mk != mapMasterKeys.end())
509 pwalletdbDecryption->EraseMasterKey((*mk).first);
513 if (!pwalletdbDecryption->TxnCommit())
514 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.
516 delete pwalletdbDecryption;
517 pwalletdbDecryption = NULL;
520 // Need to completely rewrite the wallet file; if we don't, bdb might keep
521 // encrypted private keys in the database file which can be a reason of consistency issues.
522 CDB::Rewrite(strWalletFile);
524 NotifyStatusChanged(this);
529 bool CWallet::GetPEM(const CKeyID &keyID, const std::string &fileName, const SecureString &strPassKey) const
531 BIO *pemOut = BIO_new_file(fileName.c_str(), "w");
533 return error("GetPEM() : failed to create file %s\n", fileName.c_str());
535 if (!GetKey(keyID, key))
536 return error("GetPEM() : failed to get key for address=%s\n", CBitcoinAddress(keyID).ToString().c_str());
537 bool result = key.WritePEM(pemOut, strPassKey);
542 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
544 int64_t nRet = nOrderPosNext++;
546 pwalletdb->WriteOrderPosNext(nOrderPosNext);
548 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
553 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
555 CWalletDB walletdb(strWalletFile);
557 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
560 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
561 // would make this much faster for applications that do this a lot.
562 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
564 CWalletTx* wtx = &((*it).second);
565 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
568 walletdb.ListAccountCreditDebit(strAccount, acentries);
569 BOOST_FOREACH(CAccountingEntry& entry, acentries)
571 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
577 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
579 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
580 // Update the wallet spent flag if it doesn't know due to wallet.dat being
581 // restored from backup or the user making copies of wallet.dat.
584 BOOST_FOREACH(const CTxIn& txin, tx.vin)
586 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
587 if (mi != mapWallet.end())
589 CWalletTx& wtx = (*mi).second;
590 if (txin.prevout.n >= wtx.vout.size())
591 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
592 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
594 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
595 wtx.MarkSpent(txin.prevout.n);
597 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
598 vMintingWalletUpdated.push_back(txin.prevout.hash);
605 uint256 hash = tx.GetHash();
606 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
607 CWalletTx& wtx = (*mi).second;
609 BOOST_FOREACH(const CTxOut& txout, tx.vout)
613 wtx.MarkUnspent(&txout - &tx.vout[0]);
615 NotifyTransactionChanged(this, hash, CT_UPDATED);
616 vMintingWalletUpdated.push_back(hash);
624 void CWallet::MarkDirty()
628 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
629 item.second.MarkDirty();
633 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
635 uint256 hash = wtxIn.GetHash();
638 // Inserts only if not already there, returns tx inserted or tx found
639 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
640 CWalletTx& wtx = (*ret.first).second;
641 wtx.BindWallet(this);
642 bool fInsertedNew = ret.second;
645 wtx.nTimeReceived = GetAdjustedTime();
646 wtx.nOrderPos = IncOrderPosNext();
648 wtx.nTimeSmart = wtx.nTimeReceived;
649 if (wtxIn.hashBlock != 0)
651 if (mapBlockIndex.count(wtxIn.hashBlock))
653 unsigned int latestNow = wtx.nTimeReceived;
654 unsigned int latestEntry = 0;
656 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
657 int64_t latestTolerated = latestNow + 300;
658 std::list<CAccountingEntry> acentries;
659 TxItems txOrdered = OrderedTxItems(acentries);
660 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
662 CWalletTx *const pwtx = (*it).second.first;
665 CAccountingEntry *const pacentry = (*it).second.second;
669 nSmartTime = pwtx->nTimeSmart;
671 nSmartTime = pwtx->nTimeReceived;
674 nSmartTime = pacentry->nTime;
675 if (nSmartTime <= latestTolerated)
677 latestEntry = nSmartTime;
678 if (nSmartTime > latestNow)
679 latestNow = nSmartTime;
685 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
686 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
689 printf("AddToWallet() : found %s in block %s not in index\n",
690 wtxIn.GetHash().ToString().substr(0,10).c_str(),
691 wtxIn.hashBlock.ToString().c_str());
695 bool fUpdated = false;
699 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
701 wtx.hashBlock = wtxIn.hashBlock;
704 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
706 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
707 wtx.nIndex = wtxIn.nIndex;
710 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
712 wtx.fFromMe = wtxIn.fFromMe;
715 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
719 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
722 if (fInsertedNew || fUpdated)
723 if (!wtx.WriteToDisk())
726 // If default receiving address gets used, replace it with a new one
727 CScript scriptDefaultKey;
728 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
729 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
731 if (txout.scriptPubKey == scriptDefaultKey)
733 CPubKey newDefaultKey;
734 if (GetKeyFromPool(newDefaultKey, false))
736 SetDefaultKey(newDefaultKey);
737 SetAddressBookName(vchDefaultKey.GetID(), "");
742 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
743 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
745 // Notify UI of new or updated transaction
746 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
747 vMintingWalletUpdated.push_back(hash);
748 // notify an external script when a wallet transaction comes in or is updated
749 std::string strCmd = GetArg("-walletnotify", "");
751 if ( !strCmd.empty())
753 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
754 boost::thread t(runCommand, strCmd); // thread runs free
761 // Add a transaction to the wallet, or update it.
762 // pblock is optional, but should be provided if the transaction is known to be in a block.
763 // If fUpdate is true, existing transactions will be updated.
764 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
766 uint256 hash = tx.GetHash();
769 bool fExisted = mapWallet.count(hash) != 0;
770 if (fExisted && !fUpdate) return false;
771 if (fExisted || IsMine(tx) || IsFromMe(tx))
773 CWalletTx wtx(this,tx);
774 // Get merkle branch if transaction was found in a block
776 wtx.SetMerkleBranch(pblock);
777 return AddToWallet(wtx);
780 WalletUpdateSpent(tx);
785 bool CWallet::EraseFromWallet(uint256 hash)
791 if (mapWallet.erase(hash))
792 CWalletDB(strWalletFile).EraseTx(hash);
798 isminetype CWallet::IsMine(const CTxIn &txin) const
802 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
803 if (mi != mapWallet.end())
805 const CWalletTx& prev = (*mi).second;
806 if (txin.prevout.n < prev.vout.size())
807 return IsMine(prev.vout[txin.prevout.n]);
813 // marks certain txout's as spent
814 // returns true if any update took place
815 bool CWalletTx::UpdateSpent(const std::vector<char>& vfNewSpent)
817 bool fReturn = false;
818 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
820 if (i == vfSpent.size())
823 if (vfNewSpent[i] && !vfSpent[i])
827 fAvailableCreditCached = fAvailableWatchCreditCached = false;
833 // make sure balances are recalculated
834 void CWalletTx::MarkDirty()
836 fCreditCached = false;
837 fAvailableCreditCached = fAvailableWatchCreditCached = false;
838 fDebitCached = fWatchDebitCached = false;
839 fChangeCached = false;
842 void CWalletTx::BindWallet(CWallet *pwalletIn)
848 void CWalletTx::MarkSpent(unsigned int nOut)
850 if (nOut >= vout.size())
851 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
852 vfSpent.resize(vout.size());
855 vfSpent[nOut] = true;
856 fAvailableCreditCached = fAvailableWatchCreditCached = false;
860 void CWalletTx::MarkUnspent(unsigned int nOut)
862 if (nOut >= vout.size())
863 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
864 vfSpent.resize(vout.size());
867 vfSpent[nOut] = false;
868 fAvailableCreditCached = fAvailableWatchCreditCached = false;
872 bool CWalletTx::IsSpent(unsigned int nOut) const
874 if (nOut >= vout.size())
875 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
876 if (nOut >= vfSpent.size())
878 return (!!vfSpent[nOut]);
881 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
885 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
886 if (mi != mapWallet.end())
888 const CWalletTx& prev = (*mi).second;
889 if (txin.prevout.n < prev.vout.size())
890 if (IsMine(prev.vout[txin.prevout.n]) & filter)
891 return prev.vout[txin.prevout.n].nValue;
897 isminetype CWallet::IsMine(const CTxOut& txout) const
899 return ::IsMine(*this, txout.scriptPubKey);
902 int64_t CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
904 if (!MoneyRange(txout.nValue))
905 throw std::runtime_error("CWallet::GetCredit() : value out of range");
906 return (IsMine(txout) & filter ? txout.nValue : 0);
909 bool CWallet::IsChange(const CTxOut& txout) const
911 // TODO: fix handling of 'change' outputs. The assumption is that any
912 // payment to a script that is ours, but isn't in the address book
913 // is change. That assumption is likely to break when we implement multisignature
914 // wallets that return change back into a multi-signature-protected address;
915 // a better way of identifying which outputs are 'the send' and which are
916 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
917 // which output, if any, was change).
918 if (::IsMine(*this, txout.scriptPubKey))
920 CTxDestination address;
921 if (!ExtractDestination(txout.scriptPubKey, address))
925 if (!mapAddressBook.count(address))
931 int64_t CWallet::GetChange(const CTxOut& txout) const
933 if (!MoneyRange(txout.nValue))
934 throw std::runtime_error("CWallet::GetChange() : value out of range");
935 return (IsChange(txout) ? txout.nValue : 0);
938 bool CWallet::IsMine(const CTransaction& tx) const
940 BOOST_FOREACH(const CTxOut& txout, tx.vout)
941 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
946 bool CWallet::IsFromMe(const CTransaction& tx) const
948 return (GetDebit(tx, MINE_ALL) > 0);
951 int64_t CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
954 BOOST_FOREACH(const CTxIn& txin, tx.vin)
956 nDebit += GetDebit(txin, filter);
957 if (!MoneyRange(nDebit))
958 throw std::runtime_error("CWallet::GetDebit() : value out of range");
963 int64_t CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
966 BOOST_FOREACH(const CTxOut& txout, tx.vout)
968 nCredit += GetCredit(txout, filter);
969 if (!MoneyRange(nCredit))
970 throw std::runtime_error("CWallet::GetCredit() : value out of range");
975 int64_t CWallet::GetChange(const CTransaction& tx) const
978 BOOST_FOREACH(const CTxOut& txout, tx.vout)
980 nChange += GetChange(txout);
981 if (!MoneyRange(nChange))
982 throw std::runtime_error("CWallet::GetChange() : value out of range");
987 int64_t CWalletTx::GetTxTime() const
992 int CWalletTx::GetRequestCount() const
994 // Returns -1 if it wasn't being tracked
997 LOCK(pwallet->cs_wallet);
998 if (IsCoinBase() || IsCoinStake())
1003 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1004 if (mi != pwallet->mapRequestCount.end())
1005 nRequests = (*mi).second;
1010 // Did anyone request this transaction?
1011 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1012 if (mi != pwallet->mapRequestCount.end())
1014 nRequests = (*mi).second;
1016 // How about the block it's in?
1017 if (nRequests == 0 && hashBlock != 0)
1019 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1020 if (mi != pwallet->mapRequestCount.end())
1021 nRequests = (*mi).second;
1023 nRequests = 1; // If it's in someone else's block it must have got out
1031 bool CWalletTx::InMempool() const
1034 if (mempool.exists(GetHash())) {
1040 bool CWalletTx::IsTrusted() const
1042 // Quick answer in most cases
1045 int nDepth = GetDepthInMainChain();
1050 if (!fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
1053 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1057 // Trusted if all inputs are from us and are in the mempool:
1058 BOOST_FOREACH(const CTxIn& txin, vin)
1060 // Transactions not sent by us: not trusted
1061 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1064 const CTxOut& parentOut = parent->vout[txin.prevout.n];
1065 if (pwallet->IsMine(parentOut) != MINE_SPENDABLE)
1071 int64_t CWalletTx::GetDebit(const isminefilter& filter) const
1077 if (filter & MINE_SPENDABLE)
1080 nDebit += nDebitCached;
1083 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
1084 fDebitCached = true;
1085 nDebit += nDebitCached;
1088 if (filter & MINE_WATCH_ONLY)
1090 if (fWatchDebitCached)
1091 nDebit += nWatchDebitCached;
1094 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
1095 fWatchDebitCached = true;
1096 nDebit += nWatchDebitCached;
1102 int64_t CWalletTx::GetCredit(const isminefilter& filter) const
1104 // Must wait until coinbase is safely deep enough in the chain before valuing it
1105 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1109 if (filter & MINE_SPENDABLE)
1111 // GetBalance can assume transactions in mapWallet won't change
1113 credit += nCreditCached;
1116 nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1117 fCreditCached = true;
1118 credit += nCreditCached;
1121 if (filter & MINE_WATCH_ONLY)
1123 if (fWatchCreditCached)
1124 credit += nWatchCreditCached;
1127 nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1128 fWatchCreditCached = true;
1129 credit += nWatchCreditCached;
1135 int64_t CWalletTx::GetImmatureCredit(bool fUseCache) const
1137 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1139 if (fUseCache && fImmatureCreditCached)
1140 return nImmatureCreditCached;
1141 nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1142 fImmatureCreditCached = true;
1143 return nImmatureCreditCached;
1149 int64_t CWalletTx::GetImmatureWatchOnlyCredit(bool fUseCache) const
1151 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1153 if (fUseCache && fImmatureWatchCreditCached)
1154 return nImmatureWatchCreditCached;
1155 nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1156 fImmatureWatchCreditCached = true;
1157 return nImmatureWatchCreditCached;
1164 int64_t CWalletTx::GetAvailableCredit(bool fUseCache) const
1166 // Must wait until coinbase is safely deep enough in the chain before valuing it
1167 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1171 if (fAvailableCreditCached)
1172 return nAvailableCreditCached;
1175 int64_t nCredit = 0;
1176 for (unsigned int i = 0; i < vout.size(); i++)
1180 const CTxOut &txout = vout[i];
1181 nCredit += pwallet->GetCredit(txout, MINE_SPENDABLE);
1182 if (!MoneyRange(nCredit))
1183 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1187 nAvailableCreditCached = nCredit;
1188 fAvailableCreditCached = true;
1193 int64_t CWalletTx::GetAvailableWatchCredit(bool fUseCache) const
1195 // Must wait until coinbase is safely deep enough in the chain before valuing it
1196 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1200 if (fAvailableWatchCreditCached)
1201 return nAvailableWatchCreditCached;
1204 int64_t nCredit = 0;
1205 for (unsigned int i = 0; i < vout.size(); i++)
1209 const CTxOut &txout = vout[i];
1210 nCredit += pwallet->GetCredit(txout, MINE_WATCH_ONLY);
1211 if (!MoneyRange(nCredit))
1212 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1216 nAvailableWatchCreditCached = nCredit;
1217 fAvailableWatchCreditCached = true;
1222 int64_t CWalletTx::GetChange() const
1225 return nChangeCached;
1226 nChangeCached = pwallet->GetChange(*this);
1227 fChangeCached = true;
1228 return nChangeCached;
1231 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
1232 list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
1234 nGeneratedImmature = nGeneratedMature = nFee = 0;
1235 listReceived.clear();
1237 strSentAccount = strFromAccount;
1239 if (IsCoinBase() || IsCoinStake())
1241 if (GetBlocksToMaturity() > 0)
1242 nGeneratedImmature = pwallet->GetCredit(*this, filter);
1244 nGeneratedMature = GetCredit(filter);
1249 int64_t nDebit = GetDebit(filter);
1250 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1252 int64_t nValueOut = GetValueOut();
1253 nFee = nDebit - nValueOut;
1257 BOOST_FOREACH(const CTxOut& txout, vout)
1259 isminetype fIsMine = pwallet->IsMine(txout);
1260 // Only need to handle txouts if AT LEAST one of these is true:
1261 // 1) they debit from us (sent)
1262 // 2) the output is to us (received)
1265 // Don't report 'change' txouts
1266 if (pwallet->IsChange(txout))
1269 else if (!(fIsMine & filter))
1272 // In either case, we need to get the destination address
1273 CBitcoinAddress address;
1274 if (!ExtractAddress(*pwallet, txout.scriptPubKey, address))
1276 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1277 this->GetHash().ToString().c_str());
1278 address = CBitcoinAddress();
1281 // If we are debited by the transaction, add the output as a "sent" entry
1283 listSent.push_back(make_pair(address, txout.nValue));
1285 // If we are receiving the output, add it as a "received" entry
1286 if (fIsMine & filter)
1287 listReceived.push_back(make_pair(address, txout.nValue));
1292 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
1293 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
1295 nGenerated = nReceived = nSent = nFee = 0;
1297 int64_t allGeneratedImmature, allGeneratedMature, allFee;
1298 allGeneratedImmature = allGeneratedMature = allFee = 0;
1299 string strSentAccount;
1300 list<pair<CBitcoinAddress, int64_t> > listReceived;
1301 list<pair<CBitcoinAddress, int64_t> > listSent;
1302 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
1304 if (strAccount.empty())
1305 nGenerated = allGeneratedMature;
1306 if (strAccount == strSentAccount)
1308 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& s, listSent)
1313 LOCK(pwallet->cs_wallet);
1314 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& r, listReceived)
1316 if (pwallet->mapAddressBook.count(r.first))
1318 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
1319 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
1320 nReceived += r.second;
1322 else if (strAccount.empty())
1324 nReceived += r.second;
1330 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
1334 const int COPY_DEPTH = 3;
1335 if (SetMerkleBranch() < COPY_DEPTH)
1337 vector<uint256> vWorkQueue;
1338 BOOST_FOREACH(const CTxIn& txin, vin)
1339 vWorkQueue.push_back(txin.prevout.hash);
1341 // This critsect is OK because txdb is already open
1343 LOCK(pwallet->cs_wallet);
1344 map<uint256, const CMerkleTx*> mapWalletPrev;
1345 set<uint256> setAlreadyDone;
1346 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1348 uint256 hash = vWorkQueue[i];
1349 if (setAlreadyDone.count(hash))
1351 setAlreadyDone.insert(hash);
1354 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
1355 if (mi != pwallet->mapWallet.end())
1358 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
1359 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1361 else if (mapWalletPrev.count(hash))
1363 tx = *mapWalletPrev[hash];
1365 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1371 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1375 int nDepth = tx.SetMerkleBranch();
1376 vtxPrev.push_back(tx);
1378 if (nDepth < COPY_DEPTH)
1380 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1381 vWorkQueue.push_back(txin.prevout.hash);
1387 reverse(vtxPrev.begin(), vtxPrev.end());
1390 bool CWalletTx::WriteToDisk()
1392 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1395 // Scan the block chain (starting in pindexStart) for transactions
1396 // from or to us. If fUpdate is true, found transactions that already
1397 // exist in the wallet will be updated.
1398 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1402 CBlockIndex* pindex = pindexStart;
1408 block.ReadFromDisk(pindex, true);
1409 BOOST_FOREACH(CTransaction& tx, block.vtx)
1411 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1414 pindex = pindex->pnext;
1420 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1423 tx.ReadFromDisk(COutPoint(hashTx, 0));
1424 if (AddToWalletIfInvolvingMe(tx, NULL, true))
1429 void CWallet::ReacceptWalletTransactions()
1432 bool fRepeat = true;
1437 vector<CDiskTxPos> vMissingTx;
1438 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1440 CWalletTx& wtx = item.second;
1441 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1445 bool fUpdated = false;
1446 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1448 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1449 if (txindex.vSpent.size() != wtx.vout.size())
1451 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1454 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1458 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1462 vMissingTx.push_back(txindex.vSpent[i]);
1467 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1474 // Re-accept any txes of ours that aren't already in a block
1475 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1476 wtx.AcceptWalletTransaction(txdb, false);
1479 if (!vMissingTx.empty())
1481 // TODO: optimize this to scan just part of the block chain?
1482 if (ScanForWalletTransactions(pindexGenesisBlock))
1483 fRepeat = true; // Found missing transactions: re-do re-accept.
1488 bool CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1490 uint256 hash = GetHash();
1491 if (IsCoinBase() || IsCoinStake() || txdb.ContainsTx(hash) || !InMempool())
1494 for(std::vector<CMerkleTx>::const_iterator it = vtxPrev.begin(); it != vtxPrev.end(); it++)
1496 const CMerkleTx& tx = *it;
1497 uint256 hash = tx.GetHash();
1499 if (tx.IsCoinBase() || tx.IsCoinStake())
1502 if (!txdb.ContainsTx(hash))
1503 RelayTransaction((CTransaction)tx, hash);
1506 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1507 RelayTransaction((CTransaction)*this, hash);
1511 bool CWalletTx::RelayWalletTransaction()
1514 return RelayWalletTransaction(txdb);
1517 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1519 std::vector<uint256> result;
1522 // Sort them in chronological order
1523 map<unsigned int, CWalletTx*> mapSorted;
1524 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1526 CWalletTx& wtx = item.second;
1527 // Don't rebroadcast if newer than nTime:
1528 if (wtx.nTimeReceived > nTime)
1530 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1532 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1534 CWalletTx& wtx = *item.second;
1535 if (wtx.RelayWalletTransaction())
1536 result.push_back(wtx.GetHash());
1541 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
1543 int64_t nNow = GetTime();
1545 // Do this infrequently and randomly to avoid giving away
1546 // that these are our transactions.
1547 if (nNow < nNextResend)
1549 bool fFirst = (nNextResend == 0);
1550 nNextResend = PoissonNextSend(nNow, 5*60);
1554 // Only do it if there's been a new block since last time
1555 if (nBestBlockTime < nLastResend)
1559 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1561 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime - 5*60);
1562 if (!relayed.empty())
1563 printf("CWallet::ResendWalletTransactions: rebroadcast %" PRIszu " unconfirmed transactions\n", relayed.size());
1567 //////////////////////////////////////////////////////////////////////////////
1573 int64_t CWallet::GetBalance() const
1578 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1580 const CWalletTx* pcoin = &(*it).second;
1581 if (pcoin->IsTrusted())
1582 nTotal += pcoin->GetAvailableCredit();
1589 int64_t CWallet::GetWatchOnlyBalance() const
1594 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1596 const CWalletTx* pcoin = &(*it).second;
1597 if (pcoin->IsTrusted())
1598 nTotal += pcoin->GetAvailableWatchCredit();
1605 int64_t CWallet::GetUnconfirmedBalance() const
1610 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1612 const CWalletTx* pcoin = &(*it).second;
1613 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1614 nTotal += pcoin->GetAvailableCredit();
1620 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1625 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1627 const CWalletTx* pcoin = &(*it).second;
1628 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1629 nTotal += pcoin->GetAvailableWatchCredit();
1635 int64_t CWallet::GetImmatureBalance() const
1640 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1642 const CWalletTx* pcoin = &(*it).second;
1643 nTotal += pcoin->GetImmatureCredit();
1649 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1654 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1656 const CWalletTx* pcoin = &(*it).second;
1657 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1663 // populate vCoins with vector of spendable COutputs
1664 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1670 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1672 const CWalletTx* pcoin = &(*it).second;
1674 if (!pcoin->IsFinal())
1677 if (fOnlyConfirmed && !pcoin->IsTrusted())
1680 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1683 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1686 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1687 isminetype mine = IsMine(pcoin->vout[i]);
1688 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1689 pcoin->vout[i].nValue >= nMinimumInputValue &&
1690 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1692 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1699 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1705 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1707 const CWalletTx* pcoin = &(*it).second;
1709 if (!pcoin->IsFinal())
1712 if(pcoin->GetDepthInMainChain() < nConf)
1715 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1716 isminetype mine = IsMine(pcoin->vout[i]);
1718 // ignore coin if it was already spent or we don't own it
1719 if (pcoin->IsSpent(i) || mine == MINE_NO)
1722 // if coin value is between required limits then add new item to vector
1723 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1724 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1730 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1731 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1733 vector<char> vfIncluded;
1735 vfBest.assign(vValue.size(), true);
1736 nBest = nTotalLower;
1738 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1740 vfIncluded.assign(vValue.size(), false);
1742 bool fReachedTarget = false;
1743 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1745 for (unsigned int i = 0; i < vValue.size(); i++)
1747 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1749 nTotal += vValue[i].first;
1750 vfIncluded[i] = true;
1751 if (nTotal >= nTargetValue)
1753 fReachedTarget = true;
1757 vfBest = vfIncluded;
1759 nTotal -= vValue[i].first;
1760 vfIncluded[i] = false;
1768 int64_t CWallet::GetStake() const
1772 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1774 const CWalletTx* pcoin = &(*it).second;
1775 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1776 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1781 int64_t CWallet::GetWatchOnlyStake() const
1785 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1787 const CWalletTx* pcoin = &(*it).second;
1788 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1789 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1794 int64_t CWallet::GetNewMint() const
1798 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1800 const CWalletTx* pcoin = &(*it).second;
1801 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1802 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1807 int64_t CWallet::GetWatchOnlyNewMint() const
1811 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1813 const CWalletTx* pcoin = &(*it).second;
1814 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1815 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1820 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
1822 setCoinsRet.clear();
1825 // List of values less than target
1826 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1827 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1828 coinLowestLarger.second.first = NULL;
1829 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1830 int64_t nTotalLower = 0;
1832 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1834 BOOST_FOREACH(const COutput &output, vCoins)
1836 if (!output.fSpendable)
1839 const CWalletTx *pcoin = output.tx;
1841 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1846 // Follow the timestamp rules
1847 if (pcoin->nTime > nSpendTime)
1850 int64_t n = pcoin->vout[i].nValue;
1852 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1854 if (n == nTargetValue)
1856 setCoinsRet.insert(coin.second);
1857 nValueRet += coin.first;
1860 else if (n < nTargetValue + CENT)
1862 vValue.push_back(coin);
1865 else if (n < coinLowestLarger.first)
1867 coinLowestLarger = coin;
1871 if (nTotalLower == nTargetValue)
1873 for (unsigned int i = 0; i < vValue.size(); ++i)
1875 setCoinsRet.insert(vValue[i].second);
1876 nValueRet += vValue[i].first;
1881 if (nTotalLower < nTargetValue)
1883 if (coinLowestLarger.second.first == NULL)
1885 setCoinsRet.insert(coinLowestLarger.second);
1886 nValueRet += coinLowestLarger.first;
1890 // Solve subset sum by stochastic approximation
1891 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
1892 std::reverse(vValue.begin(), vValue.end());
1893 vector<char> vfBest;
1896 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1897 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1898 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1900 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1901 // or the next bigger coin is closer), return the bigger coin
1902 if (coinLowestLarger.second.first &&
1903 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1905 setCoinsRet.insert(coinLowestLarger.second);
1906 nValueRet += coinLowestLarger.first;
1909 for (unsigned int i = 0; i < vValue.size(); i++)
1912 setCoinsRet.insert(vValue[i].second);
1913 nValueRet += vValue[i].first;
1916 if (fDebug && GetBoolArg("-printpriority"))
1919 printf("SelectCoins() best subset: ");
1920 for (unsigned int i = 0; i < vValue.size(); i++)
1922 printf("%s ", FormatMoney(vValue[i].first).c_str());
1923 printf("total %s\n", FormatMoney(nBest).c_str());
1930 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1932 vector<COutput> vCoins;
1933 AvailableCoins(vCoins, true, coinControl);
1935 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1936 if (coinControl && coinControl->HasSelected())
1938 BOOST_FOREACH(const COutput& out, vCoins)
1942 nValueRet += out.tx->vout[out.i].nValue;
1943 setCoinsRet.insert(make_pair(out.tx, out.i));
1945 return (nValueRet >= nTargetValue);
1948 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1949 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1950 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1953 // Select some coins without random shuffle or best subset approximation
1954 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
1956 vector<COutput> vCoins;
1957 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1959 setCoinsRet.clear();
1962 BOOST_FOREACH(COutput output, vCoins)
1964 if(!output.fSpendable)
1966 const CWalletTx *pcoin = output.tx;
1969 // Ignore immature coins
1970 if (pcoin->GetBlocksToMaturity() > 0)
1973 // Stop if we've chosen enough inputs
1974 if (nValueRet >= nTargetValue)
1977 // Follow the timestamp rules
1978 if (pcoin->nTime > nSpendTime)
1981 int64_t n = pcoin->vout[i].nValue;
1983 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1985 if (n >= nTargetValue)
1987 // If input value is greater or equal to target then simply insert
1988 // it into the current subset and exit
1989 setCoinsRet.insert(coin.second);
1990 nValueRet += coin.first;
1993 else if (n < nTargetValue + CENT)
1995 setCoinsRet.insert(coin.second);
1996 nValueRet += coin.first;
2003 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2006 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
2012 if (vecSend.empty() || nValue < 0)
2015 wtxNew.BindWallet(this);
2018 LOCK2(cs_main, cs_wallet);
2019 // txdb must be opened before the mapWallet lock
2022 nFeeRet = nTransactionFee;
2026 wtxNew.vout.clear();
2027 wtxNew.fFromMe = true;
2029 int64_t nTotalValue = nValue + nFeeRet;
2030 double dPriority = 0;
2031 // vouts to the payees
2032 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
2033 wtxNew.vout.push_back(CTxOut(s.second, s.first));
2035 // Choose coins to use
2036 set<pair<const CWalletTx*,unsigned int> > setCoins;
2037 int64_t nValueIn = 0;
2038 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
2040 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2042 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
2043 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
2046 int64_t nChange = nValueIn - nValue - nFeeRet;
2049 // Fill a vout to ourself
2050 // TODO: pass in scriptChange instead of reservekey so
2051 // change transaction isn't always pay-to-bitcoin-address
2052 CScript scriptChange;
2054 // coin control: send change to custom address
2055 if (coinControl && coinControl->destChange.IsValid())
2056 scriptChange.SetAddress(coinControl->destChange);
2058 // no coin control: send change to newly generated address
2061 // Note: We use a new key here to keep it from being obvious which side is the change.
2062 // The drawback is that by not reusing a previous key, the change may be lost if a
2063 // backup is restored, if the backup doesn't have the new private key for the change.
2064 // If we reused the old key, it would be possible to add code to look for and
2065 // rediscover unknown transactions that were written with keys of ours to recover
2066 // post-backup change.
2068 // Reserve a new key pair from key pool
2069 CPubKey vchPubKey = reservekey.GetReservedKey();
2071 scriptChange.SetDestination(vchPubKey.GetID());
2074 // Insert change txn at random position:
2075 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
2076 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
2079 reservekey.ReturnKey();
2082 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2083 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
2087 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2088 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
2092 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
2093 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2095 dPriority /= nBytes;
2097 // Check that enough fee is included
2098 bool fAllowFree = CTransaction::AllowFree(dPriority);
2099 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
2100 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2102 if (nFeeRet < max(nPayFee, nMinFee))
2104 nFeeRet = max(nPayFee, nMinFee);
2108 // Fill vtxPrev by copying from previous transactions vtxPrev
2109 wtxNew.AddSupportingTransactions(txdb);
2110 wtxNew.fTimeReceivedIsTxTime = true;
2119 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2121 vector< pair<CScript, int64_t> > vecSend;
2122 vecSend.push_back(make_pair(scriptPubKey, nValue));
2123 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
2126 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
2128 int64_t nTimeWeight = GetWeight(nTime, GetTime());
2130 // If time weight is lower or equal to zero then weight is zero.
2131 if (nTimeWeight <= 0)
2137 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
2138 nWeight = bnCoinDayWeight.getuint64();
2141 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
2143 int64_t nBalance = GetBalance();
2145 if (nAmount > nBalance)
2149 int64_t nValueIn = 0;
2150 set<pair<const CWalletTx*,unsigned int> > setCoins;
2152 // Simple coins selection - no randomization
2153 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
2156 if (setCoins.empty())
2160 vector<const CWalletTx*> vwtxPrev;
2162 // Reserve a new key pair from key pool
2163 CReserveKey reservekey(this);
2164 CPubKey vchPubKey = reservekey.GetReservedKey();
2167 CScript scriptOutput;
2168 scriptOutput.SetDestination(vchPubKey.GetID());
2171 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2174 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2176 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
2178 // Add current coin to inputs list and add its credit to transaction output
2179 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2180 wtxNew.vout[0].nValue += nCredit;
2181 vwtxPrev.push_back(pcoin.first);
2184 // Replaced with estimation for performance purposes
2186 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2187 const CWalletTx *txin = vwtxPrev[i];
2189 // Sign scripts to get actual transaction size for fee calculation
2190 if (!SignSignature(*this, *txin, wtxNew, i))
2195 // Assuming that average scriptsig size is 110 bytes
2196 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2197 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
2199 double dFinalPriority = dWeight /= nBytes;
2200 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2202 // Get actual transaction fee according to its estimated size and priority
2203 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2205 // Prepare transaction for commit if sum is enough ot its size is too big
2206 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
2208 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2210 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2211 const CWalletTx *txin = vwtxPrev[i];
2214 if (!SignSignature(*this, *txin, wtxNew, i))
2218 // Try to commit, return false on failure
2219 if (!CommitTransaction(wtxNew, reservekey))
2222 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2224 dWeight = 0; // Reset all temporary values
2227 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2231 // Create transactions if there are some unhandled coins left
2232 if (wtxNew.vout[0].nValue > 0) {
2233 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2235 double dFinalPriority = dWeight /= nBytes;
2236 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2238 // Get actual transaction fee according to its size and priority
2239 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2241 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2243 if (wtxNew.vout[0].nValue <= 0)
2246 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2247 const CWalletTx *txin = vwtxPrev[i];
2249 // Sign all scripts again
2250 if (!SignSignature(*this, *txin, wtxNew, i))
2254 // Try to commit, return false on failure
2255 if (!CommitTransaction(wtxNew, reservekey))
2258 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2264 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
2267 if (!GetTransaction(hashTx, wtx))
2268 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
2270 vector<valtype> vSolutions;
2271 txnouttype whichType;
2272 CScript scriptPubKeyOut;
2273 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
2274 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
2275 return error("CreateCoinStake : failed to parse kernel\n");
2277 if (fDebug && GetBoolArg("-printcoinstake"))
2278 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
2280 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
2281 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
2283 if (whichType == TX_PUBKEYHASH) // pay to address type
2285 // convert to pay to public key type
2286 if (!GetKey(uint160(vSolutions[0]), key))
2287 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2289 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
2291 if (whichType == TX_PUBKEY)
2293 valtype& vchPubKey = vSolutions[0];
2294 if (!GetKey(Hash160(vchPubKey), key))
2295 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2296 if (key.GetPubKey() != vchPubKey)
2297 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
2298 scriptPubKeyOut = scriptPubKeyKernel;
2301 // The following combine threshold is important to security
2302 // Should not be adjusted if you don't understand the consequences
2303 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
2305 int64_t nBalance = GetBalance();
2306 int64_t nCredit = wtx.vout[nOut].nValue;
2311 // List of constake dependencies
2312 vector<const CWalletTx*> vwtxPrev;
2313 vwtxPrev.push_back(&wtx);
2315 // Set generation time, and kernel input
2316 txNew.nTime = nGenerationTime;
2317 txNew.vin.push_back(CTxIn(hashTx, nOut));
2319 // Mark coin stake transaction with empty vout[0]
2320 CScript scriptEmpty;
2321 scriptEmpty.clear();
2322 txNew.vout.push_back(CTxOut(0, scriptEmpty));
2324 if (fDebug && GetBoolArg("-printcoinstake"))
2325 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2327 int64_t nValueIn = 0;
2329 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
2332 if (setCoins.empty())
2335 bool fDontSplitCoins = false;
2336 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
2338 // Only one output for old kernel inputs
2339 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2341 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
2343 // * Value is higher than 0.01 NVC;
2344 // * Only add inputs of the same key/address as kernel;
2345 // * Input hash and kernel parent hash should be different.
2346 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
2348 // Stop adding more inputs if already too many inputs
2349 if (txNew.vin.size() >= 100)
2351 // Stop adding more inputs if value is already pretty significant
2352 if (nCredit > nCombineThreshold)
2354 // Stop adding inputs if reached reserve limit
2355 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
2358 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
2360 // Do not add input that is still too young
2361 if (nTimeWeight < nStakeMaxAge)
2363 // Do not add input if key/address is not the same as kernel
2364 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2366 // Do not add input if parents are the same
2367 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2369 // Do not add additional significant input
2370 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2373 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2374 nCredit += pcoin->first->vout[pcoin->second].nValue;
2375 vwtxPrev.push_back(pcoin->first);
2378 fDontSplitCoins = true;
2382 int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2384 if (fDebug && GetBoolArg("-printcoinstake"))
2385 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2387 if (nCredit > nSplitThreshold)
2389 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2390 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2391 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2393 if (fDebug && GetBoolArg("-printcoinstake"))
2394 printf("CreateCoinStake : splitting coinstake\n");
2398 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2399 fDontSplitCoins = true;
2403 // Calculate coin age reward
2406 if (!txNew.GetCoinAge(txdb, nCoinAge))
2407 return error("CreateCoinStake : failed to calculate coin age\n");
2408 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2410 int64_t nMinFee = 0;
2413 // Set output amount
2414 if (fDontSplitCoins)
2415 txNew.vout[1].nValue = nCredit - nMinFee;
2418 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2419 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2424 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2426 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2427 return error("CreateCoinStake : failed to sign coinstake\n");
2431 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2432 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2433 return error("CreateCoinStake : exceeded coinstake size limit\n");
2435 // Check enough fee is paid
2436 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2438 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2439 continue; // try signing again
2443 if (fDebug && GetBoolArg("-printfee"))
2444 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2449 // Successfully created coinstake
2453 // Call after CreateTransaction unless you want to abort
2454 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2457 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2459 // Track how many getdata requests our transaction gets
2460 mapRequestCount[wtxNew.GetHash()] = 0;
2462 // Try to broadcast before saving
2463 if (!wtxNew.AcceptToMemoryPool())
2465 // This must not fail. The transaction has already been signed.
2466 printf("CommitTransaction() : Error: Transaction not valid");
2470 wtxNew.RelayWalletTransaction();
2473 LOCK2(cs_main, cs_wallet);
2475 // This is only to keep the database open to defeat the auto-flush for the
2476 // duration of this scope. This is the only place where this optimization
2477 // maybe makes sense; please don't do it anywhere else.
2478 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2480 // Take key pair from key pool so it won't be used again
2481 reservekey.KeepKey();
2483 // Add tx to wallet, because if it has change it's also ours,
2484 // otherwise just for transaction history.
2485 AddToWallet(wtxNew);
2487 // Mark old coins as spent
2488 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2490 CWalletTx &coin = mapWallet[txin.prevout.hash];
2491 coin.BindWallet(this);
2492 coin.MarkSpent(txin.prevout.n);
2494 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2495 vMintingWalletUpdated.push_back(coin.GetHash());
2508 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2512 return _("Invalid amount");
2513 if (nValue + nTransactionFee > GetBalance())
2514 return _("Insufficient funds");
2516 CReserveKey reservekey(this);
2517 int64_t nFeeRequired;
2521 string strError = _("Error: Wallet locked, unable to create transaction ");
2522 printf("SendMoney() : %s", strError.c_str());
2525 if (fWalletUnlockMintOnly)
2527 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2528 printf("SendMoney() : %s", strError.c_str());
2531 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2534 if (nValue + nFeeRequired > GetBalance())
2535 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());
2537 strError = _("Error: Transaction creation failed ");
2538 printf("SendMoney() : %s", strError.c_str());
2542 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2545 if (!CommitTransaction(wtxNew, reservekey))
2546 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.");
2551 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2555 fFirstRunRet = false;
2556 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2557 if (nLoadWalletRet == DB_NEED_REWRITE)
2559 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2562 // Note: can't top-up keypool here, because wallet is locked.
2563 // User will be prompted to unlock wallet the next operation
2564 // the requires a new key.
2568 if (nLoadWalletRet != DB_LOAD_OK)
2569 return nLoadWalletRet;
2570 fFirstRunRet = !vchDefaultKey.IsValid();
2572 NewThread(ThreadFlushWalletDB, &strWalletFile);
2576 DBErrors CWallet::ZapWalletTx()
2580 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2581 if (nZapWalletTxRet == DB_NEED_REWRITE)
2583 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2587 // Note: can't top-up keypool here, because wallet is locked.
2588 // User will be prompted to unlock wallet the next operation
2589 // the requires a new key.
2593 if (nZapWalletTxRet != DB_LOAD_OK)
2594 return nZapWalletTxRet;
2599 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2601 return SetAddressBookName(CBitcoinAddress(address), strName);
2604 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
2606 std::map<CBitcoinAddress, string>::iterator mi = mapAddressBook.find(address);
2607 mapAddressBook[address] = strName;
2608 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2611 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
2614 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
2616 mapAddressBook.erase(address);
2617 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2620 return CWalletDB(strWalletFile).EraseName(address.ToString());
2624 void CWallet::PrintWallet(const CBlock& block)
2628 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2630 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2631 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2633 else if (mapWallet.count(block.vtx[0].GetHash()))
2635 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2636 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2642 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2646 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2647 if (mi != mapWallet.end())
2656 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2660 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2663 vchDefaultKey = vchPubKey;
2667 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2669 if (!pwallet->fFileBacked)
2671 strWalletFileOut = pwallet->strWalletFile;
2676 // Mark old keypool keys as used,
2677 // and generate all new keys
2679 bool CWallet::NewKeyPool(unsigned int nSize)
2683 CWalletDB walletdb(strWalletFile);
2684 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2685 walletdb.ErasePool(nIndex);
2695 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2697 for (uint64_t i = 0; i < nKeys; i++)
2699 uint64_t nIndex = i+1;
2700 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2701 setKeyPool.insert(nIndex);
2703 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2708 bool CWallet::TopUpKeyPool(unsigned int nSize)
2716 CWalletDB walletdb(strWalletFile);
2719 uint64_t nTargetSize;
2721 nTargetSize = nSize;
2723 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2725 while (setKeyPool.size() < (nTargetSize + 1))
2728 if (!setKeyPool.empty())
2729 nEnd = *(--setKeyPool.end()) + 1;
2730 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2731 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2732 setKeyPool.insert(nEnd);
2733 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2739 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2742 keypool.vchPubKey = CPubKey();
2749 // Get the oldest key
2750 if(setKeyPool.empty())
2753 CWalletDB walletdb(strWalletFile);
2755 nIndex = *(setKeyPool.begin());
2756 setKeyPool.erase(setKeyPool.begin());
2757 if (!walletdb.ReadPool(nIndex, keypool))
2758 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2759 if (!HaveKey(keypool.vchPubKey.GetID()))
2760 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2761 assert(keypool.vchPubKey.IsValid());
2762 if (fDebug && GetBoolArg("-printkeypool"))
2763 printf("keypool reserve %" PRId64 "\n", nIndex);
2767 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2770 LOCK2(cs_main, cs_wallet);
2771 CWalletDB walletdb(strWalletFile);
2773 int64_t nIndex = 1 + *(--setKeyPool.end());
2774 if (!walletdb.WritePool(nIndex, keypool))
2775 throw runtime_error("AddReserveKey() : writing added key failed");
2776 setKeyPool.insert(nIndex);
2782 void CWallet::KeepKey(int64_t nIndex)
2784 // Remove from key pool
2787 CWalletDB walletdb(strWalletFile);
2788 walletdb.ErasePool(nIndex);
2791 printf("keypool keep %" PRId64 "\n", nIndex);
2794 void CWallet::ReturnKey(int64_t nIndex)
2796 // Return to key pool
2799 setKeyPool.insert(nIndex);
2802 printf("keypool return %" PRId64 "\n", nIndex);
2805 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2811 ReserveKeyFromKeyPool(nIndex, keypool);
2814 if (fAllowReuse && vchDefaultKey.IsValid())
2816 result = vchDefaultKey;
2819 if (IsLocked()) return false;
2820 result = GenerateNewKey();
2824 result = keypool.vchPubKey;
2829 int64_t CWallet::GetOldestKeyPoolTime()
2833 ReserveKeyFromKeyPool(nIndex, keypool);
2837 return keypool.nTime;
2840 std::map<CBitcoinAddress, int64_t> CWallet::GetAddressBalances()
2842 map<CBitcoinAddress, int64_t> balances;
2846 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2848 CWalletTx *pcoin = &walletEntry.second;
2850 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2853 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2856 int nDepth = pcoin->GetDepthInMainChain();
2857 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2860 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2862 CBitcoinAddress addr;
2863 if (!IsMine(pcoin->vout[i]))
2865 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, addr))
2868 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2870 if (!balances.count(addr))
2872 balances[addr] += n;
2880 set< set<CBitcoinAddress> > CWallet::GetAddressGroupings()
2882 set< set<CBitcoinAddress> > groupings;
2883 set<CBitcoinAddress> grouping;
2885 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2887 CWalletTx *pcoin = &walletEntry.second;
2889 if (pcoin->vin.size() > 0)
2891 bool any_mine = false;
2892 // group all input addresses with each other
2893 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2895 CBitcoinAddress address;
2896 if(!IsMine(txin)) // If this input isn't mine, ignore it
2898 if(!ExtractAddress(*this, mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2900 grouping.insert(address);
2904 // group change with input addresses
2907 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2908 if (IsChange(txout))
2910 CBitcoinAddress txoutAddr;
2911 if(!ExtractAddress(*this, txout.scriptPubKey, txoutAddr))
2913 grouping.insert(txoutAddr);
2916 if (!grouping.empty())
2918 groupings.insert(grouping);
2923 // group lone addrs by themselves
2924 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2925 if (IsMine(pcoin->vout[i]))
2927 CBitcoinAddress address;
2928 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, address))
2930 grouping.insert(address);
2931 groupings.insert(grouping);
2936 set< set<CBitcoinAddress>* > uniqueGroupings; // a set of pointers to groups of addresses
2937 map< CBitcoinAddress, set<CBitcoinAddress>* > setmap; // map addresses to the unique group containing it
2938 BOOST_FOREACH(set<CBitcoinAddress> grouping, groupings)
2940 // make a set of all the groups hit by this new group
2941 set< set<CBitcoinAddress>* > hits;
2942 map< CBitcoinAddress, set<CBitcoinAddress>* >::iterator it;
2943 BOOST_FOREACH(CBitcoinAddress address, grouping)
2944 if ((it = setmap.find(address)) != setmap.end())
2945 hits.insert((*it).second);
2947 // merge all hit groups into a new single group and delete old groups
2948 set<CBitcoinAddress>* merged = new set<CBitcoinAddress>(grouping);
2949 BOOST_FOREACH(set<CBitcoinAddress>* hit, hits)
2951 merged->insert(hit->begin(), hit->end());
2952 uniqueGroupings.erase(hit);
2955 uniqueGroupings.insert(merged);
2958 BOOST_FOREACH(CBitcoinAddress element, *merged)
2959 setmap[element] = merged;
2962 set< set<CBitcoinAddress> > ret;
2963 BOOST_FOREACH(set<CBitcoinAddress>* uniqueGrouping, uniqueGroupings)
2965 ret.insert(*uniqueGrouping);
2966 delete uniqueGrouping;
2972 // ppcoin: check 'spent' consistency between wallet and txindex
2973 // ppcoin: fix wallet spent state according to txindex
2974 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2977 nBalanceInQuestion = 0;
2980 vector<CWalletTx*> vCoins;
2981 vCoins.reserve(mapWallet.size());
2982 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2983 vCoins.push_back(&(*it).second);
2986 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2988 // Find the corresponding transaction index
2990 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2992 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2994 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2996 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
2997 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2999 nBalanceInQuestion += pcoin->vout[n].nValue;
3002 pcoin->MarkUnspent(n);
3003 pcoin->WriteToDisk();
3006 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
3008 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
3009 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3011 nBalanceInQuestion += pcoin->vout[n].nValue;
3014 pcoin->MarkSpent(n);
3015 pcoin->WriteToDisk();
3021 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
3023 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
3026 EraseFromWallet(pcoin->GetHash());
3032 // ppcoin: disable transaction (only for coinstake)
3033 void CWallet::DisableTransaction(const CTransaction &tx)
3035 if (!tx.IsCoinStake() || !IsFromMe(tx))
3036 return; // only disconnecting coinstake requires marking input unspent
3039 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3041 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
3042 if (mi != mapWallet.end())
3044 CWalletTx& prev = (*mi).second;
3045 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
3047 prev.MarkUnspent(txin.prevout.n);
3054 CPubKey CReserveKey::GetReservedKey()
3059 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3061 vchPubKey = keypool.vchPubKey;
3064 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
3065 vchPubKey = pwallet->vchDefaultKey;
3068 assert(vchPubKey.IsValid());
3072 void CReserveKey::KeepKey()
3075 pwallet->KeepKey(nIndex);
3077 vchPubKey = CPubKey();
3080 void CReserveKey::ReturnKey()
3083 pwallet->ReturnKey(nIndex);
3085 vchPubKey = CPubKey();
3088 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3092 CWalletDB walletdb(strWalletFile);
3094 LOCK2(cs_main, cs_wallet);
3095 BOOST_FOREACH(const int64_t& id, setKeyPool)
3098 if (!walletdb.ReadPool(id, keypool))
3099 throw runtime_error("GetAllReserveKeyHashes() : read failed");
3100 assert(keypool.vchPubKey.IsValid());
3101 CKeyID keyID = keypool.vchPubKey.GetID();
3102 if (!HaveKey(keyID))
3103 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
3104 setAddress.insert(keyID);
3108 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3112 // Only notify UI if this transaction is in this wallet
3113 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3114 if (mi != mapWallet.end())
3116 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3117 vMintingWalletUpdated.push_back(hashTx);
3122 void CWallet::GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const {
3123 mapAddresses.clear();
3125 // get birth times for keys with metadata
3126 for (std::map<CBitcoinAddress, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
3127 mapAddresses[it->first] = it->second.nCreateTime ? it->second.nCreateTime : 0;
3130 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3131 // iterate over all wallet transactions...
3132 const CWalletTx &wtx = (*it).second;
3133 if (wtx.hashBlock == 0)
3134 continue; // skip unconfirmed transactions
3136 for(std::vector<CTxOut>::const_iterator it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
3137 const CTxOut &out = (*it2);
3138 // iterate over all their outputs
3139 CBitcoinAddress addressRet;
3140 if (ExtractAddress(*this, out.scriptPubKey, addressRet)) {
3141 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
3142 mapAddresses[addressRet] = wtx.nTime;
3145 // multisig output affects more than one key
3146 std::vector<CKeyID> vAffected;
3147 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
3149 for(std::vector<CKeyID>::const_iterator it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
3150 CBitcoinAddress addrAffected(*it3);
3151 if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
3152 mapAddresses[addrAffected] = wtx.nTime;
3160 void CWallet::ClearOrphans()
3162 list<uint256> orphans;
3165 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3167 const CWalletTx *wtx = &(*it).second;
3168 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
3170 orphans.push_back(wtx->GetHash());
3174 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
3175 EraseFromWallet(*it);