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);
111 bool CWallet::EncryptWallet(const string& strWalletPassphrase)
113 CRITICAL_BLOCK(cs_mapPubKeys)
114 CRITICAL_BLOCK(cs_KeyStore)
115 CRITICAL_BLOCK(cs_vMasterKey)
116 CRITICAL_BLOCK(cs_pwalletdbEncryption)
121 CKeyingMaterial vMasterKey;
122 RandAddSeedPerfmon();
124 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
125 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
127 CMasterKey kMasterKey;
129 RandAddSeedPerfmon();
130 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
131 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
134 int64 nStartTime = GetTimeMillis();
135 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
136 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
138 nStartTime = GetTimeMillis();
139 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
140 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
142 if (kMasterKey.nDeriveIterations < 25000)
143 kMasterKey.nDeriveIterations = 25000;
145 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
147 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
149 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
152 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
155 pwalletdbEncryption = new CWalletDB(strWalletFile);
156 pwalletdbEncryption->TxnBegin();
157 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
160 if (!EncryptKeys(vMasterKey))
163 pwalletdbEncryption->TxnAbort();
164 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.
169 if (!pwalletdbEncryption->TxnCommit())
170 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.
172 pwalletdbEncryption->Close();
173 pwalletdbEncryption = NULL;
181 void CWallet::WalletUpdateSpent(const CTransaction &tx)
183 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
184 // Update the wallet spent flag if it doesn't know due to wallet.dat being
185 // restored from backup or the user making copies of wallet.dat.
186 CRITICAL_BLOCK(cs_mapWallet)
188 BOOST_FOREACH(const CTxIn& txin, tx.vin)
190 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
191 if (mi != mapWallet.end())
193 CWalletTx& wtx = (*mi).second;
194 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
196 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
197 wtx.MarkSpent(txin.prevout.n);
199 vWalletUpdated.push_back(txin.prevout.hash);
206 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
208 uint256 hash = wtxIn.GetHash();
209 CRITICAL_BLOCK(cs_mapWallet)
211 // Inserts only if not already there, returns tx inserted or tx found
212 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
213 CWalletTx& wtx = (*ret.first).second;
215 bool fInsertedNew = ret.second;
217 wtx.nTimeReceived = GetAdjustedTime();
219 bool fUpdated = false;
223 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
225 wtx.hashBlock = wtxIn.hashBlock;
228 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
230 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
231 wtx.nIndex = wtxIn.nIndex;
234 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
236 wtx.fFromMe = wtxIn.fFromMe;
239 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
243 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
246 if (fInsertedNew || fUpdated)
247 if (!wtx.WriteToDisk())
250 // If default receiving address gets used, replace it with a new one
251 CScript scriptDefaultKey;
252 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
253 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
255 if (txout.scriptPubKey == scriptDefaultKey)
256 SetDefaultKey(GetOrReuseKeyFromPool());
260 vWalletUpdated.push_back(hash);
262 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
263 WalletUpdateSpent(wtx);
271 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
273 uint256 hash = tx.GetHash();
274 bool fExisted = mapWallet.count(hash);
275 if (fExisted && !fUpdate) return false;
276 if (fExisted || IsMine(tx) || IsFromMe(tx))
278 CWalletTx wtx(this,tx);
279 // Get merkle branch if transaction was found in a block
281 wtx.SetMerkleBranch(pblock);
282 return AddToWallet(wtx);
285 WalletUpdateSpent(tx);
289 bool CWallet::EraseFromWallet(uint256 hash)
293 CRITICAL_BLOCK(cs_mapWallet)
295 if (mapWallet.erase(hash))
296 CWalletDB(strWalletFile).EraseTx(hash);
302 bool CWallet::IsMine(const CTxIn &txin) const
304 CRITICAL_BLOCK(cs_mapWallet)
306 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
307 if (mi != mapWallet.end())
309 const CWalletTx& prev = (*mi).second;
310 if (txin.prevout.n < prev.vout.size())
311 if (IsMine(prev.vout[txin.prevout.n]))
318 int64 CWallet::GetDebit(const CTxIn &txin) const
320 CRITICAL_BLOCK(cs_mapWallet)
322 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
323 if (mi != mapWallet.end())
325 const CWalletTx& prev = (*mi).second;
326 if (txin.prevout.n < prev.vout.size())
327 if (IsMine(prev.vout[txin.prevout.n]))
328 return prev.vout[txin.prevout.n].nValue;
334 int64 CWalletTx::GetTxTime() const
336 if (!fTimeReceivedIsTxTime && hashBlock != 0)
338 // If we did not receive the transaction directly, we rely on the block's
339 // time to figure out when it happened. We use the median over a range
340 // of blocks to try to filter out inaccurate block times.
341 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
342 if (mi != mapBlockIndex.end())
344 CBlockIndex* pindex = (*mi).second;
346 return pindex->GetMedianTime();
349 return nTimeReceived;
352 int CWalletTx::GetRequestCount() const
354 // Returns -1 if it wasn't being tracked
356 CRITICAL_BLOCK(pwallet->cs_mapRequestCount)
363 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
364 if (mi != pwallet->mapRequestCount.end())
365 nRequests = (*mi).second;
370 // Did anyone request this transaction?
371 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
372 if (mi != pwallet->mapRequestCount.end())
374 nRequests = (*mi).second;
376 // How about the block it's in?
377 if (nRequests == 0 && hashBlock != 0)
379 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
380 if (mi != pwallet->mapRequestCount.end())
381 nRequests = (*mi).second;
383 nRequests = 1; // If it's in someone else's block it must have got out
391 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
392 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
394 nGeneratedImmature = nGeneratedMature = nFee = 0;
395 listReceived.clear();
397 strSentAccount = strFromAccount;
401 if (GetBlocksToMaturity() > 0)
402 nGeneratedImmature = pwallet->GetCredit(*this);
404 nGeneratedMature = GetCredit();
409 int64 nDebit = GetDebit();
410 if (nDebit > 0) // debit>0 means we signed/sent this transaction
412 int64 nValueOut = GetValueOut();
413 nFee = nDebit - nValueOut;
416 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
417 // but non-standard clients might (so return a list of address/amount pairs)
418 BOOST_FOREACH(const CTxOut& txout, vout)
422 vector<unsigned char> vchPubKey;
423 if (ExtractHash160(txout.scriptPubKey, hash160))
424 address = Hash160ToAddress(hash160);
425 else if (ExtractPubKey(txout.scriptPubKey, NULL, vchPubKey))
426 address = PubKeyToAddress(vchPubKey);
429 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
430 this->GetHash().ToString().c_str());
431 address = " unknown ";
434 // Don't report 'change' txouts
435 if (nDebit > 0 && pwallet->IsChange(txout))
439 listSent.push_back(make_pair(address, txout.nValue));
441 if (pwallet->IsMine(txout))
442 listReceived.push_back(make_pair(address, txout.nValue));
447 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
448 int64& nSent, int64& nFee) const
450 nGenerated = nReceived = nSent = nFee = 0;
452 int64 allGeneratedImmature, allGeneratedMature, allFee;
453 allGeneratedImmature = allGeneratedMature = allFee = 0;
454 string strSentAccount;
455 list<pair<string, int64> > listReceived;
456 list<pair<string, int64> > listSent;
457 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
459 if (strAccount == "")
460 nGenerated = allGeneratedMature;
461 if (strAccount == strSentAccount)
463 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
467 CRITICAL_BLOCK(pwallet->cs_mapAddressBook)
469 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
471 if (pwallet->mapAddressBook.count(r.first))
473 map<string, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
474 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
475 nReceived += r.second;
477 else if (strAccount.empty())
479 nReceived += r.second;
485 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
489 const int COPY_DEPTH = 3;
490 if (SetMerkleBranch() < COPY_DEPTH)
492 vector<uint256> vWorkQueue;
493 BOOST_FOREACH(const CTxIn& txin, vin)
494 vWorkQueue.push_back(txin.prevout.hash);
496 // This critsect is OK because txdb is already open
497 CRITICAL_BLOCK(pwallet->cs_mapWallet)
499 map<uint256, const CMerkleTx*> mapWalletPrev;
500 set<uint256> setAlreadyDone;
501 for (int i = 0; i < vWorkQueue.size(); i++)
503 uint256 hash = vWorkQueue[i];
504 if (setAlreadyDone.count(hash))
506 setAlreadyDone.insert(hash);
509 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
510 if (mi != pwallet->mapWallet.end())
513 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
514 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
516 else if (mapWalletPrev.count(hash))
518 tx = *mapWalletPrev[hash];
520 else if (!fClient && txdb.ReadDiskTx(hash, tx))
526 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
530 int nDepth = tx.SetMerkleBranch();
531 vtxPrev.push_back(tx);
533 if (nDepth < COPY_DEPTH)
534 BOOST_FOREACH(const CTxIn& txin, tx.vin)
535 vWorkQueue.push_back(txin.prevout.hash);
540 reverse(vtxPrev.begin(), vtxPrev.end());
543 bool CWalletTx::WriteToDisk()
545 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
548 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
552 CBlockIndex* pindex = pindexStart;
553 CRITICAL_BLOCK(cs_mapWallet)
558 block.ReadFromDisk(pindex, true);
559 BOOST_FOREACH(CTransaction& tx, block.vtx)
561 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
564 pindex = pindex->pnext;
570 void CWallet::ReacceptWalletTransactions()
574 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
577 vector<CDiskTxPos> vMissingTx;
578 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
580 CWalletTx& wtx = item.second;
581 if (wtx.IsCoinBase() && wtx.IsSpent(0))
585 bool fUpdated = false;
586 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
588 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
589 if (txindex.vSpent.size() != wtx.vout.size())
591 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
594 for (int i = 0; i < txindex.vSpent.size(); i++)
598 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
602 vMissingTx.push_back(txindex.vSpent[i]);
607 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
614 // Reaccept any txes of ours that aren't already in a block
615 if (!wtx.IsCoinBase())
616 wtx.AcceptWalletTransaction(txdb, false);
619 if (!vMissingTx.empty())
621 // TODO: optimize this to scan just part of the block chain?
622 if (ScanForWalletTransactions(pindexGenesisBlock))
623 fRepeat = true; // Found missing transactions: re-do Reaccept.
628 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
630 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
632 if (!tx.IsCoinBase())
634 uint256 hash = tx.GetHash();
635 if (!txdb.ContainsTx(hash))
636 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
641 uint256 hash = GetHash();
642 if (!txdb.ContainsTx(hash))
644 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
645 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
650 void CWalletTx::RelayWalletTransaction()
653 RelayWalletTransaction(txdb);
656 void CWallet::ResendWalletTransactions()
658 // Do this infrequently and randomly to avoid giving away
659 // that these are our transactions.
660 static int64 nNextTime;
661 if (GetTime() < nNextTime)
663 bool fFirst = (nNextTime == 0);
664 nNextTime = GetTime() + GetRand(30 * 60);
668 // Only do it if there's been a new block since last time
669 static int64 nLastTime;
670 if (nTimeBestReceived < nLastTime)
672 nLastTime = GetTime();
674 // Rebroadcast any of our txes that aren't in a block yet
675 printf("ResendWalletTransactions()\n");
677 CRITICAL_BLOCK(cs_mapWallet)
679 // Sort them in chronological order
680 multimap<unsigned int, CWalletTx*> mapSorted;
681 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
683 CWalletTx& wtx = item.second;
684 // Don't rebroadcast until it's had plenty of time that
685 // it should have gotten in already by now.
686 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
687 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
689 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
691 CWalletTx& wtx = *item.second;
692 wtx.RelayWalletTransaction(txdb);
702 //////////////////////////////////////////////////////////////////////////////
708 int64 CWallet::GetBalance() const
710 int64 nStart = GetTimeMillis();
713 CRITICAL_BLOCK(cs_mapWallet)
715 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
717 const CWalletTx* pcoin = &(*it).second;
718 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
720 nTotal += pcoin->GetAvailableCredit();
724 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
729 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
734 // List of values less than target
735 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
736 coinLowestLarger.first = INT64_MAX;
737 coinLowestLarger.second.first = NULL;
738 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
739 int64 nTotalLower = 0;
741 CRITICAL_BLOCK(cs_mapWallet)
743 vector<const CWalletTx*> vCoins;
744 vCoins.reserve(mapWallet.size());
745 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
746 vCoins.push_back(&(*it).second);
747 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
749 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
751 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
754 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
757 int nDepth = pcoin->GetDepthInMainChain();
758 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
761 for (int i = 0; i < pcoin->vout.size(); i++)
763 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
766 int64 n = pcoin->vout[i].nValue;
771 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
773 if (n == nTargetValue)
775 setCoinsRet.insert(coin.second);
776 nValueRet += coin.first;
779 else if (n < nTargetValue + CENT)
781 vValue.push_back(coin);
784 else if (n < coinLowestLarger.first)
786 coinLowestLarger = coin;
792 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
794 for (int i = 0; i < vValue.size(); ++i)
796 setCoinsRet.insert(vValue[i].second);
797 nValueRet += vValue[i].first;
802 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
804 if (coinLowestLarger.second.first == NULL)
806 setCoinsRet.insert(coinLowestLarger.second);
807 nValueRet += coinLowestLarger.first;
811 if (nTotalLower >= nTargetValue + CENT)
812 nTargetValue += CENT;
814 // Solve subset sum by stochastic approximation
815 sort(vValue.rbegin(), vValue.rend());
816 vector<char> vfIncluded;
817 vector<char> vfBest(vValue.size(), true);
818 int64 nBest = nTotalLower;
820 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
822 vfIncluded.assign(vValue.size(), false);
824 bool fReachedTarget = false;
825 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
827 for (int i = 0; i < vValue.size(); i++)
829 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
831 nTotal += vValue[i].first;
832 vfIncluded[i] = true;
833 if (nTotal >= nTargetValue)
835 fReachedTarget = true;
841 nTotal -= vValue[i].first;
842 vfIncluded[i] = false;
849 // If the next larger is still closer, return it
850 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
852 setCoinsRet.insert(coinLowestLarger.second);
853 nValueRet += coinLowestLarger.first;
856 for (int i = 0; i < vValue.size(); i++)
859 setCoinsRet.insert(vValue[i].second);
860 nValueRet += vValue[i].first;
864 printf("SelectCoins() best subset: ");
865 for (int i = 0; i < vValue.size(); i++)
867 printf("%s ", FormatMoney(vValue[i].first).c_str());
868 printf("total %s\n", FormatMoney(nBest).c_str());
874 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
876 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
877 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
878 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
884 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
887 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
893 if (vecSend.empty() || nValue < 0)
896 wtxNew.pwallet = this;
898 CRITICAL_BLOCK(cs_main)
900 // txdb must be opened before the mapWallet lock
902 CRITICAL_BLOCK(cs_mapWallet)
904 nFeeRet = nTransactionFee;
909 wtxNew.fFromMe = true;
911 int64 nTotalValue = nValue + nFeeRet;
912 double dPriority = 0;
913 // vouts to the payees
914 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
915 wtxNew.vout.push_back(CTxOut(s.second, s.first));
917 // Choose coins to use
918 set<pair<const CWalletTx*,unsigned int> > setCoins;
920 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
922 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
924 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
925 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
928 // Fill a vout back to self with any change
929 int64 nChange = nValueIn - nTotalValue;
932 // Note: We use a new key here to keep it from being obvious which side is the change.
933 // The drawback is that by not reusing a previous key, the change may be lost if a
934 // backup is restored, if the backup doesn't have the new private key for the change.
935 // If we reused the old key, it would be possible to add code to look for and
936 // rediscover unknown transactions that were written with keys of ours to recover
937 // post-backup change.
939 // Reserve a new key pair from key pool
940 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
941 // assert(mapKeys.count(vchPubKey));
943 // Fill a vout to ourself, using same address type as the payment
944 CScript scriptChange;
945 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
946 scriptChange.SetBitcoinAddress(vchPubKey);
948 scriptChange << vchPubKey << OP_CHECKSIG;
950 // Insert change txn at random position:
951 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
952 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
955 reservekey.ReturnKey();
958 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
959 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
963 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
964 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
968 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
969 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
973 // Check that enough fee is included
974 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
975 bool fAllowFree = CTransaction::AllowFree(dPriority);
976 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
977 if (nFeeRet < max(nPayFee, nMinFee))
979 nFeeRet = max(nPayFee, nMinFee);
983 // Fill vtxPrev by copying from previous transactions vtxPrev
984 wtxNew.AddSupportingTransactions(txdb);
985 wtxNew.fTimeReceivedIsTxTime = true;
994 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
996 vector< pair<CScript, int64> > vecSend;
997 vecSend.push_back(make_pair(scriptPubKey, nValue));
998 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1001 // Call after CreateTransaction unless you want to abort
1002 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1004 CRITICAL_BLOCK(cs_main)
1006 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1007 CRITICAL_BLOCK(cs_mapWallet)
1009 // This is only to keep the database open to defeat the auto-flush for the
1010 // duration of this scope. This is the only place where this optimization
1011 // maybe makes sense; please don't do it anywhere else.
1012 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1014 // Take key pair from key pool so it won't be used again
1015 reservekey.KeepKey();
1017 // Add tx to wallet, because if it has change it's also ours,
1018 // otherwise just for transaction history.
1019 AddToWallet(wtxNew);
1021 // Mark old coins as spent
1022 set<CWalletTx*> setCoins;
1023 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1025 CWalletTx &coin = mapWallet[txin.prevout.hash];
1026 coin.pwallet = this;
1027 coin.MarkSpent(txin.prevout.n);
1029 vWalletUpdated.push_back(coin.GetHash());
1036 // Track how many getdata requests our transaction gets
1037 CRITICAL_BLOCK(cs_mapRequestCount)
1038 mapRequestCount[wtxNew.GetHash()] = 0;
1041 if (!wtxNew.AcceptToMemoryPool())
1043 // This must not fail. The transaction has already been signed and recorded.
1044 printf("CommitTransaction() : Error: Transaction not valid");
1047 wtxNew.RelayWalletTransaction();
1056 // requires cs_main lock
1057 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1059 CReserveKey reservekey(this);
1061 CRITICAL_BLOCK(cs_vMasterKey)
1065 string strError = _("Error: Wallet locked, unable to create transaction ");
1066 printf("SendMoney() : %s", strError.c_str());
1069 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1072 if (nValue + nFeeRequired > GetBalance())
1073 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());
1075 strError = _("Error: Transaction creation failed ");
1076 printf("SendMoney() : %s", strError.c_str());
1081 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1084 if (!CommitTransaction(wtxNew, reservekey))
1085 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.");
1093 // requires cs_main lock
1094 string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1098 return _("Invalid amount");
1099 if (nValue + nTransactionFee > GetBalance())
1100 return _("Insufficient funds");
1102 // Parse bitcoin address
1103 CScript scriptPubKey;
1104 if (!scriptPubKey.SetBitcoinAddress(strAddress))
1105 return _("Invalid bitcoin address");
1107 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1113 bool CWallet::LoadWallet(bool& fFirstRunRet)
1117 fFirstRunRet = false;
1118 if (!CWalletDB(strWalletFile,"cr+").LoadWallet(this))
1120 fFirstRunRet = vchDefaultKey.empty();
1122 if (!HaveKey(vchDefaultKey))
1124 // Create new keyUser and set as default key
1125 RandAddSeedPerfmon();
1127 SetDefaultKey(GetOrReuseKeyFromPool());
1128 if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))
1132 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1137 bool CWallet::SetAddressBookName(const string& strAddress, const string& strName)
1139 mapAddressBook[strAddress] = strName;
1142 return CWalletDB(strWalletFile).WriteName(strAddress, strName);
1145 bool CWallet::DelAddressBookName(const string& strAddress)
1147 mapAddressBook.erase(strAddress);
1150 return CWalletDB(strWalletFile).EraseName(strAddress);
1154 void CWallet::PrintWallet(const CBlock& block)
1156 CRITICAL_BLOCK(cs_mapWallet)
1158 if (mapWallet.count(block.vtx[0].GetHash()))
1160 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1161 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1167 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1169 CRITICAL_BLOCK(cs_mapWallet)
1171 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1172 if (mi != mapWallet.end())
1181 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1185 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1188 vchDefaultKey = vchPubKey;
1192 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1194 if (!pwallet->fFileBacked)
1196 strWalletFileOut = pwallet->strWalletFile;
1200 bool CWallet::TopUpKeyPool()
1202 CRITICAL_BLOCK(cs_main)
1203 CRITICAL_BLOCK(cs_mapWallet)
1204 CRITICAL_BLOCK(cs_setKeyPool)
1205 CRITICAL_BLOCK(cs_vMasterKey)
1210 CWalletDB walletdb(strWalletFile);
1213 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1214 while (setKeyPool.size() < nTargetSize+1)
1217 if (!setKeyPool.empty())
1218 nEnd = *(--setKeyPool.end()) + 1;
1219 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1220 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1221 setKeyPool.insert(nEnd);
1222 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1228 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1231 keypool.vchPubKey.clear();
1232 CRITICAL_BLOCK(cs_main)
1233 CRITICAL_BLOCK(cs_mapWallet)
1234 CRITICAL_BLOCK(cs_setKeyPool)
1239 // Get the oldest key
1240 if(setKeyPool.empty())
1243 CWalletDB walletdb(strWalletFile);
1245 nIndex = *(setKeyPool.begin());
1246 setKeyPool.erase(setKeyPool.begin());
1247 if (!walletdb.ReadPool(nIndex, keypool))
1248 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1249 if (!HaveKey(keypool.vchPubKey))
1250 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1251 assert(!keypool.vchPubKey.empty());
1252 printf("keypool reserve %"PRI64d"\n", nIndex);
1256 void CWallet::KeepKey(int64 nIndex)
1258 // Remove from key pool
1261 CWalletDB walletdb(strWalletFile);
1262 CRITICAL_BLOCK(cs_main)
1264 walletdb.ErasePool(nIndex);
1267 printf("keypool keep %"PRI64d"\n", nIndex);
1270 void CWallet::ReturnKey(int64 nIndex)
1272 // Return to key pool
1273 CRITICAL_BLOCK(cs_setKeyPool)
1274 setKeyPool.insert(nIndex);
1275 printf("keypool return %"PRI64d"\n", nIndex);
1278 vector<unsigned char> CWallet::GetOrReuseKeyFromPool()
1282 ReserveKeyFromKeyPool(nIndex, keypool);
1284 return vchDefaultKey;
1286 return keypool.vchPubKey;
1289 int64 CWallet::GetOldestKeyPoolTime()
1293 ReserveKeyFromKeyPool(nIndex, keypool);
1297 return keypool.nTime;
1300 vector<unsigned char> CReserveKey::GetReservedKey()
1305 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1306 vchPubKey = keypool.vchPubKey;
1308 assert(!vchPubKey.empty());
1312 void CReserveKey::KeepKey()
1315 pwallet->KeepKey(nIndex);
1320 void CReserveKey::ReturnKey()
1323 pwallet->ReturnKey(nIndex);