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 CRITICAL_BLOCK(cs_pwalletdbEncryption)
36 if (pwalletdbEncryption)
37 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
39 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
43 bool CWallet::Unlock(const string& strWalletPassphrase)
45 CRITICAL_BLOCK(cs_vMasterKey)
51 CKeyingMaterial vMasterKey;
53 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
55 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
57 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
59 if (CCryptoKeyStore::Unlock(vMasterKey))
66 bool CWallet::ChangeWalletPassphrase(const string& strOldWalletPassphrase, const string& strNewWalletPassphrase)
68 CRITICAL_BLOCK(cs_vMasterKey)
70 bool fWasLocked = IsLocked();
75 CKeyingMaterial vMasterKey;
76 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
78 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
80 if(!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
82 if (CCryptoKeyStore::Unlock(vMasterKey))
84 int64 nStartTime = GetTimeMillis();
85 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
86 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
88 nStartTime = GetTimeMillis();
89 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
90 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
92 if (pMasterKey.second.nDeriveIterations < 25000)
93 pMasterKey.second.nDeriveIterations = 25000;
95 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
97 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
99 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
101 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
112 // This class implements an addrIncoming entry that causes pre-0.4
113 // clients to crash on startup if reading a private-key-encrypted wallet.
114 class CCorruptAddress
119 if (nType & SER_DISK)
124 bool CWallet::EncryptWallet(const string& strWalletPassphrase)
126 CRITICAL_BLOCK(cs_mapPubKeys)
127 CRITICAL_BLOCK(cs_KeyStore)
128 CRITICAL_BLOCK(cs_vMasterKey)
129 CRITICAL_BLOCK(cs_pwalletdbEncryption)
134 CKeyingMaterial vMasterKey;
135 RandAddSeedPerfmon();
137 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
138 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
140 CMasterKey kMasterKey;
142 RandAddSeedPerfmon();
143 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
144 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
147 int64 nStartTime = GetTimeMillis();
148 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
149 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
151 nStartTime = GetTimeMillis();
152 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
153 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
155 if (kMasterKey.nDeriveIterations < 25000)
156 kMasterKey.nDeriveIterations = 25000;
158 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
160 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
162 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
165 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
168 pwalletdbEncryption = new CWalletDB(strWalletFile);
169 pwalletdbEncryption->TxnBegin();
170 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
173 if (!EncryptKeys(vMasterKey))
176 pwalletdbEncryption->TxnAbort();
177 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.
182 CCorruptAddress corruptAddress;
183 pwalletdbEncryption->WriteSetting("addrIncoming", corruptAddress);
184 if (!pwalletdbEncryption->TxnCommit())
185 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.
187 pwalletdbEncryption->Close();
188 pwalletdbEncryption = NULL;
196 void CWallet::WalletUpdateSpent(const CTransaction &tx)
198 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
199 // Update the wallet spent flag if it doesn't know due to wallet.dat being
200 // restored from backup or the user making copies of wallet.dat.
201 CRITICAL_BLOCK(cs_mapWallet)
203 BOOST_FOREACH(const CTxIn& txin, tx.vin)
205 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
206 if (mi != mapWallet.end())
208 CWalletTx& wtx = (*mi).second;
209 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
211 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
212 wtx.MarkSpent(txin.prevout.n);
214 vWalletUpdated.push_back(txin.prevout.hash);
221 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
223 uint256 hash = wtxIn.GetHash();
224 CRITICAL_BLOCK(cs_mapWallet)
226 // Inserts only if not already there, returns tx inserted or tx found
227 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
228 CWalletTx& wtx = (*ret.first).second;
230 bool fInsertedNew = ret.second;
232 wtx.nTimeReceived = GetAdjustedTime();
234 bool fUpdated = false;
238 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
240 wtx.hashBlock = wtxIn.hashBlock;
243 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
245 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
246 wtx.nIndex = wtxIn.nIndex;
249 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
251 wtx.fFromMe = wtxIn.fFromMe;
254 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
258 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
261 if (fInsertedNew || fUpdated)
262 if (!wtx.WriteToDisk())
265 // If default receiving address gets used, replace it with a new one
266 CScript scriptDefaultKey;
267 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
268 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
270 if (txout.scriptPubKey == scriptDefaultKey)
271 SetDefaultKey(GetOrReuseKeyFromPool());
275 vWalletUpdated.push_back(hash);
277 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
278 WalletUpdateSpent(wtx);
286 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
288 uint256 hash = tx.GetHash();
289 bool fExisted = mapWallet.count(hash);
290 if (fExisted && !fUpdate) return false;
291 if (fExisted || IsMine(tx) || IsFromMe(tx))
293 CWalletTx wtx(this,tx);
294 // Get merkle branch if transaction was found in a block
296 wtx.SetMerkleBranch(pblock);
297 return AddToWallet(wtx);
300 WalletUpdateSpent(tx);
304 bool CWallet::EraseFromWallet(uint256 hash)
308 CRITICAL_BLOCK(cs_mapWallet)
310 if (mapWallet.erase(hash))
311 CWalletDB(strWalletFile).EraseTx(hash);
317 bool CWallet::IsMine(const CTxIn &txin) const
319 CRITICAL_BLOCK(cs_mapWallet)
321 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
322 if (mi != mapWallet.end())
324 const CWalletTx& prev = (*mi).second;
325 if (txin.prevout.n < prev.vout.size())
326 if (IsMine(prev.vout[txin.prevout.n]))
333 int64 CWallet::GetDebit(const CTxIn &txin) const
335 CRITICAL_BLOCK(cs_mapWallet)
337 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
338 if (mi != mapWallet.end())
340 const CWalletTx& prev = (*mi).second;
341 if (txin.prevout.n < prev.vout.size())
342 if (IsMine(prev.vout[txin.prevout.n]))
343 return prev.vout[txin.prevout.n].nValue;
349 int64 CWalletTx::GetTxTime() const
351 if (!fTimeReceivedIsTxTime && hashBlock != 0)
353 // If we did not receive the transaction directly, we rely on the block's
354 // time to figure out when it happened. We use the median over a range
355 // of blocks to try to filter out inaccurate block times.
356 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
357 if (mi != mapBlockIndex.end())
359 CBlockIndex* pindex = (*mi).second;
361 return pindex->GetMedianTime();
364 return nTimeReceived;
367 int CWalletTx::GetRequestCount() const
369 // Returns -1 if it wasn't being tracked
371 CRITICAL_BLOCK(pwallet->cs_mapRequestCount)
378 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
379 if (mi != pwallet->mapRequestCount.end())
380 nRequests = (*mi).second;
385 // Did anyone request this transaction?
386 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
387 if (mi != pwallet->mapRequestCount.end())
389 nRequests = (*mi).second;
391 // How about the block it's in?
392 if (nRequests == 0 && hashBlock != 0)
394 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
395 if (mi != pwallet->mapRequestCount.end())
396 nRequests = (*mi).second;
398 nRequests = 1; // If it's in someone else's block it must have got out
406 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
407 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
409 nGeneratedImmature = nGeneratedMature = nFee = 0;
410 listReceived.clear();
412 strSentAccount = strFromAccount;
416 if (GetBlocksToMaturity() > 0)
417 nGeneratedImmature = pwallet->GetCredit(*this);
419 nGeneratedMature = GetCredit();
424 int64 nDebit = GetDebit();
425 if (nDebit > 0) // debit>0 means we signed/sent this transaction
427 int64 nValueOut = GetValueOut();
428 nFee = nDebit - nValueOut;
431 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
432 // but non-standard clients might (so return a list of address/amount pairs)
433 BOOST_FOREACH(const CTxOut& txout, vout)
437 vector<unsigned char> vchPubKey;
438 if (ExtractHash160(txout.scriptPubKey, hash160))
439 address = Hash160ToAddress(hash160);
440 else if (ExtractPubKey(txout.scriptPubKey, NULL, vchPubKey))
441 address = PubKeyToAddress(vchPubKey);
444 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
445 this->GetHash().ToString().c_str());
446 address = " unknown ";
449 // Don't report 'change' txouts
450 if (nDebit > 0 && pwallet->IsChange(txout))
454 listSent.push_back(make_pair(address, txout.nValue));
456 if (pwallet->IsMine(txout))
457 listReceived.push_back(make_pair(address, txout.nValue));
462 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
463 int64& nSent, int64& nFee) const
465 nGenerated = nReceived = nSent = nFee = 0;
467 int64 allGeneratedImmature, allGeneratedMature, allFee;
468 allGeneratedImmature = allGeneratedMature = allFee = 0;
469 string strSentAccount;
470 list<pair<string, int64> > listReceived;
471 list<pair<string, int64> > listSent;
472 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
474 if (strAccount == "")
475 nGenerated = allGeneratedMature;
476 if (strAccount == strSentAccount)
478 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
482 CRITICAL_BLOCK(pwallet->cs_mapAddressBook)
484 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
486 if (pwallet->mapAddressBook.count(r.first))
488 map<string, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
489 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
490 nReceived += r.second;
492 else if (strAccount.empty())
494 nReceived += r.second;
500 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
504 const int COPY_DEPTH = 3;
505 if (SetMerkleBranch() < COPY_DEPTH)
507 vector<uint256> vWorkQueue;
508 BOOST_FOREACH(const CTxIn& txin, vin)
509 vWorkQueue.push_back(txin.prevout.hash);
511 // This critsect is OK because txdb is already open
512 CRITICAL_BLOCK(pwallet->cs_mapWallet)
514 map<uint256, const CMerkleTx*> mapWalletPrev;
515 set<uint256> setAlreadyDone;
516 for (int i = 0; i < vWorkQueue.size(); i++)
518 uint256 hash = vWorkQueue[i];
519 if (setAlreadyDone.count(hash))
521 setAlreadyDone.insert(hash);
524 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
525 if (mi != pwallet->mapWallet.end())
528 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
529 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
531 else if (mapWalletPrev.count(hash))
533 tx = *mapWalletPrev[hash];
535 else if (!fClient && txdb.ReadDiskTx(hash, tx))
541 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
545 int nDepth = tx.SetMerkleBranch();
546 vtxPrev.push_back(tx);
548 if (nDepth < COPY_DEPTH)
549 BOOST_FOREACH(const CTxIn& txin, tx.vin)
550 vWorkQueue.push_back(txin.prevout.hash);
555 reverse(vtxPrev.begin(), vtxPrev.end());
558 bool CWalletTx::WriteToDisk()
560 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
563 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
567 CBlockIndex* pindex = pindexStart;
568 CRITICAL_BLOCK(cs_mapWallet)
573 block.ReadFromDisk(pindex, true);
574 BOOST_FOREACH(CTransaction& tx, block.vtx)
576 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
579 pindex = pindex->pnext;
585 void CWallet::ReacceptWalletTransactions()
589 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
592 vector<CDiskTxPos> vMissingTx;
593 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
595 CWalletTx& wtx = item.second;
596 if (wtx.IsCoinBase() && wtx.IsSpent(0))
600 bool fUpdated = false;
601 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
603 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
604 if (txindex.vSpent.size() != wtx.vout.size())
606 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
609 for (int i = 0; i < txindex.vSpent.size(); i++)
613 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
617 vMissingTx.push_back(txindex.vSpent[i]);
622 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
629 // Reaccept any txes of ours that aren't already in a block
630 if (!wtx.IsCoinBase())
631 wtx.AcceptWalletTransaction(txdb, false);
634 if (!vMissingTx.empty())
636 // TODO: optimize this to scan just part of the block chain?
637 if (ScanForWalletTransactions(pindexGenesisBlock))
638 fRepeat = true; // Found missing transactions: re-do Reaccept.
643 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
645 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
647 if (!tx.IsCoinBase())
649 uint256 hash = tx.GetHash();
650 if (!txdb.ContainsTx(hash))
651 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
656 uint256 hash = GetHash();
657 if (!txdb.ContainsTx(hash))
659 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
660 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
665 void CWalletTx::RelayWalletTransaction()
668 RelayWalletTransaction(txdb);
671 void CWallet::ResendWalletTransactions()
673 // Do this infrequently and randomly to avoid giving away
674 // that these are our transactions.
675 static int64 nNextTime;
676 if (GetTime() < nNextTime)
678 bool fFirst = (nNextTime == 0);
679 nNextTime = GetTime() + GetRand(30 * 60);
683 // Only do it if there's been a new block since last time
684 static int64 nLastTime;
685 if (nTimeBestReceived < nLastTime)
687 nLastTime = GetTime();
689 // Rebroadcast any of our txes that aren't in a block yet
690 printf("ResendWalletTransactions()\n");
692 CRITICAL_BLOCK(cs_mapWallet)
694 // Sort them in chronological order
695 multimap<unsigned int, CWalletTx*> mapSorted;
696 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
698 CWalletTx& wtx = item.second;
699 // Don't rebroadcast until it's had plenty of time that
700 // it should have gotten in already by now.
701 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
702 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
704 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
706 CWalletTx& wtx = *item.second;
707 wtx.RelayWalletTransaction(txdb);
717 //////////////////////////////////////////////////////////////////////////////
723 int64 CWallet::GetBalance() const
726 CRITICAL_BLOCK(cs_mapWallet)
728 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
730 const CWalletTx* pcoin = &(*it).second;
731 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
733 nTotal += pcoin->GetAvailableCredit();
741 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
746 // List of values less than target
747 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
748 coinLowestLarger.first = INT64_MAX;
749 coinLowestLarger.second.first = NULL;
750 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
751 int64 nTotalLower = 0;
753 CRITICAL_BLOCK(cs_mapWallet)
755 vector<const CWalletTx*> vCoins;
756 vCoins.reserve(mapWallet.size());
757 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
758 vCoins.push_back(&(*it).second);
759 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
761 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
763 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
766 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
769 int nDepth = pcoin->GetDepthInMainChain();
770 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
773 for (int i = 0; i < pcoin->vout.size(); i++)
775 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
778 int64 n = pcoin->vout[i].nValue;
783 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
785 if (n == nTargetValue)
787 setCoinsRet.insert(coin.second);
788 nValueRet += coin.first;
791 else if (n < nTargetValue + CENT)
793 vValue.push_back(coin);
796 else if (n < coinLowestLarger.first)
798 coinLowestLarger = coin;
804 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
806 for (int i = 0; i < vValue.size(); ++i)
808 setCoinsRet.insert(vValue[i].second);
809 nValueRet += vValue[i].first;
814 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
816 if (coinLowestLarger.second.first == NULL)
818 setCoinsRet.insert(coinLowestLarger.second);
819 nValueRet += coinLowestLarger.first;
823 if (nTotalLower >= nTargetValue + CENT)
824 nTargetValue += CENT;
826 // Solve subset sum by stochastic approximation
827 sort(vValue.rbegin(), vValue.rend());
828 vector<char> vfIncluded;
829 vector<char> vfBest(vValue.size(), true);
830 int64 nBest = nTotalLower;
832 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
834 vfIncluded.assign(vValue.size(), false);
836 bool fReachedTarget = false;
837 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
839 for (int i = 0; i < vValue.size(); i++)
841 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
843 nTotal += vValue[i].first;
844 vfIncluded[i] = true;
845 if (nTotal >= nTargetValue)
847 fReachedTarget = true;
853 nTotal -= vValue[i].first;
854 vfIncluded[i] = false;
861 // If the next larger is still closer, return it
862 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
864 setCoinsRet.insert(coinLowestLarger.second);
865 nValueRet += coinLowestLarger.first;
868 for (int i = 0; i < vValue.size(); i++)
871 setCoinsRet.insert(vValue[i].second);
872 nValueRet += vValue[i].first;
876 printf("SelectCoins() best subset: ");
877 for (int i = 0; i < vValue.size(); i++)
879 printf("%s ", FormatMoney(vValue[i].first).c_str());
880 printf("total %s\n", FormatMoney(nBest).c_str());
886 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
888 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
889 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
890 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
896 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
899 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
905 if (vecSend.empty() || nValue < 0)
908 wtxNew.pwallet = this;
910 CRITICAL_BLOCK(cs_main)
912 // txdb must be opened before the mapWallet lock
914 CRITICAL_BLOCK(cs_mapWallet)
916 nFeeRet = nTransactionFee;
921 wtxNew.fFromMe = true;
923 int64 nTotalValue = nValue + nFeeRet;
924 double dPriority = 0;
925 // vouts to the payees
926 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
927 wtxNew.vout.push_back(CTxOut(s.second, s.first));
929 // Choose coins to use
930 set<pair<const CWalletTx*,unsigned int> > setCoins;
932 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
934 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
936 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
937 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
940 // Fill a vout back to self with any change
941 int64 nChange = nValueIn - nTotalValue;
944 // Note: We use a new key here to keep it from being obvious which side is the change.
945 // The drawback is that by not reusing a previous key, the change may be lost if a
946 // backup is restored, if the backup doesn't have the new private key for the change.
947 // If we reused the old key, it would be possible to add code to look for and
948 // rediscover unknown transactions that were written with keys of ours to recover
949 // post-backup change.
951 // Reserve a new key pair from key pool
952 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
953 // assert(mapKeys.count(vchPubKey));
955 // Fill a vout to ourself, using same address type as the payment
956 CScript scriptChange;
957 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
958 scriptChange.SetBitcoinAddress(vchPubKey);
960 scriptChange << vchPubKey << OP_CHECKSIG;
962 // Insert change txn at random position:
963 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
964 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
967 reservekey.ReturnKey();
970 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
971 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
975 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
976 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
980 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
981 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
985 // Check that enough fee is included
986 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
987 bool fAllowFree = CTransaction::AllowFree(dPriority);
988 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
989 if (nFeeRet < max(nPayFee, nMinFee))
991 nFeeRet = max(nPayFee, nMinFee);
995 // Fill vtxPrev by copying from previous transactions vtxPrev
996 wtxNew.AddSupportingTransactions(txdb);
997 wtxNew.fTimeReceivedIsTxTime = true;
1006 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1008 vector< pair<CScript, int64> > vecSend;
1009 vecSend.push_back(make_pair(scriptPubKey, nValue));
1010 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1013 // Call after CreateTransaction unless you want to abort
1014 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1016 CRITICAL_BLOCK(cs_main)
1018 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1019 CRITICAL_BLOCK(cs_mapWallet)
1021 // This is only to keep the database open to defeat the auto-flush for the
1022 // duration of this scope. This is the only place where this optimization
1023 // maybe makes sense; please don't do it anywhere else.
1024 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1026 // Take key pair from key pool so it won't be used again
1027 reservekey.KeepKey();
1029 // Add tx to wallet, because if it has change it's also ours,
1030 // otherwise just for transaction history.
1031 AddToWallet(wtxNew);
1033 // Mark old coins as spent
1034 set<CWalletTx*> setCoins;
1035 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1037 CWalletTx &coin = mapWallet[txin.prevout.hash];
1038 coin.pwallet = this;
1039 coin.MarkSpent(txin.prevout.n);
1041 vWalletUpdated.push_back(coin.GetHash());
1048 // Track how many getdata requests our transaction gets
1049 CRITICAL_BLOCK(cs_mapRequestCount)
1050 mapRequestCount[wtxNew.GetHash()] = 0;
1053 if (!wtxNew.AcceptToMemoryPool())
1055 // This must not fail. The transaction has already been signed and recorded.
1056 printf("CommitTransaction() : Error: Transaction not valid");
1059 wtxNew.RelayWalletTransaction();
1068 // requires cs_main lock
1069 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1071 CReserveKey reservekey(this);
1073 CRITICAL_BLOCK(cs_vMasterKey)
1077 string strError = _("Error: Wallet locked, unable to create transaction ");
1078 printf("SendMoney() : %s", strError.c_str());
1081 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1084 if (nValue + nFeeRequired > GetBalance())
1085 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());
1087 strError = _("Error: Transaction creation failed ");
1088 printf("SendMoney() : %s", strError.c_str());
1093 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1096 if (!CommitTransaction(wtxNew, reservekey))
1097 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.");
1105 // requires cs_main lock
1106 string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1110 return _("Invalid amount");
1111 if (nValue + nTransactionFee > GetBalance())
1112 return _("Insufficient funds");
1114 // Parse bitcoin address
1115 CScript scriptPubKey;
1116 if (!scriptPubKey.SetBitcoinAddress(strAddress))
1117 return _("Invalid bitcoin address");
1119 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1125 int CWallet::LoadWallet(bool& fFirstRunRet)
1129 fFirstRunRet = false;
1130 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1131 if (nLoadWalletRet != DB_LOAD_OK)
1132 return nLoadWalletRet;
1133 fFirstRunRet = vchDefaultKey.empty();
1135 if (!HaveKey(vchDefaultKey))
1137 // Create new keyUser and set as default key
1138 RandAddSeedPerfmon();
1140 SetDefaultKey(GetOrReuseKeyFromPool());
1141 if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))
1142 return DB_LOAD_FAIL;
1145 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1150 bool CWallet::SetAddressBookName(const string& strAddress, const string& strName)
1152 mapAddressBook[strAddress] = strName;
1155 return CWalletDB(strWalletFile).WriteName(strAddress, strName);
1158 bool CWallet::DelAddressBookName(const string& strAddress)
1160 mapAddressBook.erase(strAddress);
1163 return CWalletDB(strWalletFile).EraseName(strAddress);
1167 void CWallet::PrintWallet(const CBlock& block)
1169 CRITICAL_BLOCK(cs_mapWallet)
1171 if (mapWallet.count(block.vtx[0].GetHash()))
1173 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1174 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1180 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1182 CRITICAL_BLOCK(cs_mapWallet)
1184 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1185 if (mi != mapWallet.end())
1194 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1198 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1201 vchDefaultKey = vchPubKey;
1205 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1207 if (!pwallet->fFileBacked)
1209 strWalletFileOut = pwallet->strWalletFile;
1213 bool CWallet::TopUpKeyPool()
1215 CRITICAL_BLOCK(cs_main)
1216 CRITICAL_BLOCK(cs_mapWallet)
1217 CRITICAL_BLOCK(cs_setKeyPool)
1218 CRITICAL_BLOCK(cs_vMasterKey)
1223 CWalletDB walletdb(strWalletFile);
1226 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1227 while (setKeyPool.size() < nTargetSize+1)
1230 if (!setKeyPool.empty())
1231 nEnd = *(--setKeyPool.end()) + 1;
1232 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1233 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1234 setKeyPool.insert(nEnd);
1235 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1241 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1244 keypool.vchPubKey.clear();
1245 CRITICAL_BLOCK(cs_main)
1246 CRITICAL_BLOCK(cs_mapWallet)
1247 CRITICAL_BLOCK(cs_setKeyPool)
1252 // Get the oldest key
1253 if(setKeyPool.empty())
1256 CWalletDB walletdb(strWalletFile);
1258 nIndex = *(setKeyPool.begin());
1259 setKeyPool.erase(setKeyPool.begin());
1260 if (!walletdb.ReadPool(nIndex, keypool))
1261 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1262 if (!HaveKey(keypool.vchPubKey))
1263 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1264 assert(!keypool.vchPubKey.empty());
1265 printf("keypool reserve %"PRI64d"\n", nIndex);
1269 void CWallet::KeepKey(int64 nIndex)
1271 // Remove from key pool
1274 CWalletDB walletdb(strWalletFile);
1275 CRITICAL_BLOCK(cs_main)
1277 walletdb.ErasePool(nIndex);
1280 printf("keypool keep %"PRI64d"\n", nIndex);
1283 void CWallet::ReturnKey(int64 nIndex)
1285 // Return to key pool
1286 CRITICAL_BLOCK(cs_setKeyPool)
1287 setKeyPool.insert(nIndex);
1288 printf("keypool return %"PRI64d"\n", nIndex);
1291 vector<unsigned char> CWallet::GetOrReuseKeyFromPool()
1295 ReserveKeyFromKeyPool(nIndex, keypool);
1297 return vchDefaultKey;
1299 return keypool.vchPubKey;
1302 int64 CWallet::GetOldestKeyPoolTime()
1306 ReserveKeyFromKeyPool(nIndex, keypool);
1310 return keypool.nTime;
1313 vector<unsigned char> CReserveKey::GetReservedKey()
1318 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1319 vchPubKey = keypool.vchPubKey;
1321 assert(!vchPubKey.empty());
1325 void CReserveKey::KeepKey()
1328 pwallet->KeepKey(nIndex);
1333 void CReserveKey::ReturnKey()
1336 pwallet->ReturnKey(nIndex);