1 // Copyright (c) 2009-2011 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10 #include "checkpoints.h"
15 //////////////////////////////////////////////////////////////////////////////
20 bool CWallet::AddKey(const CKey& key)
22 if (!CCryptoKeyStore::AddKey(key))
27 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
31 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
33 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
37 CRITICAL_BLOCK(cs_wallet)
39 if (pwalletdbEncryption)
40 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
42 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
47 // ppcoin: optional setting to create coinstake only when unlocked;
48 // serves to disable the trivial sendmoney when OS account compromised
49 bool fWalletUnlockStakeOnly = false;
51 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
57 CKeyingMaterial vMasterKey;
59 CRITICAL_BLOCK(cs_wallet)
60 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
62 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
64 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
66 if (CCryptoKeyStore::Unlock(vMasterKey))
72 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
74 bool fWasLocked = IsLocked();
76 CRITICAL_BLOCK(cs_wallet)
81 CKeyingMaterial vMasterKey;
82 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
84 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
86 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
88 if (CCryptoKeyStore::Unlock(vMasterKey))
90 int64 nStartTime = GetTimeMillis();
91 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
92 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
94 nStartTime = GetTimeMillis();
95 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
96 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
98 if (pMasterKey.second.nDeriveIterations < 25000)
99 pMasterKey.second.nDeriveIterations = 25000;
101 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
103 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
105 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
107 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
119 // This class implements an addrIncoming entry that causes pre-0.4
120 // clients to crash on startup if reading a private-key-encrypted wallet.
121 class CCorruptAddress
126 if (nType & SER_DISK)
131 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
136 CKeyingMaterial vMasterKey;
137 RandAddSeedPerfmon();
139 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
140 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
142 CMasterKey kMasterKey;
144 RandAddSeedPerfmon();
145 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
146 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
149 int64 nStartTime = GetTimeMillis();
150 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
151 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
153 nStartTime = GetTimeMillis();
154 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
155 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
157 if (kMasterKey.nDeriveIterations < 25000)
158 kMasterKey.nDeriveIterations = 25000;
160 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
162 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
164 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
167 CRITICAL_BLOCK(cs_wallet)
169 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
172 pwalletdbEncryption = new CWalletDB(strWalletFile);
173 pwalletdbEncryption->TxnBegin();
174 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
177 if (!EncryptKeys(vMasterKey))
180 pwalletdbEncryption->TxnAbort();
181 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.
186 CCorruptAddress corruptAddress;
187 pwalletdbEncryption->WriteSetting("addrIncoming", corruptAddress);
188 if (!pwalletdbEncryption->TxnCommit())
189 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.
191 pwalletdbEncryption->Close();
192 pwalletdbEncryption = NULL;
196 Unlock(strWalletPassphrase);
200 // Need to completely rewrite the wallet file; if we don't, bdb might keep
201 // bits of the unencrypted private key in slack space in the database file.
202 CDB::Rewrite(strWalletFile);
208 void CWallet::WalletUpdateSpent(const CTransaction &tx)
210 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
211 // Update the wallet spent flag if it doesn't know due to wallet.dat being
212 // restored from backup or the user making copies of wallet.dat.
213 CRITICAL_BLOCK(cs_wallet)
215 BOOST_FOREACH(const CTxIn& txin, tx.vin)
217 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
218 if (mi != mapWallet.end())
220 CWalletTx& wtx = (*mi).second;
221 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
223 printf("WalletUpdateSpent found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
224 wtx.MarkSpent(txin.prevout.n);
226 vWalletUpdated.push_back(txin.prevout.hash);
233 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
235 uint256 hash = wtxIn.GetHash();
236 CRITICAL_BLOCK(cs_wallet)
238 // Inserts only if not already there, returns tx inserted or tx found
239 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
240 CWalletTx& wtx = (*ret.first).second;
242 bool fInsertedNew = ret.second;
244 wtx.nTimeReceived = GetAdjustedTime();
246 bool fUpdated = false;
250 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
252 wtx.hashBlock = wtxIn.hashBlock;
255 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
257 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
258 wtx.nIndex = wtxIn.nIndex;
261 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
263 wtx.fFromMe = wtxIn.fFromMe;
266 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
270 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
273 if (fInsertedNew || fUpdated)
274 if (!wtx.WriteToDisk())
277 // If default receiving address gets used, replace it with a new one
278 CScript scriptDefaultKey;
279 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
280 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
282 if (txout.scriptPubKey == scriptDefaultKey)
284 std::vector<unsigned char> newDefaultKey;
285 if (GetKeyFromPool(newDefaultKey, false))
287 SetDefaultKey(newDefaultKey);
288 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
294 vWalletUpdated.push_back(hash);
296 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
297 WalletUpdateSpent(wtx);
305 // Add a transaction to the wallet, or update it.
306 // pblock is optional, but should be provided if the transaction is known to be in a block.
307 // If fUpdate is true, existing transactions will be updated.
308 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
310 uint256 hash = tx.GetHash();
311 CRITICAL_BLOCK(cs_wallet)
313 bool fExisted = mapWallet.count(hash);
314 if (fExisted && !fUpdate) return false;
315 if (fExisted || IsMine(tx) || IsFromMe(tx))
317 CWalletTx wtx(this,tx);
318 // Get merkle branch if transaction was found in a block
320 wtx.SetMerkleBranch(pblock);
321 return AddToWallet(wtx);
324 WalletUpdateSpent(tx);
329 bool CWallet::EraseFromWallet(uint256 hash)
333 CRITICAL_BLOCK(cs_wallet)
335 if (mapWallet.erase(hash))
336 CWalletDB(strWalletFile).EraseTx(hash);
342 bool CWallet::IsMine(const CTxIn &txin) const
344 CRITICAL_BLOCK(cs_wallet)
346 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
347 if (mi != mapWallet.end())
349 const CWalletTx& prev = (*mi).second;
350 if (txin.prevout.n < prev.vout.size())
351 if (IsMine(prev.vout[txin.prevout.n]))
358 int64 CWallet::GetDebit(const CTxIn &txin) const
360 CRITICAL_BLOCK(cs_wallet)
362 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
363 if (mi != mapWallet.end())
365 const CWalletTx& prev = (*mi).second;
366 if (txin.prevout.n < prev.vout.size())
367 if (IsMine(prev.vout[txin.prevout.n]))
368 return prev.vout[txin.prevout.n].nValue;
374 int64 CWalletTx::GetTxTime() const
376 return nTimeReceived;
379 int CWalletTx::GetRequestCount() const
381 // Returns -1 if it wasn't being tracked
383 CRITICAL_BLOCK(pwallet->cs_wallet)
385 if (IsCoinBase() || IsCoinStake())
390 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
391 if (mi != pwallet->mapRequestCount.end())
392 nRequests = (*mi).second;
397 // Did anyone request this transaction?
398 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
399 if (mi != pwallet->mapRequestCount.end())
401 nRequests = (*mi).second;
403 // How about the block it's in?
404 if (nRequests == 0 && hashBlock != 0)
406 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
407 if (mi != pwallet->mapRequestCount.end())
408 nRequests = (*mi).second;
410 nRequests = 1; // If it's in someone else's block it must have got out
418 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
419 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
421 nGeneratedImmature = nGeneratedMature = nFee = 0;
422 listReceived.clear();
424 strSentAccount = strFromAccount;
426 if (IsCoinBase() || IsCoinStake())
428 if (GetBlocksToMaturity() > 0)
429 nGeneratedImmature = pwallet->GetCredit(*this);
431 nGeneratedMature = GetCredit();
436 int64 nDebit = GetDebit();
437 if (nDebit > 0) // debit>0 means we signed/sent this transaction
439 int64 nValueOut = GetValueOut();
440 nFee = nDebit - nValueOut;
443 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
444 // but non-standard clients might (so return a list of address/amount pairs)
445 BOOST_FOREACH(const CTxOut& txout, vout)
447 CBitcoinAddress address;
448 vector<unsigned char> vchPubKey;
449 if (!ExtractAddress(txout.scriptPubKey, NULL, address))
451 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
452 this->GetHash().ToString().c_str());
453 address = " unknown ";
456 // Don't report 'change' txouts
457 if (nDebit > 0 && pwallet->IsChange(txout))
461 listSent.push_back(make_pair(address, txout.nValue));
463 if (pwallet->IsMine(txout))
464 listReceived.push_back(make_pair(address, txout.nValue));
469 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
470 int64& nSent, int64& nFee) const
472 nGenerated = nReceived = nSent = nFee = 0;
474 int64 allGeneratedImmature, allGeneratedMature, allFee;
475 allGeneratedImmature = allGeneratedMature = allFee = 0;
476 string strSentAccount;
477 list<pair<CBitcoinAddress, int64> > listReceived;
478 list<pair<CBitcoinAddress, int64> > listSent;
479 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
481 if (strAccount == "")
482 nGenerated = allGeneratedMature;
483 if (strAccount == strSentAccount)
485 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
489 CRITICAL_BLOCK(pwallet->cs_wallet)
491 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
493 if (pwallet->mapAddressBook.count(r.first))
495 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
496 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
497 nReceived += r.second;
499 else if (strAccount.empty())
501 nReceived += r.second;
507 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
511 const int COPY_DEPTH = 3;
512 if (SetMerkleBranch() < COPY_DEPTH)
514 vector<uint256> vWorkQueue;
515 BOOST_FOREACH(const CTxIn& txin, vin)
516 vWorkQueue.push_back(txin.prevout.hash);
518 // This critsect is OK because txdb is already open
519 CRITICAL_BLOCK(pwallet->cs_wallet)
521 map<uint256, const CMerkleTx*> mapWalletPrev;
522 set<uint256> setAlreadyDone;
523 for (int i = 0; i < vWorkQueue.size(); i++)
525 uint256 hash = vWorkQueue[i];
526 if (setAlreadyDone.count(hash))
528 setAlreadyDone.insert(hash);
531 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
532 if (mi != pwallet->mapWallet.end())
535 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
536 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
538 else if (mapWalletPrev.count(hash))
540 tx = *mapWalletPrev[hash];
542 else if (!fClient && txdb.ReadDiskTx(hash, tx))
548 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
552 int nDepth = tx.SetMerkleBranch();
553 vtxPrev.push_back(tx);
555 if (nDepth < COPY_DEPTH)
556 BOOST_FOREACH(const CTxIn& txin, tx.vin)
557 vWorkQueue.push_back(txin.prevout.hash);
562 reverse(vtxPrev.begin(), vtxPrev.end());
565 bool CWalletTx::WriteToDisk()
567 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
570 // Scan the block chain (starting in pindexStart) for transactions
571 // from or to us. If fUpdate is true, found transactions that already
572 // exist in the wallet will be updated.
573 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
577 CBlockIndex* pindex = pindexStart;
578 CRITICAL_BLOCK(cs_wallet)
583 block.ReadFromDisk(pindex, true);
584 BOOST_FOREACH(CTransaction& tx, block.vtx)
586 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
589 pindex = pindex->pnext;
595 void CWallet::ReacceptWalletTransactions()
599 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
602 vector<CDiskTxPos> vMissingTx;
603 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
605 CWalletTx& wtx = item.second;
606 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
610 bool fUpdated = false;
611 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
613 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
614 if (txindex.vSpent.size() != wtx.vout.size())
616 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
619 for (int i = 0; i < txindex.vSpent.size(); i++)
623 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
627 vMissingTx.push_back(txindex.vSpent[i]);
632 printf("ReacceptWalletTransactions found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
639 // Reaccept any txes of ours that aren't already in a block
640 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
641 wtx.AcceptWalletTransaction(txdb, false);
644 if (!vMissingTx.empty())
646 // TODO: optimize this to scan just part of the block chain?
647 if (ScanForWalletTransactions(pindexGenesisBlock))
648 fRepeat = true; // Found missing transactions: re-do Reaccept.
653 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
655 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
657 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
659 uint256 hash = tx.GetHash();
660 if (!txdb.ContainsTx(hash))
661 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
664 if (!(IsCoinBase() || IsCoinStake()))
666 uint256 hash = GetHash();
667 if (!txdb.ContainsTx(hash))
669 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
670 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
675 void CWalletTx::RelayWalletTransaction()
678 RelayWalletTransaction(txdb);
681 void CWallet::ResendWalletTransactions()
683 // Do this infrequently and randomly to avoid giving away
684 // that these are our transactions.
685 static int64 nNextTime;
686 if (GetTime() < nNextTime)
688 bool fFirst = (nNextTime == 0);
689 nNextTime = GetTime() + GetRand(30 * 60);
693 // Only do it if there's been a new block since last time
694 static int64 nLastTime;
695 if (nTimeBestReceived < nLastTime)
697 nLastTime = GetTime();
699 // Rebroadcast any of our txes that aren't in a block yet
700 printf("ResendWalletTransactions()\n");
702 CRITICAL_BLOCK(cs_wallet)
704 // Sort them in chronological order
705 multimap<unsigned int, CWalletTx*> mapSorted;
706 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
708 CWalletTx& wtx = item.second;
709 // Don't rebroadcast until it's had plenty of time that
710 // it should have gotten in already by now.
711 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
712 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
714 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
716 CWalletTx& wtx = *item.second;
717 wtx.RelayWalletTransaction(txdb);
727 //////////////////////////////////////////////////////////////////////////////
733 int64 CWallet::GetBalance() const
736 CRITICAL_BLOCK(cs_wallet)
738 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
740 const CWalletTx* pcoin = &(*it).second;
741 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
743 nTotal += pcoin->GetAvailableCredit();
750 int64 CWallet::GetUnconfirmedBalance() const
753 CRITICAL_BLOCK(cs_wallet)
755 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
757 const CWalletTx* pcoin = &(*it).second;
758 if (pcoin->IsFinal() && pcoin->IsConfirmed())
760 nTotal += pcoin->GetAvailableCredit();
766 // ppcoin: total coins staked (non-spendable until maturity)
767 int64 CWallet::GetStake() const
770 CRITICAL_BLOCK(cs_wallet)
772 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
774 const CWalletTx* pcoin = &(*it).second;
775 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
776 nTotal += CWallet::GetCredit(*pcoin);
782 int64 CWallet::GetNewMint() const
785 CRITICAL_BLOCK(cs_wallet)
787 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
789 const CWalletTx* pcoin = &(*it).second;
790 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
791 nTotal += CWallet::GetCredit(*pcoin);
798 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
803 // List of values less than target
804 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
805 coinLowestLarger.first = INT64_MAX;
806 coinLowestLarger.second.first = NULL;
807 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
808 int64 nTotalLower = 0;
810 CRITICAL_BLOCK(cs_wallet)
812 vector<const CWalletTx*> vCoins;
813 vCoins.reserve(mapWallet.size());
814 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
815 vCoins.push_back(&(*it).second);
816 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
818 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
820 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
823 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
826 int nDepth = pcoin->GetDepthInMainChain();
827 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
830 for (int i = 0; i < pcoin->vout.size(); i++)
832 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
835 if (pcoin->nTime > nSpendTime)
836 continue; // ppcoin: timestamp must not exceed spend time
838 int64 n = pcoin->vout[i].nValue;
843 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
845 if (n == nTargetValue)
847 setCoinsRet.insert(coin.second);
848 nValueRet += coin.first;
851 else if (n < nTargetValue + CENT)
853 vValue.push_back(coin);
856 else if (n < coinLowestLarger.first)
858 coinLowestLarger = coin;
864 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
866 for (int i = 0; i < vValue.size(); ++i)
868 setCoinsRet.insert(vValue[i].second);
869 nValueRet += vValue[i].first;
874 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
876 if (coinLowestLarger.second.first == NULL)
878 setCoinsRet.insert(coinLowestLarger.second);
879 nValueRet += coinLowestLarger.first;
883 if (nTotalLower >= nTargetValue + CENT)
884 nTargetValue += CENT;
886 // Solve subset sum by stochastic approximation
887 sort(vValue.rbegin(), vValue.rend());
888 vector<char> vfIncluded;
889 vector<char> vfBest(vValue.size(), true);
890 int64 nBest = nTotalLower;
892 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
894 vfIncluded.assign(vValue.size(), false);
896 bool fReachedTarget = false;
897 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
899 for (int i = 0; i < vValue.size(); i++)
901 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
903 nTotal += vValue[i].first;
904 vfIncluded[i] = true;
905 if (nTotal >= nTargetValue)
907 fReachedTarget = true;
913 nTotal -= vValue[i].first;
914 vfIncluded[i] = false;
921 // If the next larger is still closer, return it
922 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
924 setCoinsRet.insert(coinLowestLarger.second);
925 nValueRet += coinLowestLarger.first;
928 for (int i = 0; i < vValue.size(); i++)
931 setCoinsRet.insert(vValue[i].second);
932 nValueRet += vValue[i].first;
936 printf("SelectCoins() best subset: ");
937 for (int i = 0; i < vValue.size(); i++)
939 printf("%s ", FormatMoney(vValue[i].first).c_str());
940 printf("total %s\n", FormatMoney(nBest).c_str());
946 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
948 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
949 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
950 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
956 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
959 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
965 if (vecSend.empty() || nValue < 0)
968 wtxNew.pwallet = this;
970 CRITICAL_BLOCK(cs_main)
971 CRITICAL_BLOCK(cs_wallet)
973 // txdb must be opened before the mapWallet lock
976 nFeeRet = nTransactionFee;
981 wtxNew.fFromMe = true;
983 int64 nTotalValue = nValue + nFeeRet;
984 double dPriority = 0;
985 // vouts to the payees
986 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
987 wtxNew.vout.push_back(CTxOut(s.second, s.first));
989 // Choose coins to use
990 set<pair<const CWalletTx*,unsigned int> > setCoins;
992 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
994 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
996 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
997 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1000 int64 nChange = nValueIn - nValue - nFeeRet;
1001 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1002 // or until nChange becomes zero
1003 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1005 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1006 nChange -= nMoveToFee;
1007 nFeeRet += nMoveToFee;
1012 // Note: We use a new key here to keep it from being obvious which side is the change.
1013 // The drawback is that by not reusing a previous key, the change may be lost if a
1014 // backup is restored, if the backup doesn't have the new private key for the change.
1015 // If we reused the old key, it would be possible to add code to look for and
1016 // rediscover unknown transactions that were written with keys of ours to recover
1017 // post-backup change.
1019 // Reserve a new key pair from key pool
1020 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1021 // assert(mapKeys.count(vchPubKey));
1023 // Fill a vout to ourself, using same address type as the payment
1024 CScript scriptChange;
1025 if (vecSend[0].first.GetBitcoinAddress().IsValid())
1026 scriptChange.SetBitcoinAddress(vchPubKey);
1028 scriptChange << vchPubKey << OP_CHECKSIG;
1030 // Insert change txn at random position:
1031 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1032 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1035 reservekey.ReturnKey();
1038 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1039 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1043 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1044 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1048 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1049 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1051 dPriority /= nBytes;
1053 // Check that enough fee is included
1054 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1055 int64 nMinFee = wtxNew.GetMinFee(1, false);
1056 if (nFeeRet < max(nPayFee, nMinFee))
1058 nFeeRet = max(nPayFee, nMinFee);
1062 // Fill vtxPrev by copying from previous transactions vtxPrev
1063 wtxNew.AddSupportingTransactions(txdb);
1064 wtxNew.fTimeReceivedIsTxTime = true;
1073 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1075 vector< pair<CScript, int64> > vecSend;
1076 vecSend.push_back(make_pair(scriptPubKey, nValue));
1077 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1080 // ppcoin: create coin stake transaction
1081 bool CWallet::CreateCoinStake(unsigned int nBits, CTransaction& txNew)
1083 CBigNum bnTargetPerCoinDay;
1084 bnTargetPerCoinDay.SetCompact(nBits);
1086 CRITICAL_BLOCK(cs_main)
1087 CRITICAL_BLOCK(cs_wallet)
1091 // Mark coin stake transaction
1092 CScript scriptEmpty;
1093 scriptEmpty.clear();
1094 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1095 // Choose coins to use
1096 int64 nBalance = GetBalance();
1097 if (nBalance <= nBalanceReserve)
1099 set<pair<const CWalletTx*,unsigned int> > setCoins;
1100 vector<const CWalletTx*> vwtxPrev;
1102 if (!SelectCoins(nBalance - nBalanceReserve, txNew.nTime, setCoins, nValueIn))
1104 if (setCoins.empty())
1107 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1111 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1114 // Read block header
1116 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1118 if (block.GetBlockTime() + STAKE_MIN_AGE > txNew.nTime)
1119 continue; // only count coins meeting min age requirement
1121 int64 nValueIn = pcoin.first->vout[pcoin.second].nValue;
1122 CBigNum bnCoinDay = CBigNum(nValueIn) * (txNew.nTime-pcoin.first->nTime) / COIN / (24 * 60 * 60);
1124 CDataStream ss(SER_GETHASH, VERSION);
1125 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin.first->nTime << pcoin.second << txNew.nTime;
1126 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1128 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1129 nCredit += pcoin.first->vout[pcoin.second].nValue;
1130 vwtxPrev.push_back(pcoin.first);
1131 // Set output scriptPubKey
1132 txNew.vout.push_back(CTxOut(0, pcoin.first->vout[pcoin.second].scriptPubKey));
1136 if (nCredit == 0 || nCredit > nBalance - nBalanceReserve)
1138 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1140 if (pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1142 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nBalanceReserve)
1144 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1145 nCredit += pcoin.first->vout[pcoin.second].nValue;
1146 vwtxPrev.push_back(pcoin.first);
1149 // Calculate coin age reward
1153 if (!txNew.GetCoinAge(txdb, nCoinAge))
1154 return error("CreateCoinStake : failed to calculate coin age");
1155 nCredit += GetProofOfStakeReward(nCoinAge);
1157 // Set output amount
1158 txNew.vout[1].nValue = nCredit;
1162 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1164 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1165 return error("CreateCoinStake : failed to sign coinstake");
1171 // Call after CreateTransaction unless you want to abort
1172 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1174 CRITICAL_BLOCK(cs_main)
1175 CRITICAL_BLOCK(cs_wallet)
1177 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1179 // This is only to keep the database open to defeat the auto-flush for the
1180 // duration of this scope. This is the only place where this optimization
1181 // maybe makes sense; please don't do it anywhere else.
1182 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1184 // Take key pair from key pool so it won't be used again
1185 reservekey.KeepKey();
1187 // Add tx to wallet, because if it has change it's also ours,
1188 // otherwise just for transaction history.
1189 AddToWallet(wtxNew);
1191 // Mark old coins as spent
1192 set<CWalletTx*> setCoins;
1193 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1195 CWalletTx &coin = mapWallet[txin.prevout.hash];
1196 coin.pwallet = this;
1197 coin.MarkSpent(txin.prevout.n);
1199 vWalletUpdated.push_back(coin.GetHash());
1206 // Track how many getdata requests our transaction gets
1207 mapRequestCount[wtxNew.GetHash()] = 0;
1210 if (!wtxNew.AcceptToMemoryPool())
1212 // This must not fail. The transaction has already been signed and recorded.
1213 printf("CommitTransaction() : Error: Transaction not valid");
1216 wtxNew.RelayWalletTransaction();
1225 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1227 CReserveKey reservekey(this);
1232 string strError = _("Error: Wallet locked, unable to create transaction ");
1233 printf("SendMoney() : %s", strError.c_str());
1236 if (fWalletUnlockStakeOnly)
1238 string strError = _("Error: Wallet unlocked for coinstake only, unable to create transaction.");
1239 printf("SendMoney() : %s", strError.c_str());
1242 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1245 if (nValue + nFeeRequired > GetBalance())
1246 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());
1248 strError = _("Error: Transaction creation failed ");
1249 printf("SendMoney() : %s", strError.c_str());
1253 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1256 if (!CommitTransaction(wtxNew, reservekey))
1257 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.");
1265 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1269 return _("Invalid amount");
1270 if (nValue + nTransactionFee > GetBalance())
1271 return _("Insufficient funds");
1273 // Parse bitcoin address
1274 CScript scriptPubKey;
1275 scriptPubKey.SetBitcoinAddress(address);
1277 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1283 int CWallet::LoadWallet(bool& fFirstRunRet)
1287 fFirstRunRet = false;
1288 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1289 if (nLoadWalletRet == DB_NEED_REWRITE)
1291 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1294 // Note: can't top-up keypool here, because wallet is locked.
1295 // User will be prompted to unlock wallet the next operation
1296 // the requires a new key.
1298 nLoadWalletRet = DB_NEED_REWRITE;
1301 if (nLoadWalletRet != DB_LOAD_OK)
1302 return nLoadWalletRet;
1303 fFirstRunRet = vchDefaultKey.empty();
1305 if (!HaveKey(Hash160(vchDefaultKey)))
1307 // Create new keyUser and set as default key
1308 RandAddSeedPerfmon();
1310 std::vector<unsigned char> newDefaultKey;
1311 if (!GetKeyFromPool(newDefaultKey, false))
1312 return DB_LOAD_FAIL;
1313 SetDefaultKey(newDefaultKey);
1314 if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""))
1315 return DB_LOAD_FAIL;
1318 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1323 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1325 mapAddressBook[address] = strName;
1328 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1331 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1333 mapAddressBook.erase(address);
1336 return CWalletDB(strWalletFile).EraseName(address.ToString());
1340 void CWallet::PrintWallet(const CBlock& block)
1342 CRITICAL_BLOCK(cs_wallet)
1344 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1346 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1347 printf(" mine: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1349 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1351 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1352 printf(" stake: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1358 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1360 CRITICAL_BLOCK(cs_wallet)
1362 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1363 if (mi != mapWallet.end())
1372 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1376 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1379 vchDefaultKey = vchPubKey;
1383 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1385 if (!pwallet->fFileBacked)
1387 strWalletFileOut = pwallet->strWalletFile;
1392 // Mark old keypool keys as used,
1393 // and generate all new keys
1395 bool CWallet::NewKeyPool()
1397 CRITICAL_BLOCK(cs_wallet)
1399 CWalletDB walletdb(strWalletFile);
1400 BOOST_FOREACH(int64 nIndex, setKeyPool)
1401 walletdb.ErasePool(nIndex);
1407 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1408 for (int i = 0; i < nKeys; i++)
1411 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1412 setKeyPool.insert(nIndex);
1414 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1419 bool CWallet::TopUpKeyPool()
1421 CRITICAL_BLOCK(cs_wallet)
1426 CWalletDB walletdb(strWalletFile);
1429 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1430 while (setKeyPool.size() < nTargetSize+1)
1433 if (!setKeyPool.empty())
1434 nEnd = *(--setKeyPool.end()) + 1;
1435 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1436 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1437 setKeyPool.insert(nEnd);
1438 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1444 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1447 keypool.vchPubKey.clear();
1448 CRITICAL_BLOCK(cs_wallet)
1453 // Get the oldest key
1454 if(setKeyPool.empty())
1457 CWalletDB walletdb(strWalletFile);
1459 nIndex = *(setKeyPool.begin());
1460 setKeyPool.erase(setKeyPool.begin());
1461 if (!walletdb.ReadPool(nIndex, keypool))
1462 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1463 if (!HaveKey(Hash160(keypool.vchPubKey)))
1464 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1465 assert(!keypool.vchPubKey.empty());
1466 printf("keypool reserve %"PRI64d"\n", nIndex);
1470 void CWallet::KeepKey(int64 nIndex)
1472 // Remove from key pool
1475 CWalletDB walletdb(strWalletFile);
1476 walletdb.ErasePool(nIndex);
1478 printf("keypool keep %"PRI64d"\n", nIndex);
1481 void CWallet::ReturnKey(int64 nIndex)
1483 // Return to key pool
1484 CRITICAL_BLOCK(cs_wallet)
1485 setKeyPool.insert(nIndex);
1486 printf("keypool return %"PRI64d"\n", nIndex);
1489 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1493 CRITICAL_BLOCK(cs_wallet)
1495 ReserveKeyFromKeyPool(nIndex, keypool);
1498 if (fAllowReuse && !vchDefaultKey.empty())
1500 result = vchDefaultKey;
1503 if (IsLocked()) return false;
1504 result = GenerateNewKey();
1508 result = keypool.vchPubKey;
1513 int64 CWallet::GetOldestKeyPoolTime()
1517 ReserveKeyFromKeyPool(nIndex, keypool);
1521 return keypool.nTime;
1524 // ppcoin: check 'spent' consistency between wallet and txindex
1525 bool CWallet::CheckSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1528 nBalanceInQuestion = 0;
1529 CRITICAL_BLOCK(cs_wallet)
1531 vector<const CWalletTx*> vCoins;
1532 vCoins.reserve(mapWallet.size());
1533 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1534 vCoins.push_back(&(*it).second);
1537 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
1539 // Find the corresponding transaction index
1541 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1543 for (int n=0; n < pcoin->vout.size(); n++)
1545 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1547 printf("CheckSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1549 nBalanceInQuestion += pcoin->vout[n].nValue;
1551 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1553 printf("CheckSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1555 nBalanceInQuestion += pcoin->vout[n].nValue;
1560 return (nMismatchFound == 0);
1563 // ppcoin: fix wallet spent state according to txindex
1564 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1567 nBalanceInQuestion = 0;
1568 CRITICAL_BLOCK(cs_wallet)
1570 vector<CWalletTx*> vCoins;
1571 vCoins.reserve(mapWallet.size());
1572 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1573 vCoins.push_back(&(*it).second);
1576 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
1578 // Find the corresponding transaction index
1580 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1582 for (int n=0; n < pcoin->vout.size(); n++)
1584 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1586 printf("FixSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1588 nBalanceInQuestion += pcoin->vout[n].nValue;
1589 pcoin->MarkUnspent(n);
1590 pcoin->WriteToDisk();
1592 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1594 printf("FixSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1596 nBalanceInQuestion += pcoin->vout[n].nValue;
1597 pcoin->MarkSpent(n);
1598 pcoin->WriteToDisk();
1605 // ppcoin: disable transaction (only for coinstake)
1606 void CWallet::DisableTransaction(const CTransaction &tx)
1608 if (!tx.IsCoinStake() || !IsFromMe(tx))
1609 return; // only disconnecting coinstake requires marking input unspent
1610 CRITICAL_BLOCK(cs_wallet)
1612 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1614 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
1615 if (mi != mapWallet.end())
1617 CWalletTx& prev = (*mi).second;
1618 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
1620 prev.MarkUnspent(txin.prevout.n);
1628 vector<unsigned char> CReserveKey::GetReservedKey()
1633 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1635 vchPubKey = keypool.vchPubKey;
1638 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1639 vchPubKey = pwallet->vchDefaultKey;
1642 assert(!vchPubKey.empty());
1646 void CReserveKey::KeepKey()
1649 pwallet->KeepKey(nIndex);
1654 void CReserveKey::ReturnKey()
1657 pwallet->ReturnKey(nIndex);