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 <boost/algorithm/string/replace.hpp>
16 extern int nStakeMaxAge;
19 //////////////////////////////////////////////////////////////////////////////
24 struct CompareValueOnly
26 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
27 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
29 return t1.first < t2.first;
33 CPubKey CWallet::GenerateNewKey()
35 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
39 key.MakeNewKey(fCompressed);
41 // Compressed public keys were introduced in version 0.6.0
43 SetMinVersion(FEATURE_COMPRPUBKEY);
45 CPubKey pubkey = key.GetPubKey();
47 // Create new metadata
48 int64 nCreationTime = GetTime();
49 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
50 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
51 nTimeFirstKey = nCreationTime;
54 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
55 return key.GetPubKey();
58 bool CWallet::AddKey(const CKey& key)
60 CPubKey pubkey = key.GetPubKey();
62 if (!CCryptoKeyStore::AddKey(key))
67 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
71 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
73 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
79 if (pwalletdbEncryption)
80 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
82 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
87 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
89 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
90 nTimeFirstKey = meta.nCreateTime;
92 mapKeyMetadata[pubkey.GetID()] = meta;
96 bool CWallet::AddCScript(const CScript& redeemScript)
98 if (!CCryptoKeyStore::AddCScript(redeemScript))
102 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
105 // ppcoin: optional setting to unlock wallet for block minting only;
106 // serves to disable the trivial sendmoney when OS account compromised
107 bool fWalletUnlockMintOnly = false;
109 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
115 CKeyingMaterial vMasterKey;
119 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
121 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
123 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
125 if (CCryptoKeyStore::Unlock(vMasterKey))
132 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
134 bool fWasLocked = IsLocked();
141 CKeyingMaterial vMasterKey;
142 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
144 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
146 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
148 if (CCryptoKeyStore::Unlock(vMasterKey))
150 int64 nStartTime = GetTimeMillis();
151 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
152 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
154 nStartTime = GetTimeMillis();
155 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
156 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
158 if (pMasterKey.second.nDeriveIterations < 25000)
159 pMasterKey.second.nDeriveIterations = 25000;
161 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
163 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
165 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
167 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
178 void CWallet::SetBestChain(const CBlockLocator& loc)
180 CWalletDB walletdb(strWalletFile);
181 walletdb.WriteBestBlock(loc);
184 // This class implements an addrIncoming entry that causes pre-0.4
185 // clients to crash on startup if reading a private-key-encrypted wallet.
186 class CCorruptAddress
191 if (nType & SER_DISK)
196 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
198 if (nWalletVersion >= nVersion)
201 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
202 if (fExplicit && nVersion > nWalletMaxVersion)
203 nVersion = FEATURE_LATEST;
205 nWalletVersion = nVersion;
207 if (nVersion > nWalletMaxVersion)
208 nWalletMaxVersion = nVersion;
212 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
213 if (nWalletVersion >= 40000)
215 // Versions prior to 0.4.0 did not support the "minversion" record.
216 // Use a CCorruptAddress to make them crash instead.
217 CCorruptAddress corruptAddress;
218 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
220 if (nWalletVersion > 40000)
221 pwalletdb->WriteMinVersion(nWalletVersion);
229 bool CWallet::SetMaxVersion(int nVersion)
231 // cannot downgrade below current version
232 if (nWalletVersion > nVersion)
235 nWalletMaxVersion = nVersion;
240 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
245 CKeyingMaterial vMasterKey;
246 RandAddSeedPerfmon();
248 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
249 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
251 CMasterKey kMasterKey(nDerivationMethodIndex);
253 RandAddSeedPerfmon();
254 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
255 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
258 int64 nStartTime = GetTimeMillis();
259 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
260 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
262 nStartTime = GetTimeMillis();
263 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
264 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
266 if (kMasterKey.nDeriveIterations < 25000)
267 kMasterKey.nDeriveIterations = 25000;
269 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
271 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
273 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
278 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
281 pwalletdbEncryption = new CWalletDB(strWalletFile);
282 if (!pwalletdbEncryption->TxnBegin())
284 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
287 if (!EncryptKeys(vMasterKey))
290 pwalletdbEncryption->TxnAbort();
291 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.
294 // Encryption was introduced in version 0.4.0
295 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
299 if (!pwalletdbEncryption->TxnCommit())
300 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.
302 delete pwalletdbEncryption;
303 pwalletdbEncryption = NULL;
307 Unlock(strWalletPassphrase);
311 // Need to completely rewrite the wallet file; if we don't, bdb might keep
312 // bits of the unencrypted private key in slack space in the database file.
313 CDB::Rewrite(strWalletFile);
316 NotifyStatusChanged(this);
321 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
323 int64 nRet = nOrderPosNext++;
325 pwalletdb->WriteOrderPosNext(nOrderPosNext);
327 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
332 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
334 CWalletDB walletdb(strWalletFile);
336 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
339 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
340 // would make this much faster for applications that do this a lot.
341 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
343 CWalletTx* wtx = &((*it).second);
344 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
347 walletdb.ListAccountCreditDebit(strAccount, acentries);
348 BOOST_FOREACH(CAccountingEntry& entry, acentries)
350 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
356 void CWallet::WalletUpdateSpent(const CTransaction &tx)
358 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
359 // Update the wallet spent flag if it doesn't know due to wallet.dat being
360 // restored from backup or the user making copies of wallet.dat.
363 BOOST_FOREACH(const CTxIn& txin, tx.vin)
365 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
366 if (mi != mapWallet.end())
368 CWalletTx& wtx = (*mi).second;
369 if (txin.prevout.n >= wtx.vout.size())
370 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
371 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
373 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
374 wtx.MarkSpent(txin.prevout.n);
376 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
383 void CWallet::MarkDirty()
387 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
388 item.second.MarkDirty();
392 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
394 uint256 hash = wtxIn.GetHash();
397 // Inserts only if not already there, returns tx inserted or tx found
398 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
399 CWalletTx& wtx = (*ret.first).second;
400 wtx.BindWallet(this);
401 bool fInsertedNew = ret.second;
404 wtx.nTimeReceived = GetAdjustedTime();
405 wtx.nOrderPos = IncOrderPosNext();
407 wtx.nTimeSmart = wtx.nTimeReceived;
408 if (wtxIn.hashBlock != 0)
410 if (mapBlockIndex.count(wtxIn.hashBlock))
412 unsigned int latestNow = wtx.nTimeReceived;
413 unsigned int latestEntry = 0;
415 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
416 int64 latestTolerated = latestNow + 300;
417 std::list<CAccountingEntry> acentries;
418 TxItems txOrdered = OrderedTxItems(acentries);
419 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
421 CWalletTx *const pwtx = (*it).second.first;
424 CAccountingEntry *const pacentry = (*it).second.second;
428 nSmartTime = pwtx->nTimeSmart;
430 nSmartTime = pwtx->nTimeReceived;
433 nSmartTime = pacentry->nTime;
434 if (nSmartTime <= latestTolerated)
436 latestEntry = nSmartTime;
437 if (nSmartTime > latestNow)
438 latestNow = nSmartTime;
444 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
445 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
448 printf("AddToWallet() : found %s in block %s not in index\n",
449 wtxIn.GetHash().ToString().substr(0,10).c_str(),
450 wtxIn.hashBlock.ToString().c_str());
454 bool fUpdated = false;
458 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
460 wtx.hashBlock = wtxIn.hashBlock;
463 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
465 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
466 wtx.nIndex = wtxIn.nIndex;
469 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
471 wtx.fFromMe = wtxIn.fFromMe;
474 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
478 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
481 if (fInsertedNew || fUpdated)
482 if (!wtx.WriteToDisk())
485 // If default receiving address gets used, replace it with a new one
486 CScript scriptDefaultKey;
487 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
488 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
490 if (txout.scriptPubKey == scriptDefaultKey)
492 CPubKey newDefaultKey;
493 if (GetKeyFromPool(newDefaultKey, false))
495 SetDefaultKey(newDefaultKey);
496 SetAddressBookName(vchDefaultKey.GetID(), "");
501 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
502 WalletUpdateSpent(wtx);
504 // Notify UI of new or updated transaction
505 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
507 // notify an external script when a wallet transaction comes in or is updated
508 std::string strCmd = GetArg("-walletnotify", "");
510 if ( !strCmd.empty())
512 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
513 boost::thread t(runCommand, strCmd); // thread runs free
520 // Add a transaction to the wallet, or update it.
521 // pblock is optional, but should be provided if the transaction is known to be in a block.
522 // If fUpdate is true, existing transactions will be updated.
523 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
525 uint256 hash = tx.GetHash();
528 bool fExisted = mapWallet.count(hash);
529 if (fExisted && !fUpdate) return false;
530 if (fExisted || IsMine(tx) || IsFromMe(tx))
532 CWalletTx wtx(this,tx);
533 // Get merkle branch if transaction was found in a block
535 wtx.SetMerkleBranch(pblock);
536 return AddToWallet(wtx);
539 WalletUpdateSpent(tx);
544 bool CWallet::EraseFromWallet(uint256 hash)
550 if (mapWallet.erase(hash))
551 CWalletDB(strWalletFile).EraseTx(hash);
557 bool CWallet::IsMine(const CTxIn &txin) const
561 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
562 if (mi != mapWallet.end())
564 const CWalletTx& prev = (*mi).second;
565 if (txin.prevout.n < prev.vout.size())
566 if (IsMine(prev.vout[txin.prevout.n]))
573 int64 CWallet::GetDebit(const CTxIn &txin) const
577 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
578 if (mi != mapWallet.end())
580 const CWalletTx& prev = (*mi).second;
581 if (txin.prevout.n < prev.vout.size())
582 if (IsMine(prev.vout[txin.prevout.n]))
583 return prev.vout[txin.prevout.n].nValue;
589 bool CWallet::IsChange(const CTxOut& txout) const
591 CTxDestination address;
593 // TODO: fix handling of 'change' outputs. The assumption is that any
594 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
595 // is change. That assumption is likely to break when we implement multisignature
596 // wallets that return change back into a multi-signature-protected address;
597 // a better way of identifying which outputs are 'the send' and which are
598 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
599 // which output, if any, was change).
600 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
603 if (!mapAddressBook.count(address))
609 int64 CWalletTx::GetTxTime() const
611 int64 n = nTimeSmart;
612 return n ? n : nTimeReceived;
615 int CWalletTx::GetRequestCount() const
617 // Returns -1 if it wasn't being tracked
620 LOCK(pwallet->cs_wallet);
621 if (IsCoinBase() || IsCoinStake())
626 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
627 if (mi != pwallet->mapRequestCount.end())
628 nRequests = (*mi).second;
633 // Did anyone request this transaction?
634 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
635 if (mi != pwallet->mapRequestCount.end())
637 nRequests = (*mi).second;
639 // How about the block it's in?
640 if (nRequests == 0 && hashBlock != 0)
642 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
643 if (mi != pwallet->mapRequestCount.end())
644 nRequests = (*mi).second;
646 nRequests = 1; // If it's in someone else's block it must have got out
654 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
655 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
657 nGeneratedImmature = nGeneratedMature = nFee = 0;
658 listReceived.clear();
660 strSentAccount = strFromAccount;
662 if (IsCoinBase() || IsCoinStake())
664 if (GetBlocksToMaturity() > 0)
665 nGeneratedImmature = pwallet->GetCredit(*this);
667 nGeneratedMature = GetCredit();
672 int64 nDebit = GetDebit();
673 if (nDebit > 0) // debit>0 means we signed/sent this transaction
675 int64 nValueOut = GetValueOut();
676 nFee = nDebit - nValueOut;
680 BOOST_FOREACH(const CTxOut& txout, vout)
682 CTxDestination address;
683 vector<unsigned char> vchPubKey;
684 if (!ExtractDestination(txout.scriptPubKey, address))
686 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
687 this->GetHash().ToString().c_str());
690 // Don't report 'change' txouts
691 if (nDebit > 0 && pwallet->IsChange(txout))
695 listSent.push_back(make_pair(address, txout.nValue));
697 if (pwallet->IsMine(txout))
698 listReceived.push_back(make_pair(address, txout.nValue));
703 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
704 int64& nSent, int64& nFee) const
706 nGenerated = nReceived = nSent = nFee = 0;
708 int64 allGeneratedImmature, allGeneratedMature, allFee;
709 allGeneratedImmature = allGeneratedMature = allFee = 0;
710 string strSentAccount;
711 list<pair<CTxDestination, int64> > listReceived;
712 list<pair<CTxDestination, int64> > listSent;
713 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
715 if (strAccount == "")
716 nGenerated = allGeneratedMature;
717 if (strAccount == strSentAccount)
719 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
724 LOCK(pwallet->cs_wallet);
725 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
727 if (pwallet->mapAddressBook.count(r.first))
729 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
730 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
731 nReceived += r.second;
733 else if (strAccount.empty())
735 nReceived += r.second;
741 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
745 const int COPY_DEPTH = 3;
746 if (SetMerkleBranch() < COPY_DEPTH)
748 vector<uint256> vWorkQueue;
749 BOOST_FOREACH(const CTxIn& txin, vin)
750 vWorkQueue.push_back(txin.prevout.hash);
752 // This critsect is OK because txdb is already open
754 LOCK(pwallet->cs_wallet);
755 map<uint256, const CMerkleTx*> mapWalletPrev;
756 set<uint256> setAlreadyDone;
757 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
759 uint256 hash = vWorkQueue[i];
760 if (setAlreadyDone.count(hash))
762 setAlreadyDone.insert(hash);
765 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
766 if (mi != pwallet->mapWallet.end())
769 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
770 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
772 else if (mapWalletPrev.count(hash))
774 tx = *mapWalletPrev[hash];
776 else if (!fClient && txdb.ReadDiskTx(hash, tx))
782 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
786 int nDepth = tx.SetMerkleBranch();
787 vtxPrev.push_back(tx);
789 if (nDepth < COPY_DEPTH)
791 BOOST_FOREACH(const CTxIn& txin, tx.vin)
792 vWorkQueue.push_back(txin.prevout.hash);
798 reverse(vtxPrev.begin(), vtxPrev.end());
801 bool CWalletTx::WriteToDisk()
803 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
806 // Scan the block chain (starting in pindexStart) for transactions
807 // from or to us. If fUpdate is true, found transactions that already
808 // exist in the wallet will be updated.
809 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
813 CBlockIndex* pindex = pindexStart;
819 block.ReadFromDisk(pindex, true);
820 BOOST_FOREACH(CTransaction& tx, block.vtx)
822 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
825 pindex = pindex->pnext;
831 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
834 tx.ReadFromDisk(COutPoint(hashTx, 0));
835 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
840 void CWallet::ReacceptWalletTransactions()
848 vector<CDiskTxPos> vMissingTx;
849 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
851 CWalletTx& wtx = item.second;
852 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
856 bool fUpdated = false;
857 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
859 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
860 if (txindex.vSpent.size() != wtx.vout.size())
862 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
865 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
869 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
873 vMissingTx.push_back(txindex.vSpent[i]);
878 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
885 // Re-accept any txes of ours that aren't already in a block
886 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
887 wtx.AcceptWalletTransaction(txdb, false);
890 if (!vMissingTx.empty())
892 // TODO: optimize this to scan just part of the block chain?
893 if (ScanForWalletTransactions(pindexGenesisBlock))
894 fRepeat = true; // Found missing transactions: re-do re-accept.
899 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
901 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
903 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
905 uint256 hash = tx.GetHash();
906 if (!txdb.ContainsTx(hash))
907 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
910 if (!(IsCoinBase() || IsCoinStake()))
912 uint256 hash = GetHash();
913 if (!txdb.ContainsTx(hash))
915 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
916 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
921 void CWalletTx::RelayWalletTransaction()
924 RelayWalletTransaction(txdb);
927 void CWallet::ResendWalletTransactions()
929 // Do this infrequently and randomly to avoid giving away
930 // that these are our transactions.
931 static int64 nNextTime;
932 if (GetTime() < nNextTime)
934 bool fFirst = (nNextTime == 0);
935 nNextTime = GetTime() + GetRand(30 * 60);
939 // Only do it if there's been a new block since last time
940 static int64 nLastTime;
941 if (nTimeBestReceived < nLastTime)
943 nLastTime = GetTime();
945 // Rebroadcast any of our txes that aren't in a block yet
946 printf("ResendWalletTransactions()\n");
950 // Sort them in chronological order
951 multimap<unsigned int, CWalletTx*> mapSorted;
952 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
954 CWalletTx& wtx = item.second;
955 // Don't rebroadcast until it's had plenty of time that
956 // it should have gotten in already by now.
957 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
958 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
960 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
962 CWalletTx& wtx = *item.second;
963 if (wtx.CheckTransaction())
964 wtx.RelayWalletTransaction(txdb);
966 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
976 //////////////////////////////////////////////////////////////////////////////
982 int64 CWallet::GetBalance() const
987 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
989 const CWalletTx* pcoin = &(*it).second;
990 if (pcoin->IsConfirmed())
991 nTotal += pcoin->GetAvailableCredit();
998 int64 CWallet::GetUnconfirmedBalance() const
1003 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1005 const CWalletTx* pcoin = &(*it).second;
1006 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
1007 nTotal += pcoin->GetAvailableCredit();
1013 int64 CWallet::GetImmatureBalance() const
1018 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1020 const CWalletTx& pcoin = (*it).second;
1021 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1022 nTotal += GetCredit(pcoin);
1028 // populate vCoins with vector of spendable COutputs
1029 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
1035 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1037 const CWalletTx* pcoin = &(*it).second;
1039 if (!pcoin->IsFinal())
1042 if (fOnlyConfirmed && !pcoin->IsConfirmed())
1045 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1048 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1051 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1052 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue > 0)
1053 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1058 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1059 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1061 vector<char> vfIncluded;
1063 vfBest.assign(vValue.size(), true);
1064 nBest = nTotalLower;
1066 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1068 vfIncluded.assign(vValue.size(), false);
1070 bool fReachedTarget = false;
1071 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1073 for (unsigned int i = 0; i < vValue.size(); i++)
1075 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1077 nTotal += vValue[i].first;
1078 vfIncluded[i] = true;
1079 if (nTotal >= nTargetValue)
1081 fReachedTarget = true;
1085 vfBest = vfIncluded;
1087 nTotal -= vValue[i].first;
1088 vfIncluded[i] = false;
1096 // ppcoin: total coins staked (non-spendable until maturity)
1097 int64 CWallet::GetStake() const
1101 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1103 const CWalletTx* pcoin = &(*it).second;
1104 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1105 nTotal += CWallet::GetCredit(*pcoin);
1110 int64 CWallet::GetNewMint() const
1114 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1116 const CWalletTx* pcoin = &(*it).second;
1117 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1118 nTotal += CWallet::GetCredit(*pcoin);
1123 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1125 setCoinsRet.clear();
1128 // List of values less than target
1129 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1130 coinLowestLarger.first = std::numeric_limits<int64>::max();
1131 coinLowestLarger.second.first = NULL;
1132 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1133 int64 nTotalLower = 0;
1135 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1137 BOOST_FOREACH(COutput output, vCoins)
1139 const CWalletTx *pcoin = output.tx;
1141 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1146 if (pcoin->nTime > nSpendTime)
1147 continue; // ppcoin: timestamp must not exceed spend time
1149 int64 n = pcoin->vout[i].nValue;
1151 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1153 if (n == nTargetValue)
1155 setCoinsRet.insert(coin.second);
1156 nValueRet += coin.first;
1159 else if (n < nTargetValue + CENT)
1161 vValue.push_back(coin);
1164 else if (n < coinLowestLarger.first)
1166 coinLowestLarger = coin;
1170 if (nTotalLower == nTargetValue)
1172 for (unsigned int i = 0; i < vValue.size(); ++i)
1174 setCoinsRet.insert(vValue[i].second);
1175 nValueRet += vValue[i].first;
1180 if (nTotalLower < nTargetValue)
1182 if (coinLowestLarger.second.first == NULL)
1184 setCoinsRet.insert(coinLowestLarger.second);
1185 nValueRet += coinLowestLarger.first;
1189 // Solve subset sum by stochastic approximation
1190 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1191 vector<char> vfBest;
1194 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1195 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1196 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1198 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1199 // or the next bigger coin is closer), return the bigger coin
1200 if (coinLowestLarger.second.first &&
1201 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1203 setCoinsRet.insert(coinLowestLarger.second);
1204 nValueRet += coinLowestLarger.first;
1207 for (unsigned int i = 0; i < vValue.size(); i++)
1210 setCoinsRet.insert(vValue[i].second);
1211 nValueRet += vValue[i].first;
1214 if (fDebug && GetBoolArg("-printpriority"))
1217 printf("SelectCoins() best subset: ");
1218 for (unsigned int i = 0; i < vValue.size(); i++)
1220 printf("%s ", FormatMoney(vValue[i].first).c_str());
1221 printf("total %s\n", FormatMoney(nBest).c_str());
1228 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1230 vector<COutput> vCoins;
1231 AvailableCoins(vCoins);
1233 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1234 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1235 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1241 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1244 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1250 if (vecSend.empty() || nValue < 0)
1253 wtxNew.BindWallet(this);
1256 LOCK2(cs_main, cs_wallet);
1257 // txdb must be opened before the mapWallet lock
1260 nFeeRet = nTransactionFee;
1264 wtxNew.vout.clear();
1265 wtxNew.fFromMe = true;
1267 int64 nTotalValue = nValue + nFeeRet;
1268 double dPriority = 0;
1269 // vouts to the payees
1270 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1271 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1273 // Choose coins to use
1274 set<pair<const CWalletTx*,unsigned int> > setCoins;
1276 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1278 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1280 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1281 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1284 int64 nChange = nValueIn - nValue - nFeeRet;
1285 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1286 // or until nChange becomes zero
1287 // NOTE: this depends on the exact behaviour of GetMinFee
1288 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1290 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1291 nChange -= nMoveToFee;
1292 nFeeRet += nMoveToFee;
1295 // ppcoin: sub-cent change is moved to fee
1296 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1304 // Note: We use a new key here to keep it from being obvious which side is the change.
1305 // The drawback is that by not reusing a previous key, the change may be lost if a
1306 // backup is restored, if the backup doesn't have the new private key for the change.
1307 // If we reused the old key, it would be possible to add code to look for and
1308 // rediscover unknown transactions that were written with keys of ours to recover
1309 // post-backup change.
1311 // Reserve a new key pair from key pool
1312 CPubKey vchPubKey = reservekey.GetReservedKey();
1313 // assert(mapKeys.count(vchPubKey));
1315 // Fill a vout to ourself
1316 // TODO: pass in scriptChange instead of reservekey so
1317 // change transaction isn't always pay-to-bitcoin-address
1318 CScript scriptChange;
1319 scriptChange.SetDestination(vchPubKey.GetID());
1321 // Insert change txn at random position:
1322 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1323 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1326 reservekey.ReturnKey();
1329 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1330 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1334 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1335 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1339 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1340 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1342 dPriority /= nBytes;
1344 // Check that enough fee is included
1345 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1346 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1348 if (nFeeRet < max(nPayFee, nMinFee))
1350 nFeeRet = max(nPayFee, nMinFee);
1354 // Fill vtxPrev by copying from previous transactions vtxPrev
1355 wtxNew.AddSupportingTransactions(txdb);
1356 wtxNew.fTimeReceivedIsTxTime = true;
1365 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1367 vector< pair<CScript, int64> > vecSend;
1368 vecSend.push_back(make_pair(scriptPubKey, nValue));
1369 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1372 // NovaCoin: get current stake weight
1373 uint64 CWallet::GetStakeWeight(const CKeyStore& keystore, enum StakeWeightMode mode)
1375 LOCK2(cs_main, cs_wallet);
1377 // Choose coins to use
1378 int64 nBalance = GetBalance();
1379 int64 nReserveBalance = 0;
1380 uint64 nCoinAge = 0;
1382 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1384 error("GetStakeWeight : invalid reserve balance amount");
1388 if (nBalance <= nReserveBalance)
1391 set<pair<const CWalletTx*,unsigned int> > setCoins;
1392 vector<const CWalletTx*> vwtxPrev;
1394 if (!SelectCoins(nBalance - nReserveBalance, GetTime(), setCoins, nValueIn))
1396 if (setCoins.empty())
1399 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1403 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1406 unsigned int nTime = pcoin.first->nTime;
1411 // Do not count input that is still less than 30 days old
1412 if (nTime + nStakeMinAge > GetTime())
1415 case STAKE_MAXWEIGHT:
1416 // Do not count input that is still less than 90 days old
1417 if (nTime + nStakeMaxAge > GetTime())
1420 case STAKE_MINWEIGHT:
1421 // Count only inputs with suitable age (from 30 to 90 days old)
1422 if (nTime + nStakeMaxAge < GetTime())
1424 if (nTime + nStakeMinAge > GetTime())
1431 // Kernel hash weight starts from 0 at the 30-day min age
1432 // this change increases active coins participating the hash and helps
1433 // to secure the network when proof-of-stake difficulty is low
1435 if(fTestNet || (STAKEWEIGHT_SWITCH_TIME < nTime))
1437 // New rule since 01 Jan 2014: Maximum TimeWeight is 90 days.
1438 nTimeWeight = min((int64)GetTime() - nTime - nStakeMinAge, (int64)nStakeMaxAge);
1442 // Current rule: Maximum TimeWeight is 60 days.
1443 nTimeWeight = min((int64)GetTime() - nTime, (int64)nStakeMaxAge) - nStakeMinAge;
1446 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1448 nCoinAge += bnCoinDayWeight.getuint64();
1451 if (fDebug && GetBoolArg("-printcoinage"))
1452 printf("StakeWeight bnCoinDay=%"PRI64d"\n", nCoinAge);
1457 // ppcoin: create coin stake transaction
1458 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew)
1460 // The following split & combine thresholds are important to security
1461 // Should not be adjusted if you don't understand the consequences
1462 static unsigned int nStakeSplitAge = (60 * 60 * 24 * 90);
1463 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1465 CBigNum bnTargetPerCoinDay;
1466 bnTargetPerCoinDay.SetCompact(nBits);
1468 LOCK2(cs_main, cs_wallet);
1471 // Mark coin stake transaction
1472 CScript scriptEmpty;
1473 scriptEmpty.clear();
1474 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1475 // Choose coins to use
1476 int64 nBalance = GetBalance();
1477 int64 nReserveBalance = 0;
1478 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1479 return error("CreateCoinStake : invalid reserve balance amount");
1480 if (nBalance <= nReserveBalance)
1482 set<pair<const CWalletTx*,unsigned int> > setCoins;
1483 vector<const CWalletTx*> vwtxPrev;
1485 if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
1487 if (setCoins.empty())
1490 CScript scriptPubKeyKernel;
1491 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1495 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1498 // Read block header
1500 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1502 static int nMaxStakeSearchInterval = 60;
1503 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1504 continue; // only count coins meeting min age requirement
1506 bool fKernelFound = false;
1507 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1509 // Search backward in time from the given txNew timestamp
1510 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1511 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1512 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1513 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1516 if (fDebug && GetBoolArg("-printcoinstake"))
1517 printf("CreateCoinStake : kernel found\n");
1518 vector<valtype> vSolutions;
1519 txnouttype whichType;
1520 CScript scriptPubKeyOut;
1521 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1522 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1524 if (fDebug && GetBoolArg("-printcoinstake"))
1525 printf("CreateCoinStake : failed to parse kernel\n");
1528 if (fDebug && GetBoolArg("-printcoinstake"))
1529 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1530 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1532 if (fDebug && GetBoolArg("-printcoinstake"))
1533 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1534 break; // only support pay to public key and pay to address
1536 if (whichType == TX_PUBKEYHASH) // pay to address type
1538 // convert to pay to public key type
1540 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1542 if (fDebug && GetBoolArg("-printcoinstake"))
1543 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1544 break; // unable to find corresponding public key
1546 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1549 scriptPubKeyOut = scriptPubKeyKernel;
1552 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1553 nCredit += pcoin.first->vout[pcoin.second].nValue;
1554 vwtxPrev.push_back(pcoin.first);
1555 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1556 if (block.GetBlockTime() + nStakeSplitAge > txNew.nTime)
1557 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1558 if (fDebug && GetBoolArg("-printcoinstake"))
1559 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1560 fKernelFound = true;
1564 if (fKernelFound || fShutdown)
1565 break; // if kernel is found stop searching
1567 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1569 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1571 // Attempt to add more inputs
1572 // Only add coins of the same key/address as kernel
1573 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1574 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1576 // Stop adding more inputs if already too many inputs
1577 if (txNew.vin.size() >= 100)
1579 // Stop adding more inputs if value is already pretty significant
1580 if (nCredit > nCombineThreshold)
1582 // Stop adding inputs if reached reserve limit
1583 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1585 // Do not add additional significant input
1586 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1588 // Do not add input that is still too young
1589 if (pcoin.first->nTime + nStakeMaxAge > txNew.nTime)
1591 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1592 nCredit += pcoin.first->vout[pcoin.second].nValue;
1593 vwtxPrev.push_back(pcoin.first);
1596 // Calculate coin age reward
1600 if (!txNew.GetCoinAge(txdb, nCoinAge))
1601 return error("CreateCoinStake : failed to calculate coin age");
1602 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1608 // Set output amount
1609 if (txNew.vout.size() == 3)
1611 // Should we use keys from pool for the last coinstake output?
1612 if (fStakeUsePooledKeys)
1614 CReserveKey reservekey((CWallet*) &keystore);
1616 // Replace current key with the new one
1617 txNew.vout[2].SetNull();
1618 txNew.vout[2].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
1620 // Remove key from pool
1621 reservekey.KeepKey();
1624 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1625 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1628 txNew.vout[1].nValue = nCredit - nMinFee;
1632 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1634 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1635 return error("CreateCoinStake : failed to sign coinstake");
1639 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1640 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1641 return error("CreateCoinStake : exceeded coinstake size limit");
1643 // Check enough fee is paid
1644 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1646 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1647 continue; // try signing again
1651 if (fDebug && GetBoolArg("-printfee"))
1652 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1657 // Successfully generated coinstake
1662 // Call after CreateTransaction unless you want to abort
1663 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1666 LOCK2(cs_main, cs_wallet);
1667 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1669 // This is only to keep the database open to defeat the auto-flush for the
1670 // duration of this scope. This is the only place where this optimization
1671 // maybe makes sense; please don't do it anywhere else.
1672 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1674 // Take key pair from key pool so it won't be used again
1675 reservekey.KeepKey();
1677 // Add tx to wallet, because if it has change it's also ours,
1678 // otherwise just for transaction history.
1679 AddToWallet(wtxNew);
1681 // Mark old coins as spent
1682 set<CWalletTx*> setCoins;
1683 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1685 CWalletTx &coin = mapWallet[txin.prevout.hash];
1686 coin.BindWallet(this);
1687 coin.MarkSpent(txin.prevout.n);
1689 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1696 // Track how many getdata requests our transaction gets
1697 mapRequestCount[wtxNew.GetHash()] = 0;
1700 if (!wtxNew.AcceptToMemoryPool())
1702 // This must not fail. The transaction has already been signed and recorded.
1703 printf("CommitTransaction() : Error: Transaction not valid");
1706 wtxNew.RelayWalletTransaction();
1714 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1716 CReserveKey reservekey(this);
1721 string strError = _("Error: Wallet locked, unable to create transaction ");
1722 printf("SendMoney() : %s", strError.c_str());
1725 if (fWalletUnlockMintOnly)
1727 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1728 printf("SendMoney() : %s", strError.c_str());
1731 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1734 if (nValue + nFeeRequired > GetBalance())
1735 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());
1737 strError = _("Error: Transaction creation failed ");
1738 printf("SendMoney() : %s", strError.c_str());
1742 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1745 if (!CommitTransaction(wtxNew, reservekey))
1746 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.");
1753 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1757 return _("Invalid amount");
1758 if (nValue + nTransactionFee > GetBalance())
1759 return _("Insufficient funds");
1761 // Parse Bitcoin address
1762 CScript scriptPubKey;
1763 scriptPubKey.SetDestination(address);
1765 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1771 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1775 fFirstRunRet = false;
1776 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1777 if (nLoadWalletRet == DB_NEED_REWRITE)
1779 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1782 // Note: can't top-up keypool here, because wallet is locked.
1783 // User will be prompted to unlock wallet the next operation
1784 // the requires a new key.
1788 if (nLoadWalletRet != DB_LOAD_OK)
1789 return nLoadWalletRet;
1790 fFirstRunRet = !vchDefaultKey.IsValid();
1792 NewThread(ThreadFlushWalletDB, &strWalletFile);
1797 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1799 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1800 mapAddressBook[address] = strName;
1801 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1804 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1807 bool CWallet::DelAddressBookName(const CTxDestination& address)
1809 mapAddressBook.erase(address);
1810 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1813 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1817 void CWallet::PrintWallet(const CBlock& block)
1821 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1823 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1824 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1826 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1828 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1829 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1836 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1840 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1841 if (mi != mapWallet.end())
1850 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1854 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1857 vchDefaultKey = vchPubKey;
1861 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1863 if (!pwallet->fFileBacked)
1865 strWalletFileOut = pwallet->strWalletFile;
1870 // Mark old keypool keys as used,
1871 // and generate all new keys
1873 bool CWallet::NewKeyPool()
1877 CWalletDB walletdb(strWalletFile);
1878 BOOST_FOREACH(int64 nIndex, setKeyPool)
1879 walletdb.ErasePool(nIndex);
1885 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1886 for (int i = 0; i < nKeys; i++)
1889 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1890 setKeyPool.insert(nIndex);
1892 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1897 bool CWallet::TopUpKeyPool(unsigned int nSize)
1905 CWalletDB walletdb(strWalletFile);
1908 unsigned int nTargetSize;
1910 nTargetSize = nSize;
1912 nTargetSize = max(GetArg("-keypool", 100), 0LL);
1914 while (setKeyPool.size() < (nTargetSize + 1))
1917 if (!setKeyPool.empty())
1918 nEnd = *(--setKeyPool.end()) + 1;
1919 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1920 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1921 setKeyPool.insert(nEnd);
1922 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
1928 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1931 keypool.vchPubKey = CPubKey();
1938 // Get the oldest key
1939 if(setKeyPool.empty())
1942 CWalletDB walletdb(strWalletFile);
1944 nIndex = *(setKeyPool.begin());
1945 setKeyPool.erase(setKeyPool.begin());
1946 if (!walletdb.ReadPool(nIndex, keypool))
1947 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1948 if (!HaveKey(keypool.vchPubKey.GetID()))
1949 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1950 assert(keypool.vchPubKey.IsValid());
1951 if (fDebug && GetBoolArg("-printkeypool"))
1952 printf("keypool reserve %"PRI64d"\n", nIndex);
1956 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1959 LOCK2(cs_main, cs_wallet);
1960 CWalletDB walletdb(strWalletFile);
1962 int64 nIndex = 1 + *(--setKeyPool.end());
1963 if (!walletdb.WritePool(nIndex, keypool))
1964 throw runtime_error("AddReserveKey() : writing added key failed");
1965 setKeyPool.insert(nIndex);
1971 void CWallet::KeepKey(int64 nIndex)
1973 // Remove from key pool
1976 CWalletDB walletdb(strWalletFile);
1977 walletdb.ErasePool(nIndex);
1980 printf("keypool keep %"PRI64d"\n", nIndex);
1983 void CWallet::ReturnKey(int64 nIndex)
1985 // Return to key pool
1988 setKeyPool.insert(nIndex);
1991 printf("keypool return %"PRI64d"\n", nIndex);
1994 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2000 ReserveKeyFromKeyPool(nIndex, keypool);
2003 if (fAllowReuse && vchDefaultKey.IsValid())
2005 result = vchDefaultKey;
2008 if (IsLocked()) return false;
2009 result = GenerateNewKey();
2013 result = keypool.vchPubKey;
2018 int64 CWallet::GetOldestKeyPoolTime()
2022 ReserveKeyFromKeyPool(nIndex, keypool);
2026 return keypool.nTime;
2029 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2031 map<CTxDestination, int64> balances;
2035 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2037 CWalletTx *pcoin = &walletEntry.second;
2039 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
2042 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2045 int nDepth = pcoin->GetDepthInMainChain();
2046 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2049 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2051 CTxDestination addr;
2052 if (!IsMine(pcoin->vout[i]))
2054 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2057 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2059 if (!balances.count(addr))
2061 balances[addr] += n;
2069 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2071 set< set<CTxDestination> > groupings;
2072 set<CTxDestination> grouping;
2074 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2076 CWalletTx *pcoin = &walletEntry.second;
2078 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2080 // group all input addresses with each other
2081 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2083 CTxDestination address;
2084 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2086 grouping.insert(address);
2089 // group change with input addresses
2090 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2091 if (IsChange(txout))
2093 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2094 CTxDestination txoutAddr;
2095 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2097 grouping.insert(txoutAddr);
2099 groupings.insert(grouping);
2103 // group lone addrs by themselves
2104 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2105 if (IsMine(pcoin->vout[i]))
2107 CTxDestination address;
2108 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2110 grouping.insert(address);
2111 groupings.insert(grouping);
2116 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2117 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2118 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2120 // make a set of all the groups hit by this new group
2121 set< set<CTxDestination>* > hits;
2122 map< CTxDestination, set<CTxDestination>* >::iterator it;
2123 BOOST_FOREACH(CTxDestination address, grouping)
2124 if ((it = setmap.find(address)) != setmap.end())
2125 hits.insert((*it).second);
2127 // merge all hit groups into a new single group and delete old groups
2128 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2129 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2131 merged->insert(hit->begin(), hit->end());
2132 uniqueGroupings.erase(hit);
2135 uniqueGroupings.insert(merged);
2138 BOOST_FOREACH(CTxDestination element, *merged)
2139 setmap[element] = merged;
2142 set< set<CTxDestination> > ret;
2143 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2145 ret.insert(*uniqueGrouping);
2146 delete uniqueGrouping;
2152 // ppcoin: check 'spent' consistency between wallet and txindex
2153 // ppcoin: fix wallet spent state according to txindex
2154 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2157 nBalanceInQuestion = 0;
2160 vector<CWalletTx*> vCoins;
2161 vCoins.reserve(mapWallet.size());
2162 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2163 vCoins.push_back(&(*it).second);
2166 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2168 // Find the corresponding transaction index
2170 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2172 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2174 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2176 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2177 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2179 nBalanceInQuestion += pcoin->vout[n].nValue;
2182 pcoin->MarkUnspent(n);
2183 pcoin->WriteToDisk();
2186 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2188 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2189 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2191 nBalanceInQuestion += pcoin->vout[n].nValue;
2194 pcoin->MarkSpent(n);
2195 pcoin->WriteToDisk();
2202 // ppcoin: disable transaction (only for coinstake)
2203 void CWallet::DisableTransaction(const CTransaction &tx)
2205 if (!tx.IsCoinStake() || !IsFromMe(tx))
2206 return; // only disconnecting coinstake requires marking input unspent
2209 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2211 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2212 if (mi != mapWallet.end())
2214 CWalletTx& prev = (*mi).second;
2215 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2217 prev.MarkUnspent(txin.prevout.n);
2224 CPubKey CReserveKey::GetReservedKey()
2229 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2231 vchPubKey = keypool.vchPubKey;
2234 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2235 vchPubKey = pwallet->vchDefaultKey;
2238 assert(vchPubKey.IsValid());
2242 void CReserveKey::KeepKey()
2245 pwallet->KeepKey(nIndex);
2247 vchPubKey = CPubKey();
2250 void CReserveKey::ReturnKey()
2253 pwallet->ReturnKey(nIndex);
2255 vchPubKey = CPubKey();
2258 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2262 CWalletDB walletdb(strWalletFile);
2264 LOCK2(cs_main, cs_wallet);
2265 BOOST_FOREACH(const int64& id, setKeyPool)
2268 if (!walletdb.ReadPool(id, keypool))
2269 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2270 assert(keypool.vchPubKey.IsValid());
2271 CKeyID keyID = keypool.vchPubKey.GetID();
2272 if (!HaveKey(keyID))
2273 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2274 setAddress.insert(keyID);
2278 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2282 // Only notify UI if this transaction is in this wallet
2283 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2284 if (mi != mapWallet.end())
2285 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2289 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2290 mapKeyBirth.clear();
2292 // get birth times for keys with metadata
2293 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2294 if (it->second.nCreateTime)
2295 mapKeyBirth[it->first] = it->second.nCreateTime;
2297 // map in which we'll infer heights of other keys
2298 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2299 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2300 std::set<CKeyID> setKeys;
2302 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2303 if (mapKeyBirth.count(keyid) == 0)
2304 mapKeyFirstBlock[keyid] = pindexMax;
2308 // if there are no such keys, we're done
2309 if (mapKeyFirstBlock.empty())
2312 // find first block that affects those keys, if there are any left
2313 std::vector<CKeyID> vAffected;
2314 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2315 // iterate over all wallet transactions...
2316 const CWalletTx &wtx = (*it).second;
2317 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2318 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2319 // ... which are already in a block
2320 int nHeight = blit->second->nHeight;
2321 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2322 // iterate over all their outputs
2323 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2324 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2325 // ... and all their affected keys
2326 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2327 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2328 rit->second = blit->second;
2335 // Extract block timestamps for those keys
2336 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2337 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off