1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "checkpoints.h"
11 #include "ui_interface.h"
16 //////////////////////////////////////////////////////////////////////////////
21 std::vector<unsigned char> CWallet::GenerateNewKey()
23 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
27 key.MakeNewKey(fCompressed);
29 // Compressed public keys were introduced in version 0.6.0
31 SetMinVersion(FEATURE_COMPRPUBKEY);
34 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
35 return key.GetPubKey();
38 bool CWallet::AddKey(const CKey& key)
40 if (!CCryptoKeyStore::AddKey(key))
45 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
49 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
51 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
57 if (pwalletdbEncryption)
58 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
60 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
65 bool CWallet::AddCScript(const CScript& redeemScript)
67 if (!CCryptoKeyStore::AddCScript(redeemScript))
71 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
74 // ppcoin: optional setting to create coinstake only when unlocked;
75 // serves to disable the trivial sendmoney when OS account compromised
76 bool fWalletUnlockStakeOnly = false;
78 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
84 CKeyingMaterial vMasterKey;
88 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
90 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
92 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
94 if (CCryptoKeyStore::Unlock(vMasterKey))
101 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
103 bool fWasLocked = IsLocked();
110 CKeyingMaterial vMasterKey;
111 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
113 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
115 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
117 if (CCryptoKeyStore::Unlock(vMasterKey))
119 int64 nStartTime = GetTimeMillis();
120 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
121 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
123 nStartTime = GetTimeMillis();
124 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
125 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
127 if (pMasterKey.second.nDeriveIterations < 25000)
128 pMasterKey.second.nDeriveIterations = 25000;
130 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
132 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
134 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
136 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
147 void CWallet::SetBestChain(const CBlockLocator& loc)
149 CWalletDB walletdb(strWalletFile);
150 walletdb.WriteBestBlock(loc);
153 // This class implements an addrIncoming entry that causes pre-0.4
154 // clients to crash on startup if reading a private-key-encrypted wallet.
155 class CCorruptAddress
160 if (nType & SER_DISK)
165 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
167 if (nWalletVersion >= nVersion)
170 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
171 if (fExplicit && nVersion > nWalletMaxVersion)
172 nVersion = FEATURE_LATEST;
174 nWalletVersion = nVersion;
176 if (nVersion > nWalletMaxVersion)
177 nWalletMaxVersion = nVersion;
181 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
182 if (nWalletVersion >= 40000)
184 // Versions prior to 0.4.0 did not support the "minversion" record.
185 // Use a CCorruptAddress to make them crash instead.
186 CCorruptAddress corruptAddress;
187 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
189 if (nWalletVersion > 40000)
190 pwalletdb->WriteMinVersion(nWalletVersion);
198 bool CWallet::SetMaxVersion(int nVersion)
200 // cannot downgrade below current version
201 if (nWalletVersion > nVersion)
204 nWalletMaxVersion = nVersion;
209 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
214 CKeyingMaterial vMasterKey;
215 RandAddSeedPerfmon();
217 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
218 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
220 CMasterKey kMasterKey;
222 RandAddSeedPerfmon();
223 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
224 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
227 int64 nStartTime = GetTimeMillis();
228 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
229 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
231 nStartTime = GetTimeMillis();
232 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
233 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
235 if (kMasterKey.nDeriveIterations < 25000)
236 kMasterKey.nDeriveIterations = 25000;
238 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
240 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
242 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
247 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
250 pwalletdbEncryption = new CWalletDB(strWalletFile);
251 if (!pwalletdbEncryption->TxnBegin())
253 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
256 if (!EncryptKeys(vMasterKey))
259 pwalletdbEncryption->TxnAbort();
260 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.
263 // Encryption was introduced in version 0.4.0
264 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
268 if (!pwalletdbEncryption->TxnCommit())
269 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.
271 delete pwalletdbEncryption;
272 pwalletdbEncryption = NULL;
276 Unlock(strWalletPassphrase);
280 // Need to completely rewrite the wallet file; if we don't, bdb might keep
281 // bits of the unencrypted private key in slack space in the database file.
282 CDB::Rewrite(strWalletFile);
288 void CWallet::WalletUpdateSpent(const CTransaction &tx)
290 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
291 // Update the wallet spent flag if it doesn't know due to wallet.dat being
292 // restored from backup or the user making copies of wallet.dat.
295 BOOST_FOREACH(const CTxIn& txin, tx.vin)
297 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
298 if (mi != mapWallet.end())
300 CWalletTx& wtx = (*mi).second;
301 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
303 printf("WalletUpdateSpent found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
304 wtx.MarkSpent(txin.prevout.n);
306 vWalletUpdated.push_back(txin.prevout.hash);
313 void CWallet::MarkDirty()
317 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
318 item.second.MarkDirty();
322 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
324 uint256 hash = wtxIn.GetHash();
327 // Inserts only if not already there, returns tx inserted or tx found
328 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
329 CWalletTx& wtx = (*ret.first).second;
330 wtx.BindWallet(this);
331 bool fInsertedNew = ret.second;
333 wtx.nTimeReceived = GetAdjustedTime();
335 bool fUpdated = false;
339 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
341 wtx.hashBlock = wtxIn.hashBlock;
344 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
346 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
347 wtx.nIndex = wtxIn.nIndex;
350 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
352 wtx.fFromMe = wtxIn.fFromMe;
355 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
359 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
362 if (fInsertedNew || fUpdated)
363 if (!wtx.WriteToDisk())
366 // If default receiving address gets used, replace it with a new one
367 CScript scriptDefaultKey;
368 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
369 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
371 if (txout.scriptPubKey == scriptDefaultKey)
373 std::vector<unsigned char> newDefaultKey;
374 if (GetKeyFromPool(newDefaultKey, false))
376 SetDefaultKey(newDefaultKey);
377 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
383 vWalletUpdated.push_back(hash);
385 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
386 WalletUpdateSpent(wtx);
394 // Add a transaction to the wallet, or update it.
395 // pblock is optional, but should be provided if the transaction is known to be in a block.
396 // If fUpdate is true, existing transactions will be updated.
397 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
399 uint256 hash = tx.GetHash();
402 bool fExisted = mapWallet.count(hash);
403 if (fExisted && !fUpdate) return false;
404 if (fExisted || IsMine(tx) || IsFromMe(tx))
406 CWalletTx wtx(this,tx);
407 // Get merkle branch if transaction was found in a block
409 wtx.SetMerkleBranch(pblock);
410 return AddToWallet(wtx);
413 WalletUpdateSpent(tx);
418 bool CWallet::EraseFromWallet(uint256 hash)
424 if (mapWallet.erase(hash))
425 CWalletDB(strWalletFile).EraseTx(hash);
431 bool CWallet::IsMine(const CTxIn &txin) const
435 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
436 if (mi != mapWallet.end())
438 const CWalletTx& prev = (*mi).second;
439 if (txin.prevout.n < prev.vout.size())
440 if (IsMine(prev.vout[txin.prevout.n]))
447 int64 CWallet::GetDebit(const CTxIn &txin) const
451 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
452 if (mi != mapWallet.end())
454 const CWalletTx& prev = (*mi).second;
455 if (txin.prevout.n < prev.vout.size())
456 if (IsMine(prev.vout[txin.prevout.n]))
457 return prev.vout[txin.prevout.n].nValue;
463 bool CWallet::IsChange(const CTxOut& txout) const
465 CBitcoinAddress address;
467 // TODO: fix handling of 'change' outputs. The assumption is that any
468 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
469 // is change. That assumption is likely to break when we implement multisignature
470 // wallets that return change back into a multi-signature-protected address;
471 // a better way of identifying which outputs are 'the send' and which are
472 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
473 // which output, if any, was change).
474 if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
477 if (!mapAddressBook.count(address))
483 int64 CWalletTx::GetTxTime() const
485 return nTimeReceived;
488 int CWalletTx::GetRequestCount() const
490 // Returns -1 if it wasn't being tracked
493 LOCK(pwallet->cs_wallet);
494 if (IsCoinBase() || IsCoinStake())
499 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
500 if (mi != pwallet->mapRequestCount.end())
501 nRequests = (*mi).second;
506 // Did anyone request this transaction?
507 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
508 if (mi != pwallet->mapRequestCount.end())
510 nRequests = (*mi).second;
512 // How about the block it's in?
513 if (nRequests == 0 && hashBlock != 0)
515 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
516 if (mi != pwallet->mapRequestCount.end())
517 nRequests = (*mi).second;
519 nRequests = 1; // If it's in someone else's block it must have got out
527 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
528 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
530 nGeneratedImmature = nGeneratedMature = nFee = 0;
531 listReceived.clear();
533 strSentAccount = strFromAccount;
535 if (IsCoinBase() || IsCoinStake())
537 if (GetBlocksToMaturity() > 0)
538 nGeneratedImmature = pwallet->GetCredit(*this);
540 nGeneratedMature = GetCredit();
545 int64 nDebit = GetDebit();
546 if (nDebit > 0) // debit>0 means we signed/sent this transaction
548 int64 nValueOut = GetValueOut();
549 nFee = nDebit - nValueOut;
553 BOOST_FOREACH(const CTxOut& txout, vout)
555 CBitcoinAddress address;
556 vector<unsigned char> vchPubKey;
557 if (!ExtractAddress(txout.scriptPubKey, address))
559 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
560 this->GetHash().ToString().c_str());
561 address = " unknown ";
564 // Don't report 'change' txouts
565 if (nDebit > 0 && pwallet->IsChange(txout))
569 listSent.push_back(make_pair(address, txout.nValue));
571 if (pwallet->IsMine(txout))
572 listReceived.push_back(make_pair(address, txout.nValue));
577 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
578 int64& nSent, int64& nFee) const
580 nGenerated = nReceived = nSent = nFee = 0;
582 int64 allGeneratedImmature, allGeneratedMature, allFee;
583 allGeneratedImmature = allGeneratedMature = allFee = 0;
584 string strSentAccount;
585 list<pair<CBitcoinAddress, int64> > listReceived;
586 list<pair<CBitcoinAddress, int64> > listSent;
587 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
589 if (strAccount == "")
590 nGenerated = allGeneratedMature;
591 if (strAccount == strSentAccount)
593 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
598 LOCK(pwallet->cs_wallet);
599 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
601 if (pwallet->mapAddressBook.count(r.first))
603 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
604 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
605 nReceived += r.second;
607 else if (strAccount.empty())
609 nReceived += r.second;
615 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
619 const int COPY_DEPTH = 3;
620 if (SetMerkleBranch() < COPY_DEPTH)
622 vector<uint256> vWorkQueue;
623 BOOST_FOREACH(const CTxIn& txin, vin)
624 vWorkQueue.push_back(txin.prevout.hash);
626 // This critsect is OK because txdb is already open
628 LOCK(pwallet->cs_wallet);
629 map<uint256, const CMerkleTx*> mapWalletPrev;
630 set<uint256> setAlreadyDone;
631 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
633 uint256 hash = vWorkQueue[i];
634 if (setAlreadyDone.count(hash))
636 setAlreadyDone.insert(hash);
639 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
640 if (mi != pwallet->mapWallet.end())
643 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
644 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
646 else if (mapWalletPrev.count(hash))
648 tx = *mapWalletPrev[hash];
650 else if (!fClient && txdb.ReadDiskTx(hash, tx))
656 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
660 int nDepth = tx.SetMerkleBranch();
661 vtxPrev.push_back(tx);
663 if (nDepth < COPY_DEPTH)
665 BOOST_FOREACH(const CTxIn& txin, tx.vin)
666 vWorkQueue.push_back(txin.prevout.hash);
672 reverse(vtxPrev.begin(), vtxPrev.end());
675 bool CWalletTx::WriteToDisk()
677 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
680 // Scan the block chain (starting in pindexStart) for transactions
681 // from or to us. If fUpdate is true, found transactions that already
682 // exist in the wallet will be updated.
683 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
687 CBlockIndex* pindex = pindexStart;
693 block.ReadFromDisk(pindex, true);
694 BOOST_FOREACH(CTransaction& tx, block.vtx)
696 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
699 pindex = pindex->pnext;
705 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
708 tx.ReadFromDisk(COutPoint(hashTx, 0));
709 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
714 void CWallet::ReacceptWalletTransactions()
722 vector<CDiskTxPos> vMissingTx;
723 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
725 CWalletTx& wtx = item.second;
726 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
730 bool fUpdated = false;
731 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
733 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
734 if (txindex.vSpent.size() != wtx.vout.size())
736 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
739 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
743 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
747 vMissingTx.push_back(txindex.vSpent[i]);
752 printf("ReacceptWalletTransactions found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
759 // Reaccept any txes of ours that aren't already in a block
760 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
761 wtx.AcceptWalletTransaction(txdb, false);
764 if (!vMissingTx.empty())
766 // TODO: optimize this to scan just part of the block chain?
767 if (ScanForWalletTransactions(pindexGenesisBlock))
768 fRepeat = true; // Found missing transactions: re-do Reaccept.
773 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
775 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
777 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
779 uint256 hash = tx.GetHash();
780 if (!txdb.ContainsTx(hash))
781 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
784 if (!(IsCoinBase() || IsCoinStake()))
786 uint256 hash = GetHash();
787 if (!txdb.ContainsTx(hash))
789 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
790 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
795 void CWalletTx::RelayWalletTransaction()
798 RelayWalletTransaction(txdb);
801 void CWallet::ResendWalletTransactions()
803 // Do this infrequently and randomly to avoid giving away
804 // that these are our transactions.
805 static int64 nNextTime;
806 if (GetTime() < nNextTime)
808 bool fFirst = (nNextTime == 0);
809 nNextTime = GetTime() + GetRand(30 * 60);
813 // Only do it if there's been a new block since last time
814 static int64 nLastTime;
815 if (nTimeBestReceived < nLastTime)
817 nLastTime = GetTime();
819 // Rebroadcast any of our txes that aren't in a block yet
820 printf("ResendWalletTransactions()\n");
824 // Sort them in chronological order
825 multimap<unsigned int, CWalletTx*> mapSorted;
826 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
828 CWalletTx& wtx = item.second;
829 // Don't rebroadcast until it's had plenty of time that
830 // it should have gotten in already by now.
831 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
832 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
834 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
836 CWalletTx& wtx = *item.second;
837 wtx.RelayWalletTransaction(txdb);
847 //////////////////////////////////////////////////////////////////////////////
853 int64 CWallet::GetBalance() const
858 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
860 const CWalletTx* pcoin = &(*it).second;
861 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
863 nTotal += pcoin->GetAvailableCredit();
870 int64 CWallet::GetUnconfirmedBalance() const
875 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
877 const CWalletTx* pcoin = &(*it).second;
878 if (pcoin->IsFinal() && pcoin->IsConfirmed())
880 nTotal += pcoin->GetAvailableCredit();
886 // ppcoin: total coins staked (non-spendable until maturity)
887 int64 CWallet::GetStake() const
891 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
893 const CWalletTx* pcoin = &(*it).second;
894 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
895 nTotal += CWallet::GetCredit(*pcoin);
900 int64 CWallet::GetNewMint() const
904 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
906 const CWalletTx* pcoin = &(*it).second;
907 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
908 nTotal += CWallet::GetCredit(*pcoin);
914 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
919 // List of values less than target
920 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
921 coinLowestLarger.first = std::numeric_limits<int64>::max();
922 coinLowestLarger.second.first = NULL;
923 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
924 int64 nTotalLower = 0;
928 vector<const CWalletTx*> vCoins;
929 vCoins.reserve(mapWallet.size());
930 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
931 vCoins.push_back(&(*it).second);
932 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
934 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
936 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
939 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
942 int nDepth = pcoin->GetDepthInMainChain();
943 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
946 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
948 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
951 if (pcoin->nTime > nSpendTime)
952 continue; // ppcoin: timestamp must not exceed spend time
954 int64 n = pcoin->vout[i].nValue;
959 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
961 if (n == nTargetValue)
963 setCoinsRet.insert(coin.second);
964 nValueRet += coin.first;
967 else if (n < nTargetValue + CENT)
969 vValue.push_back(coin);
972 else if (n < coinLowestLarger.first)
974 coinLowestLarger = coin;
980 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
982 for (unsigned int i = 0; i < vValue.size(); ++i)
984 setCoinsRet.insert(vValue[i].second);
985 nValueRet += vValue[i].first;
990 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
992 if (coinLowestLarger.second.first == NULL)
994 setCoinsRet.insert(coinLowestLarger.second);
995 nValueRet += coinLowestLarger.first;
999 if (nTotalLower >= nTargetValue + CENT)
1000 nTargetValue += CENT;
1002 // Solve subset sum by stochastic approximation
1003 sort(vValue.rbegin(), vValue.rend());
1004 vector<char> vfIncluded;
1005 vector<char> vfBest(vValue.size(), true);
1006 int64 nBest = nTotalLower;
1008 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
1010 vfIncluded.assign(vValue.size(), false);
1012 bool fReachedTarget = false;
1013 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1015 for (unsigned int i = 0; i < vValue.size(); i++)
1017 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1019 nTotal += vValue[i].first;
1020 vfIncluded[i] = true;
1021 if (nTotal >= nTargetValue)
1023 fReachedTarget = true;
1027 vfBest = vfIncluded;
1029 nTotal -= vValue[i].first;
1030 vfIncluded[i] = false;
1037 // If the next larger is still closer, return it
1038 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
1040 setCoinsRet.insert(coinLowestLarger.second);
1041 nValueRet += coinLowestLarger.first;
1044 for (unsigned int i = 0; i < vValue.size(); i++)
1047 setCoinsRet.insert(vValue[i].second);
1048 nValueRet += vValue[i].first;
1052 if (fDebug && GetBoolArg("-printselectcoin"))
1054 printf("SelectCoins() best subset: ");
1055 for (unsigned int i = 0; i < vValue.size(); i++)
1057 printf("%s ", FormatMoney(vValue[i].first).c_str());
1058 printf("total %s\n", FormatMoney(nBest).c_str());
1065 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1067 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
1068 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
1069 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
1075 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1078 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1084 if (vecSend.empty() || nValue < 0)
1087 wtxNew.BindWallet(this);
1090 LOCK2(cs_main, cs_wallet);
1091 // txdb must be opened before the mapWallet lock
1094 nFeeRet = nTransactionFee;
1098 wtxNew.vout.clear();
1099 wtxNew.fFromMe = true;
1101 int64 nTotalValue = nValue + nFeeRet;
1102 double dPriority = 0;
1103 // vouts to the payees
1104 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1105 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1107 // Choose coins to use
1108 set<pair<const CWalletTx*,unsigned int> > setCoins;
1110 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1112 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1114 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1115 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1118 int64 nChange = nValueIn - nValue - nFeeRet;
1119 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1120 // or until nChange becomes zero
1121 // NOTE: this depends on the exact behaviour of GetMinFee
1122 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1124 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1125 nChange -= nMoveToFee;
1126 nFeeRet += nMoveToFee;
1131 // Note: We use a new key here to keep it from being obvious which side is the change.
1132 // The drawback is that by not reusing a previous key, the change may be lost if a
1133 // backup is restored, if the backup doesn't have the new private key for the change.
1134 // If we reused the old key, it would be possible to add code to look for and
1135 // rediscover unknown transactions that were written with keys of ours to recover
1136 // post-backup change.
1138 // Reserve a new key pair from key pool
1139 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1140 // assert(mapKeys.count(vchPubKey));
1142 // Fill a vout to ourself
1143 // TODO: pass in scriptChange instead of reservekey so
1144 // change transaction isn't always pay-to-bitcoin-address
1145 CScript scriptChange;
1146 scriptChange.SetBitcoinAddress(vchPubKey);
1148 // Insert change txn at random position:
1149 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1150 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1153 reservekey.ReturnKey();
1156 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1157 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1161 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1162 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1166 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1167 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1169 dPriority /= nBytes;
1171 // Check that enough fee is included
1172 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1173 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1174 if (nFeeRet < max(nPayFee, nMinFee))
1176 nFeeRet = max(nPayFee, nMinFee);
1180 // Fill vtxPrev by copying from previous transactions vtxPrev
1181 wtxNew.AddSupportingTransactions(txdb);
1182 wtxNew.fTimeReceivedIsTxTime = true;
1191 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1193 vector< pair<CScript, int64> > vecSend;
1194 vecSend.push_back(make_pair(scriptPubKey, nValue));
1195 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1198 // ppcoin: create coin stake transaction
1199 bool CWallet::CreateCoinStake(unsigned int nBits, CTransaction& txNew)
1201 CBigNum bnTargetPerCoinDay;
1202 bnTargetPerCoinDay.SetCompact(nBits);
1204 LOCK2(cs_main, cs_wallet);
1207 // Mark coin stake transaction
1208 CScript scriptEmpty;
1209 scriptEmpty.clear();
1210 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1211 // Choose coins to use
1212 int64 nBalance = GetBalance();
1213 int64 nReserveBalance = 0;
1214 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1215 return error("CreateCoinStake : invalid reserve balance amount");
1216 if (nBalance <= nReserveBalance)
1218 set<pair<const CWalletTx*,unsigned int> > setCoins;
1219 vector<const CWalletTx*> vwtxPrev;
1221 if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
1223 if (setCoins.empty())
1226 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1230 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1233 // Read block header
1235 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1237 if (block.GetBlockTime() + STAKE_MIN_AGE > txNew.nTime)
1238 continue; // only count coins meeting min age requirement
1240 int64 nValueIn = pcoin.first->vout[pcoin.second].nValue;
1241 CBigNum bnCoinDay = CBigNum(nValueIn) * (txNew.nTime-pcoin.first->nTime) / COIN / (24 * 60 * 60);
1243 CDataStream ss(SER_GETHASH, 0);
1244 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin.first->nTime << pcoin.second << txNew.nTime;
1245 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1247 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1248 nCredit += pcoin.first->vout[pcoin.second].nValue;
1249 vwtxPrev.push_back(pcoin.first);
1250 // Set output scriptPubKey
1251 txNew.vout.push_back(CTxOut(0, pcoin.first->vout[pcoin.second].scriptPubKey));
1255 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1257 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1259 if (pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1261 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1263 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1264 nCredit += pcoin.first->vout[pcoin.second].nValue;
1265 vwtxPrev.push_back(pcoin.first);
1268 // Calculate coin age reward
1272 if (!txNew.GetCoinAge(txdb, nCoinAge))
1273 return error("CreateCoinStake : failed to calculate coin age");
1274 nCredit += GetProofOfStakeReward(nCoinAge);
1276 // Set output amount
1277 txNew.vout[1].nValue = nCredit;
1281 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1283 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1284 return error("CreateCoinStake : failed to sign coinstake");
1289 // Call after CreateTransaction unless you want to abort
1290 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1293 LOCK2(cs_main, cs_wallet);
1294 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1296 // This is only to keep the database open to defeat the auto-flush for the
1297 // duration of this scope. This is the only place where this optimization
1298 // maybe makes sense; please don't do it anywhere else.
1299 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1301 // Take key pair from key pool so it won't be used again
1302 reservekey.KeepKey();
1304 // Add tx to wallet, because if it has change it's also ours,
1305 // otherwise just for transaction history.
1306 AddToWallet(wtxNew);
1308 // Mark old coins as spent
1309 set<CWalletTx*> setCoins;
1310 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1312 CWalletTx &coin = mapWallet[txin.prevout.hash];
1313 coin.BindWallet(this);
1314 coin.MarkSpent(txin.prevout.n);
1316 vWalletUpdated.push_back(coin.GetHash());
1323 // Track how many getdata requests our transaction gets
1324 mapRequestCount[wtxNew.GetHash()] = 0;
1327 if (!wtxNew.AcceptToMemoryPool())
1329 // This must not fail. The transaction has already been signed and recorded.
1330 printf("CommitTransaction() : Error: Transaction not valid");
1333 wtxNew.RelayWalletTransaction();
1342 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1344 CReserveKey reservekey(this);
1349 string strError = _("Error: Wallet locked, unable to create transaction ");
1350 printf("SendMoney() : %s", strError.c_str());
1353 if (fWalletUnlockStakeOnly)
1355 string strError = _("Error: Wallet unlocked for coinstake only, unable to create transaction.");
1356 printf("SendMoney() : %s", strError.c_str());
1359 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1362 if (nValue + nFeeRequired > GetBalance())
1363 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());
1365 strError = _("Error: Transaction creation failed ");
1366 printf("SendMoney() : %s", strError.c_str());
1370 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1373 if (!CommitTransaction(wtxNew, reservekey))
1374 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.");
1382 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1386 return _("Invalid amount");
1387 if (nValue + nTransactionFee > GetBalance())
1388 return _("Insufficient funds");
1390 // Parse bitcoin address
1391 CScript scriptPubKey;
1392 scriptPubKey.SetBitcoinAddress(address);
1394 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1400 int CWallet::LoadWallet(bool& fFirstRunRet)
1404 fFirstRunRet = false;
1405 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1406 if (nLoadWalletRet == DB_NEED_REWRITE)
1408 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1411 // Note: can't top-up keypool here, because wallet is locked.
1412 // User will be prompted to unlock wallet the next operation
1413 // the requires a new key.
1415 nLoadWalletRet = DB_NEED_REWRITE;
1418 if (nLoadWalletRet != DB_LOAD_OK)
1419 return nLoadWalletRet;
1420 fFirstRunRet = vchDefaultKey.empty();
1422 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1427 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1429 mapAddressBook[address] = strName;
1430 AddressBookRepaint();
1433 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1436 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1438 mapAddressBook.erase(address);
1439 AddressBookRepaint();
1442 return CWalletDB(strWalletFile).EraseName(address.ToString());
1446 void CWallet::PrintWallet(const CBlock& block)
1450 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1452 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1453 printf(" mine: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1455 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1457 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1458 printf(" stake: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1464 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1468 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1469 if (mi != mapWallet.end())
1478 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1482 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1485 vchDefaultKey = vchPubKey;
1489 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1491 if (!pwallet->fFileBacked)
1493 strWalletFileOut = pwallet->strWalletFile;
1498 // Mark old keypool keys as used,
1499 // and generate all new keys
1501 bool CWallet::NewKeyPool()
1505 CWalletDB walletdb(strWalletFile);
1506 BOOST_FOREACH(int64 nIndex, setKeyPool)
1507 walletdb.ErasePool(nIndex);
1513 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1514 for (int i = 0; i < nKeys; i++)
1517 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1518 setKeyPool.insert(nIndex);
1520 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1525 bool CWallet::TopUpKeyPool()
1533 CWalletDB walletdb(strWalletFile);
1536 unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1537 while (setKeyPool.size() < (nTargetSize + 1))
1540 if (!setKeyPool.empty())
1541 nEnd = *(--setKeyPool.end()) + 1;
1542 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1543 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1544 setKeyPool.insert(nEnd);
1545 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1551 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1554 keypool.vchPubKey.clear();
1561 // Get the oldest key
1562 if(setKeyPool.empty())
1565 CWalletDB walletdb(strWalletFile);
1567 nIndex = *(setKeyPool.begin());
1568 setKeyPool.erase(setKeyPool.begin());
1569 if (!walletdb.ReadPool(nIndex, keypool))
1570 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1571 if (!HaveKey(Hash160(keypool.vchPubKey)))
1572 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1573 assert(!keypool.vchPubKey.empty());
1574 printf("keypool reserve %"PRI64d"\n", nIndex);
1578 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1581 LOCK2(cs_main, cs_wallet);
1582 CWalletDB walletdb(strWalletFile);
1584 int64 nIndex = 1 + *(--setKeyPool.end());
1585 if (!walletdb.WritePool(nIndex, keypool))
1586 throw runtime_error("AddReserveKey() : writing added key failed");
1587 setKeyPool.insert(nIndex);
1593 void CWallet::KeepKey(int64 nIndex)
1595 // Remove from key pool
1598 CWalletDB walletdb(strWalletFile);
1599 walletdb.ErasePool(nIndex);
1601 printf("keypool keep %"PRI64d"\n", nIndex);
1604 void CWallet::ReturnKey(int64 nIndex)
1606 // Return to key pool
1609 setKeyPool.insert(nIndex);
1611 printf("keypool return %"PRI64d"\n", nIndex);
1614 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1620 ReserveKeyFromKeyPool(nIndex, keypool);
1623 if (fAllowReuse && !vchDefaultKey.empty())
1625 result = vchDefaultKey;
1628 if (IsLocked()) return false;
1629 result = GenerateNewKey();
1633 result = keypool.vchPubKey;
1638 int64 CWallet::GetOldestKeyPoolTime()
1642 ReserveKeyFromKeyPool(nIndex, keypool);
1646 return keypool.nTime;
1649 // ppcoin: check 'spent' consistency between wallet and txindex
1650 bool CWallet::CheckSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1653 nBalanceInQuestion = 0;
1656 vector<const CWalletTx*> vCoins;
1657 vCoins.reserve(mapWallet.size());
1658 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1659 vCoins.push_back(&(*it).second);
1662 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
1664 // Find the corresponding transaction index
1666 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1668 for (int n=0; n < pcoin->vout.size(); n++)
1670 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1672 printf("CheckSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1674 nBalanceInQuestion += pcoin->vout[n].nValue;
1676 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1678 printf("CheckSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1680 nBalanceInQuestion += pcoin->vout[n].nValue;
1684 return (nMismatchFound == 0);
1687 // ppcoin: fix wallet spent state according to txindex
1688 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1691 nBalanceInQuestion = 0;
1694 vector<CWalletTx*> vCoins;
1695 vCoins.reserve(mapWallet.size());
1696 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1697 vCoins.push_back(&(*it).second);
1700 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
1702 // Find the corresponding transaction index
1704 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1706 for (int n=0; n < pcoin->vout.size(); n++)
1708 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1710 printf("FixSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1712 nBalanceInQuestion += pcoin->vout[n].nValue;
1713 pcoin->MarkUnspent(n);
1714 pcoin->WriteToDisk();
1716 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1718 printf("FixSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1720 nBalanceInQuestion += pcoin->vout[n].nValue;
1721 pcoin->MarkSpent(n);
1722 pcoin->WriteToDisk();
1728 // ppcoin: disable transaction (only for coinstake)
1729 void CWallet::DisableTransaction(const CTransaction &tx)
1731 if (!tx.IsCoinStake() || !IsFromMe(tx))
1732 return; // only disconnecting coinstake requires marking input unspent
1735 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1737 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
1738 if (mi != mapWallet.end())
1740 CWalletTx& prev = (*mi).second;
1741 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
1743 prev.MarkUnspent(txin.prevout.n);
1750 vector<unsigned char> CReserveKey::GetReservedKey()
1755 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1757 vchPubKey = keypool.vchPubKey;
1760 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1761 vchPubKey = pwallet->vchDefaultKey;
1764 assert(!vchPubKey.empty());
1768 void CReserveKey::KeepKey()
1771 pwallet->KeepKey(nIndex);
1776 void CReserveKey::ReturnKey()
1779 pwallet->ReturnKey(nIndex);
1784 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1788 CWalletDB walletdb(strWalletFile);
1790 LOCK2(cs_main, cs_wallet);
1791 BOOST_FOREACH(const int64& id, setKeyPool)
1794 if (!walletdb.ReadPool(id, keypool))
1795 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1796 CBitcoinAddress address(keypool.vchPubKey);
1797 assert(!keypool.vchPubKey.empty());
1798 if (!HaveKey(address))
1799 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1800 setAddress.insert(address);