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 uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
527 bool fExisted = mapWallet.count(hash);
528 if (fExisted && !fUpdate) return false;
529 if (fExisted || IsMine(tx) || IsFromMe(tx))
531 CWalletTx wtx(this,tx);
532 // Get merkle branch if transaction was found in a block
534 wtx.SetMerkleBranch(pblock);
535 return AddToWallet(wtx);
538 WalletUpdateSpent(tx);
543 bool CWallet::EraseFromWallet(uint256 hash)
549 if (mapWallet.erase(hash))
550 CWalletDB(strWalletFile).EraseTx(hash);
556 bool CWallet::IsMine(const CTxIn &txin) const
560 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
561 if (mi != mapWallet.end())
563 const CWalletTx& prev = (*mi).second;
564 if (txin.prevout.n < prev.vout.size())
565 if (IsMine(prev.vout[txin.prevout.n]))
572 int64 CWallet::GetDebit(const CTxIn &txin) const
576 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
577 if (mi != mapWallet.end())
579 const CWalletTx& prev = (*mi).second;
580 if (txin.prevout.n < prev.vout.size())
581 if (IsMine(prev.vout[txin.prevout.n]))
582 return prev.vout[txin.prevout.n].nValue;
588 bool CWallet::IsChange(const CTxOut& txout) const
590 CTxDestination address;
592 // TODO: fix handling of 'change' outputs. The assumption is that any
593 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
594 // is change. That assumption is likely to break when we implement multisignature
595 // wallets that return change back into a multi-signature-protected address;
596 // a better way of identifying which outputs are 'the send' and which are
597 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
598 // which output, if any, was change).
599 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
602 if (!mapAddressBook.count(address))
608 int64 CWalletTx::GetTxTime() const
610 int64 n = nTimeSmart;
611 return n ? n : nTimeReceived;
614 int CWalletTx::GetRequestCount() const
616 // Returns -1 if it wasn't being tracked
619 LOCK(pwallet->cs_wallet);
620 if (IsCoinBase() || IsCoinStake())
625 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
626 if (mi != pwallet->mapRequestCount.end())
627 nRequests = (*mi).second;
632 // Did anyone request this transaction?
633 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
634 if (mi != pwallet->mapRequestCount.end())
636 nRequests = (*mi).second;
638 // How about the block it's in?
639 if (nRequests == 0 && hashBlock != 0)
641 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
642 if (mi != pwallet->mapRequestCount.end())
643 nRequests = (*mi).second;
645 nRequests = 1; // If it's in someone else's block it must have got out
653 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
654 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
656 nGeneratedImmature = nGeneratedMature = nFee = 0;
657 listReceived.clear();
659 strSentAccount = strFromAccount;
661 if (IsCoinBase() || IsCoinStake())
663 if (GetBlocksToMaturity() > 0)
664 nGeneratedImmature = pwallet->GetCredit(*this);
666 nGeneratedMature = GetCredit();
671 int64 nDebit = GetDebit();
672 if (nDebit > 0) // debit>0 means we signed/sent this transaction
674 int64 nValueOut = GetValueOut();
675 nFee = nDebit - nValueOut;
679 BOOST_FOREACH(const CTxOut& txout, vout)
681 CTxDestination address;
682 vector<unsigned char> vchPubKey;
683 if (!ExtractDestination(txout.scriptPubKey, address))
685 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
686 this->GetHash().ToString().c_str());
689 // Don't report 'change' txouts
690 if (nDebit > 0 && pwallet->IsChange(txout))
694 listSent.push_back(make_pair(address, txout.nValue));
696 if (pwallet->IsMine(txout))
697 listReceived.push_back(make_pair(address, txout.nValue));
702 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
703 int64& nSent, int64& nFee) const
705 nGenerated = nReceived = nSent = nFee = 0;
707 int64 allGeneratedImmature, allGeneratedMature, allFee;
708 allGeneratedImmature = allGeneratedMature = allFee = 0;
709 string strSentAccount;
710 list<pair<CTxDestination, int64> > listReceived;
711 list<pair<CTxDestination, int64> > listSent;
712 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
714 if (strAccount == "")
715 nGenerated = allGeneratedMature;
716 if (strAccount == strSentAccount)
718 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
723 LOCK(pwallet->cs_wallet);
724 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
726 if (pwallet->mapAddressBook.count(r.first))
728 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
729 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
730 nReceived += r.second;
732 else if (strAccount.empty())
734 nReceived += r.second;
740 void CWalletTx::AddSupportingTransactions()
744 const int COPY_DEPTH = 3;
745 if (SetMerkleBranch() < COPY_DEPTH)
747 vector<uint256> vWorkQueue;
748 BOOST_FOREACH(const CTxIn& txin, vin)
749 vWorkQueue.push_back(txin.prevout.hash);
752 LOCK(pwallet->cs_wallet);
753 map<uint256, const CMerkleTx*> mapWalletPrev;
754 set<uint256> setAlreadyDone;
755 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
757 uint256 hash = vWorkQueue[i];
758 if (setAlreadyDone.count(hash))
760 setAlreadyDone.insert(hash);
763 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
764 if (mi != pwallet->mapWallet.end())
767 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
768 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
770 else if (mapWalletPrev.count(hash))
772 tx = *mapWalletPrev[hash];
775 int nDepth = tx.SetMerkleBranch();
776 vtxPrev.push_back(tx);
778 if (nDepth < COPY_DEPTH)
780 BOOST_FOREACH(const CTxIn& txin, tx.vin)
781 vWorkQueue.push_back(txin.prevout.hash);
787 reverse(vtxPrev.begin(), vtxPrev.end());
790 bool CWalletTx::WriteToDisk()
792 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
795 // Scan the block chain (starting in pindexStart) for transactions
796 // from or to us. If fUpdate is true, found transactions that already
797 // exist in the wallet will be updated.
798 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
802 CBlockIndex* pindex = pindexStart;
808 block.ReadFromDisk(pindex, true);
809 BOOST_FOREACH(CTransaction& tx, block.vtx)
811 if (AddToWalletIfInvolvingMe(tx.GetHash(), tx, &block, fUpdate))
814 pindex = pindex->pnext;
820 void CWallet::ReacceptWalletTransactions()
827 bool fMissing = false;
828 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
830 CWalletTx& wtx = item.second;
831 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
835 bool fUpdated = false;
836 bool fNotFound = pcoinsTip->GetCoins(wtx.GetHash(), coins);
837 if (!fNotFound || wtx.GetDepthInMainChain() > 0)
839 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
840 for (unsigned int i = 0; i < wtx.vout.size(); i++)
844 if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i]))
853 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
860 // Re-accept any txes of ours that aren't already in a block
861 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
862 wtx.AcceptWalletTransaction(false);
867 // TODO: optimize this to scan just part of the block chain?
868 if (ScanForWalletTransactions(pindexGenesisBlock))
869 fRepeat = true; // Found missing transactions: re-do re-accept.
874 void CWalletTx::RelayWalletTransaction()
876 CCoinsViewCache& coins = *pcoinsTip;
877 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
879 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
881 uint256 hash = tx.GetHash();
882 if (!coins.HaveCoins(hash))
883 RelayTransaction((CTransaction)tx, hash);
886 if (!(IsCoinBase() || IsCoinStake()))
888 uint256 hash = GetHash();
889 if (!coins.HaveCoins(hash))
891 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
892 RelayTransaction((CTransaction)*this, hash);
897 void CWallet::ResendWalletTransactions()
899 // Do this infrequently and randomly to avoid giving away
900 // that these are our transactions.
901 static int64 nNextTime;
902 if (GetTime() < nNextTime)
904 bool fFirst = (nNextTime == 0);
905 nNextTime = GetTime() + GetRand(30 * 60);
909 // Only do it if there's been a new block since last time
910 static int64 nLastTime;
911 if (nTimeBestReceived < nLastTime)
913 nLastTime = GetTime();
915 // Rebroadcast any of our txes that aren't in a block yet
916 printf("ResendWalletTransactions()\n");
919 // Sort them in chronological order
920 multimap<unsigned int, CWalletTx*> mapSorted;
921 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
923 CWalletTx& wtx = item.second;
924 // Don't rebroadcast until it's had plenty of time that
925 // it should have gotten in already by now.
926 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
927 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
929 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
931 CWalletTx& wtx = *item.second;
932 wtx.RelayWalletTransaction();
942 //////////////////////////////////////////////////////////////////////////////
948 int64 CWallet::GetBalance() const
953 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
955 const CWalletTx* pcoin = &(*it).second;
956 if (pcoin->IsConfirmed())
957 nTotal += pcoin->GetAvailableCredit();
964 int64 CWallet::GetUnconfirmedBalance() const
969 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
971 const CWalletTx* pcoin = &(*it).second;
972 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
973 nTotal += pcoin->GetAvailableCredit();
979 int64 CWallet::GetImmatureBalance() const
984 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
986 const CWalletTx& pcoin = (*it).second;
987 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
988 nTotal += GetCredit(pcoin);
994 // populate vCoins with vector of spendable COutputs
995 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1001 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1003 const CWalletTx* pcoin = &(*it).second;
1005 if (!pcoin->IsFinal())
1008 if (fOnlyConfirmed && !pcoin->IsConfirmed())
1011 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1014 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1017 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1018 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1019 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1020 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1026 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1032 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1034 const CWalletTx* pcoin = &(*it).second;
1036 if (!pcoin->IsFinal())
1039 if(pcoin->GetDepthInMainChain() < nConf)
1042 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1043 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1044 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1049 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1050 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1052 vector<char> vfIncluded;
1054 vfBest.assign(vValue.size(), true);
1055 nBest = nTotalLower;
1057 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1059 vfIncluded.assign(vValue.size(), false);
1061 bool fReachedTarget = false;
1062 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1064 for (unsigned int i = 0; i < vValue.size(); i++)
1066 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1068 nTotal += vValue[i].first;
1069 vfIncluded[i] = true;
1070 if (nTotal >= nTargetValue)
1072 fReachedTarget = true;
1076 vfBest = vfIncluded;
1078 nTotal -= vValue[i].first;
1079 vfIncluded[i] = false;
1087 // ppcoin: total coins staked (non-spendable until maturity)
1088 int64 CWallet::GetStake() const
1092 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1094 const CWalletTx* pcoin = &(*it).second;
1095 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1096 nTotal += CWallet::GetCredit(*pcoin);
1101 int64 CWallet::GetNewMint() const
1105 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1107 const CWalletTx* pcoin = &(*it).second;
1108 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1109 nTotal += CWallet::GetCredit(*pcoin);
1114 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
1116 setCoinsRet.clear();
1119 // List of values less than target
1120 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1121 coinLowestLarger.first = std::numeric_limits<int64>::max();
1122 coinLowestLarger.second.first = NULL;
1123 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1124 int64 nTotalLower = 0;
1126 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1128 BOOST_FOREACH(COutput output, vCoins)
1130 const CWalletTx *pcoin = output.tx;
1132 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1137 // Follow the timestamp rules
1138 if (pcoin->nTime > nSpendTime)
1141 int64 n = pcoin->vout[i].nValue;
1143 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1145 if (n == nTargetValue)
1147 setCoinsRet.insert(coin.second);
1148 nValueRet += coin.first;
1151 else if (n < nTargetValue + CENT)
1153 vValue.push_back(coin);
1156 else if (n < coinLowestLarger.first)
1158 coinLowestLarger = coin;
1162 if (nTotalLower == nTargetValue)
1164 for (unsigned int i = 0; i < vValue.size(); ++i)
1166 setCoinsRet.insert(vValue[i].second);
1167 nValueRet += vValue[i].first;
1172 if (nTotalLower < nTargetValue)
1174 if (coinLowestLarger.second.first == NULL)
1176 setCoinsRet.insert(coinLowestLarger.second);
1177 nValueRet += coinLowestLarger.first;
1181 // Solve subset sum by stochastic approximation
1182 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1183 vector<char> vfBest;
1186 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1187 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1188 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1190 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1191 // or the next bigger coin is closer), return the bigger coin
1192 if (coinLowestLarger.second.first &&
1193 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1195 setCoinsRet.insert(coinLowestLarger.second);
1196 nValueRet += coinLowestLarger.first;
1199 for (unsigned int i = 0; i < vValue.size(); i++)
1202 setCoinsRet.insert(vValue[i].second);
1203 nValueRet += vValue[i].first;
1206 if (fDebug && GetBoolArg("-printpriority"))
1209 printf("SelectCoins() best subset: ");
1210 for (unsigned int i = 0; i < vValue.size(); i++)
1212 printf("%s ", FormatMoney(vValue[i].first).c_str());
1213 printf("total %s\n", FormatMoney(nBest).c_str());
1220 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1222 vector<COutput> vCoins;
1223 AvailableCoins(vCoins, true, coinControl);
1225 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1226 if (coinControl && coinControl->HasSelected())
1228 BOOST_FOREACH(const COutput& out, vCoins)
1230 nValueRet += out.tx->vout[out.i].nValue;
1231 setCoinsRet.insert(make_pair(out.tx, out.i));
1233 return (nValueRet >= nTargetValue);
1236 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1237 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1238 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1241 // Select some coins without random shuffle or best subset approximation
1242 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1244 vector<COutput> vCoins;
1245 AvailableCoinsMinConf(vCoins, nMinConf);
1247 setCoinsRet.clear();
1250 BOOST_FOREACH(COutput output, vCoins)
1252 const CWalletTx *pcoin = output.tx;
1255 // Stop if we've chosen enough inputs
1256 if (nValueRet >= nTargetValue)
1259 // Follow the timestamp rules
1260 if (pcoin->nTime > nSpendTime)
1263 int64 n = pcoin->vout[i].nValue;
1265 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1267 if (n >= nTargetValue)
1269 // If input value is greater or equal to target then simply insert
1270 // it into the current subset and exit
1271 setCoinsRet.insert(coin.second);
1272 nValueRet += coin.first;
1275 else if (n < nTargetValue + CENT)
1277 setCoinsRet.insert(coin.second);
1278 nValueRet += coin.first;
1285 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1288 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1294 if (vecSend.empty() || nValue < 0)
1297 wtxNew.BindWallet(this);
1300 LOCK2(cs_main, cs_wallet);
1302 nFeeRet = nTransactionFee;
1306 wtxNew.vout.clear();
1307 wtxNew.fFromMe = true;
1309 int64 nTotalValue = nValue + nFeeRet;
1310 double dPriority = 0;
1311 // vouts to the payees
1312 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1313 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1315 // Choose coins to use
1316 set<pair<const CWalletTx*,unsigned int> > setCoins;
1318 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1320 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1322 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1323 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1326 int64 nChange = nValueIn - nValue - nFeeRet;
1327 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1328 // or until nChange becomes zero
1329 // NOTE: this depends on the exact behaviour of GetMinFee
1330 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1332 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1333 nChange -= nMoveToFee;
1334 nFeeRet += nMoveToFee;
1337 // sub-cent change is moved to fee
1338 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1346 // Fill a vout to ourself
1347 // TODO: pass in scriptChange instead of reservekey so
1348 // change transaction isn't always pay-to-bitcoin-address
1349 CScript scriptChange;
1351 // coin control: send change to custom address
1352 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1353 scriptChange.SetDestination(coinControl->destChange);
1355 // no coin control: send change to newly generated address
1358 // Note: We use a new key here to keep it from being obvious which side is the change.
1359 // The drawback is that by not reusing a previous key, the change may be lost if a
1360 // backup is restored, if the backup doesn't have the new private key for the change.
1361 // If we reused the old key, it would be possible to add code to look for and
1362 // rediscover unknown transactions that were written with keys of ours to recover
1363 // post-backup change.
1365 // Reserve a new key pair from key pool
1366 CPubKey vchPubKey = reservekey.GetReservedKey();
1368 scriptChange.SetDestination(vchPubKey.GetID());
1371 // Insert change txn at random position:
1372 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1373 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1376 reservekey.ReturnKey();
1379 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1380 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1384 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1385 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1389 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1390 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1392 dPriority /= nBytes;
1394 // Check that enough fee is included
1395 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1396 bool fAllowFree = CTransaction::AllowFree(dPriority);
1397 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1398 if (nFeeRet < max(nPayFee, nMinFee))
1400 nFeeRet = max(nPayFee, nMinFee);
1404 // Fill vtxPrev by copying from previous transactions vtxPrev
1405 wtxNew.AddSupportingTransactions();
1406 wtxNew.fTimeReceivedIsTxTime = true;
1415 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1417 vector< pair<CScript, int64> > vecSend;
1418 vecSend.push_back(make_pair(scriptPubKey, nValue));
1419 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1422 // NovaCoin: get current stake weight
1423 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1425 // Choose coins to use
1426 int64 nBalance = GetBalance();
1427 int64 nReserveBalance = 0;
1429 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1431 error("GetStakeWeight : invalid reserve balance amount");
1435 if (nBalance <= nReserveBalance)
1438 vector<const CWalletTx*> vwtxPrev;
1439 set<pair<const CWalletTx*,unsigned int> > setCoins;
1442 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1445 if (setCoins.empty())
1448 CCoinsViewCache &view = *pcoinsTip;
1449 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1453 LOCK2(cs_main, cs_wallet);
1454 if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1458 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1459 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1461 // Weight is greater than zero
1462 if (nTimeWeight > 0)
1464 nWeight += bnCoinDayWeight.getuint64();
1467 // Weight is greater than zero, but the maximum value isn't reached yet
1468 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1470 nMinWeight += bnCoinDayWeight.getuint64();
1473 // Maximum weight was reached
1474 if (nTimeWeight == nStakeMaxAge)
1476 nMaxWeight += bnCoinDayWeight.getuint64();
1483 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1485 // The following combine threshold is important to security
1486 // Should not be adjusted if you don't understand the consequences
1487 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1488 CBlockIndex* pindexPrev = pindexBest;
1489 CBigNum bnTargetPerCoinDay;
1490 bnTargetPerCoinDay.SetCompact(nBits);
1495 // Mark coin stake transaction
1496 CScript scriptEmpty;
1497 scriptEmpty.clear();
1498 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1500 // Choose coins to use
1501 int64 nBalance = GetBalance();
1502 int64 nReserveBalance = 0;
1504 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1505 return error("CreateCoinStake : invalid reserve balance amount");
1507 if (nBalance <= nReserveBalance)
1510 vector<const CWalletTx*> vwtxPrev;
1511 set<pair<const CWalletTx*,unsigned int> > setCoins;
1514 // Select coins with suitable depth
1515 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1518 if (setCoins.empty())
1522 CScript scriptPubKeyKernel;
1524 CCoinsViewCache &view = *pcoinsTip;
1525 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1529 LOCK2(cs_main, cs_wallet);
1530 if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1534 static int nMaxStakeSearchInterval = 60;
1535 if (coins.nBlockTime + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1536 continue; // only count coins meeting min age requirement
1538 // Read block header
1540 unsigned int nTxPos = 0;
1542 LOCK2(cs_main, cs_wallet);
1543 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
1545 if (!block.ReadFromDisk(pindex))
1548 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1549 if (tx.GetHash() == pcoin.first->GetHash()) {
1552 nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
1554 nTxPos += GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
1558 bool fFatal = false;
1559 bool fKernelFound = false;
1560 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown && pindexPrev == pindexBest; n++)
1562 // Search backward in time from the given txNew timestamp
1563 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1564 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1565 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1566 if (CheckStakeKernelHash(nBits, block, nTxPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake, fFatal, true))
1569 if (fDebug && GetBoolArg("-printcoinstake"))
1570 printf("CreateCoinStake : kernel found\n");
1571 vector<valtype> vSolutions;
1572 txnouttype whichType;
1573 CScript scriptPubKeyOut;
1574 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1575 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1577 if (fDebug && GetBoolArg("-printcoinstake"))
1578 printf("CreateCoinStake : failed to parse kernel\n");
1581 if (fDebug && GetBoolArg("-printcoinstake"))
1582 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1583 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1585 if (fDebug && GetBoolArg("-printcoinstake"))
1586 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1587 break; // only support pay to public key and pay to address
1589 if (whichType == TX_PUBKEYHASH) // pay to address type
1591 // convert to pay to public key type
1592 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1594 if (fDebug && GetBoolArg("-printcoinstake"))
1595 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1596 break; // unable to find corresponding public key
1598 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1600 if (whichType == TX_PUBKEY)
1602 valtype& vchPubKey = vSolutions[0];
1603 if (!keystore.GetKey(Hash160(vchPubKey), key))
1605 if (fDebug && GetBoolArg("-printcoinstake"))
1606 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1607 break; // unable to find corresponding public key
1610 if (key.GetPubKey() != vchPubKey)
1612 if (fDebug && GetBoolArg("-printcoinstake"))
1613 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1614 break; // keys mismatch
1617 scriptPubKeyOut = scriptPubKeyKernel;
1621 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1622 nCredit += pcoin.first->vout[pcoin.second].nValue;
1623 vwtxPrev.push_back(pcoin.first);
1624 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1626 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1627 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1628 if (fDebug && GetBoolArg("-printcoinstake"))
1629 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1630 fKernelFound = true;
1635 if (fKernelFound || fShutdown)
1636 break; // if kernel is found stop searching
1639 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1642 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1644 // Attempt to add more inputs
1645 // Only add coins of the same key/address as kernel
1646 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1647 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1649 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1651 // Stop adding more inputs if already too many inputs
1652 if (txNew.vin.size() >= 100)
1654 // Stop adding more inputs if value is already pretty significant
1655 if (nCredit > nCombineThreshold)
1657 // Stop adding inputs if reached reserve limit
1658 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1660 // Do not add additional significant input
1661 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1663 // Do not add input that is still too young
1664 if (nTimeWeight < nStakeMaxAge)
1667 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1668 nCredit += pcoin.first->vout[pcoin.second].nValue;
1669 vwtxPrev.push_back(pcoin.first);
1673 // Calculate coin age reward
1677 if (!txNew.GetCoinAge(nCoinAge))
1678 return error("CreateCoinStake : failed to calculate coin age");
1679 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1685 // Set output amount
1686 if (txNew.vout.size() == 3)
1688 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1689 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1692 txNew.vout[1].nValue = nCredit - nMinFee;
1696 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1698 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1699 return error("CreateCoinStake : failed to sign coinstake");
1703 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1704 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1705 return error("CreateCoinStake : exceeded coinstake size limit");
1707 // Check enough fee is paid
1708 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1710 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1711 continue; // try signing again
1715 if (fDebug && GetBoolArg("-printfee"))
1716 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1721 // Successfully generated coinstake
1726 // Call after CreateTransaction unless you want to abort
1727 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1730 LOCK2(cs_main, cs_wallet);
1731 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1733 // This is only to keep the database open to defeat the auto-flush for the
1734 // duration of this scope. This is the only place where this optimization
1735 // maybe makes sense; please don't do it anywhere else.
1736 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1738 // Take key pair from key pool so it won't be used again
1739 reservekey.KeepKey();
1741 // Add tx to wallet, because if it has change it's also ours,
1742 // otherwise just for transaction history.
1743 AddToWallet(wtxNew);
1745 // Mark old coins as spent
1746 set<CWalletTx*> setCoins;
1747 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1749 CWalletTx &coin = mapWallet[txin.prevout.hash];
1750 coin.BindWallet(this);
1751 coin.MarkSpent(txin.prevout.n);
1753 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1760 // Track how many getdata requests our transaction gets
1761 mapRequestCount[wtxNew.GetHash()] = 0;
1764 if (!wtxNew.AcceptToMemoryPool())
1766 // This must not fail. The transaction has already been signed and recorded.
1767 printf("CommitTransaction() : Error: Transaction not valid");
1770 wtxNew.RelayWalletTransaction();
1778 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1780 CReserveKey reservekey(this);
1785 string strError = _("Error: Wallet locked, unable to create transaction ");
1786 printf("SendMoney() : %s", strError.c_str());
1789 if (fWalletUnlockMintOnly)
1791 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1792 printf("SendMoney() : %s", strError.c_str());
1795 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1798 if (nValue + nFeeRequired > GetBalance())
1799 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());
1801 strError = _("Error: Transaction creation failed ");
1802 printf("SendMoney() : %s", strError.c_str());
1806 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1809 if (!CommitTransaction(wtxNew, reservekey))
1810 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.");
1817 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1821 return _("Invalid amount");
1822 if (nValue + nTransactionFee > GetBalance())
1823 return _("Insufficient funds");
1825 // Parse Bitcoin address
1826 CScript scriptPubKey;
1827 scriptPubKey.SetDestination(address);
1829 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1835 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1839 fFirstRunRet = false;
1840 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1841 if (nLoadWalletRet == DB_NEED_REWRITE)
1843 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1846 // Note: can't top-up keypool here, because wallet is locked.
1847 // User will be prompted to unlock wallet the next operation
1848 // the requires a new key.
1852 if (nLoadWalletRet != DB_LOAD_OK)
1853 return nLoadWalletRet;
1854 fFirstRunRet = !vchDefaultKey.IsValid();
1856 NewThread(ThreadFlushWalletDB, &strWalletFile);
1861 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1863 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1864 mapAddressBook[address] = strName;
1865 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1868 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1871 bool CWallet::DelAddressBookName(const CTxDestination& address)
1873 mapAddressBook.erase(address);
1874 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1877 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1881 void CWallet::PrintWallet(const CBlock& block)
1885 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1887 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1888 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1890 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1892 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1893 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1900 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1904 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1905 if (mi != mapWallet.end())
1914 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1918 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1921 vchDefaultKey = vchPubKey;
1925 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1927 if (!pwallet->fFileBacked)
1929 strWalletFileOut = pwallet->strWalletFile;
1934 // Mark old keypool keys as used,
1935 // and generate all new keys
1937 bool CWallet::NewKeyPool()
1941 CWalletDB walletdb(strWalletFile);
1942 BOOST_FOREACH(int64 nIndex, setKeyPool)
1943 walletdb.ErasePool(nIndex);
1949 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1950 for (int i = 0; i < nKeys; i++)
1953 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1954 setKeyPool.insert(nIndex);
1956 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1961 bool CWallet::TopUpKeyPool(unsigned int nSize)
1969 CWalletDB walletdb(strWalletFile);
1972 unsigned int nTargetSize;
1974 nTargetSize = nSize;
1976 nTargetSize = max(GetArg("-keypool", 100), 0LL);
1978 while (setKeyPool.size() < (nTargetSize + 1))
1981 if (!setKeyPool.empty())
1982 nEnd = *(--setKeyPool.end()) + 1;
1983 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1984 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1985 setKeyPool.insert(nEnd);
1986 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
1992 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1995 keypool.vchPubKey = CPubKey();
2002 // Get the oldest key
2003 if(setKeyPool.empty())
2006 CWalletDB walletdb(strWalletFile);
2008 nIndex = *(setKeyPool.begin());
2009 setKeyPool.erase(setKeyPool.begin());
2010 if (!walletdb.ReadPool(nIndex, keypool))
2011 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2012 if (!HaveKey(keypool.vchPubKey.GetID()))
2013 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2014 assert(keypool.vchPubKey.IsValid());
2015 if (fDebug && GetBoolArg("-printkeypool"))
2016 printf("keypool reserve %"PRI64d"\n", nIndex);
2020 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2023 LOCK2(cs_main, cs_wallet);
2024 CWalletDB walletdb(strWalletFile);
2026 int64 nIndex = 1 + *(--setKeyPool.end());
2027 if (!walletdb.WritePool(nIndex, keypool))
2028 throw runtime_error("AddReserveKey() : writing added key failed");
2029 setKeyPool.insert(nIndex);
2035 void CWallet::KeepKey(int64 nIndex)
2037 // Remove from key pool
2040 CWalletDB walletdb(strWalletFile);
2041 walletdb.ErasePool(nIndex);
2044 printf("keypool keep %"PRI64d"\n", nIndex);
2047 void CWallet::ReturnKey(int64 nIndex)
2049 // Return to key pool
2052 setKeyPool.insert(nIndex);
2055 printf("keypool return %"PRI64d"\n", nIndex);
2058 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2064 ReserveKeyFromKeyPool(nIndex, keypool);
2067 if (fAllowReuse && vchDefaultKey.IsValid())
2069 result = vchDefaultKey;
2072 if (IsLocked()) return false;
2073 result = GenerateNewKey();
2077 result = keypool.vchPubKey;
2082 int64 CWallet::GetOldestKeyPoolTime()
2086 ReserveKeyFromKeyPool(nIndex, keypool);
2090 return keypool.nTime;
2093 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2095 map<CTxDestination, int64> balances;
2099 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2101 CWalletTx *pcoin = &walletEntry.second;
2103 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
2106 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2109 int nDepth = pcoin->GetDepthInMainChain();
2110 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2113 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2115 CTxDestination addr;
2116 if (!IsMine(pcoin->vout[i]))
2118 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2121 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2123 if (!balances.count(addr))
2125 balances[addr] += n;
2133 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2135 set< set<CTxDestination> > groupings;
2136 set<CTxDestination> grouping;
2138 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2140 CWalletTx *pcoin = &walletEntry.second;
2142 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2144 // group all input addresses with each other
2145 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2147 CTxDestination address;
2148 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2150 grouping.insert(address);
2153 // group change with input addresses
2154 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2155 if (IsChange(txout))
2157 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2158 CTxDestination txoutAddr;
2159 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2161 grouping.insert(txoutAddr);
2163 groupings.insert(grouping);
2167 // group lone addrs by themselves
2168 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2169 if (IsMine(pcoin->vout[i]))
2171 CTxDestination address;
2172 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2174 grouping.insert(address);
2175 groupings.insert(grouping);
2180 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2181 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2182 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2184 // make a set of all the groups hit by this new group
2185 set< set<CTxDestination>* > hits;
2186 map< CTxDestination, set<CTxDestination>* >::iterator it;
2187 BOOST_FOREACH(CTxDestination address, grouping)
2188 if ((it = setmap.find(address)) != setmap.end())
2189 hits.insert((*it).second);
2191 // merge all hit groups into a new single group and delete old groups
2192 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2193 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2195 merged->insert(hit->begin(), hit->end());
2196 uniqueGroupings.erase(hit);
2199 uniqueGroupings.insert(merged);
2202 BOOST_FOREACH(CTxDestination element, *merged)
2203 setmap[element] = merged;
2206 set< set<CTxDestination> > ret;
2207 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2209 ret.insert(*uniqueGrouping);
2210 delete uniqueGrouping;
2216 // ppcoin: check 'spent' consistency between wallet and txindex
2217 // ppcoin: fix wallet spent state according to txindex
2218 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2221 nBalanceInQuestion = 0;
2224 vector<CWalletTx*> vCoins;
2225 vCoins.reserve(mapWallet.size());
2226 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2227 vCoins.push_back(&(*it).second);
2229 CCoinsViewCache &view = *pcoinsTip;
2230 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2232 // Find the corresponding transaction index
2235 bool fNotFound = view.GetCoins(pcoin->GetHash(), coins);
2237 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2239 if (!fNotFound && IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && coins.IsAvailable(n))
2241 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2242 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2244 nBalanceInQuestion += pcoin->vout[n].nValue;
2247 pcoin->MarkUnspent(n);
2248 pcoin->WriteToDisk();
2251 else if (!fNotFound && IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && coins.IsAvailable(n))
2253 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2254 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2256 nBalanceInQuestion += pcoin->vout[n].nValue;
2259 pcoin->MarkSpent(n);
2260 pcoin->WriteToDisk();
2266 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2268 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2271 EraseFromWallet(pcoin->GetHash());
2277 // ppcoin: disable transaction (only for coinstake)
2278 void CWallet::DisableTransaction(const CTransaction &tx)
2280 if (!tx.IsCoinStake() || !IsFromMe(tx))
2281 return; // only disconnecting coinstake requires marking input unspent
2284 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2286 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2287 if (mi != mapWallet.end())
2289 CWalletTx& prev = (*mi).second;
2290 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2292 prev.MarkUnspent(txin.prevout.n);
2299 CPubKey CReserveKey::GetReservedKey()
2304 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2306 vchPubKey = keypool.vchPubKey;
2309 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2310 vchPubKey = pwallet->vchDefaultKey;
2313 assert(vchPubKey.IsValid());
2317 void CReserveKey::KeepKey()
2320 pwallet->KeepKey(nIndex);
2322 vchPubKey = CPubKey();
2325 void CReserveKey::ReturnKey()
2328 pwallet->ReturnKey(nIndex);
2330 vchPubKey = CPubKey();
2333 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2337 CWalletDB walletdb(strWalletFile);
2339 LOCK2(cs_main, cs_wallet);
2340 BOOST_FOREACH(const int64& id, setKeyPool)
2343 if (!walletdb.ReadPool(id, keypool))
2344 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2345 assert(keypool.vchPubKey.IsValid());
2346 CKeyID keyID = keypool.vchPubKey.GetID();
2347 if (!HaveKey(keyID))
2348 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2349 setAddress.insert(keyID);
2353 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2357 // Only notify UI if this transaction is in this wallet
2358 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2359 if (mi != mapWallet.end())
2360 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2364 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2365 mapKeyBirth.clear();
2367 // get birth times for keys with metadata
2368 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2369 if (it->second.nCreateTime)
2370 mapKeyBirth[it->first] = it->second.nCreateTime;
2372 // map in which we'll infer heights of other keys
2373 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2374 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2375 std::set<CKeyID> setKeys;
2377 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2378 if (mapKeyBirth.count(keyid) == 0)
2379 mapKeyFirstBlock[keyid] = pindexMax;
2383 // if there are no such keys, we're done
2384 if (mapKeyFirstBlock.empty())
2387 // find first block that affects those keys, if there are any left
2388 std::vector<CKeyID> vAffected;
2389 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2390 // iterate over all wallet transactions...
2391 const CWalletTx &wtx = (*it).second;
2392 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2393 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2394 // ... which are already in a block
2395 int nHeight = blit->second->nHeight;
2396 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2397 // iterate over all their outputs
2398 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2399 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2400 // ... and all their affected keys
2401 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2402 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2403 rit->second = blit->second;
2410 // Extract block timestamps for those keys
2411 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2412 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off