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->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
776 nTotal += CWallet::GetCredit(*pcoin);
782 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
787 // List of values less than target
788 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
789 coinLowestLarger.first = INT64_MAX;
790 coinLowestLarger.second.first = NULL;
791 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
792 int64 nTotalLower = 0;
794 CRITICAL_BLOCK(cs_wallet)
796 vector<const CWalletTx*> vCoins;
797 vCoins.reserve(mapWallet.size());
798 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
799 vCoins.push_back(&(*it).second);
800 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
802 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
804 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
807 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
810 int nDepth = pcoin->GetDepthInMainChain();
811 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
814 for (int i = 0; i < pcoin->vout.size(); i++)
816 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
819 if (pcoin->nTime > nSpendTime)
820 continue; // ppcoin: timestamp must not exceed spend time
822 int64 n = pcoin->vout[i].nValue;
827 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
829 if (n == nTargetValue)
831 setCoinsRet.insert(coin.second);
832 nValueRet += coin.first;
835 else if (n < nTargetValue + CENT)
837 vValue.push_back(coin);
840 else if (n < coinLowestLarger.first)
842 coinLowestLarger = coin;
848 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
850 for (int i = 0; i < vValue.size(); ++i)
852 setCoinsRet.insert(vValue[i].second);
853 nValueRet += vValue[i].first;
858 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
860 if (coinLowestLarger.second.first == NULL)
862 setCoinsRet.insert(coinLowestLarger.second);
863 nValueRet += coinLowestLarger.first;
867 if (nTotalLower >= nTargetValue + CENT)
868 nTargetValue += CENT;
870 // Solve subset sum by stochastic approximation
871 sort(vValue.rbegin(), vValue.rend());
872 vector<char> vfIncluded;
873 vector<char> vfBest(vValue.size(), true);
874 int64 nBest = nTotalLower;
876 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
878 vfIncluded.assign(vValue.size(), false);
880 bool fReachedTarget = false;
881 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
883 for (int i = 0; i < vValue.size(); i++)
885 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
887 nTotal += vValue[i].first;
888 vfIncluded[i] = true;
889 if (nTotal >= nTargetValue)
891 fReachedTarget = true;
897 nTotal -= vValue[i].first;
898 vfIncluded[i] = false;
905 // If the next larger is still closer, return it
906 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
908 setCoinsRet.insert(coinLowestLarger.second);
909 nValueRet += coinLowestLarger.first;
912 for (int i = 0; i < vValue.size(); i++)
915 setCoinsRet.insert(vValue[i].second);
916 nValueRet += vValue[i].first;
920 printf("SelectCoins() best subset: ");
921 for (int i = 0; i < vValue.size(); i++)
923 printf("%s ", FormatMoney(vValue[i].first).c_str());
924 printf("total %s\n", FormatMoney(nBest).c_str());
930 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
932 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
933 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
934 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
940 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
943 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
949 if (vecSend.empty() || nValue < 0)
952 wtxNew.pwallet = this;
954 CRITICAL_BLOCK(cs_main)
955 CRITICAL_BLOCK(cs_wallet)
957 // txdb must be opened before the mapWallet lock
960 nFeeRet = nTransactionFee;
965 wtxNew.fFromMe = true;
967 int64 nTotalValue = nValue + nFeeRet;
968 double dPriority = 0;
969 // vouts to the payees
970 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
971 wtxNew.vout.push_back(CTxOut(s.second, s.first));
973 // Choose coins to use
974 set<pair<const CWalletTx*,unsigned int> > setCoins;
976 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
978 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
980 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
981 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
984 int64 nChange = nValueIn - nValue - nFeeRet;
985 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
986 // or until nChange becomes zero
987 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
989 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
990 nChange -= nMoveToFee;
991 nFeeRet += nMoveToFee;
996 // Note: We use a new key here to keep it from being obvious which side is the change.
997 // The drawback is that by not reusing a previous key, the change may be lost if a
998 // backup is restored, if the backup doesn't have the new private key for the change.
999 // If we reused the old key, it would be possible to add code to look for and
1000 // rediscover unknown transactions that were written with keys of ours to recover
1001 // post-backup change.
1003 // Reserve a new key pair from key pool
1004 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1005 // assert(mapKeys.count(vchPubKey));
1007 // Fill a vout to ourself, using same address type as the payment
1008 CScript scriptChange;
1009 if (vecSend[0].first.GetBitcoinAddress().IsValid())
1010 scriptChange.SetBitcoinAddress(vchPubKey);
1012 scriptChange << vchPubKey << OP_CHECKSIG;
1014 // Insert change txn at random position:
1015 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1016 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1019 reservekey.ReturnKey();
1022 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1023 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1027 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1028 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1032 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1033 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1035 dPriority /= nBytes;
1037 // Check that enough fee is included
1038 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1039 int64 nMinFee = wtxNew.GetMinFee(1, false);
1040 if (nFeeRet < max(nPayFee, nMinFee))
1042 nFeeRet = max(nPayFee, nMinFee);
1046 // Fill vtxPrev by copying from previous transactions vtxPrev
1047 wtxNew.AddSupportingTransactions(txdb);
1048 wtxNew.fTimeReceivedIsTxTime = true;
1057 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1059 vector< pair<CScript, int64> > vecSend;
1060 vecSend.push_back(make_pair(scriptPubKey, nValue));
1061 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1064 // ppcoin: create coin stake transaction
1065 bool CWallet::CreateCoinStake(CScript scriptPubKey, unsigned int nBits, CTransaction& txNew)
1067 CBigNum bnTargetPerCoinDay;
1068 bnTargetPerCoinDay.SetCompact(nBits);
1070 CRITICAL_BLOCK(cs_main)
1071 CRITICAL_BLOCK(cs_wallet)
1075 // Mark coin stake transaction
1076 CScript scriptEmpty;
1077 scriptEmpty.clear();
1078 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1079 // Choose coins to use
1080 int64 nBalance = GetBalance();
1081 if (nBalance <= nBalanceReserve)
1083 set<pair<const CWalletTx*,unsigned int> > setCoins;
1084 vector<const CWalletTx*> vwtxPrev;
1086 if (!SelectCoins(nBalance - nBalanceReserve, txNew.nTime, setCoins, nValueIn))
1088 if (setCoins.empty())
1091 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1095 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1098 // Read block header
1100 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1102 if (block.GetBlockTime() + AUTO_CHECKPOINT_TRUST_SPAN > txNew.nTime)
1103 continue; // only count coins from at least one week ago
1105 int64 nValueIn = pcoin.first->vout[pcoin.second].nValue;
1106 CBigNum bnCoinDay = CBigNum(nValueIn) * (txNew.nTime-pcoin.first->nTime) / COIN / (24 * 60 * 60);
1108 CDataStream ss(SER_GETHASH, VERSION);
1109 ss << nBits << block.nTime << pcoin.first->nTime << txNew.nTime;
1110 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1112 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1113 nCredit += pcoin.first->vout[pcoin.second].nValue;
1114 // Only spend one tx for now
1115 vwtxPrev.push_back(pcoin.first);
1119 if (nCredit == 0 || nCredit > nBalance - nBalanceReserve)
1121 // Calculate coin age reward
1125 if (!txNew.GetCoinAge(txdb, nCoinAge))
1126 return error("CreateCoinStake : failed to calculate coin age");
1127 nCredit += GetProofOfStakeReward(nCoinAge);
1130 txNew.vout.push_back(CTxOut(nCredit, scriptPubKey));
1135 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1137 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1138 return error("CreateCoinStake : failed to sign coinstake");
1144 // Call after CreateTransaction unless you want to abort
1145 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1147 CRITICAL_BLOCK(cs_main)
1148 CRITICAL_BLOCK(cs_wallet)
1150 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1152 // This is only to keep the database open to defeat the auto-flush for the
1153 // duration of this scope. This is the only place where this optimization
1154 // maybe makes sense; please don't do it anywhere else.
1155 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1157 // Take key pair from key pool so it won't be used again
1158 reservekey.KeepKey();
1160 // Add tx to wallet, because if it has change it's also ours,
1161 // otherwise just for transaction history.
1162 AddToWallet(wtxNew);
1164 // Mark old coins as spent
1165 set<CWalletTx*> setCoins;
1166 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1168 CWalletTx &coin = mapWallet[txin.prevout.hash];
1169 coin.pwallet = this;
1170 coin.MarkSpent(txin.prevout.n);
1172 vWalletUpdated.push_back(coin.GetHash());
1179 // Track how many getdata requests our transaction gets
1180 mapRequestCount[wtxNew.GetHash()] = 0;
1183 if (!wtxNew.AcceptToMemoryPool())
1185 // This must not fail. The transaction has already been signed and recorded.
1186 printf("CommitTransaction() : Error: Transaction not valid");
1189 wtxNew.RelayWalletTransaction();
1198 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1200 CReserveKey reservekey(this);
1205 string strError = _("Error: Wallet locked, unable to create transaction ");
1206 printf("SendMoney() : %s", strError.c_str());
1209 if (fWalletUnlockStakeOnly)
1211 string strError = _("Error: Wallet unlocked for coinstake only, unable to create transaction.");
1212 printf("SendMoney() : %s", strError.c_str());
1215 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1218 if (nValue + nFeeRequired > GetBalance())
1219 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());
1221 strError = _("Error: Transaction creation failed ");
1222 printf("SendMoney() : %s", strError.c_str());
1226 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1229 if (!CommitTransaction(wtxNew, reservekey))
1230 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.");
1238 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1242 return _("Invalid amount");
1243 if (nValue + nTransactionFee > GetBalance())
1244 return _("Insufficient funds");
1246 // Parse bitcoin address
1247 CScript scriptPubKey;
1248 scriptPubKey.SetBitcoinAddress(address);
1250 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1256 int CWallet::LoadWallet(bool& fFirstRunRet)
1260 fFirstRunRet = false;
1261 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1262 if (nLoadWalletRet == DB_NEED_REWRITE)
1264 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1267 // Note: can't top-up keypool here, because wallet is locked.
1268 // User will be prompted to unlock wallet the next operation
1269 // the requires a new key.
1271 nLoadWalletRet = DB_NEED_REWRITE;
1274 if (nLoadWalletRet != DB_LOAD_OK)
1275 return nLoadWalletRet;
1276 fFirstRunRet = vchDefaultKey.empty();
1278 if (!HaveKey(Hash160(vchDefaultKey)))
1280 // Create new keyUser and set as default key
1281 RandAddSeedPerfmon();
1283 std::vector<unsigned char> newDefaultKey;
1284 if (!GetKeyFromPool(newDefaultKey, false))
1285 return DB_LOAD_FAIL;
1286 SetDefaultKey(newDefaultKey);
1287 if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""))
1288 return DB_LOAD_FAIL;
1291 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1296 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1298 mapAddressBook[address] = strName;
1301 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1304 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1306 mapAddressBook.erase(address);
1309 return CWalletDB(strWalletFile).EraseName(address.ToString());
1313 void CWallet::PrintWallet(const CBlock& block)
1315 CRITICAL_BLOCK(cs_wallet)
1317 if (mapWallet.count(block.vtx[0].GetHash()))
1319 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1320 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1326 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1328 CRITICAL_BLOCK(cs_wallet)
1330 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1331 if (mi != mapWallet.end())
1340 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1344 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1347 vchDefaultKey = vchPubKey;
1351 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1353 if (!pwallet->fFileBacked)
1355 strWalletFileOut = pwallet->strWalletFile;
1360 // Mark old keypool keys as used,
1361 // and generate all new keys
1363 bool CWallet::NewKeyPool()
1365 CRITICAL_BLOCK(cs_wallet)
1367 CWalletDB walletdb(strWalletFile);
1368 BOOST_FOREACH(int64 nIndex, setKeyPool)
1369 walletdb.ErasePool(nIndex);
1375 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1376 for (int i = 0; i < nKeys; i++)
1379 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1380 setKeyPool.insert(nIndex);
1382 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1387 bool CWallet::TopUpKeyPool()
1389 CRITICAL_BLOCK(cs_wallet)
1394 CWalletDB walletdb(strWalletFile);
1397 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1398 while (setKeyPool.size() < nTargetSize+1)
1401 if (!setKeyPool.empty())
1402 nEnd = *(--setKeyPool.end()) + 1;
1403 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1404 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1405 setKeyPool.insert(nEnd);
1406 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1412 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1415 keypool.vchPubKey.clear();
1416 CRITICAL_BLOCK(cs_wallet)
1421 // Get the oldest key
1422 if(setKeyPool.empty())
1425 CWalletDB walletdb(strWalletFile);
1427 nIndex = *(setKeyPool.begin());
1428 setKeyPool.erase(setKeyPool.begin());
1429 if (!walletdb.ReadPool(nIndex, keypool))
1430 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1431 if (!HaveKey(Hash160(keypool.vchPubKey)))
1432 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1433 assert(!keypool.vchPubKey.empty());
1434 printf("keypool reserve %"PRI64d"\n", nIndex);
1438 void CWallet::KeepKey(int64 nIndex)
1440 // Remove from key pool
1443 CWalletDB walletdb(strWalletFile);
1444 walletdb.ErasePool(nIndex);
1446 printf("keypool keep %"PRI64d"\n", nIndex);
1449 void CWallet::ReturnKey(int64 nIndex)
1451 // Return to key pool
1452 CRITICAL_BLOCK(cs_wallet)
1453 setKeyPool.insert(nIndex);
1454 printf("keypool return %"PRI64d"\n", nIndex);
1457 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1461 CRITICAL_BLOCK(cs_wallet)
1463 ReserveKeyFromKeyPool(nIndex, keypool);
1466 if (fAllowReuse && !vchDefaultKey.empty())
1468 result = vchDefaultKey;
1471 if (IsLocked()) return false;
1472 result = GenerateNewKey();
1476 result = keypool.vchPubKey;
1481 int64 CWallet::GetOldestKeyPoolTime()
1485 ReserveKeyFromKeyPool(nIndex, keypool);
1489 return keypool.nTime;
1492 // ppcoin: check 'spent' consistency between wallet and txindex
1493 bool CWallet::CheckSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1496 nBalanceInQuestion = 0;
1497 CRITICAL_BLOCK(cs_wallet)
1499 vector<const CWalletTx*> vCoins;
1500 vCoins.reserve(mapWallet.size());
1501 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1502 vCoins.push_back(&(*it).second);
1505 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
1507 // Find the corresponding transaction index
1509 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1511 for (int n=0; n < pcoin->vout.size(); n++)
1513 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1515 printf("CheckSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1517 nBalanceInQuestion += pcoin->vout[n].nValue;
1519 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1521 printf("CheckSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1523 nBalanceInQuestion += pcoin->vout[n].nValue;
1528 return (nMismatchFound == 0);
1531 // ppcoin: fix wallet spent state according to txindex
1532 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1535 nBalanceInQuestion = 0;
1536 CRITICAL_BLOCK(cs_wallet)
1538 vector<CWalletTx*> vCoins;
1539 vCoins.reserve(mapWallet.size());
1540 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1541 vCoins.push_back(&(*it).second);
1544 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
1546 // Find the corresponding transaction index
1548 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1550 for (int n=0; n < pcoin->vout.size(); n++)
1552 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1554 printf("FixSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1556 nBalanceInQuestion += pcoin->vout[n].nValue;
1557 pcoin->MarkUnspent(n);
1558 pcoin->WriteToDisk();
1560 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1562 printf("FixSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1564 nBalanceInQuestion += pcoin->vout[n].nValue;
1565 pcoin->MarkSpent(n);
1566 pcoin->WriteToDisk();
1573 // ppcoin: disable transaction (only for coinstake)
1574 void CWallet::DisableTransaction(const CTransaction &tx)
1576 if (!tx.IsCoinStake() || !IsFromMe(tx))
1577 return; // only disconnecting coinstake requires marking input unspent
1578 CRITICAL_BLOCK(cs_wallet)
1580 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1582 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
1583 if (mi != mapWallet.end())
1585 CWalletTx& prev = (*mi).second;
1586 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
1588 prev.MarkUnspent(txin.prevout.n);
1596 vector<unsigned char> CReserveKey::GetReservedKey()
1601 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1603 vchPubKey = keypool.vchPubKey;
1606 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1607 vchPubKey = pwallet->vchDefaultKey;
1610 assert(!vchPubKey.empty());
1614 void CReserveKey::KeepKey()
1617 pwallet->KeepKey(nIndex);
1622 void CReserveKey::ReturnKey()
1625 pwallet->ReturnKey(nIndex);