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>
17 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()
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);
753 LOCK(pwallet->cs_wallet);
754 map<uint256, const CMerkleTx*> mapWalletPrev;
755 set<uint256> setAlreadyDone;
756 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
758 uint256 hash = vWorkQueue[i];
759 if (setAlreadyDone.count(hash))
761 setAlreadyDone.insert(hash);
764 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
765 if (mi != pwallet->mapWallet.end())
768 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
769 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
771 else if (mapWalletPrev.count(hash))
773 tx = *mapWalletPrev[hash];
776 int nDepth = tx.SetMerkleBranch();
777 vtxPrev.push_back(tx);
779 if (nDepth < COPY_DEPTH)
781 BOOST_FOREACH(const CTxIn& txin, tx.vin)
782 vWorkQueue.push_back(txin.prevout.hash);
788 reverse(vtxPrev.begin(), vtxPrev.end());
791 bool CWalletTx::WriteToDisk()
793 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
796 // Scan the block chain (starting in pindexStart) for transactions
797 // from or to us. If fUpdate is true, found transactions that already
798 // exist in the wallet will be updated.
799 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
803 CBlockIndex* pindex = pindexStart;
809 block.ReadFromDisk(pindex, true);
810 BOOST_FOREACH(CTransaction& tx, block.vtx)
812 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
815 pindex = pindex->pnext;
821 void CWallet::ReacceptWalletTransactions()
828 bool fMissing = false;
829 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
831 CWalletTx& wtx = item.second;
832 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
836 bool fUpdated = false;
837 bool fNotFound = pcoinsTip->GetCoins(wtx.GetHash(), coins);
838 if (!fNotFound || wtx.GetDepthInMainChain() > 0)
840 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
841 for (unsigned int i = 0; i < wtx.vout.size(); i++)
845 if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i]))
854 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
861 // Re-accept any txes of ours that aren't already in a block
862 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
863 wtx.AcceptWalletTransaction(false);
868 // TODO: optimize this to scan just part of the block chain?
869 if (ScanForWalletTransactions(pindexGenesisBlock))
870 fRepeat = true; // Found missing transactions: re-do re-accept.
875 void CWalletTx::RelayWalletTransaction()
877 CCoinsViewCache& coins = *pcoinsTip;
878 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
880 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
882 uint256 hash = tx.GetHash();
883 if (!coins.HaveCoins(hash))
884 RelayTransaction((CTransaction)tx, hash);
887 if (!(IsCoinBase() || IsCoinStake()))
889 uint256 hash = GetHash();
890 if (!coins.HaveCoins(hash))
892 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
893 RelayTransaction((CTransaction)*this, hash);
898 void CWallet::ResendWalletTransactions()
900 // Do this infrequently and randomly to avoid giving away
901 // that these are our transactions.
902 static int64 nNextTime;
903 if (GetTime() < nNextTime)
905 bool fFirst = (nNextTime == 0);
906 nNextTime = GetTime() + GetRand(30 * 60);
910 // Only do it if there's been a new block since last time
911 static int64 nLastTime;
912 if (nTimeBestReceived < nLastTime)
914 nLastTime = GetTime();
916 // Rebroadcast any of our txes that aren't in a block yet
917 printf("ResendWalletTransactions()\n");
920 // Sort them in chronological order
921 multimap<unsigned int, CWalletTx*> mapSorted;
922 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
924 CWalletTx& wtx = item.second;
925 // Don't rebroadcast until it's had plenty of time that
926 // it should have gotten in already by now.
927 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
928 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
930 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
932 CWalletTx& wtx = *item.second;
933 wtx.RelayWalletTransaction();
943 //////////////////////////////////////////////////////////////////////////////
949 int64 CWallet::GetBalance() const
954 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
956 const CWalletTx* pcoin = &(*it).second;
957 if (pcoin->IsConfirmed())
958 nTotal += pcoin->GetAvailableCredit();
965 int64 CWallet::GetUnconfirmedBalance() const
970 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
972 const CWalletTx* pcoin = &(*it).second;
973 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
974 nTotal += pcoin->GetAvailableCredit();
980 int64 CWallet::GetImmatureBalance() const
985 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
987 const CWalletTx& pcoin = (*it).second;
988 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
989 nTotal += GetCredit(pcoin);
995 // populate vCoins with vector of spendable COutputs
996 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1002 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1004 const CWalletTx* pcoin = &(*it).second;
1006 if (!pcoin->IsFinal())
1009 if (fOnlyConfirmed && !pcoin->IsConfirmed())
1012 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1015 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1018 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1019 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1020 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1021 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1027 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1033 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1035 const CWalletTx* pcoin = &(*it).second;
1037 if (!pcoin->IsFinal())
1040 if(pcoin->GetDepthInMainChain() < nConf)
1043 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1044 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1045 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1050 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1051 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1053 vector<char> vfIncluded;
1055 vfBest.assign(vValue.size(), true);
1056 nBest = nTotalLower;
1058 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1060 vfIncluded.assign(vValue.size(), false);
1062 bool fReachedTarget = false;
1063 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1065 for (unsigned int i = 0; i < vValue.size(); i++)
1067 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1069 nTotal += vValue[i].first;
1070 vfIncluded[i] = true;
1071 if (nTotal >= nTargetValue)
1073 fReachedTarget = true;
1077 vfBest = vfIncluded;
1079 nTotal -= vValue[i].first;
1080 vfIncluded[i] = false;
1088 // ppcoin: total coins staked (non-spendable until maturity)
1089 int64 CWallet::GetStake() const
1093 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1095 const CWalletTx* pcoin = &(*it).second;
1096 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1097 nTotal += CWallet::GetCredit(*pcoin);
1102 int64 CWallet::GetNewMint() const
1106 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1108 const CWalletTx* pcoin = &(*it).second;
1109 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1110 nTotal += CWallet::GetCredit(*pcoin);
1115 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
1117 setCoinsRet.clear();
1120 // List of values less than target
1121 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1122 coinLowestLarger.first = std::numeric_limits<int64>::max();
1123 coinLowestLarger.second.first = NULL;
1124 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1125 int64 nTotalLower = 0;
1127 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1129 BOOST_FOREACH(COutput output, vCoins)
1131 const CWalletTx *pcoin = output.tx;
1133 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1138 // Follow the timestamp rules
1139 if (pcoin->nTime > nSpendTime)
1142 int64 n = pcoin->vout[i].nValue;
1144 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1146 if (n == nTargetValue)
1148 setCoinsRet.insert(coin.second);
1149 nValueRet += coin.first;
1152 else if (n < nTargetValue + CENT)
1154 vValue.push_back(coin);
1157 else if (n < coinLowestLarger.first)
1159 coinLowestLarger = coin;
1163 if (nTotalLower == nTargetValue)
1165 for (unsigned int i = 0; i < vValue.size(); ++i)
1167 setCoinsRet.insert(vValue[i].second);
1168 nValueRet += vValue[i].first;
1173 if (nTotalLower < nTargetValue)
1175 if (coinLowestLarger.second.first == NULL)
1177 setCoinsRet.insert(coinLowestLarger.second);
1178 nValueRet += coinLowestLarger.first;
1182 // Solve subset sum by stochastic approximation
1183 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1184 vector<char> vfBest;
1187 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1188 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1189 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1191 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1192 // or the next bigger coin is closer), return the bigger coin
1193 if (coinLowestLarger.second.first &&
1194 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1196 setCoinsRet.insert(coinLowestLarger.second);
1197 nValueRet += coinLowestLarger.first;
1200 for (unsigned int i = 0; i < vValue.size(); i++)
1203 setCoinsRet.insert(vValue[i].second);
1204 nValueRet += vValue[i].first;
1207 if (fDebug && GetBoolArg("-printpriority"))
1210 printf("SelectCoins() best subset: ");
1211 for (unsigned int i = 0; i < vValue.size(); i++)
1213 printf("%s ", FormatMoney(vValue[i].first).c_str());
1214 printf("total %s\n", FormatMoney(nBest).c_str());
1221 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1223 vector<COutput> vCoins;
1224 AvailableCoins(vCoins, true, coinControl);
1226 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1227 if (coinControl && coinControl->HasSelected())
1229 BOOST_FOREACH(const COutput& out, vCoins)
1231 nValueRet += out.tx->vout[out.i].nValue;
1232 setCoinsRet.insert(make_pair(out.tx, out.i));
1234 return (nValueRet >= nTargetValue);
1237 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1238 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1239 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1242 // Select some coins without random shuffle or best subset approximation
1243 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1245 vector<COutput> vCoins;
1246 AvailableCoinsMinConf(vCoins, nMinConf);
1248 setCoinsRet.clear();
1251 BOOST_FOREACH(COutput output, vCoins)
1253 const CWalletTx *pcoin = output.tx;
1256 // Stop if we've chosen enough inputs
1257 if (nValueRet >= nTargetValue)
1260 // Follow the timestamp rules
1261 if (pcoin->nTime > nSpendTime)
1264 int64 n = pcoin->vout[i].nValue;
1266 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1268 if (n >= nTargetValue)
1270 // If input value is greater or equal to target then simply insert
1271 // it into the current subset and exit
1272 setCoinsRet.insert(coin.second);
1273 nValueRet += coin.first;
1276 else if (n < nTargetValue + CENT)
1278 setCoinsRet.insert(coin.second);
1279 nValueRet += coin.first;
1286 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1289 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1295 if (vecSend.empty() || nValue < 0)
1298 wtxNew.BindWallet(this);
1301 LOCK2(cs_main, cs_wallet);
1303 nFeeRet = nTransactionFee;
1307 wtxNew.vout.clear();
1308 wtxNew.fFromMe = true;
1310 int64 nTotalValue = nValue + nFeeRet;
1311 double dPriority = 0;
1312 // vouts to the payees
1313 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1314 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1316 // Choose coins to use
1317 set<pair<const CWalletTx*,unsigned int> > setCoins;
1319 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1321 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1323 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1324 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1327 int64 nChange = nValueIn - nValue - nFeeRet;
1328 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1329 // or until nChange becomes zero
1330 // NOTE: this depends on the exact behaviour of GetMinFee
1331 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1333 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1334 nChange -= nMoveToFee;
1335 nFeeRet += nMoveToFee;
1338 // sub-cent change is moved to fee
1339 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1347 // Fill a vout to ourself
1348 // TODO: pass in scriptChange instead of reservekey so
1349 // change transaction isn't always pay-to-bitcoin-address
1350 CScript scriptChange;
1352 // coin control: send change to custom address
1353 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1354 scriptChange.SetDestination(coinControl->destChange);
1356 // no coin control: send change to newly generated address
1359 // Note: We use a new key here to keep it from being obvious which side is the change.
1360 // The drawback is that by not reusing a previous key, the change may be lost if a
1361 // backup is restored, if the backup doesn't have the new private key for the change.
1362 // If we reused the old key, it would be possible to add code to look for and
1363 // rediscover unknown transactions that were written with keys of ours to recover
1364 // post-backup change.
1366 // Reserve a new key pair from key pool
1367 CPubKey vchPubKey = reservekey.GetReservedKey();
1369 scriptChange.SetDestination(vchPubKey.GetID());
1372 // Insert change txn at random position:
1373 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1374 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1377 reservekey.ReturnKey();
1380 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1381 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1385 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1386 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1390 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1391 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1393 dPriority /= nBytes;
1395 // Check that enough fee is included
1396 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1397 bool fAllowFree = CTransaction::AllowFree(dPriority);
1398 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1399 if (nFeeRet < max(nPayFee, nMinFee))
1401 nFeeRet = max(nPayFee, nMinFee);
1405 // Fill vtxPrev by copying from previous transactions vtxPrev
1406 wtxNew.AddSupportingTransactions();
1407 wtxNew.fTimeReceivedIsTxTime = true;
1416 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1418 vector< pair<CScript, int64> > vecSend;
1419 vecSend.push_back(make_pair(scriptPubKey, nValue));
1420 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1423 // NovaCoin: get current stake weight
1424 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1426 // Choose coins to use
1427 int64 nBalance = GetBalance();
1428 int64 nReserveBalance = 0;
1430 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1432 error("GetStakeWeight : invalid reserve balance amount");
1436 if (nBalance <= nReserveBalance)
1439 vector<const CWalletTx*> vwtxPrev;
1440 set<pair<const CWalletTx*,unsigned int> > setCoins;
1443 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1446 if (setCoins.empty())
1449 CCoinsViewCache &view = *pcoinsTip;
1450 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1454 LOCK2(cs_main, cs_wallet);
1455 if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1459 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1460 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1462 // Weight is greater than zero
1463 if (nTimeWeight > 0)
1465 nWeight += bnCoinDayWeight.getuint64();
1468 // Weight is greater than zero, but the maximum value isn't reached yet
1469 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1471 nMinWeight += bnCoinDayWeight.getuint64();
1474 // Maximum weight was reached
1475 if (nTimeWeight == nStakeMaxAge)
1477 nMaxWeight += bnCoinDayWeight.getuint64();
1484 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1486 // The following combine threshold is important to security
1487 // Should not be adjusted if you don't understand the consequences
1488 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1489 CBlockIndex* pindexPrev = pindexBest;
1490 CBigNum bnTargetPerCoinDay;
1491 bnTargetPerCoinDay.SetCompact(nBits);
1496 // Mark coin stake transaction
1497 CScript scriptEmpty;
1498 scriptEmpty.clear();
1499 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1501 // Choose coins to use
1502 int64 nBalance = GetBalance();
1503 int64 nReserveBalance = 0;
1505 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1506 return error("CreateCoinStake : invalid reserve balance amount");
1508 if (nBalance <= nReserveBalance)
1511 vector<const CWalletTx*> vwtxPrev;
1512 set<pair<const CWalletTx*,unsigned int> > setCoins;
1515 // Select coins with suitable depth
1516 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1519 if (setCoins.empty())
1523 CScript scriptPubKeyKernel;
1525 CCoinsViewCache &view = *pcoinsTip;
1526 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1530 LOCK2(cs_main, cs_wallet);
1531 if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1535 static int nMaxStakeSearchInterval = 60;
1536 if (coins.nBlockTime + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1537 continue; // only count coins meeting min age requirement
1539 // Read block header
1541 unsigned int nTxPos = 0;
1543 LOCK2(cs_main, cs_wallet);
1544 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
1546 if (!block.ReadFromDisk(pindex))
1549 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1550 if (tx.GetHash() == pcoin.first->GetHash()) {
1553 nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
1555 nTxPos += GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
1559 bool fFatal = false;
1560 bool fKernelFound = false;
1561 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown && pindexPrev == pindexBest; n++)
1563 // Search backward in time from the given txNew timestamp
1564 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1565 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1566 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1567 if (CheckStakeKernelHash(nBits, block, nTxPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake, fFatal, true))
1570 if (fDebug && GetBoolArg("-printcoinstake"))
1571 printf("CreateCoinStake : kernel found\n");
1572 vector<valtype> vSolutions;
1573 txnouttype whichType;
1574 CScript scriptPubKeyOut;
1575 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1576 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1578 if (fDebug && GetBoolArg("-printcoinstake"))
1579 printf("CreateCoinStake : failed to parse kernel\n");
1582 if (fDebug && GetBoolArg("-printcoinstake"))
1583 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1584 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1586 if (fDebug && GetBoolArg("-printcoinstake"))
1587 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1588 break; // only support pay to public key and pay to address
1590 if (whichType == TX_PUBKEYHASH) // pay to address type
1592 // convert to pay to public key type
1593 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1595 if (fDebug && GetBoolArg("-printcoinstake"))
1596 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1597 break; // unable to find corresponding public key
1599 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1601 if (whichType == TX_PUBKEY)
1603 valtype& vchPubKey = vSolutions[0];
1604 if (!keystore.GetKey(Hash160(vchPubKey), key))
1606 if (fDebug && GetBoolArg("-printcoinstake"))
1607 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1608 break; // unable to find corresponding public key
1611 if (key.GetPubKey() != vchPubKey)
1613 if (fDebug && GetBoolArg("-printcoinstake"))
1614 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1615 break; // keys mismatch
1618 scriptPubKeyOut = scriptPubKeyKernel;
1622 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1623 nCredit += pcoin.first->vout[pcoin.second].nValue;
1624 vwtxPrev.push_back(pcoin.first);
1625 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1627 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1628 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1629 if (fDebug && GetBoolArg("-printcoinstake"))
1630 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1631 fKernelFound = true;
1636 if (fKernelFound || fShutdown)
1637 break; // if kernel is found stop searching
1640 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1643 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1645 // Attempt to add more inputs
1646 // Only add coins of the same key/address as kernel
1647 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1648 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1650 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1652 // Stop adding more inputs if already too many inputs
1653 if (txNew.vin.size() >= 100)
1655 // Stop adding more inputs if value is already pretty significant
1656 if (nCredit > nCombineThreshold)
1658 // Stop adding inputs if reached reserve limit
1659 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1661 // Do not add additional significant input
1662 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1664 // Do not add input that is still too young
1665 if (nTimeWeight < nStakeMaxAge)
1668 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1669 nCredit += pcoin.first->vout[pcoin.second].nValue;
1670 vwtxPrev.push_back(pcoin.first);
1674 // Calculate coin age reward
1678 if (!txNew.GetCoinAge(nCoinAge))
1679 return error("CreateCoinStake : failed to calculate coin age");
1680 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1686 // Set output amount
1687 if (txNew.vout.size() == 3)
1689 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1690 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1693 txNew.vout[1].nValue = nCredit - nMinFee;
1697 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1699 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1700 return error("CreateCoinStake : failed to sign coinstake");
1704 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1705 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1706 return error("CreateCoinStake : exceeded coinstake size limit");
1708 // Check enough fee is paid
1709 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1711 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1712 continue; // try signing again
1716 if (fDebug && GetBoolArg("-printfee"))
1717 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1722 // Successfully generated coinstake
1727 // Call after CreateTransaction unless you want to abort
1728 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1731 LOCK2(cs_main, cs_wallet);
1732 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1734 // This is only to keep the database open to defeat the auto-flush for the
1735 // duration of this scope. This is the only place where this optimization
1736 // maybe makes sense; please don't do it anywhere else.
1737 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1739 // Take key pair from key pool so it won't be used again
1740 reservekey.KeepKey();
1742 // Add tx to wallet, because if it has change it's also ours,
1743 // otherwise just for transaction history.
1744 AddToWallet(wtxNew);
1746 // Mark old coins as spent
1747 set<CWalletTx*> setCoins;
1748 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1750 CWalletTx &coin = mapWallet[txin.prevout.hash];
1751 coin.BindWallet(this);
1752 coin.MarkSpent(txin.prevout.n);
1754 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1761 // Track how many getdata requests our transaction gets
1762 mapRequestCount[wtxNew.GetHash()] = 0;
1765 if (!wtxNew.AcceptToMemoryPool())
1767 // This must not fail. The transaction has already been signed and recorded.
1768 printf("CommitTransaction() : Error: Transaction not valid");
1771 wtxNew.RelayWalletTransaction();
1779 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1781 CReserveKey reservekey(this);
1786 string strError = _("Error: Wallet locked, unable to create transaction ");
1787 printf("SendMoney() : %s", strError.c_str());
1790 if (fWalletUnlockMintOnly)
1792 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1793 printf("SendMoney() : %s", strError.c_str());
1796 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1799 if (nValue + nFeeRequired > GetBalance())
1800 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());
1802 strError = _("Error: Transaction creation failed ");
1803 printf("SendMoney() : %s", strError.c_str());
1807 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1810 if (!CommitTransaction(wtxNew, reservekey))
1811 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.");
1818 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1822 return _("Invalid amount");
1823 if (nValue + nTransactionFee > GetBalance())
1824 return _("Insufficient funds");
1826 // Parse Bitcoin address
1827 CScript scriptPubKey;
1828 scriptPubKey.SetDestination(address);
1830 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1836 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1840 fFirstRunRet = false;
1841 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1842 if (nLoadWalletRet == DB_NEED_REWRITE)
1844 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1847 // Note: can't top-up keypool here, because wallet is locked.
1848 // User will be prompted to unlock wallet the next operation
1849 // the requires a new key.
1853 if (nLoadWalletRet != DB_LOAD_OK)
1854 return nLoadWalletRet;
1855 fFirstRunRet = !vchDefaultKey.IsValid();
1857 NewThread(ThreadFlushWalletDB, &strWalletFile);
1862 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1864 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1865 mapAddressBook[address] = strName;
1866 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1869 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1872 bool CWallet::DelAddressBookName(const CTxDestination& address)
1874 mapAddressBook.erase(address);
1875 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1878 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1882 void CWallet::PrintWallet(const CBlock& block)
1886 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1888 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1889 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1891 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1893 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1894 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1901 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1905 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1906 if (mi != mapWallet.end())
1915 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1919 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1922 vchDefaultKey = vchPubKey;
1926 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1928 if (!pwallet->fFileBacked)
1930 strWalletFileOut = pwallet->strWalletFile;
1935 // Mark old keypool keys as used,
1936 // and generate all new keys
1938 bool CWallet::NewKeyPool()
1942 CWalletDB walletdb(strWalletFile);
1943 BOOST_FOREACH(int64 nIndex, setKeyPool)
1944 walletdb.ErasePool(nIndex);
1950 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1951 for (int i = 0; i < nKeys; i++)
1954 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1955 setKeyPool.insert(nIndex);
1957 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1962 bool CWallet::TopUpKeyPool(unsigned int nSize)
1970 CWalletDB walletdb(strWalletFile);
1973 unsigned int nTargetSize;
1975 nTargetSize = nSize;
1977 nTargetSize = max(GetArg("-keypool", 100), 0LL);
1979 while (setKeyPool.size() < (nTargetSize + 1))
1982 if (!setKeyPool.empty())
1983 nEnd = *(--setKeyPool.end()) + 1;
1984 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1985 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1986 setKeyPool.insert(nEnd);
1987 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
1993 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1996 keypool.vchPubKey = CPubKey();
2003 // Get the oldest key
2004 if(setKeyPool.empty())
2007 CWalletDB walletdb(strWalletFile);
2009 nIndex = *(setKeyPool.begin());
2010 setKeyPool.erase(setKeyPool.begin());
2011 if (!walletdb.ReadPool(nIndex, keypool))
2012 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2013 if (!HaveKey(keypool.vchPubKey.GetID()))
2014 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2015 assert(keypool.vchPubKey.IsValid());
2016 if (fDebug && GetBoolArg("-printkeypool"))
2017 printf("keypool reserve %"PRI64d"\n", nIndex);
2021 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2024 LOCK2(cs_main, cs_wallet);
2025 CWalletDB walletdb(strWalletFile);
2027 int64 nIndex = 1 + *(--setKeyPool.end());
2028 if (!walletdb.WritePool(nIndex, keypool))
2029 throw runtime_error("AddReserveKey() : writing added key failed");
2030 setKeyPool.insert(nIndex);
2036 void CWallet::KeepKey(int64 nIndex)
2038 // Remove from key pool
2041 CWalletDB walletdb(strWalletFile);
2042 walletdb.ErasePool(nIndex);
2045 printf("keypool keep %"PRI64d"\n", nIndex);
2048 void CWallet::ReturnKey(int64 nIndex)
2050 // Return to key pool
2053 setKeyPool.insert(nIndex);
2056 printf("keypool return %"PRI64d"\n", nIndex);
2059 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2065 ReserveKeyFromKeyPool(nIndex, keypool);
2068 if (fAllowReuse && vchDefaultKey.IsValid())
2070 result = vchDefaultKey;
2073 if (IsLocked()) return false;
2074 result = GenerateNewKey();
2078 result = keypool.vchPubKey;
2083 int64 CWallet::GetOldestKeyPoolTime()
2087 ReserveKeyFromKeyPool(nIndex, keypool);
2091 return keypool.nTime;
2094 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2096 map<CTxDestination, int64> balances;
2100 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2102 CWalletTx *pcoin = &walletEntry.second;
2104 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
2107 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2110 int nDepth = pcoin->GetDepthInMainChain();
2111 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2114 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2116 CTxDestination addr;
2117 if (!IsMine(pcoin->vout[i]))
2119 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2122 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2124 if (!balances.count(addr))
2126 balances[addr] += n;
2134 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2136 set< set<CTxDestination> > groupings;
2137 set<CTxDestination> grouping;
2139 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2141 CWalletTx *pcoin = &walletEntry.second;
2143 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2145 // group all input addresses with each other
2146 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2148 CTxDestination address;
2149 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2151 grouping.insert(address);
2154 // group change with input addresses
2155 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2156 if (IsChange(txout))
2158 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2159 CTxDestination txoutAddr;
2160 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2162 grouping.insert(txoutAddr);
2164 groupings.insert(grouping);
2168 // group lone addrs by themselves
2169 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2170 if (IsMine(pcoin->vout[i]))
2172 CTxDestination address;
2173 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2175 grouping.insert(address);
2176 groupings.insert(grouping);
2181 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2182 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2183 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2185 // make a set of all the groups hit by this new group
2186 set< set<CTxDestination>* > hits;
2187 map< CTxDestination, set<CTxDestination>* >::iterator it;
2188 BOOST_FOREACH(CTxDestination address, grouping)
2189 if ((it = setmap.find(address)) != setmap.end())
2190 hits.insert((*it).second);
2192 // merge all hit groups into a new single group and delete old groups
2193 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2194 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2196 merged->insert(hit->begin(), hit->end());
2197 uniqueGroupings.erase(hit);
2200 uniqueGroupings.insert(merged);
2203 BOOST_FOREACH(CTxDestination element, *merged)
2204 setmap[element] = merged;
2207 set< set<CTxDestination> > ret;
2208 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2210 ret.insert(*uniqueGrouping);
2211 delete uniqueGrouping;
2217 // ppcoin: check 'spent' consistency between wallet and txindex
2218 // ppcoin: fix wallet spent state according to txindex
2219 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2222 nBalanceInQuestion = 0;
2225 vector<CWalletTx*> vCoins;
2226 vCoins.reserve(mapWallet.size());
2227 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2228 vCoins.push_back(&(*it).second);
2230 CCoinsViewCache &view = *pcoinsTip;
2231 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2233 // Find the corresponding transaction index
2236 bool fNotFound = view.GetCoins(pcoin->GetHash(), coins);
2238 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2240 if (!fNotFound && IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && coins.IsAvailable(n))
2242 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2243 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2245 nBalanceInQuestion += pcoin->vout[n].nValue;
2248 pcoin->MarkUnspent(n);
2249 pcoin->WriteToDisk();
2252 else if (!fNotFound && IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && coins.IsAvailable(n))
2254 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2255 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2257 nBalanceInQuestion += pcoin->vout[n].nValue;
2260 pcoin->MarkSpent(n);
2261 pcoin->WriteToDisk();
2267 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2269 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2272 EraseFromWallet(pcoin->GetHash());
2278 // ppcoin: disable transaction (only for coinstake)
2279 void CWallet::DisableTransaction(const CTransaction &tx)
2281 if (!tx.IsCoinStake() || !IsFromMe(tx))
2282 return; // only disconnecting coinstake requires marking input unspent
2285 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2287 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2288 if (mi != mapWallet.end())
2290 CWalletTx& prev = (*mi).second;
2291 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2293 prev.MarkUnspent(txin.prevout.n);
2300 CPubKey CReserveKey::GetReservedKey()
2305 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2307 vchPubKey = keypool.vchPubKey;
2310 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2311 vchPubKey = pwallet->vchDefaultKey;
2314 assert(vchPubKey.IsValid());
2318 void CReserveKey::KeepKey()
2321 pwallet->KeepKey(nIndex);
2323 vchPubKey = CPubKey();
2326 void CReserveKey::ReturnKey()
2329 pwallet->ReturnKey(nIndex);
2331 vchPubKey = CPubKey();
2334 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2338 CWalletDB walletdb(strWalletFile);
2340 LOCK2(cs_main, cs_wallet);
2341 BOOST_FOREACH(const int64& id, setKeyPool)
2344 if (!walletdb.ReadPool(id, keypool))
2345 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2346 assert(keypool.vchPubKey.IsValid());
2347 CKeyID keyID = keypool.vchPubKey.GetID();
2348 if (!HaveKey(keyID))
2349 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2350 setAddress.insert(keyID);
2354 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2358 // Only notify UI if this transaction is in this wallet
2359 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2360 if (mi != mapWallet.end())
2361 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2365 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2366 mapKeyBirth.clear();
2368 // get birth times for keys with metadata
2369 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2370 if (it->second.nCreateTime)
2371 mapKeyBirth[it->first] = it->second.nCreateTime;
2373 // map in which we'll infer heights of other keys
2374 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2375 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2376 std::set<CKeyID> setKeys;
2378 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2379 if (mapKeyBirth.count(keyid) == 0)
2380 mapKeyFirstBlock[keyid] = pindexMax;
2384 // if there are no such keys, we're done
2385 if (mapKeyFirstBlock.empty())
2388 // find first block that affects those keys, if there are any left
2389 std::vector<CKeyID> vAffected;
2390 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2391 // iterate over all wallet transactions...
2392 const CWalletTx &wtx = (*it).second;
2393 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2394 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2395 // ... which are already in a block
2396 int nHeight = blit->second->nHeight;
2397 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2398 // iterate over all their outputs
2399 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2400 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2401 // ... and all their affected keys
2402 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2403 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2404 rit->second = blit->second;
2411 // Extract block timestamps for those keys
2412 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2413 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off