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, bool fBlock)
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 uint256 hash = tx.GetHash();
384 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
385 CWalletTx& wtx = (*mi).second;
387 BOOST_FOREACH(const CTxOut& txout, tx.vout)
391 wtx.MarkUnspent(&txout - &tx.vout[0]);
393 NotifyTransactionChanged(this, hash, CT_UPDATED);
400 void CWallet::MarkDirty()
404 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
405 item.second.MarkDirty();
409 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
411 uint256 hash = wtxIn.GetHash();
414 // Inserts only if not already there, returns tx inserted or tx found
415 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
416 CWalletTx& wtx = (*ret.first).second;
417 wtx.BindWallet(this);
418 bool fInsertedNew = ret.second;
421 wtx.nTimeReceived = GetAdjustedTime();
422 wtx.nOrderPos = IncOrderPosNext();
424 wtx.nTimeSmart = wtx.nTimeReceived;
425 if (wtxIn.hashBlock != 0)
427 if (mapBlockIndex.count(wtxIn.hashBlock))
429 unsigned int latestNow = wtx.nTimeReceived;
430 unsigned int latestEntry = 0;
432 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
433 int64 latestTolerated = latestNow + 300;
434 std::list<CAccountingEntry> acentries;
435 TxItems txOrdered = OrderedTxItems(acentries);
436 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
438 CWalletTx *const pwtx = (*it).second.first;
441 CAccountingEntry *const pacentry = (*it).second.second;
445 nSmartTime = pwtx->nTimeSmart;
447 nSmartTime = pwtx->nTimeReceived;
450 nSmartTime = pacentry->nTime;
451 if (nSmartTime <= latestTolerated)
453 latestEntry = nSmartTime;
454 if (nSmartTime > latestNow)
455 latestNow = nSmartTime;
461 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
462 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
465 printf("AddToWallet() : found %s in block %s not in index\n",
466 hash.ToString().substr(0,10).c_str(),
467 wtxIn.hashBlock.ToString().c_str());
471 bool fUpdated = false;
475 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
477 wtx.hashBlock = wtxIn.hashBlock;
480 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
482 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
483 wtx.nIndex = wtxIn.nIndex;
486 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
488 wtx.fFromMe = wtxIn.fFromMe;
491 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
495 printf("AddToWallet %s %s%s\n", hash.ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
498 if (fInsertedNew || fUpdated)
499 if (!wtx.WriteToDisk())
502 // If default receiving address gets used, replace it with a new one
503 CScript scriptDefaultKey;
504 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
505 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
507 if (txout.scriptPubKey == scriptDefaultKey)
509 CPubKey newDefaultKey;
510 if (GetKeyFromPool(newDefaultKey, false))
512 SetDefaultKey(newDefaultKey);
513 SetAddressBookName(vchDefaultKey.GetID(), "");
518 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
519 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
521 // Notify UI of new or updated transaction
522 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
524 // notify an external script when a wallet transaction comes in or is updated
525 std::string strCmd = GetArg("-walletnotify", "");
527 if ( !strCmd.empty())
529 boost::replace_all(strCmd, "%s", hash.GetHex());
530 boost::thread t(runCommand, strCmd); // thread runs free
537 // Add a transaction to the wallet, or update it.
538 // pblock is optional, but should be provided if the transaction is known to be in a block.
539 // If fUpdate is true, existing transactions will be updated.
540 bool CWallet::AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
544 bool fExisted = mapWallet.count(hash);
545 if (fExisted && !fUpdate) return false;
546 if (fExisted || IsMine(tx) || IsFromMe(tx))
548 CWalletTx wtx(this,tx);
549 // Get merkle branch if transaction was found in a block
551 wtx.SetMerkleBranch(pblock);
552 return AddToWallet(wtx);
555 WalletUpdateSpent(tx);
560 bool CWallet::EraseFromWallet(uint256 hash)
566 if (mapWallet.erase(hash))
567 CWalletDB(strWalletFile).EraseTx(hash);
573 bool CWallet::IsMine(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]))
589 int64 CWallet::GetDebit(const CTxIn &txin) const
593 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
594 if (mi != mapWallet.end())
596 const CWalletTx& prev = (*mi).second;
597 if (txin.prevout.n < prev.vout.size())
598 if (IsMine(prev.vout[txin.prevout.n]))
599 return prev.vout[txin.prevout.n].nValue;
605 bool CWallet::IsChange(const CTxOut& txout) const
607 CTxDestination address;
609 // TODO: fix handling of 'change' outputs. The assumption is that any
610 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
611 // is change. That assumption is likely to break when we implement multisignature
612 // wallets that return change back into a multi-signature-protected address;
613 // a better way of identifying which outputs are 'the send' and which are
614 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
615 // which output, if any, was change).
616 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
619 if (!mapAddressBook.count(address))
625 int64 CWalletTx::GetTxTime() const
627 int64 n = nTimeSmart;
628 return n ? n : nTimeReceived;
631 int CWalletTx::GetRequestCount() const
633 // Returns -1 if it wasn't being tracked
636 LOCK(pwallet->cs_wallet);
637 if (IsCoinBase() || IsCoinStake())
642 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
643 if (mi != pwallet->mapRequestCount.end())
644 nRequests = (*mi).second;
649 // Did anyone request this transaction?
650 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
651 if (mi != pwallet->mapRequestCount.end())
653 nRequests = (*mi).second;
655 // How about the block it's in?
656 if (nRequests == 0 && hashBlock != 0)
658 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
659 if (mi != pwallet->mapRequestCount.end())
660 nRequests = (*mi).second;
662 nRequests = 1; // If it's in someone else's block it must have got out
670 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
671 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
673 nGeneratedImmature = nGeneratedMature = nFee = 0;
674 listReceived.clear();
676 strSentAccount = strFromAccount;
678 if (IsCoinBase() || IsCoinStake())
680 if (GetBlocksToMaturity() > 0)
681 nGeneratedImmature = pwallet->GetCredit(*this);
683 nGeneratedMature = GetCredit();
688 int64 nDebit = GetDebit();
689 if (nDebit > 0) // debit>0 means we signed/sent this transaction
691 int64 nValueOut = GetValueOut();
692 nFee = nDebit - nValueOut;
696 BOOST_FOREACH(const CTxOut& txout, vout)
698 CTxDestination address;
699 vector<unsigned char> vchPubKey;
700 if (!ExtractDestination(txout.scriptPubKey, address))
702 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
703 this->GetHash().ToString().c_str());
706 // Don't report 'change' txouts
707 if (nDebit > 0 && pwallet->IsChange(txout))
711 listSent.push_back(make_pair(address, txout.nValue));
713 if (pwallet->IsMine(txout))
714 listReceived.push_back(make_pair(address, txout.nValue));
719 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
720 int64& nSent, int64& nFee) const
722 nGenerated = nReceived = nSent = nFee = 0;
724 int64 allGeneratedImmature, allGeneratedMature, allFee;
725 allGeneratedImmature = allGeneratedMature = allFee = 0;
726 string strSentAccount;
727 list<pair<CTxDestination, int64> > listReceived;
728 list<pair<CTxDestination, int64> > listSent;
729 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
731 if (strAccount == "")
732 nGenerated = allGeneratedMature;
733 if (strAccount == strSentAccount)
735 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
740 LOCK(pwallet->cs_wallet);
741 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
743 if (pwallet->mapAddressBook.count(r.first))
745 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
746 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
747 nReceived += r.second;
749 else if (strAccount.empty())
751 nReceived += r.second;
757 void CWalletTx::AddSupportingTransactions()
761 const int COPY_DEPTH = 3;
762 if (SetMerkleBranch() < COPY_DEPTH)
764 vector<uint256> vWorkQueue;
765 BOOST_FOREACH(const CTxIn& txin, vin)
766 vWorkQueue.push_back(txin.prevout.hash);
769 LOCK(pwallet->cs_wallet);
770 map<uint256, const CMerkleTx*> mapWalletPrev;
771 set<uint256> setAlreadyDone;
772 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
774 uint256 hash = vWorkQueue[i];
775 if (setAlreadyDone.count(hash))
777 setAlreadyDone.insert(hash);
780 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
781 if (mi != pwallet->mapWallet.end())
784 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
785 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
787 else if (mapWalletPrev.count(hash))
789 tx = *mapWalletPrev[hash];
792 int nDepth = tx.SetMerkleBranch();
793 vtxPrev.push_back(tx);
795 if (nDepth < COPY_DEPTH)
797 BOOST_FOREACH(const CTxIn& txin, tx.vin)
798 vWorkQueue.push_back(txin.prevout.hash);
804 reverse(vtxPrev.begin(), vtxPrev.end());
807 bool CWalletTx::WriteToDisk()
809 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
812 // Scan the block chain (starting in pindexStart) for transactions
813 // from or to us. If fUpdate is true, found transactions that already
814 // exist in the wallet will be updated.
815 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
819 CBlockIndex* pindex = pindexStart;
825 block.ReadFromDisk(pindex, true);
826 BOOST_FOREACH(CTransaction& tx, block.vtx)
828 if (AddToWalletIfInvolvingMe(tx.GetHash(), tx, &block, fUpdate))
831 pindex = pindex->pnext;
837 void CWallet::ReacceptWalletTransactions()
844 bool fMissing = false;
845 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
847 CWalletTx& wtx = item.second;
848 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
852 bool fUpdated = false;
853 bool fNotFound = pcoinsTip->GetCoins(wtx.GetHash(), coins);
854 if (!fNotFound || wtx.GetDepthInMainChain() > 0)
856 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
857 for (unsigned int i = 0; i < wtx.vout.size(); i++)
861 if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i]))
870 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
877 // Re-accept any txes of ours that aren't already in a block
878 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
879 wtx.AcceptWalletTransaction(false);
884 // TODO: optimize this to scan just part of the block chain?
885 if (ScanForWalletTransactions(pindexGenesisBlock))
886 fRepeat = true; // Found missing transactions: re-do re-accept.
891 void CWalletTx::RelayWalletTransaction()
893 CCoinsViewCache& coins = *pcoinsTip;
894 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
896 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
898 uint256 hash = tx.GetHash();
899 if (!coins.HaveCoins(hash))
900 RelayTransaction((CTransaction)tx, hash);
903 if (!(IsCoinBase() || IsCoinStake()))
905 uint256 hash = GetHash();
906 if (!coins.HaveCoins(hash))
908 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
909 RelayTransaction((CTransaction)*this, hash);
914 void CWallet::ResendWalletTransactions()
916 // Do this infrequently and randomly to avoid giving away
917 // that these are our transactions.
918 static int64 nNextTime;
919 if (GetTime() < nNextTime)
921 bool fFirst = (nNextTime == 0);
922 nNextTime = GetTime() + GetRand(30 * 60);
926 // Only do it if there's been a new block since last time
927 static int64 nLastTime;
928 if (nTimeBestReceived < nLastTime)
930 nLastTime = GetTime();
932 // Rebroadcast any of our txes that aren't in a block yet
933 printf("ResendWalletTransactions()\n");
936 // Sort them in chronological order
937 multimap<unsigned int, CWalletTx*> mapSorted;
938 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
940 CWalletTx& wtx = item.second;
941 // Don't rebroadcast until it's had plenty of time that
942 // it should have gotten in already by now.
943 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
944 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
946 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
948 CWalletTx& wtx = *item.second;
949 wtx.RelayWalletTransaction();
959 //////////////////////////////////////////////////////////////////////////////
965 int64 CWallet::GetBalance() const
970 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
972 const CWalletTx* pcoin = &(*it).second;
973 if (pcoin->IsConfirmed())
974 nTotal += pcoin->GetAvailableCredit();
981 int64 CWallet::GetUnconfirmedBalance() const
986 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
988 const CWalletTx* pcoin = &(*it).second;
989 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
990 nTotal += pcoin->GetAvailableCredit();
996 int64 CWallet::GetImmatureBalance() const
1001 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1003 const CWalletTx& pcoin = (*it).second;
1004 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1005 nTotal += GetCredit(pcoin);
1011 // populate vCoins with vector of spendable COutputs
1012 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1018 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1020 const CWalletTx* pcoin = &(*it).second;
1022 if (!pcoin->IsFinal())
1025 if (fOnlyConfirmed && !pcoin->IsConfirmed())
1028 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1031 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1034 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1035 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1036 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1037 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1043 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1049 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1051 const CWalletTx* pcoin = &(*it).second;
1053 if (!pcoin->IsFinal())
1056 if(pcoin->GetDepthInMainChain() < nConf)
1059 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1060 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1061 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1066 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1067 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1069 vector<char> vfIncluded;
1071 vfBest.assign(vValue.size(), true);
1072 nBest = nTotalLower;
1074 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1076 vfIncluded.assign(vValue.size(), false);
1078 bool fReachedTarget = false;
1079 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1081 for (unsigned int i = 0; i < vValue.size(); i++)
1083 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1085 nTotal += vValue[i].first;
1086 vfIncluded[i] = true;
1087 if (nTotal >= nTargetValue)
1089 fReachedTarget = true;
1093 vfBest = vfIncluded;
1095 nTotal -= vValue[i].first;
1096 vfIncluded[i] = false;
1104 // ppcoin: total coins staked (non-spendable until maturity)
1105 int64 CWallet::GetStake() const
1109 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1111 const CWalletTx* pcoin = &(*it).second;
1112 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1113 nTotal += CWallet::GetCredit(*pcoin);
1118 int64 CWallet::GetNewMint() const
1122 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1124 const CWalletTx* pcoin = &(*it).second;
1125 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1126 nTotal += CWallet::GetCredit(*pcoin);
1131 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
1133 setCoinsRet.clear();
1136 // List of values less than target
1137 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1138 coinLowestLarger.first = std::numeric_limits<int64>::max();
1139 coinLowestLarger.second.first = NULL;
1140 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1141 int64 nTotalLower = 0;
1143 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1145 BOOST_FOREACH(COutput output, vCoins)
1147 const CWalletTx *pcoin = output.tx;
1149 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1154 // Follow the timestamp rules
1155 if (pcoin->nTime > nSpendTime)
1158 int64 n = pcoin->vout[i].nValue;
1160 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1162 if (n == nTargetValue)
1164 setCoinsRet.insert(coin.second);
1165 nValueRet += coin.first;
1168 else if (n < nTargetValue + CENT)
1170 vValue.push_back(coin);
1173 else if (n < coinLowestLarger.first)
1175 coinLowestLarger = coin;
1179 if (nTotalLower == nTargetValue)
1181 for (unsigned int i = 0; i < vValue.size(); ++i)
1183 setCoinsRet.insert(vValue[i].second);
1184 nValueRet += vValue[i].first;
1189 if (nTotalLower < nTargetValue)
1191 if (coinLowestLarger.second.first == NULL)
1193 setCoinsRet.insert(coinLowestLarger.second);
1194 nValueRet += coinLowestLarger.first;
1198 // Solve subset sum by stochastic approximation
1199 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1200 vector<char> vfBest;
1203 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1204 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1205 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1207 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1208 // or the next bigger coin is closer), return the bigger coin
1209 if (coinLowestLarger.second.first &&
1210 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1212 setCoinsRet.insert(coinLowestLarger.second);
1213 nValueRet += coinLowestLarger.first;
1216 for (unsigned int i = 0; i < vValue.size(); i++)
1219 setCoinsRet.insert(vValue[i].second);
1220 nValueRet += vValue[i].first;
1223 if (fDebug && GetBoolArg("-printpriority"))
1226 printf("SelectCoins() best subset: ");
1227 for (unsigned int i = 0; i < vValue.size(); i++)
1229 printf("%s ", FormatMoney(vValue[i].first).c_str());
1230 printf("total %s\n", FormatMoney(nBest).c_str());
1237 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1239 vector<COutput> vCoins;
1240 AvailableCoins(vCoins, true, coinControl);
1242 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1243 if (coinControl && coinControl->HasSelected())
1245 BOOST_FOREACH(const COutput& out, vCoins)
1247 nValueRet += out.tx->vout[out.i].nValue;
1248 setCoinsRet.insert(make_pair(out.tx, out.i));
1250 return (nValueRet >= nTargetValue);
1253 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1254 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1255 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1258 // Select some coins without random shuffle or best subset approximation
1259 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1261 vector<COutput> vCoins;
1262 AvailableCoinsMinConf(vCoins, nMinConf);
1264 setCoinsRet.clear();
1267 BOOST_FOREACH(COutput output, vCoins)
1269 const CWalletTx *pcoin = output.tx;
1272 // Stop if we've chosen enough inputs
1273 if (nValueRet >= nTargetValue)
1276 // Follow the timestamp rules
1277 if (pcoin->nTime > nSpendTime)
1280 int64 n = pcoin->vout[i].nValue;
1282 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1284 if (n >= nTargetValue)
1286 // If input value is greater or equal to target then simply insert
1287 // it into the current subset and exit
1288 setCoinsRet.insert(coin.second);
1289 nValueRet += coin.first;
1292 else if (n < nTargetValue + CENT)
1294 setCoinsRet.insert(coin.second);
1295 nValueRet += coin.first;
1302 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1305 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1311 if (vecSend.empty() || nValue < 0)
1314 wtxNew.BindWallet(this);
1317 LOCK2(cs_main, cs_wallet);
1319 nFeeRet = nTransactionFee;
1323 wtxNew.vout.clear();
1324 wtxNew.fFromMe = true;
1326 int64 nTotalValue = nValue + nFeeRet;
1327 double dPriority = 0;
1328 // vouts to the payees
1329 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1330 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1332 // Choose coins to use
1333 set<pair<const CWalletTx*,unsigned int> > setCoins;
1335 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1337 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1339 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1340 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1343 int64 nChange = nValueIn - nValue - nFeeRet;
1344 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1345 // or until nChange becomes zero
1346 // NOTE: this depends on the exact behaviour of GetMinFee
1347 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1349 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1350 nChange -= nMoveToFee;
1351 nFeeRet += nMoveToFee;
1354 // sub-cent change is moved to fee
1355 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1363 // Fill a vout to ourself
1364 // TODO: pass in scriptChange instead of reservekey so
1365 // change transaction isn't always pay-to-bitcoin-address
1366 CScript scriptChange;
1368 // coin control: send change to custom address
1369 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1370 scriptChange.SetDestination(coinControl->destChange);
1372 // no coin control: send change to newly generated address
1375 // Note: We use a new key here to keep it from being obvious which side is the change.
1376 // The drawback is that by not reusing a previous key, the change may be lost if a
1377 // backup is restored, if the backup doesn't have the new private key for the change.
1378 // If we reused the old key, it would be possible to add code to look for and
1379 // rediscover unknown transactions that were written with keys of ours to recover
1380 // post-backup change.
1382 // Reserve a new key pair from key pool
1383 CPubKey vchPubKey = reservekey.GetReservedKey();
1385 scriptChange.SetDestination(vchPubKey.GetID());
1388 // Insert change txn at random position:
1389 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1390 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1393 reservekey.ReturnKey();
1396 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1397 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1401 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1402 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1406 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1407 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1409 dPriority /= nBytes;
1411 // Check that enough fee is included
1412 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1413 bool fAllowFree = CTransaction::AllowFree(dPriority);
1414 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1415 if (nFeeRet < max(nPayFee, nMinFee))
1417 nFeeRet = max(nPayFee, nMinFee);
1421 // Fill vtxPrev by copying from previous transactions vtxPrev
1422 wtxNew.AddSupportingTransactions();
1423 wtxNew.fTimeReceivedIsTxTime = true;
1432 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1434 vector< pair<CScript, int64> > vecSend;
1435 vecSend.push_back(make_pair(scriptPubKey, nValue));
1436 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1439 // NovaCoin: get current stake weight
1440 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1442 // Choose coins to use
1443 int64 nBalance = GetBalance();
1444 int64 nReserveBalance = 0;
1446 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1448 error("GetStakeWeight : invalid reserve balance amount");
1452 if (nBalance <= nReserveBalance)
1455 vector<const CWalletTx*> vwtxPrev;
1456 set<pair<const CWalletTx*,unsigned int> > setCoins;
1459 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1462 if (setCoins.empty())
1465 CCoinsViewCache &view = *pcoinsTip;
1466 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1470 LOCK2(cs_main, cs_wallet);
1471 if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1475 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1476 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1478 // Weight is greater than zero
1479 if (nTimeWeight > 0)
1481 nWeight += bnCoinDayWeight.getuint64();
1484 // Weight is greater than zero, but the maximum value isn't reached yet
1485 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1487 nMinWeight += bnCoinDayWeight.getuint64();
1490 // Maximum weight was reached
1491 if (nTimeWeight == nStakeMaxAge)
1493 nMaxWeight += bnCoinDayWeight.getuint64();
1500 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1502 // The following combine threshold is important to security
1503 // Should not be adjusted if you don't understand the consequences
1504 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1505 CBlockIndex* pindexPrev = pindexBest;
1506 CBigNum bnTargetPerCoinDay;
1507 bnTargetPerCoinDay.SetCompact(nBits);
1512 // Mark coin stake transaction
1513 CScript scriptEmpty;
1514 scriptEmpty.clear();
1515 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1517 // Choose coins to use
1518 int64 nBalance = GetBalance();
1519 int64 nReserveBalance = 0;
1521 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1522 return error("CreateCoinStake : invalid reserve balance amount");
1524 if (nBalance <= nReserveBalance)
1527 vector<const CWalletTx*> vwtxPrev;
1528 set<pair<const CWalletTx*,unsigned int> > setCoins;
1531 // Select coins with suitable depth
1532 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1535 if (setCoins.empty())
1539 CScript scriptPubKeyKernel;
1541 CCoinsViewCache &view = *pcoinsTip;
1542 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1546 LOCK2(cs_main, cs_wallet);
1547 if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1551 static int nMaxStakeSearchInterval = 60;
1552 if (coins.nBlockTime + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1553 continue; // only count coins meeting min age requirement
1555 // Read block header
1557 unsigned int nTxPos = 0;
1559 LOCK2(cs_main, cs_wallet);
1560 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
1562 if (!block.ReadFromDisk(pindex))
1565 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1566 if (tx.GetHash() == pcoin.first->GetHash()) {
1569 nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
1571 nTxPos += GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
1575 bool fFatal = false;
1576 bool fKernelFound = false;
1577 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown && pindexPrev == pindexBest; n++)
1579 // Search backward in time from the given txNew timestamp
1580 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1581 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1582 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1583 if (CheckStakeKernelHash(nBits, block, nTxPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake, fFatal, true))
1586 if (fDebug && GetBoolArg("-printcoinstake"))
1587 printf("CreateCoinStake : kernel found\n");
1588 vector<valtype> vSolutions;
1589 txnouttype whichType;
1590 CScript scriptPubKeyOut;
1591 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1592 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1594 if (fDebug && GetBoolArg("-printcoinstake"))
1595 printf("CreateCoinStake : failed to parse kernel\n");
1598 if (fDebug && GetBoolArg("-printcoinstake"))
1599 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1600 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1602 if (fDebug && GetBoolArg("-printcoinstake"))
1603 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1604 break; // only support pay to public key and pay to address
1606 if (whichType == TX_PUBKEYHASH) // pay to address type
1608 // convert to pay to public key type
1609 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1611 if (fDebug && GetBoolArg("-printcoinstake"))
1612 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1613 break; // unable to find corresponding public key
1615 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1617 if (whichType == TX_PUBKEY)
1619 valtype& vchPubKey = vSolutions[0];
1620 if (!keystore.GetKey(Hash160(vchPubKey), key))
1622 if (fDebug && GetBoolArg("-printcoinstake"))
1623 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1624 break; // unable to find corresponding public key
1627 if (key.GetPubKey() != vchPubKey)
1629 if (fDebug && GetBoolArg("-printcoinstake"))
1630 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1631 break; // keys mismatch
1634 scriptPubKeyOut = scriptPubKeyKernel;
1638 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1639 nCredit += pcoin.first->vout[pcoin.second].nValue;
1640 vwtxPrev.push_back(pcoin.first);
1641 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1643 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1644 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1645 if (fDebug && GetBoolArg("-printcoinstake"))
1646 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1647 fKernelFound = true;
1652 if (fKernelFound || fShutdown)
1653 break; // if kernel is found stop searching
1656 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1659 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1661 // Attempt to add more inputs
1662 // Only add coins of the same key/address as kernel
1663 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1664 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1666 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1668 // Stop adding more inputs if already too many inputs
1669 if (txNew.vin.size() >= 100)
1671 // Stop adding more inputs if value is already pretty significant
1672 if (nCredit > nCombineThreshold)
1674 // Stop adding inputs if reached reserve limit
1675 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1677 // Do not add additional significant input
1678 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1680 // Do not add input that is still too young
1681 if (nTimeWeight < nStakeMaxAge)
1684 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1685 nCredit += pcoin.first->vout[pcoin.second].nValue;
1686 vwtxPrev.push_back(pcoin.first);
1690 // Calculate coin age reward
1694 if (!txNew.GetCoinAge(nCoinAge))
1695 return error("CreateCoinStake : failed to calculate coin age");
1696 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1702 // Set output amount
1703 if (txNew.vout.size() == 3)
1705 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1706 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1709 txNew.vout[1].nValue = nCredit - nMinFee;
1713 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1715 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1716 return error("CreateCoinStake : failed to sign coinstake");
1720 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1721 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1722 return error("CreateCoinStake : exceeded coinstake size limit");
1724 // Check enough fee is paid
1725 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1727 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1728 continue; // try signing again
1732 if (fDebug && GetBoolArg("-printfee"))
1733 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1738 // Successfully generated coinstake
1743 // Call after CreateTransaction unless you want to abort
1744 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1747 LOCK2(cs_main, cs_wallet);
1748 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1750 // This is only to keep the database open to defeat the auto-flush for the
1751 // duration of this scope. This is the only place where this optimization
1752 // maybe makes sense; please don't do it anywhere else.
1753 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1755 // Take key pair from key pool so it won't be used again
1756 reservekey.KeepKey();
1758 // Add tx to wallet, because if it has change it's also ours,
1759 // otherwise just for transaction history.
1760 AddToWallet(wtxNew);
1762 // Mark old coins as spent
1763 set<CWalletTx*> setCoins;
1764 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1766 CWalletTx &coin = mapWallet[txin.prevout.hash];
1767 coin.BindWallet(this);
1768 coin.MarkSpent(txin.prevout.n);
1770 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1777 // Track how many getdata requests our transaction gets
1778 mapRequestCount[wtxNew.GetHash()] = 0;
1781 if (!wtxNew.AcceptToMemoryPool())
1783 // This must not fail. The transaction has already been signed and recorded.
1784 printf("CommitTransaction() : Error: Transaction not valid");
1787 wtxNew.RelayWalletTransaction();
1795 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1797 CReserveKey reservekey(this);
1802 string strError = _("Error: Wallet locked, unable to create transaction ");
1803 printf("SendMoney() : %s", strError.c_str());
1806 if (fWalletUnlockMintOnly)
1808 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1809 printf("SendMoney() : %s", strError.c_str());
1812 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1815 if (nValue + nFeeRequired > GetBalance())
1816 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());
1818 strError = _("Error: Transaction creation failed ");
1819 printf("SendMoney() : %s", strError.c_str());
1823 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1826 if (!CommitTransaction(wtxNew, reservekey))
1827 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.");
1834 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1838 return _("Invalid amount");
1839 if (nValue + nTransactionFee > GetBalance())
1840 return _("Insufficient funds");
1842 // Parse Bitcoin address
1843 CScript scriptPubKey;
1844 scriptPubKey.SetDestination(address);
1846 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1852 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1856 fFirstRunRet = false;
1857 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1858 if (nLoadWalletRet == DB_NEED_REWRITE)
1860 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1863 // Note: can't top-up keypool here, because wallet is locked.
1864 // User will be prompted to unlock wallet the next operation
1865 // the requires a new key.
1869 if (nLoadWalletRet != DB_LOAD_OK)
1870 return nLoadWalletRet;
1871 fFirstRunRet = !vchDefaultKey.IsValid();
1873 NewThread(ThreadFlushWalletDB, &strWalletFile);
1878 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1880 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1881 mapAddressBook[address] = strName;
1882 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1885 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1888 bool CWallet::DelAddressBookName(const CTxDestination& address)
1890 mapAddressBook.erase(address);
1891 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1894 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1898 void CWallet::PrintWallet(const CBlock& block)
1902 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1904 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1905 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1907 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1909 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1910 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1917 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1921 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1922 if (mi != mapWallet.end())
1931 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1935 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1938 vchDefaultKey = vchPubKey;
1942 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1944 if (!pwallet->fFileBacked)
1946 strWalletFileOut = pwallet->strWalletFile;
1951 // Mark old keypool keys as used,
1952 // and generate all new keys
1954 bool CWallet::NewKeyPool()
1958 CWalletDB walletdb(strWalletFile);
1959 BOOST_FOREACH(int64 nIndex, setKeyPool)
1960 walletdb.ErasePool(nIndex);
1966 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1967 for (int i = 0; i < nKeys; i++)
1970 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1971 setKeyPool.insert(nIndex);
1973 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1978 bool CWallet::TopUpKeyPool(unsigned int nSize)
1986 CWalletDB walletdb(strWalletFile);
1989 unsigned int nTargetSize;
1991 nTargetSize = nSize;
1993 nTargetSize = max(GetArg("-keypool", 100), 0LL);
1995 while (setKeyPool.size() < (nTargetSize + 1))
1998 if (!setKeyPool.empty())
1999 nEnd = *(--setKeyPool.end()) + 1;
2000 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2001 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2002 setKeyPool.insert(nEnd);
2003 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2009 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2012 keypool.vchPubKey = CPubKey();
2019 // Get the oldest key
2020 if(setKeyPool.empty())
2023 CWalletDB walletdb(strWalletFile);
2025 nIndex = *(setKeyPool.begin());
2026 setKeyPool.erase(setKeyPool.begin());
2027 if (!walletdb.ReadPool(nIndex, keypool))
2028 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2029 if (!HaveKey(keypool.vchPubKey.GetID()))
2030 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2031 assert(keypool.vchPubKey.IsValid());
2032 if (fDebug && GetBoolArg("-printkeypool"))
2033 printf("keypool reserve %"PRI64d"\n", nIndex);
2037 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2040 LOCK2(cs_main, cs_wallet);
2041 CWalletDB walletdb(strWalletFile);
2043 int64 nIndex = 1 + *(--setKeyPool.end());
2044 if (!walletdb.WritePool(nIndex, keypool))
2045 throw runtime_error("AddReserveKey() : writing added key failed");
2046 setKeyPool.insert(nIndex);
2052 void CWallet::KeepKey(int64 nIndex)
2054 // Remove from key pool
2057 CWalletDB walletdb(strWalletFile);
2058 walletdb.ErasePool(nIndex);
2061 printf("keypool keep %"PRI64d"\n", nIndex);
2064 void CWallet::ReturnKey(int64 nIndex)
2066 // Return to key pool
2069 setKeyPool.insert(nIndex);
2072 printf("keypool return %"PRI64d"\n", nIndex);
2075 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2081 ReserveKeyFromKeyPool(nIndex, keypool);
2084 if (fAllowReuse && vchDefaultKey.IsValid())
2086 result = vchDefaultKey;
2089 if (IsLocked()) return false;
2090 result = GenerateNewKey();
2094 result = keypool.vchPubKey;
2099 int64 CWallet::GetOldestKeyPoolTime()
2103 ReserveKeyFromKeyPool(nIndex, keypool);
2107 return keypool.nTime;
2110 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2112 map<CTxDestination, int64> balances;
2116 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2118 CWalletTx *pcoin = &walletEntry.second;
2120 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
2123 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2126 int nDepth = pcoin->GetDepthInMainChain();
2127 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2130 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2132 CTxDestination addr;
2133 if (!IsMine(pcoin->vout[i]))
2135 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2138 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2140 if (!balances.count(addr))
2142 balances[addr] += n;
2150 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2152 set< set<CTxDestination> > groupings;
2153 set<CTxDestination> grouping;
2155 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2157 CWalletTx *pcoin = &walletEntry.second;
2159 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2161 // group all input addresses with each other
2162 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2164 CTxDestination address;
2165 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2167 grouping.insert(address);
2170 // group change with input addresses
2171 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2172 if (IsChange(txout))
2174 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2175 CTxDestination txoutAddr;
2176 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2178 grouping.insert(txoutAddr);
2180 groupings.insert(grouping);
2184 // group lone addrs by themselves
2185 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2186 if (IsMine(pcoin->vout[i]))
2188 CTxDestination address;
2189 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2191 grouping.insert(address);
2192 groupings.insert(grouping);
2197 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2198 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2199 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2201 // make a set of all the groups hit by this new group
2202 set< set<CTxDestination>* > hits;
2203 map< CTxDestination, set<CTxDestination>* >::iterator it;
2204 BOOST_FOREACH(CTxDestination address, grouping)
2205 if ((it = setmap.find(address)) != setmap.end())
2206 hits.insert((*it).second);
2208 // merge all hit groups into a new single group and delete old groups
2209 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2210 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2212 merged->insert(hit->begin(), hit->end());
2213 uniqueGroupings.erase(hit);
2216 uniqueGroupings.insert(merged);
2219 BOOST_FOREACH(CTxDestination element, *merged)
2220 setmap[element] = merged;
2223 set< set<CTxDestination> > ret;
2224 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2226 ret.insert(*uniqueGrouping);
2227 delete uniqueGrouping;
2233 // 1. check 'spent' consistency between wallet and coins database
2234 // 2. fix wallet spent state according to coins database
2235 // 3. remove orphaned coinstakes and coinbases from wallet
2236 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2239 nBalanceInQuestion = 0;
2242 vector<CWalletTx*> vCoins;
2243 vCoins.reserve(mapWallet.size());
2244 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2245 vCoins.push_back(&(*it).second);
2247 CCoinsViewCache &view = *pcoinsTip;
2248 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2250 uint256 hash = pcoin->GetHash();
2251 if(!view.HaveCoins(hash))
2254 // Find the corresponding transaction index
2255 CCoins &coins = view.GetCoins(hash);
2257 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2259 bool fUpdated = false;
2260 if (IsMine(pcoin->vout[n]))
2262 if (pcoin->IsSpent(n) && coins.IsAvailable(n))
2264 printf("FixSpentCoins found lost coin %snvc %s[%d], %s\n",
2265 FormatMoney(pcoin->vout[n].nValue).c_str(), hash.ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2267 nBalanceInQuestion += pcoin->vout[n].nValue;
2271 pcoin->MarkUnspent(n);
2272 pcoin->WriteToDisk();
2275 else if (!pcoin->IsSpent(n) && !coins.IsAvailable(n))
2277 printf("FixSpentCoins found spent coin %snvc %s[%d], %s\n",
2278 FormatMoney(pcoin->vout[n].nValue).c_str(), hash.ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2280 nBalanceInQuestion += pcoin->vout[n].nValue;
2284 pcoin->MarkSpent(n);
2285 pcoin->WriteToDisk();
2290 NotifyTransactionChanged(this, hash, CT_UPDATED);
2294 if((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2298 EraseFromWallet(hash);
2299 NotifyTransactionChanged(this, hash, CT_DELETED);
2302 printf("FixSpentCoins %s orphaned generation tx %s\n", fCheckOnly ? "found" : "removed", hash.ToString().c_str());
2307 // ppcoin: disable transaction (only for coinstake)
2308 void CWallet::DisableTransaction(const CTransaction &tx)
2310 if (!tx.IsCoinStake() || !IsFromMe(tx))
2311 return; // only disconnecting coinstake requires marking input unspent
2314 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2316 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2317 if (mi != mapWallet.end())
2319 CWalletTx& prev = (*mi).second;
2320 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2322 prev.MarkUnspent(txin.prevout.n);
2329 CPubKey CReserveKey::GetReservedKey()
2334 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2336 vchPubKey = keypool.vchPubKey;
2339 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2340 vchPubKey = pwallet->vchDefaultKey;
2343 assert(vchPubKey.IsValid());
2347 void CReserveKey::KeepKey()
2350 pwallet->KeepKey(nIndex);
2352 vchPubKey = CPubKey();
2355 void CReserveKey::ReturnKey()
2358 pwallet->ReturnKey(nIndex);
2360 vchPubKey = CPubKey();
2363 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2367 CWalletDB walletdb(strWalletFile);
2369 LOCK2(cs_main, cs_wallet);
2370 BOOST_FOREACH(const int64& id, setKeyPool)
2373 if (!walletdb.ReadPool(id, keypool))
2374 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2375 assert(keypool.vchPubKey.IsValid());
2376 CKeyID keyID = keypool.vchPubKey.GetID();
2377 if (!HaveKey(keyID))
2378 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2379 setAddress.insert(keyID);
2383 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2387 // Only notify UI if this transaction is in this wallet
2388 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2389 if (mi != mapWallet.end())
2390 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2394 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2395 mapKeyBirth.clear();
2397 // get birth times for keys with metadata
2398 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2399 if (it->second.nCreateTime)
2400 mapKeyBirth[it->first] = it->second.nCreateTime;
2402 // map in which we'll infer heights of other keys
2403 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2404 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2405 std::set<CKeyID> setKeys;
2407 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2408 if (mapKeyBirth.count(keyid) == 0)
2409 mapKeyFirstBlock[keyid] = pindexMax;
2413 // if there are no such keys, we're done
2414 if (mapKeyFirstBlock.empty())
2417 // find first block that affects those keys, if there are any left
2418 std::vector<CKeyID> vAffected;
2419 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2420 // iterate over all wallet transactions...
2421 const CWalletTx &wtx = (*it).second;
2422 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2423 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2424 // ... which are already in a block
2425 int nHeight = blit->second->nHeight;
2426 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2427 // iterate over all their outputs
2428 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2429 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2430 // ... and all their affected keys
2431 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2432 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2433 rit->second = blit->second;
2440 // Extract block timestamps for those keys
2441 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2442 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off