1 // Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include "cryptopp/sha.h"
13 //////////////////////////////////////////////////////////////////////////////
18 bool CWallet::AddKey(const CKey& key)
20 if (!CCryptoKeyStore::AddKey(key))
25 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
28 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
30 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
34 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
37 bool CWallet::Unlock(const string& strWalletPassphrase)
39 CRITICAL_BLOCK(cs_vMasterKey)
45 CKeyingMaterial vMasterKey;
47 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
49 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
51 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
53 if (CCryptoKeyStore::Unlock(vMasterKey))
60 bool CWallet::ChangeWalletPassphrase(const string& strOldWalletPassphrase, const string& strNewWalletPassphrase)
62 CRITICAL_BLOCK(cs_vMasterKey)
64 bool fWasLocked = IsLocked();
69 CKeyingMaterial vMasterKey;
70 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
72 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
74 if(!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
76 if (CCryptoKeyStore::Unlock(vMasterKey))
78 int64 nStartTime = GetTimeMillis();
79 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
80 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
82 nStartTime = GetTimeMillis();
83 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
84 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
86 if (pMasterKey.second.nDeriveIterations < 25000)
87 pMasterKey.second.nDeriveIterations = 25000;
89 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
91 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
93 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
95 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
105 bool CWallet::EncryptWallet(const string& strWalletPassphrase)
107 //TODO: use db commits
108 CRITICAL_BLOCK(cs_mapPubKeys)
109 CRITICAL_BLOCK(cs_KeyStore)
110 CRITICAL_BLOCK(cs_vMasterKey)
115 CKeyingMaterial vMasterKey;
116 RandAddSeedPerfmon();
118 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
119 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
121 CMasterKey kMasterKey;
123 RandAddSeedPerfmon();
124 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
125 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
128 int64 nStartTime = GetTimeMillis();
129 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
130 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
132 nStartTime = GetTimeMillis();
133 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
134 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
136 if (kMasterKey.nDeriveIterations < 25000)
137 kMasterKey.nDeriveIterations = 25000;
139 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
141 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
143 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
146 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
150 CWalletDB(strWalletFile).WriteMasterKey(nMasterKeyMaxID, kMasterKey);
154 if (!EncryptKeys(vMasterKey))
155 exit(1); //We now probably have half of our keys encrypted, and half not...die and let the user ask someone with experience to recover their wallet.
162 void CWallet::WalletUpdateSpent(const CTransaction &tx)
164 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
165 // Update the wallet spent flag if it doesn't know due to wallet.dat being
166 // restored from backup or the user making copies of wallet.dat.
167 CRITICAL_BLOCK(cs_mapWallet)
169 BOOST_FOREACH(const CTxIn& txin, tx.vin)
171 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
172 if (mi != mapWallet.end())
174 CWalletTx& wtx = (*mi).second;
175 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
177 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
178 wtx.MarkSpent(txin.prevout.n);
180 vWalletUpdated.push_back(txin.prevout.hash);
187 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
189 uint256 hash = wtxIn.GetHash();
190 CRITICAL_BLOCK(cs_mapWallet)
192 // Inserts only if not already there, returns tx inserted or tx found
193 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
194 CWalletTx& wtx = (*ret.first).second;
196 bool fInsertedNew = ret.second;
198 wtx.nTimeReceived = GetAdjustedTime();
200 bool fUpdated = false;
204 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
206 wtx.hashBlock = wtxIn.hashBlock;
209 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
211 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
212 wtx.nIndex = wtxIn.nIndex;
215 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
217 wtx.fFromMe = wtxIn.fFromMe;
220 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
224 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
227 if (fInsertedNew || fUpdated)
228 if (!wtx.WriteToDisk())
231 // If default receiving address gets used, replace it with a new one
232 CScript scriptDefaultKey;
233 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
234 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
236 if (txout.scriptPubKey == scriptDefaultKey)
237 SetDefaultKey(GetOrReuseKeyFromPool());
241 vWalletUpdated.push_back(hash);
243 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
244 WalletUpdateSpent(wtx);
252 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
254 uint256 hash = tx.GetHash();
255 bool fExisted = mapWallet.count(hash);
256 if (fExisted && !fUpdate) return false;
257 if (fExisted || IsMine(tx) || IsFromMe(tx))
259 CWalletTx wtx(this,tx);
260 // Get merkle branch if transaction was found in a block
262 wtx.SetMerkleBranch(pblock);
263 return AddToWallet(wtx);
266 WalletUpdateSpent(tx);
270 bool CWallet::EraseFromWallet(uint256 hash)
274 CRITICAL_BLOCK(cs_mapWallet)
276 if (mapWallet.erase(hash))
277 CWalletDB(strWalletFile).EraseTx(hash);
283 bool CWallet::IsMine(const CTxIn &txin) const
285 CRITICAL_BLOCK(cs_mapWallet)
287 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
288 if (mi != mapWallet.end())
290 const CWalletTx& prev = (*mi).second;
291 if (txin.prevout.n < prev.vout.size())
292 if (IsMine(prev.vout[txin.prevout.n]))
299 int64 CWallet::GetDebit(const CTxIn &txin) const
301 CRITICAL_BLOCK(cs_mapWallet)
303 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
304 if (mi != mapWallet.end())
306 const CWalletTx& prev = (*mi).second;
307 if (txin.prevout.n < prev.vout.size())
308 if (IsMine(prev.vout[txin.prevout.n]))
309 return prev.vout[txin.prevout.n].nValue;
315 int64 CWalletTx::GetTxTime() const
317 if (!fTimeReceivedIsTxTime && hashBlock != 0)
319 // If we did not receive the transaction directly, we rely on the block's
320 // time to figure out when it happened. We use the median over a range
321 // of blocks to try to filter out inaccurate block times.
322 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
323 if (mi != mapBlockIndex.end())
325 CBlockIndex* pindex = (*mi).second;
327 return pindex->GetMedianTime();
330 return nTimeReceived;
333 int CWalletTx::GetRequestCount() const
335 // Returns -1 if it wasn't being tracked
337 CRITICAL_BLOCK(pwallet->cs_mapRequestCount)
344 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
345 if (mi != pwallet->mapRequestCount.end())
346 nRequests = (*mi).second;
351 // Did anyone request this transaction?
352 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
353 if (mi != pwallet->mapRequestCount.end())
355 nRequests = (*mi).second;
357 // How about the block it's in?
358 if (nRequests == 0 && hashBlock != 0)
360 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
361 if (mi != pwallet->mapRequestCount.end())
362 nRequests = (*mi).second;
364 nRequests = 1; // If it's in someone else's block it must have got out
372 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
373 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
375 nGeneratedImmature = nGeneratedMature = nFee = 0;
376 listReceived.clear();
378 strSentAccount = strFromAccount;
382 if (GetBlocksToMaturity() > 0)
383 nGeneratedImmature = pwallet->GetCredit(*this);
385 nGeneratedMature = GetCredit();
390 int64 nDebit = GetDebit();
391 if (nDebit > 0) // debit>0 means we signed/sent this transaction
393 int64 nValueOut = GetValueOut();
394 nFee = nDebit - nValueOut;
397 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
398 // but non-standard clients might (so return a list of address/amount pairs)
399 BOOST_FOREACH(const CTxOut& txout, vout)
403 vector<unsigned char> vchPubKey;
404 if (ExtractHash160(txout.scriptPubKey, hash160))
405 address = Hash160ToAddress(hash160);
406 else if (ExtractPubKey(txout.scriptPubKey, NULL, vchPubKey))
407 address = PubKeyToAddress(vchPubKey);
410 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
411 this->GetHash().ToString().c_str());
412 address = " unknown ";
415 // Don't report 'change' txouts
416 if (nDebit > 0 && pwallet->IsChange(txout))
420 listSent.push_back(make_pair(address, txout.nValue));
422 if (pwallet->IsMine(txout))
423 listReceived.push_back(make_pair(address, txout.nValue));
428 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
429 int64& nSent, int64& nFee) const
431 nGenerated = nReceived = nSent = nFee = 0;
433 int64 allGeneratedImmature, allGeneratedMature, allFee;
434 allGeneratedImmature = allGeneratedMature = allFee = 0;
435 string strSentAccount;
436 list<pair<string, int64> > listReceived;
437 list<pair<string, int64> > listSent;
438 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
440 if (strAccount == "")
441 nGenerated = allGeneratedMature;
442 if (strAccount == strSentAccount)
444 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
448 CRITICAL_BLOCK(pwallet->cs_mapAddressBook)
450 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
452 if (pwallet->mapAddressBook.count(r.first))
454 map<string, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
455 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
456 nReceived += r.second;
458 else if (strAccount.empty())
460 nReceived += r.second;
466 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
470 const int COPY_DEPTH = 3;
471 if (SetMerkleBranch() < COPY_DEPTH)
473 vector<uint256> vWorkQueue;
474 BOOST_FOREACH(const CTxIn& txin, vin)
475 vWorkQueue.push_back(txin.prevout.hash);
477 // This critsect is OK because txdb is already open
478 CRITICAL_BLOCK(pwallet->cs_mapWallet)
480 map<uint256, const CMerkleTx*> mapWalletPrev;
481 set<uint256> setAlreadyDone;
482 for (int i = 0; i < vWorkQueue.size(); i++)
484 uint256 hash = vWorkQueue[i];
485 if (setAlreadyDone.count(hash))
487 setAlreadyDone.insert(hash);
490 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
491 if (mi != pwallet->mapWallet.end())
494 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
495 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
497 else if (mapWalletPrev.count(hash))
499 tx = *mapWalletPrev[hash];
501 else if (!fClient && txdb.ReadDiskTx(hash, tx))
507 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
511 int nDepth = tx.SetMerkleBranch();
512 vtxPrev.push_back(tx);
514 if (nDepth < COPY_DEPTH)
515 BOOST_FOREACH(const CTxIn& txin, tx.vin)
516 vWorkQueue.push_back(txin.prevout.hash);
521 reverse(vtxPrev.begin(), vtxPrev.end());
524 bool CWalletTx::WriteToDisk()
526 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
529 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
533 CBlockIndex* pindex = pindexStart;
534 CRITICAL_BLOCK(cs_mapWallet)
539 block.ReadFromDisk(pindex, true);
540 BOOST_FOREACH(CTransaction& tx, block.vtx)
542 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
545 pindex = pindex->pnext;
551 void CWallet::ReacceptWalletTransactions()
555 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
558 vector<CDiskTxPos> vMissingTx;
559 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
561 CWalletTx& wtx = item.second;
562 if (wtx.IsCoinBase() && wtx.IsSpent(0))
566 bool fUpdated = false;
567 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
569 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
570 if (txindex.vSpent.size() != wtx.vout.size())
572 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
575 for (int i = 0; i < txindex.vSpent.size(); i++)
579 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
583 vMissingTx.push_back(txindex.vSpent[i]);
588 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
595 // Reaccept any txes of ours that aren't already in a block
596 if (!wtx.IsCoinBase())
597 wtx.AcceptWalletTransaction(txdb, false);
600 if (!vMissingTx.empty())
602 // TODO: optimize this to scan just part of the block chain?
603 if (ScanForWalletTransactions(pindexGenesisBlock))
604 fRepeat = true; // Found missing transactions: re-do Reaccept.
609 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
611 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
613 if (!tx.IsCoinBase())
615 uint256 hash = tx.GetHash();
616 if (!txdb.ContainsTx(hash))
617 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
622 uint256 hash = GetHash();
623 if (!txdb.ContainsTx(hash))
625 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
626 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
631 void CWalletTx::RelayWalletTransaction()
634 RelayWalletTransaction(txdb);
637 void CWallet::ResendWalletTransactions()
639 // Do this infrequently and randomly to avoid giving away
640 // that these are our transactions.
641 static int64 nNextTime;
642 if (GetTime() < nNextTime)
644 bool fFirst = (nNextTime == 0);
645 nNextTime = GetTime() + GetRand(30 * 60);
649 // Only do it if there's been a new block since last time
650 static int64 nLastTime;
651 if (nTimeBestReceived < nLastTime)
653 nLastTime = GetTime();
655 // Rebroadcast any of our txes that aren't in a block yet
656 printf("ResendWalletTransactions()\n");
658 CRITICAL_BLOCK(cs_mapWallet)
660 // Sort them in chronological order
661 multimap<unsigned int, CWalletTx*> mapSorted;
662 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
664 CWalletTx& wtx = item.second;
665 // Don't rebroadcast until it's had plenty of time that
666 // it should have gotten in already by now.
667 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
668 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
670 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
672 CWalletTx& wtx = *item.second;
673 wtx.RelayWalletTransaction(txdb);
683 //////////////////////////////////////////////////////////////////////////////
689 int64 CWallet::GetBalance() const
691 int64 nStart = GetTimeMillis();
694 CRITICAL_BLOCK(cs_mapWallet)
696 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
698 const CWalletTx* pcoin = &(*it).second;
699 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
701 nTotal += pcoin->GetAvailableCredit();
705 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
710 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
715 // List of values less than target
716 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
717 coinLowestLarger.first = INT64_MAX;
718 coinLowestLarger.second.first = NULL;
719 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
720 int64 nTotalLower = 0;
722 CRITICAL_BLOCK(cs_mapWallet)
724 vector<const CWalletTx*> vCoins;
725 vCoins.reserve(mapWallet.size());
726 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
727 vCoins.push_back(&(*it).second);
728 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
730 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
732 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
735 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
738 int nDepth = pcoin->GetDepthInMainChain();
739 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
742 for (int i = 0; i < pcoin->vout.size(); i++)
744 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
747 int64 n = pcoin->vout[i].nValue;
752 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
754 if (n == nTargetValue)
756 setCoinsRet.insert(coin.second);
757 nValueRet += coin.first;
760 else if (n < nTargetValue + CENT)
762 vValue.push_back(coin);
765 else if (n < coinLowestLarger.first)
767 coinLowestLarger = coin;
773 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
775 for (int i = 0; i < vValue.size(); ++i)
777 setCoinsRet.insert(vValue[i].second);
778 nValueRet += vValue[i].first;
783 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
785 if (coinLowestLarger.second.first == NULL)
787 setCoinsRet.insert(coinLowestLarger.second);
788 nValueRet += coinLowestLarger.first;
792 if (nTotalLower >= nTargetValue + CENT)
793 nTargetValue += CENT;
795 // Solve subset sum by stochastic approximation
796 sort(vValue.rbegin(), vValue.rend());
797 vector<char> vfIncluded;
798 vector<char> vfBest(vValue.size(), true);
799 int64 nBest = nTotalLower;
801 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
803 vfIncluded.assign(vValue.size(), false);
805 bool fReachedTarget = false;
806 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
808 for (int i = 0; i < vValue.size(); i++)
810 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
812 nTotal += vValue[i].first;
813 vfIncluded[i] = true;
814 if (nTotal >= nTargetValue)
816 fReachedTarget = true;
822 nTotal -= vValue[i].first;
823 vfIncluded[i] = false;
830 // If the next larger is still closer, return it
831 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
833 setCoinsRet.insert(coinLowestLarger.second);
834 nValueRet += coinLowestLarger.first;
837 for (int i = 0; i < vValue.size(); i++)
840 setCoinsRet.insert(vValue[i].second);
841 nValueRet += vValue[i].first;
845 printf("SelectCoins() best subset: ");
846 for (int i = 0; i < vValue.size(); i++)
848 printf("%s ", FormatMoney(vValue[i].first).c_str());
849 printf("total %s\n", FormatMoney(nBest).c_str());
855 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
857 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
858 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
859 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
865 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
868 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
874 if (vecSend.empty() || nValue < 0)
877 wtxNew.pwallet = this;
879 CRITICAL_BLOCK(cs_main)
881 // txdb must be opened before the mapWallet lock
883 CRITICAL_BLOCK(cs_mapWallet)
885 nFeeRet = nTransactionFee;
890 wtxNew.fFromMe = true;
892 int64 nTotalValue = nValue + nFeeRet;
893 double dPriority = 0;
894 // vouts to the payees
895 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
896 wtxNew.vout.push_back(CTxOut(s.second, s.first));
898 // Choose coins to use
899 set<pair<const CWalletTx*,unsigned int> > setCoins;
901 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
903 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
905 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
906 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
909 // Fill a vout back to self with any change
910 int64 nChange = nValueIn - nTotalValue;
913 // Note: We use a new key here to keep it from being obvious which side is the change.
914 // The drawback is that by not reusing a previous key, the change may be lost if a
915 // backup is restored, if the backup doesn't have the new private key for the change.
916 // If we reused the old key, it would be possible to add code to look for and
917 // rediscover unknown transactions that were written with keys of ours to recover
918 // post-backup change.
920 // Reserve a new key pair from key pool
921 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
922 // assert(mapKeys.count(vchPubKey));
924 // Fill a vout to ourself, using same address type as the payment
925 CScript scriptChange;
926 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
927 scriptChange.SetBitcoinAddress(vchPubKey);
929 scriptChange << vchPubKey << OP_CHECKSIG;
931 // Insert change txn at random position:
932 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
933 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
936 reservekey.ReturnKey();
939 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
940 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
944 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
945 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
949 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
950 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
954 // Check that enough fee is included
955 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
956 bool fAllowFree = CTransaction::AllowFree(dPriority);
957 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
958 if (nFeeRet < max(nPayFee, nMinFee))
960 nFeeRet = max(nPayFee, nMinFee);
964 // Fill vtxPrev by copying from previous transactions vtxPrev
965 wtxNew.AddSupportingTransactions(txdb);
966 wtxNew.fTimeReceivedIsTxTime = true;
975 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
977 vector< pair<CScript, int64> > vecSend;
978 vecSend.push_back(make_pair(scriptPubKey, nValue));
979 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
982 // Call after CreateTransaction unless you want to abort
983 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
985 CRITICAL_BLOCK(cs_main)
987 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
988 CRITICAL_BLOCK(cs_mapWallet)
990 // This is only to keep the database open to defeat the auto-flush for the
991 // duration of this scope. This is the only place where this optimization
992 // maybe makes sense; please don't do it anywhere else.
993 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
995 // Take key pair from key pool so it won't be used again
996 reservekey.KeepKey();
998 // Add tx to wallet, because if it has change it's also ours,
999 // otherwise just for transaction history.
1000 AddToWallet(wtxNew);
1002 // Mark old coins as spent
1003 set<CWalletTx*> setCoins;
1004 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1006 CWalletTx &coin = mapWallet[txin.prevout.hash];
1007 coin.pwallet = this;
1008 coin.MarkSpent(txin.prevout.n);
1010 vWalletUpdated.push_back(coin.GetHash());
1017 // Track how many getdata requests our transaction gets
1018 CRITICAL_BLOCK(cs_mapRequestCount)
1019 mapRequestCount[wtxNew.GetHash()] = 0;
1022 if (!wtxNew.AcceptToMemoryPool())
1024 // This must not fail. The transaction has already been signed and recorded.
1025 printf("CommitTransaction() : Error: Transaction not valid");
1028 wtxNew.RelayWalletTransaction();
1037 // requires cs_main lock
1038 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1040 CReserveKey reservekey(this);
1042 CRITICAL_BLOCK(cs_vMasterKey)
1046 string strError = _("Error: Wallet locked, unable to create transaction ");
1047 printf("SendMoney() : %s", strError.c_str());
1050 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1053 if (nValue + nFeeRequired > GetBalance())
1054 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());
1056 strError = _("Error: Transaction creation failed ");
1057 printf("SendMoney() : %s", strError.c_str());
1062 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1065 if (!CommitTransaction(wtxNew, reservekey))
1066 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.");
1074 // requires cs_main lock
1075 string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1079 return _("Invalid amount");
1080 if (nValue + nTransactionFee > GetBalance())
1081 return _("Insufficient funds");
1083 // Parse bitcoin address
1084 CScript scriptPubKey;
1085 if (!scriptPubKey.SetBitcoinAddress(strAddress))
1086 return _("Invalid bitcoin address");
1088 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1094 bool CWallet::LoadWallet(bool& fFirstRunRet)
1098 fFirstRunRet = false;
1099 if (!CWalletDB(strWalletFile,"cr+").LoadWallet(this))
1101 fFirstRunRet = vchDefaultKey.empty();
1103 if (!HaveKey(vchDefaultKey))
1105 // Create new keyUser and set as default key
1106 RandAddSeedPerfmon();
1108 SetDefaultKey(GetOrReuseKeyFromPool());
1109 if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))
1113 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1118 bool CWallet::SetAddressBookName(const string& strAddress, const string& strName)
1120 mapAddressBook[strAddress] = strName;
1123 return CWalletDB(strWalletFile).WriteName(strAddress, strName);
1126 bool CWallet::DelAddressBookName(const string& strAddress)
1128 mapAddressBook.erase(strAddress);
1131 return CWalletDB(strWalletFile).EraseName(strAddress);
1135 void CWallet::PrintWallet(const CBlock& block)
1137 CRITICAL_BLOCK(cs_mapWallet)
1139 if (mapWallet.count(block.vtx[0].GetHash()))
1141 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1142 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1148 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1150 CRITICAL_BLOCK(cs_mapWallet)
1152 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1153 if (mi != mapWallet.end())
1162 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1166 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1169 vchDefaultKey = vchPubKey;
1173 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1175 if (!pwallet->fFileBacked)
1177 strWalletFileOut = pwallet->strWalletFile;
1181 bool CWallet::TopUpKeyPool()
1183 CRITICAL_BLOCK(cs_main)
1184 CRITICAL_BLOCK(cs_mapWallet)
1185 CRITICAL_BLOCK(cs_setKeyPool)
1186 CRITICAL_BLOCK(cs_vMasterKey)
1191 CWalletDB walletdb(strWalletFile);
1194 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1195 while (setKeyPool.size() < nTargetSize+1)
1198 if (!setKeyPool.empty())
1199 nEnd = *(--setKeyPool.end()) + 1;
1200 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1201 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1202 setKeyPool.insert(nEnd);
1203 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1209 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1212 keypool.vchPubKey.clear();
1213 CRITICAL_BLOCK(cs_main)
1214 CRITICAL_BLOCK(cs_mapWallet)
1215 CRITICAL_BLOCK(cs_setKeyPool)
1220 // Get the oldest key
1221 if(setKeyPool.empty())
1224 CWalletDB walletdb(strWalletFile);
1226 nIndex = *(setKeyPool.begin());
1227 setKeyPool.erase(setKeyPool.begin());
1228 if (!walletdb.ReadPool(nIndex, keypool))
1229 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1230 if (!HaveKey(keypool.vchPubKey))
1231 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1232 assert(!keypool.vchPubKey.empty());
1233 printf("keypool reserve %"PRI64d"\n", nIndex);
1237 void CWallet::KeepKey(int64 nIndex)
1239 // Remove from key pool
1242 CWalletDB walletdb(strWalletFile);
1243 CRITICAL_BLOCK(cs_main)
1245 walletdb.ErasePool(nIndex);
1248 printf("keypool keep %"PRI64d"\n", nIndex);
1251 void CWallet::ReturnKey(int64 nIndex)
1253 // Return to key pool
1254 CRITICAL_BLOCK(cs_setKeyPool)
1255 setKeyPool.insert(nIndex);
1256 printf("keypool return %"PRI64d"\n", nIndex);
1259 vector<unsigned char> CWallet::GetOrReuseKeyFromPool()
1263 ReserveKeyFromKeyPool(nIndex, keypool);
1265 return vchDefaultKey;
1267 return keypool.vchPubKey;
1270 int64 CWallet::GetOldestKeyPoolTime()
1274 ReserveKeyFromKeyPool(nIndex, keypool);
1278 return keypool.nTime;
1281 vector<unsigned char> CReserveKey::GetReservedKey()
1286 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1287 vchPubKey = keypool.vchPubKey;
1289 assert(!vchPubKey.empty());
1293 void CReserveKey::KeepKey()
1296 pwallet->KeepKey(nIndex);
1301 void CReserveKey::ReturnKey()
1304 pwallet->ReturnKey(nIndex);