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.
14 //////////////////////////////////////////////////////////////////////////////
19 bool CWallet::AddKey(const CKey& key)
21 if (!CCryptoKeyStore::AddKey(key))
26 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
30 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
32 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
36 CRITICAL_BLOCK(cs_wallet)
38 if (pwalletdbEncryption)
39 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
41 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
46 // ppcoin: optional setting to create coinstake only when unlocked;
47 // serves to disable the trivial sendmoney when OS account compromised
48 bool fWalletUnlockStakeOnly = false;
50 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
56 CKeyingMaterial vMasterKey;
58 CRITICAL_BLOCK(cs_wallet)
59 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
61 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
63 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
65 if (CCryptoKeyStore::Unlock(vMasterKey))
71 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
73 bool fWasLocked = IsLocked();
75 CRITICAL_BLOCK(cs_wallet)
80 CKeyingMaterial vMasterKey;
81 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
83 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
85 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
87 if (CCryptoKeyStore::Unlock(vMasterKey))
89 int64 nStartTime = GetTimeMillis();
90 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
91 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
93 nStartTime = GetTimeMillis();
94 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
95 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
97 if (pMasterKey.second.nDeriveIterations < 25000)
98 pMasterKey.second.nDeriveIterations = 25000;
100 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
102 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
104 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
106 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
118 // This class implements an addrIncoming entry that causes pre-0.4
119 // clients to crash on startup if reading a private-key-encrypted wallet.
120 class CCorruptAddress
125 if (nType & SER_DISK)
130 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
135 CKeyingMaterial vMasterKey;
136 RandAddSeedPerfmon();
138 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
139 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
141 CMasterKey kMasterKey;
143 RandAddSeedPerfmon();
144 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
145 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
148 int64 nStartTime = GetTimeMillis();
149 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
150 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
152 nStartTime = GetTimeMillis();
153 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
154 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
156 if (kMasterKey.nDeriveIterations < 25000)
157 kMasterKey.nDeriveIterations = 25000;
159 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
161 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
163 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
166 CRITICAL_BLOCK(cs_wallet)
168 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
171 pwalletdbEncryption = new CWalletDB(strWalletFile);
172 pwalletdbEncryption->TxnBegin();
173 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
176 if (!EncryptKeys(vMasterKey))
179 pwalletdbEncryption->TxnAbort();
180 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.
185 CCorruptAddress corruptAddress;
186 pwalletdbEncryption->WriteSetting("addrIncoming", corruptAddress);
187 if (!pwalletdbEncryption->TxnCommit())
188 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.
190 pwalletdbEncryption->Close();
191 pwalletdbEncryption = NULL;
195 Unlock(strWalletPassphrase);
199 // Need to completely rewrite the wallet file; if we don't, bdb might keep
200 // bits of the unencrypted private key in slack space in the database file.
201 CDB::Rewrite(strWalletFile);
207 void CWallet::WalletUpdateSpent(const CTransaction &tx)
209 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
210 // Update the wallet spent flag if it doesn't know due to wallet.dat being
211 // restored from backup or the user making copies of wallet.dat.
212 CRITICAL_BLOCK(cs_wallet)
214 BOOST_FOREACH(const CTxIn& txin, tx.vin)
216 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
217 if (mi != mapWallet.end())
219 CWalletTx& wtx = (*mi).second;
220 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
222 printf("WalletUpdateSpent found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
223 wtx.MarkSpent(txin.prevout.n);
225 vWalletUpdated.push_back(txin.prevout.hash);
232 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
234 uint256 hash = wtxIn.GetHash();
235 CRITICAL_BLOCK(cs_wallet)
237 // Inserts only if not already there, returns tx inserted or tx found
238 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
239 CWalletTx& wtx = (*ret.first).second;
241 bool fInsertedNew = ret.second;
243 wtx.nTimeReceived = GetAdjustedTime();
245 bool fUpdated = false;
249 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
251 wtx.hashBlock = wtxIn.hashBlock;
254 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
256 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
257 wtx.nIndex = wtxIn.nIndex;
260 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
262 wtx.fFromMe = wtxIn.fFromMe;
265 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
269 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
272 if (fInsertedNew || fUpdated)
273 if (!wtx.WriteToDisk())
276 // If default receiving address gets used, replace it with a new one
277 CScript scriptDefaultKey;
278 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
279 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
281 if (txout.scriptPubKey == scriptDefaultKey)
283 std::vector<unsigned char> newDefaultKey;
284 if (GetKeyFromPool(newDefaultKey, false))
286 SetDefaultKey(newDefaultKey);
287 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
293 vWalletUpdated.push_back(hash);
295 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
296 WalletUpdateSpent(wtx);
304 // Add a transaction to the wallet, or update it.
305 // pblock is optional, but should be provided if the transaction is known to be in a block.
306 // If fUpdate is true, existing transactions will be updated.
307 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
309 uint256 hash = tx.GetHash();
310 CRITICAL_BLOCK(cs_wallet)
312 bool fExisted = mapWallet.count(hash);
313 if (fExisted && !fUpdate) return false;
314 if (fExisted || IsMine(tx) || IsFromMe(tx))
316 CWalletTx wtx(this,tx);
317 // Get merkle branch if transaction was found in a block
319 wtx.SetMerkleBranch(pblock);
320 return AddToWallet(wtx);
323 WalletUpdateSpent(tx);
328 bool CWallet::EraseFromWallet(uint256 hash)
332 CRITICAL_BLOCK(cs_wallet)
334 if (mapWallet.erase(hash))
335 CWalletDB(strWalletFile).EraseTx(hash);
341 bool CWallet::IsMine(const CTxIn &txin) const
343 CRITICAL_BLOCK(cs_wallet)
345 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
346 if (mi != mapWallet.end())
348 const CWalletTx& prev = (*mi).second;
349 if (txin.prevout.n < prev.vout.size())
350 if (IsMine(prev.vout[txin.prevout.n]))
357 int64 CWallet::GetDebit(const CTxIn &txin) const
359 CRITICAL_BLOCK(cs_wallet)
361 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
362 if (mi != mapWallet.end())
364 const CWalletTx& prev = (*mi).second;
365 if (txin.prevout.n < prev.vout.size())
366 if (IsMine(prev.vout[txin.prevout.n]))
367 return prev.vout[txin.prevout.n].nValue;
373 int64 CWalletTx::GetTxTime() const
375 return nTimeReceived;
378 int CWalletTx::GetRequestCount() const
380 // Returns -1 if it wasn't being tracked
382 CRITICAL_BLOCK(pwallet->cs_wallet)
384 if (IsCoinBase() || IsCoinStake())
389 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
390 if (mi != pwallet->mapRequestCount.end())
391 nRequests = (*mi).second;
396 // Did anyone request this transaction?
397 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
398 if (mi != pwallet->mapRequestCount.end())
400 nRequests = (*mi).second;
402 // How about the block it's in?
403 if (nRequests == 0 && hashBlock != 0)
405 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
406 if (mi != pwallet->mapRequestCount.end())
407 nRequests = (*mi).second;
409 nRequests = 1; // If it's in someone else's block it must have got out
417 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
418 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
420 nGeneratedImmature = nGeneratedMature = nFee = 0;
421 listReceived.clear();
423 strSentAccount = strFromAccount;
425 if (IsCoinBase() || IsCoinStake())
427 if (GetBlocksToMaturity() > 0)
428 nGeneratedImmature = pwallet->GetCredit(*this);
430 nGeneratedMature = GetCredit();
435 int64 nDebit = GetDebit();
436 if (nDebit > 0) // debit>0 means we signed/sent this transaction
438 int64 nValueOut = GetValueOut();
439 nFee = nDebit - nValueOut;
442 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
443 // but non-standard clients might (so return a list of address/amount pairs)
444 BOOST_FOREACH(const CTxOut& txout, vout)
446 CBitcoinAddress address;
447 vector<unsigned char> vchPubKey;
448 if (!ExtractAddress(txout.scriptPubKey, NULL, address))
450 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
451 this->GetHash().ToString().c_str());
452 address = " unknown ";
455 // Don't report 'change' txouts
456 if (nDebit > 0 && pwallet->IsChange(txout))
460 listSent.push_back(make_pair(address, txout.nValue));
462 if (pwallet->IsMine(txout))
463 listReceived.push_back(make_pair(address, txout.nValue));
468 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
469 int64& nSent, int64& nFee) const
471 nGenerated = nReceived = nSent = nFee = 0;
473 int64 allGeneratedImmature, allGeneratedMature, allFee;
474 allGeneratedImmature = allGeneratedMature = allFee = 0;
475 string strSentAccount;
476 list<pair<CBitcoinAddress, int64> > listReceived;
477 list<pair<CBitcoinAddress, int64> > listSent;
478 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
480 if (strAccount == "")
481 nGenerated = allGeneratedMature;
482 if (strAccount == strSentAccount)
484 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
488 CRITICAL_BLOCK(pwallet->cs_wallet)
490 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
492 if (pwallet->mapAddressBook.count(r.first))
494 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
495 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
496 nReceived += r.second;
498 else if (strAccount.empty())
500 nReceived += r.second;
506 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
510 const int COPY_DEPTH = 3;
511 if (SetMerkleBranch() < COPY_DEPTH)
513 vector<uint256> vWorkQueue;
514 BOOST_FOREACH(const CTxIn& txin, vin)
515 vWorkQueue.push_back(txin.prevout.hash);
517 // This critsect is OK because txdb is already open
518 CRITICAL_BLOCK(pwallet->cs_wallet)
520 map<uint256, const CMerkleTx*> mapWalletPrev;
521 set<uint256> setAlreadyDone;
522 for (int i = 0; i < vWorkQueue.size(); i++)
524 uint256 hash = vWorkQueue[i];
525 if (setAlreadyDone.count(hash))
527 setAlreadyDone.insert(hash);
530 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
531 if (mi != pwallet->mapWallet.end())
534 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
535 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
537 else if (mapWalletPrev.count(hash))
539 tx = *mapWalletPrev[hash];
541 else if (!fClient && txdb.ReadDiskTx(hash, tx))
547 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
551 int nDepth = tx.SetMerkleBranch();
552 vtxPrev.push_back(tx);
554 if (nDepth < COPY_DEPTH)
555 BOOST_FOREACH(const CTxIn& txin, tx.vin)
556 vWorkQueue.push_back(txin.prevout.hash);
561 reverse(vtxPrev.begin(), vtxPrev.end());
564 bool CWalletTx::WriteToDisk()
566 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
569 // Scan the block chain (starting in pindexStart) for transactions
570 // from or to us. If fUpdate is true, found transactions that already
571 // exist in the wallet will be updated.
572 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
576 CBlockIndex* pindex = pindexStart;
577 CRITICAL_BLOCK(cs_wallet)
582 block.ReadFromDisk(pindex, true);
583 BOOST_FOREACH(CTransaction& tx, block.vtx)
585 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
588 pindex = pindex->pnext;
594 void CWallet::ReacceptWalletTransactions()
598 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
601 vector<CDiskTxPos> vMissingTx;
602 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
604 CWalletTx& wtx = item.second;
605 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
609 bool fUpdated = false;
610 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
612 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
613 if (txindex.vSpent.size() != wtx.vout.size())
615 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
618 for (int i = 0; i < txindex.vSpent.size(); i++)
622 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
626 vMissingTx.push_back(txindex.vSpent[i]);
631 printf("ReacceptWalletTransactions found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
638 // Reaccept any txes of ours that aren't already in a block
639 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
640 wtx.AcceptWalletTransaction(txdb, false);
643 if (!vMissingTx.empty())
645 // TODO: optimize this to scan just part of the block chain?
646 if (ScanForWalletTransactions(pindexGenesisBlock))
647 fRepeat = true; // Found missing transactions: re-do Reaccept.
652 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
654 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
656 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
658 uint256 hash = tx.GetHash();
659 if (!txdb.ContainsTx(hash))
660 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
663 if (!(IsCoinBase() || IsCoinStake()))
665 uint256 hash = GetHash();
666 if (!txdb.ContainsTx(hash))
668 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
669 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
674 void CWalletTx::RelayWalletTransaction()
677 RelayWalletTransaction(txdb);
680 void CWallet::ResendWalletTransactions()
682 // Do this infrequently and randomly to avoid giving away
683 // that these are our transactions.
684 static int64 nNextTime;
685 if (GetTime() < nNextTime)
687 bool fFirst = (nNextTime == 0);
688 nNextTime = GetTime() + GetRand(30 * 60);
692 // Only do it if there's been a new block since last time
693 static int64 nLastTime;
694 if (nTimeBestReceived < nLastTime)
696 nLastTime = GetTime();
698 // Rebroadcast any of our txes that aren't in a block yet
699 printf("ResendWalletTransactions()\n");
701 CRITICAL_BLOCK(cs_wallet)
703 // Sort them in chronological order
704 multimap<unsigned int, CWalletTx*> mapSorted;
705 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
707 CWalletTx& wtx = item.second;
708 // Don't rebroadcast until it's had plenty of time that
709 // it should have gotten in already by now.
710 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
711 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
713 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
715 CWalletTx& wtx = *item.second;
716 wtx.RelayWalletTransaction(txdb);
726 //////////////////////////////////////////////////////////////////////////////
732 int64 CWallet::GetBalance() const
735 CRITICAL_BLOCK(cs_wallet)
737 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
739 const CWalletTx* pcoin = &(*it).second;
740 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
742 nTotal += pcoin->GetAvailableCredit();
749 int64 CWallet::GetUnconfirmedBalance() const
752 CRITICAL_BLOCK(cs_wallet)
754 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
756 const CWalletTx* pcoin = &(*it).second;
757 if (pcoin->IsFinal() && pcoin->IsConfirmed())
759 nTotal += pcoin->GetAvailableCredit();
765 // ppcoin: total coins staked (non-spendable until maturity)
766 int64 CWallet::GetStake() const
769 CRITICAL_BLOCK(cs_wallet)
771 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
773 const CWalletTx* pcoin = &(*it).second;
774 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
775 nTotal += CWallet::GetCredit(*pcoin);
781 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
786 // List of values less than target
787 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
788 coinLowestLarger.first = INT64_MAX;
789 coinLowestLarger.second.first = NULL;
790 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
791 int64 nTotalLower = 0;
793 CRITICAL_BLOCK(cs_wallet)
795 vector<const CWalletTx*> vCoins;
796 vCoins.reserve(mapWallet.size());
797 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
798 vCoins.push_back(&(*it).second);
799 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
801 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
803 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
806 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
809 int nDepth = pcoin->GetDepthInMainChain();
810 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
813 for (int i = 0; i < pcoin->vout.size(); i++)
815 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
818 if (pcoin->nTime > nSpendTime)
819 continue; // ppcoin: timestamp must not exceed spend time
821 int64 n = pcoin->vout[i].nValue;
826 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
828 if (n == nTargetValue)
830 setCoinsRet.insert(coin.second);
831 nValueRet += coin.first;
834 else if (n < nTargetValue + CENT)
836 vValue.push_back(coin);
839 else if (n < coinLowestLarger.first)
841 coinLowestLarger = coin;
847 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
849 for (int i = 0; i < vValue.size(); ++i)
851 setCoinsRet.insert(vValue[i].second);
852 nValueRet += vValue[i].first;
857 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
859 if (coinLowestLarger.second.first == NULL)
861 setCoinsRet.insert(coinLowestLarger.second);
862 nValueRet += coinLowestLarger.first;
866 if (nTotalLower >= nTargetValue + CENT)
867 nTargetValue += CENT;
869 // Solve subset sum by stochastic approximation
870 sort(vValue.rbegin(), vValue.rend());
871 vector<char> vfIncluded;
872 vector<char> vfBest(vValue.size(), true);
873 int64 nBest = nTotalLower;
875 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
877 vfIncluded.assign(vValue.size(), false);
879 bool fReachedTarget = false;
880 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
882 for (int i = 0; i < vValue.size(); i++)
884 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
886 nTotal += vValue[i].first;
887 vfIncluded[i] = true;
888 if (nTotal >= nTargetValue)
890 fReachedTarget = true;
896 nTotal -= vValue[i].first;
897 vfIncluded[i] = false;
904 // If the next larger is still closer, return it
905 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
907 setCoinsRet.insert(coinLowestLarger.second);
908 nValueRet += coinLowestLarger.first;
911 for (int i = 0; i < vValue.size(); i++)
914 setCoinsRet.insert(vValue[i].second);
915 nValueRet += vValue[i].first;
919 printf("SelectCoins() best subset: ");
920 for (int i = 0; i < vValue.size(); i++)
922 printf("%s ", FormatMoney(vValue[i].first).c_str());
923 printf("total %s\n", FormatMoney(nBest).c_str());
929 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
931 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
932 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
933 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
939 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
942 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
948 if (vecSend.empty() || nValue < 0)
951 wtxNew.pwallet = this;
953 CRITICAL_BLOCK(cs_main)
954 CRITICAL_BLOCK(cs_wallet)
956 // txdb must be opened before the mapWallet lock
959 nFeeRet = nTransactionFee;
964 wtxNew.fFromMe = true;
966 int64 nTotalValue = nValue + nFeeRet;
967 double dPriority = 0;
968 // vouts to the payees
969 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
970 wtxNew.vout.push_back(CTxOut(s.second, s.first));
972 // Choose coins to use
973 set<pair<const CWalletTx*,unsigned int> > setCoins;
975 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
977 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
979 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
980 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
983 int64 nChange = nValueIn - nValue - nFeeRet;
984 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
985 // or until nChange becomes zero
986 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
988 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
989 nChange -= nMoveToFee;
990 nFeeRet += nMoveToFee;
995 // Note: We use a new key here to keep it from being obvious which side is the change.
996 // The drawback is that by not reusing a previous key, the change may be lost if a
997 // backup is restored, if the backup doesn't have the new private key for the change.
998 // If we reused the old key, it would be possible to add code to look for and
999 // rediscover unknown transactions that were written with keys of ours to recover
1000 // post-backup change.
1002 // Reserve a new key pair from key pool
1003 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1004 // assert(mapKeys.count(vchPubKey));
1006 // Fill a vout to ourself, using same address type as the payment
1007 CScript scriptChange;
1008 if (vecSend[0].first.GetBitcoinAddress().IsValid())
1009 scriptChange.SetBitcoinAddress(vchPubKey);
1011 scriptChange << vchPubKey << OP_CHECKSIG;
1013 // Insert change txn at random position:
1014 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1015 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1018 reservekey.ReturnKey();
1021 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1022 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1026 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1027 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1031 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1032 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1034 dPriority /= nBytes;
1036 // Check that enough fee is included
1037 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1038 int64 nMinFee = wtxNew.GetMinFee(1, false);
1039 if (nFeeRet < max(nPayFee, nMinFee))
1041 nFeeRet = max(nPayFee, nMinFee);
1045 // Fill vtxPrev by copying from previous transactions vtxPrev
1046 wtxNew.AddSupportingTransactions(txdb);
1047 wtxNew.fTimeReceivedIsTxTime = true;
1056 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1058 vector< pair<CScript, int64> > vecSend;
1059 vecSend.push_back(make_pair(scriptPubKey, nValue));
1060 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1063 // ppcoin: create coin stake transaction
1064 bool CWallet::CreateCoinStake(CScript scriptPubKey, CTransaction& txNew)
1066 CRITICAL_BLOCK(cs_main)
1067 CRITICAL_BLOCK(cs_wallet)
1071 // Mark coin stake transaction
1072 CScript scriptEmpty;
1073 scriptEmpty.clear();
1074 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1075 // Choose coins to use
1076 int64 nBalance = GetBalance();
1077 if (nBalance <= nBalanceReserve)
1079 set<pair<const CWalletTx*,unsigned int> > setCoins;
1081 if (!SelectCoins(nBalance - nBalanceReserve, txNew.nTime, setCoins, nValueIn))
1083 if (setCoins.empty())
1086 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1088 nCredit += pcoin.first->vout[pcoin.second].nValue;
1089 // Only spend one tx for now
1092 if (nCredit > nBalance - nBalanceReserve)
1095 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1097 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1098 // Only spend one tx for now
1101 // Calculate coin age reward
1105 if (!txNew.GetCoinAge(txdb, nCoinAge))
1107 nCredit += GetProofOfStakeReward(nCoinAge);
1110 txNew.vout.push_back(CTxOut(nCredit, scriptPubKey));
1115 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1117 if (!SignSignature(*this, *coin.first, txNew, nIn++))
1119 // Only spend one tx for now
1126 // Call after CreateTransaction unless you want to abort
1127 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1129 CRITICAL_BLOCK(cs_main)
1130 CRITICAL_BLOCK(cs_wallet)
1132 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1134 // This is only to keep the database open to defeat the auto-flush for the
1135 // duration of this scope. This is the only place where this optimization
1136 // maybe makes sense; please don't do it anywhere else.
1137 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1139 // Take key pair from key pool so it won't be used again
1140 reservekey.KeepKey();
1142 // Add tx to wallet, because if it has change it's also ours,
1143 // otherwise just for transaction history.
1144 AddToWallet(wtxNew);
1146 // Mark old coins as spent
1147 set<CWalletTx*> setCoins;
1148 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1150 CWalletTx &coin = mapWallet[txin.prevout.hash];
1151 coin.pwallet = this;
1152 coin.MarkSpent(txin.prevout.n);
1154 vWalletUpdated.push_back(coin.GetHash());
1161 // Track how many getdata requests our transaction gets
1162 mapRequestCount[wtxNew.GetHash()] = 0;
1165 if (!wtxNew.AcceptToMemoryPool())
1167 // This must not fail. The transaction has already been signed and recorded.
1168 printf("CommitTransaction() : Error: Transaction not valid");
1171 wtxNew.RelayWalletTransaction();
1180 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1182 CReserveKey reservekey(this);
1187 string strError = _("Error: Wallet locked, unable to create transaction ");
1188 printf("SendMoney() : %s", strError.c_str());
1191 if (fWalletUnlockStakeOnly)
1193 string strError = _("Error: Wallet unlocked for coinstake only, unable to create transaction.");
1194 printf("SendMoney() : %s", strError.c_str());
1197 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1200 if (nValue + nFeeRequired > GetBalance())
1201 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());
1203 strError = _("Error: Transaction creation failed ");
1204 printf("SendMoney() : %s", strError.c_str());
1208 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1211 if (!CommitTransaction(wtxNew, reservekey))
1212 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.");
1220 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1224 return _("Invalid amount");
1225 if (nValue + nTransactionFee > GetBalance())
1226 return _("Insufficient funds");
1228 // Parse bitcoin address
1229 CScript scriptPubKey;
1230 scriptPubKey.SetBitcoinAddress(address);
1232 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1238 int CWallet::LoadWallet(bool& fFirstRunRet)
1242 fFirstRunRet = false;
1243 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1244 if (nLoadWalletRet == DB_NEED_REWRITE)
1246 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1249 // Note: can't top-up keypool here, because wallet is locked.
1250 // User will be prompted to unlock wallet the next operation
1251 // the requires a new key.
1253 nLoadWalletRet = DB_NEED_REWRITE;
1256 if (nLoadWalletRet != DB_LOAD_OK)
1257 return nLoadWalletRet;
1258 fFirstRunRet = vchDefaultKey.empty();
1260 if (!HaveKey(Hash160(vchDefaultKey)))
1262 // Create new keyUser and set as default key
1263 RandAddSeedPerfmon();
1265 std::vector<unsigned char> newDefaultKey;
1266 if (!GetKeyFromPool(newDefaultKey, false))
1267 return DB_LOAD_FAIL;
1268 SetDefaultKey(newDefaultKey);
1269 if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""))
1270 return DB_LOAD_FAIL;
1273 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1278 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1280 mapAddressBook[address] = strName;
1283 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1286 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1288 mapAddressBook.erase(address);
1291 return CWalletDB(strWalletFile).EraseName(address.ToString());
1295 void CWallet::PrintWallet(const CBlock& block)
1297 CRITICAL_BLOCK(cs_wallet)
1299 if (mapWallet.count(block.vtx[0].GetHash()))
1301 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1302 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1308 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1310 CRITICAL_BLOCK(cs_wallet)
1312 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1313 if (mi != mapWallet.end())
1322 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1326 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1329 vchDefaultKey = vchPubKey;
1333 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1335 if (!pwallet->fFileBacked)
1337 strWalletFileOut = pwallet->strWalletFile;
1342 // Mark old keypool keys as used,
1343 // and generate all new keys
1345 bool CWallet::NewKeyPool()
1347 CRITICAL_BLOCK(cs_wallet)
1349 CWalletDB walletdb(strWalletFile);
1350 BOOST_FOREACH(int64 nIndex, setKeyPool)
1351 walletdb.ErasePool(nIndex);
1357 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1358 for (int i = 0; i < nKeys; i++)
1361 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1362 setKeyPool.insert(nIndex);
1364 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1369 bool CWallet::TopUpKeyPool()
1371 CRITICAL_BLOCK(cs_wallet)
1376 CWalletDB walletdb(strWalletFile);
1379 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1380 while (setKeyPool.size() < nTargetSize+1)
1383 if (!setKeyPool.empty())
1384 nEnd = *(--setKeyPool.end()) + 1;
1385 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1386 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1387 setKeyPool.insert(nEnd);
1388 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1394 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1397 keypool.vchPubKey.clear();
1398 CRITICAL_BLOCK(cs_wallet)
1403 // Get the oldest key
1404 if(setKeyPool.empty())
1407 CWalletDB walletdb(strWalletFile);
1409 nIndex = *(setKeyPool.begin());
1410 setKeyPool.erase(setKeyPool.begin());
1411 if (!walletdb.ReadPool(nIndex, keypool))
1412 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1413 if (!HaveKey(Hash160(keypool.vchPubKey)))
1414 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1415 assert(!keypool.vchPubKey.empty());
1416 printf("keypool reserve %"PRI64d"\n", nIndex);
1420 void CWallet::KeepKey(int64 nIndex)
1422 // Remove from key pool
1425 CWalletDB walletdb(strWalletFile);
1426 walletdb.ErasePool(nIndex);
1428 printf("keypool keep %"PRI64d"\n", nIndex);
1431 void CWallet::ReturnKey(int64 nIndex)
1433 // Return to key pool
1434 CRITICAL_BLOCK(cs_wallet)
1435 setKeyPool.insert(nIndex);
1436 printf("keypool return %"PRI64d"\n", nIndex);
1439 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1443 CRITICAL_BLOCK(cs_wallet)
1445 ReserveKeyFromKeyPool(nIndex, keypool);
1448 if (fAllowReuse && !vchDefaultKey.empty())
1450 result = vchDefaultKey;
1453 if (IsLocked()) return false;
1454 result = GenerateNewKey();
1458 result = keypool.vchPubKey;
1463 int64 CWallet::GetOldestKeyPoolTime()
1467 ReserveKeyFromKeyPool(nIndex, keypool);
1471 return keypool.nTime;
1474 // ppcoin: check 'spent' consistency between wallet and txindex
1475 bool CWallet::CheckSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1478 nBalanceInQuestion = 0;
1479 CRITICAL_BLOCK(cs_wallet)
1481 vector<const CWalletTx*> vCoins;
1482 vCoins.reserve(mapWallet.size());
1483 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1484 vCoins.push_back(&(*it).second);
1487 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
1489 // Find the corresponding transaction index
1491 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1493 for (int n=0; n < pcoin->vout.size(); n++)
1495 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1497 printf("CheckSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1499 nBalanceInQuestion += pcoin->vout[n].nValue;
1501 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1503 printf("CheckSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1505 nBalanceInQuestion += pcoin->vout[n].nValue;
1510 return (nMismatchFound == 0);
1513 vector<unsigned char> CReserveKey::GetReservedKey()
1518 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1520 vchPubKey = keypool.vchPubKey;
1523 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1524 vchPubKey = pwallet->vchDefaultKey;
1527 assert(!vchPubKey.empty());
1531 void CReserveKey::KeepKey()
1534 pwallet->KeepKey(nIndex);
1539 void CReserveKey::ReturnKey()
1542 pwallet->ReturnKey(nIndex);