1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
13 //////////////////////////////////////////////////////////////////////////////
18 bool CWallet::AddKey(const CKey& key)
20 if (!CCryptoKeyStore::AddKey(key))
25 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
29 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
31 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
35 CRITICAL_BLOCK(cs_wallet)
37 if (pwalletdbEncryption)
38 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
40 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
44 bool CWallet::Unlock(const string& strWalletPassphrase)
50 CKeyingMaterial vMasterKey;
52 CRITICAL_BLOCK(cs_wallet)
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))
65 bool CWallet::ChangeWalletPassphrase(const string& strOldWalletPassphrase, const string& strNewWalletPassphrase)
67 bool fWasLocked = IsLocked();
69 CRITICAL_BLOCK(cs_wallet)
74 CKeyingMaterial vMasterKey;
75 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
77 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
79 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
81 if (CCryptoKeyStore::Unlock(vMasterKey))
83 int64 nStartTime = GetTimeMillis();
84 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
85 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
87 nStartTime = GetTimeMillis();
88 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
89 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
91 if (pMasterKey.second.nDeriveIterations < 25000)
92 pMasterKey.second.nDeriveIterations = 25000;
94 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
96 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
98 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
100 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)
129 CKeyingMaterial vMasterKey;
130 RandAddSeedPerfmon();
132 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
133 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
135 CMasterKey kMasterKey;
137 RandAddSeedPerfmon();
138 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
139 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
142 int64 nStartTime = GetTimeMillis();
143 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
144 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
146 nStartTime = GetTimeMillis();
147 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
148 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
150 if (kMasterKey.nDeriveIterations < 25000)
151 kMasterKey.nDeriveIterations = 25000;
153 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
155 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
157 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
160 CRITICAL_BLOCK(cs_wallet)
162 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
165 pwalletdbEncryption = new CWalletDB(strWalletFile);
166 pwalletdbEncryption->TxnBegin();
167 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
170 if (!EncryptKeys(vMasterKey))
173 pwalletdbEncryption->TxnAbort();
174 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.
179 CCorruptAddress corruptAddress;
180 pwalletdbEncryption->WriteSetting("addrIncoming", corruptAddress);
181 if (!pwalletdbEncryption->TxnCommit())
182 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.
184 pwalletdbEncryption->Close();
185 pwalletdbEncryption = NULL;
194 void CWallet::WalletUpdateSpent(const CTransaction &tx)
196 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
197 // Update the wallet spent flag if it doesn't know due to wallet.dat being
198 // restored from backup or the user making copies of wallet.dat.
199 CRITICAL_BLOCK(cs_wallet)
201 BOOST_FOREACH(const CTxIn& txin, tx.vin)
203 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
204 if (mi != mapWallet.end())
206 CWalletTx& wtx = (*mi).second;
207 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
209 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
210 wtx.MarkSpent(txin.prevout.n);
212 vWalletUpdated.push_back(txin.prevout.hash);
219 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
221 uint256 hash = wtxIn.GetHash();
222 CRITICAL_BLOCK(cs_wallet)
224 // Inserts only if not already there, returns tx inserted or tx found
225 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
226 CWalletTx& wtx = (*ret.first).second;
228 bool fInsertedNew = ret.second;
230 wtx.nTimeReceived = GetAdjustedTime();
232 bool fUpdated = false;
236 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
238 wtx.hashBlock = wtxIn.hashBlock;
241 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
243 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
244 wtx.nIndex = wtxIn.nIndex;
247 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
249 wtx.fFromMe = wtxIn.fFromMe;
252 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
256 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
259 if (fInsertedNew || fUpdated)
260 if (!wtx.WriteToDisk())
263 // If default receiving address gets used, replace it with a new one
264 CScript scriptDefaultKey;
265 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
266 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
268 if (txout.scriptPubKey == scriptDefaultKey)
270 std::vector<unsigned char> newDefaultKey;
271 if (GetKeyFromPool(newDefaultKey, false))
273 SetDefaultKey(newDefaultKey);
274 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
280 vWalletUpdated.push_back(hash);
282 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
283 WalletUpdateSpent(wtx);
291 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
293 uint256 hash = tx.GetHash();
294 CRITICAL_BLOCK(cs_wallet)
296 bool fExisted = mapWallet.count(hash);
297 if (fExisted && !fUpdate) return false;
298 if (fExisted || IsMine(tx) || IsFromMe(tx))
300 CWalletTx wtx(this,tx);
301 // Get merkle branch if transaction was found in a block
303 wtx.SetMerkleBranch(pblock);
304 return AddToWallet(wtx);
307 WalletUpdateSpent(tx);
312 bool CWallet::EraseFromWallet(uint256 hash)
316 CRITICAL_BLOCK(cs_wallet)
318 if (mapWallet.erase(hash))
319 CWalletDB(strWalletFile).EraseTx(hash);
325 bool CWallet::IsMine(const CTxIn &txin) const
327 CRITICAL_BLOCK(cs_wallet)
329 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
330 if (mi != mapWallet.end())
332 const CWalletTx& prev = (*mi).second;
333 if (txin.prevout.n < prev.vout.size())
334 if (IsMine(prev.vout[txin.prevout.n]))
341 int64 CWallet::GetDebit(const CTxIn &txin) const
343 CRITICAL_BLOCK(cs_wallet)
345 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
346 if (mi != mapWallet.end())
348 const CWalletTx& prev = (*mi).second;
349 if (txin.prevout.n < prev.vout.size())
350 if (IsMine(prev.vout[txin.prevout.n]))
351 return prev.vout[txin.prevout.n].nValue;
357 int64 CWalletTx::GetTxTime() const
359 return nTimeReceived;
362 int CWalletTx::GetRequestCount() const
364 // Returns -1 if it wasn't being tracked
366 CRITICAL_BLOCK(pwallet->cs_wallet)
373 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
374 if (mi != pwallet->mapRequestCount.end())
375 nRequests = (*mi).second;
380 // Did anyone request this transaction?
381 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
382 if (mi != pwallet->mapRequestCount.end())
384 nRequests = (*mi).second;
386 // How about the block it's in?
387 if (nRequests == 0 && hashBlock != 0)
389 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
390 if (mi != pwallet->mapRequestCount.end())
391 nRequests = (*mi).second;
393 nRequests = 1; // If it's in someone else's block it must have got out
401 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
402 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
404 nGeneratedImmature = nGeneratedMature = nFee = 0;
405 listReceived.clear();
407 strSentAccount = strFromAccount;
411 if (GetBlocksToMaturity() > 0)
412 nGeneratedImmature = pwallet->GetCredit(*this);
414 nGeneratedMature = GetCredit();
419 int64 nDebit = GetDebit();
420 if (nDebit > 0) // debit>0 means we signed/sent this transaction
422 int64 nValueOut = GetValueOut();
423 nFee = nDebit - nValueOut;
426 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
427 // but non-standard clients might (so return a list of address/amount pairs)
428 BOOST_FOREACH(const CTxOut& txout, vout)
430 CBitcoinAddress address;
431 vector<unsigned char> vchPubKey;
432 if (!ExtractAddress(txout.scriptPubKey, NULL, address))
434 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
435 this->GetHash().ToString().c_str());
436 address = " unknown ";
439 // Don't report 'change' txouts
440 if (nDebit > 0 && pwallet->IsChange(txout))
444 listSent.push_back(make_pair(address, txout.nValue));
446 if (pwallet->IsMine(txout))
447 listReceived.push_back(make_pair(address, txout.nValue));
452 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
453 int64& nSent, int64& nFee) const
455 nGenerated = nReceived = nSent = nFee = 0;
457 int64 allGeneratedImmature, allGeneratedMature, allFee;
458 allGeneratedImmature = allGeneratedMature = allFee = 0;
459 string strSentAccount;
460 list<pair<CBitcoinAddress, int64> > listReceived;
461 list<pair<CBitcoinAddress, int64> > listSent;
462 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
464 if (strAccount == "")
465 nGenerated = allGeneratedMature;
466 if (strAccount == strSentAccount)
468 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
472 CRITICAL_BLOCK(pwallet->cs_wallet)
474 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
476 if (pwallet->mapAddressBook.count(r.first))
478 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
479 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
480 nReceived += r.second;
482 else if (strAccount.empty())
484 nReceived += r.second;
490 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
494 const int COPY_DEPTH = 3;
495 if (SetMerkleBranch() < COPY_DEPTH)
497 vector<uint256> vWorkQueue;
498 BOOST_FOREACH(const CTxIn& txin, vin)
499 vWorkQueue.push_back(txin.prevout.hash);
501 // This critsect is OK because txdb is already open
502 CRITICAL_BLOCK(pwallet->cs_wallet)
504 map<uint256, const CMerkleTx*> mapWalletPrev;
505 set<uint256> setAlreadyDone;
506 for (int i = 0; i < vWorkQueue.size(); i++)
508 uint256 hash = vWorkQueue[i];
509 if (setAlreadyDone.count(hash))
511 setAlreadyDone.insert(hash);
514 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
515 if (mi != pwallet->mapWallet.end())
518 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
519 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
521 else if (mapWalletPrev.count(hash))
523 tx = *mapWalletPrev[hash];
525 else if (!fClient && txdb.ReadDiskTx(hash, tx))
531 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
535 int nDepth = tx.SetMerkleBranch();
536 vtxPrev.push_back(tx);
538 if (nDepth < COPY_DEPTH)
539 BOOST_FOREACH(const CTxIn& txin, tx.vin)
540 vWorkQueue.push_back(txin.prevout.hash);
545 reverse(vtxPrev.begin(), vtxPrev.end());
548 bool CWalletTx::WriteToDisk()
550 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
553 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
557 CBlockIndex* pindex = pindexStart;
558 CRITICAL_BLOCK(cs_wallet)
563 block.ReadFromDisk(pindex, true);
564 BOOST_FOREACH(CTransaction& tx, block.vtx)
566 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
569 pindex = pindex->pnext;
575 void CWallet::ReacceptWalletTransactions()
579 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
582 vector<CDiskTxPos> vMissingTx;
583 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
585 CWalletTx& wtx = item.second;
586 if (wtx.IsCoinBase() && wtx.IsSpent(0))
590 bool fUpdated = false;
591 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
593 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
594 if (txindex.vSpent.size() != wtx.vout.size())
596 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
599 for (int i = 0; i < txindex.vSpent.size(); i++)
603 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
607 vMissingTx.push_back(txindex.vSpent[i]);
612 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
619 // Reaccept any txes of ours that aren't already in a block
620 if (!wtx.IsCoinBase())
621 wtx.AcceptWalletTransaction(txdb, false);
624 if (!vMissingTx.empty())
626 // TODO: optimize this to scan just part of the block chain?
627 if (ScanForWalletTransactions(pindexGenesisBlock))
628 fRepeat = true; // Found missing transactions: re-do Reaccept.
633 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
635 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
637 if (!tx.IsCoinBase())
639 uint256 hash = tx.GetHash();
640 if (!txdb.ContainsTx(hash))
641 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
646 uint256 hash = GetHash();
647 if (!txdb.ContainsTx(hash))
649 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
650 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
655 void CWalletTx::RelayWalletTransaction()
658 RelayWalletTransaction(txdb);
661 void CWallet::ResendWalletTransactions()
663 // Do this infrequently and randomly to avoid giving away
664 // that these are our transactions.
665 static int64 nNextTime;
666 if (GetTime() < nNextTime)
668 bool fFirst = (nNextTime == 0);
669 nNextTime = GetTime() + GetRand(30 * 60);
673 // Only do it if there's been a new block since last time
674 static int64 nLastTime;
675 if (nTimeBestReceived < nLastTime)
677 nLastTime = GetTime();
679 // Rebroadcast any of our txes that aren't in a block yet
680 printf("ResendWalletTransactions()\n");
682 CRITICAL_BLOCK(cs_wallet)
684 // Sort them in chronological order
685 multimap<unsigned int, CWalletTx*> mapSorted;
686 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
688 CWalletTx& wtx = item.second;
689 // Don't rebroadcast until it's had plenty of time that
690 // it should have gotten in already by now.
691 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
692 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
694 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
696 CWalletTx& wtx = *item.second;
697 wtx.RelayWalletTransaction(txdb);
707 //////////////////////////////////////////////////////////////////////////////
713 int64 CWallet::GetBalance() const
716 CRITICAL_BLOCK(cs_wallet)
718 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
720 const CWalletTx* pcoin = &(*it).second;
721 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
723 nTotal += pcoin->GetAvailableCredit();
730 int64 CWallet::GetUnconfirmedBalance() const
733 CRITICAL_BLOCK(cs_wallet)
735 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
737 const CWalletTx* pcoin = &(*it).second;
738 if (pcoin->IsFinal() && pcoin->IsConfirmed())
740 nTotal += pcoin->GetAvailableCredit();
746 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
751 // List of values less than target
752 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
753 coinLowestLarger.first = INT64_MAX;
754 coinLowestLarger.second.first = NULL;
755 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
756 int64 nTotalLower = 0;
758 CRITICAL_BLOCK(cs_wallet)
760 vector<const CWalletTx*> vCoins;
761 vCoins.reserve(mapWallet.size());
762 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
763 vCoins.push_back(&(*it).second);
764 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
766 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
768 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
771 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
774 int nDepth = pcoin->GetDepthInMainChain();
775 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
778 for (int i = 0; i < pcoin->vout.size(); i++)
780 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
783 int64 n = pcoin->vout[i].nValue;
788 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
790 if (n == nTargetValue)
792 setCoinsRet.insert(coin.second);
793 nValueRet += coin.first;
796 else if (n < nTargetValue + CENT)
798 vValue.push_back(coin);
801 else if (n < coinLowestLarger.first)
803 coinLowestLarger = coin;
809 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
811 for (int i = 0; i < vValue.size(); ++i)
813 setCoinsRet.insert(vValue[i].second);
814 nValueRet += vValue[i].first;
819 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
821 if (coinLowestLarger.second.first == NULL)
823 setCoinsRet.insert(coinLowestLarger.second);
824 nValueRet += coinLowestLarger.first;
828 if (nTotalLower >= nTargetValue + CENT)
829 nTargetValue += CENT;
831 // Solve subset sum by stochastic approximation
832 sort(vValue.rbegin(), vValue.rend());
833 vector<char> vfIncluded;
834 vector<char> vfBest(vValue.size(), true);
835 int64 nBest = nTotalLower;
837 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
839 vfIncluded.assign(vValue.size(), false);
841 bool fReachedTarget = false;
842 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
844 for (int i = 0; i < vValue.size(); i++)
846 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
848 nTotal += vValue[i].first;
849 vfIncluded[i] = true;
850 if (nTotal >= nTargetValue)
852 fReachedTarget = true;
858 nTotal -= vValue[i].first;
859 vfIncluded[i] = false;
866 // If the next larger is still closer, return it
867 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
869 setCoinsRet.insert(coinLowestLarger.second);
870 nValueRet += coinLowestLarger.first;
873 for (int i = 0; i < vValue.size(); i++)
876 setCoinsRet.insert(vValue[i].second);
877 nValueRet += vValue[i].first;
881 printf("SelectCoins() best subset: ");
882 for (int i = 0; i < vValue.size(); i++)
884 printf("%s ", FormatMoney(vValue[i].first).c_str());
885 printf("total %s\n", FormatMoney(nBest).c_str());
891 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
893 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
894 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
895 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
901 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
904 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
910 if (vecSend.empty() || nValue < 0)
913 wtxNew.pwallet = this;
915 CRITICAL_BLOCK(cs_main)
916 CRITICAL_BLOCK(cs_wallet)
918 // txdb must be opened before the mapWallet lock
921 nFeeRet = nTransactionFee;
926 wtxNew.fFromMe = true;
928 int64 nTotalValue = nValue + nFeeRet;
929 double dPriority = 0;
930 // vouts to the payees
931 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
932 wtxNew.vout.push_back(CTxOut(s.second, s.first));
934 // Choose coins to use
935 set<pair<const CWalletTx*,unsigned int> > setCoins;
937 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
939 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
941 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
942 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
945 int64 nChange = nValueIn - nValue - nFeeRet;
946 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
947 // or until nChange becomes zero
948 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
950 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
951 nChange -= nMoveToFee;
952 nFeeRet += nMoveToFee;
957 // Note: We use a new key here to keep it from being obvious which side is the change.
958 // The drawback is that by not reusing a previous key, the change may be lost if a
959 // backup is restored, if the backup doesn't have the new private key for the change.
960 // If we reused the old key, it would be possible to add code to look for and
961 // rediscover unknown transactions that were written with keys of ours to recover
962 // post-backup change.
964 // Reserve a new key pair from key pool
965 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
966 // assert(mapKeys.count(vchPubKey));
968 // Fill a vout to ourself, using same address type as the payment
969 CScript scriptChange;
970 if (vecSend[0].first.GetBitcoinAddress().IsValid())
971 scriptChange.SetBitcoinAddress(vchPubKey);
973 scriptChange << vchPubKey << OP_CHECKSIG;
975 // Insert change txn at random position:
976 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
977 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
980 reservekey.ReturnKey();
983 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
984 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
988 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
989 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
993 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
994 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
998 // Check that enough fee is included
999 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1000 bool fAllowFree = CTransaction::AllowFree(dPriority);
1001 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
1002 if (nFeeRet < max(nPayFee, nMinFee))
1004 nFeeRet = max(nPayFee, nMinFee);
1008 // Fill vtxPrev by copying from previous transactions vtxPrev
1009 wtxNew.AddSupportingTransactions(txdb);
1010 wtxNew.fTimeReceivedIsTxTime = true;
1019 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1021 vector< pair<CScript, int64> > vecSend;
1022 vecSend.push_back(make_pair(scriptPubKey, nValue));
1023 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1026 // Call after CreateTransaction unless you want to abort
1027 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1029 CRITICAL_BLOCK(cs_main)
1030 CRITICAL_BLOCK(cs_wallet)
1032 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1034 // This is only to keep the database open to defeat the auto-flush for the
1035 // duration of this scope. This is the only place where this optimization
1036 // maybe makes sense; please don't do it anywhere else.
1037 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1039 // Take key pair from key pool so it won't be used again
1040 reservekey.KeepKey();
1042 // Add tx to wallet, because if it has change it's also ours,
1043 // otherwise just for transaction history.
1044 AddToWallet(wtxNew);
1046 // Mark old coins as spent
1047 set<CWalletTx*> setCoins;
1048 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1050 CWalletTx &coin = mapWallet[txin.prevout.hash];
1051 coin.pwallet = this;
1052 coin.MarkSpent(txin.prevout.n);
1054 vWalletUpdated.push_back(coin.GetHash());
1061 // Track how many getdata requests our transaction gets
1062 mapRequestCount[wtxNew.GetHash()] = 0;
1065 if (!wtxNew.AcceptToMemoryPool())
1067 // This must not fail. The transaction has already been signed and recorded.
1068 printf("CommitTransaction() : Error: Transaction not valid");
1071 wtxNew.RelayWalletTransaction();
1080 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1082 CReserveKey reservekey(this);
1087 string strError = _("Error: Wallet locked, unable to create transaction ");
1088 printf("SendMoney() : %s", strError.c_str());
1091 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1094 if (nValue + nFeeRequired > GetBalance())
1095 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());
1097 strError = _("Error: Transaction creation failed ");
1098 printf("SendMoney() : %s", strError.c_str());
1102 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1105 if (!CommitTransaction(wtxNew, reservekey))
1106 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.");
1114 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1118 return _("Invalid amount");
1119 if (nValue + nTransactionFee > GetBalance())
1120 return _("Insufficient funds");
1122 // Parse bitcoin address
1123 CScript scriptPubKey;
1124 scriptPubKey.SetBitcoinAddress(address);
1126 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1132 int CWallet::LoadWallet(bool& fFirstRunRet)
1136 fFirstRunRet = false;
1137 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1138 if (nLoadWalletRet != DB_LOAD_OK)
1139 return nLoadWalletRet;
1140 fFirstRunRet = vchDefaultKey.empty();
1142 if (!HaveKey(Hash160(vchDefaultKey)))
1144 // Create new keyUser and set as default key
1145 RandAddSeedPerfmon();
1147 std::vector<unsigned char> newDefaultKey;
1148 if (!GetKeyFromPool(newDefaultKey, false))
1149 return DB_LOAD_FAIL;
1150 SetDefaultKey(newDefaultKey);
1151 if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""))
1152 return DB_LOAD_FAIL;
1155 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1160 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1162 mapAddressBook[address] = strName;
1165 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1168 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1170 mapAddressBook.erase(address);
1173 return CWalletDB(strWalletFile).EraseName(address.ToString());
1177 void CWallet::PrintWallet(const CBlock& block)
1179 CRITICAL_BLOCK(cs_wallet)
1181 if (mapWallet.count(block.vtx[0].GetHash()))
1183 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1184 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1190 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1192 CRITICAL_BLOCK(cs_wallet)
1194 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1195 if (mi != mapWallet.end())
1204 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1208 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1211 vchDefaultKey = vchPubKey;
1215 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1217 if (!pwallet->fFileBacked)
1219 strWalletFileOut = pwallet->strWalletFile;
1223 bool CWallet::TopUpKeyPool()
1225 CRITICAL_BLOCK(cs_wallet)
1230 CWalletDB walletdb(strWalletFile);
1233 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1234 while (setKeyPool.size() < nTargetSize+1)
1237 if (!setKeyPool.empty())
1238 nEnd = *(--setKeyPool.end()) + 1;
1239 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1240 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1241 setKeyPool.insert(nEnd);
1242 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1248 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1251 keypool.vchPubKey.clear();
1252 CRITICAL_BLOCK(cs_wallet)
1257 // Get the oldest key
1258 if(setKeyPool.empty())
1261 CWalletDB walletdb(strWalletFile);
1263 nIndex = *(setKeyPool.begin());
1264 setKeyPool.erase(setKeyPool.begin());
1265 if (!walletdb.ReadPool(nIndex, keypool))
1266 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1267 if (!HaveKey(Hash160(keypool.vchPubKey)))
1268 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1269 assert(!keypool.vchPubKey.empty());
1270 printf("keypool reserve %"PRI64d"\n", nIndex);
1274 void CWallet::KeepKey(int64 nIndex)
1276 // Remove from key pool
1279 CWalletDB walletdb(strWalletFile);
1280 walletdb.ErasePool(nIndex);
1282 printf("keypool keep %"PRI64d"\n", nIndex);
1285 void CWallet::ReturnKey(int64 nIndex)
1287 // Return to key pool
1288 CRITICAL_BLOCK(cs_wallet)
1289 setKeyPool.insert(nIndex);
1290 printf("keypool return %"PRI64d"\n", nIndex);
1293 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1297 CRITICAL_BLOCK(cs_wallet)
1299 ReserveKeyFromKeyPool(nIndex, keypool);
1302 if (fAllowReuse && !vchDefaultKey.empty())
1304 result = vchDefaultKey;
1307 if (IsLocked()) return false;
1308 result = GenerateNewKey();
1312 result = keypool.vchPubKey;
1317 int64 CWallet::GetOldestKeyPoolTime()
1321 ReserveKeyFromKeyPool(nIndex, keypool);
1325 return keypool.nTime;
1328 vector<unsigned char> CReserveKey::GetReservedKey()
1333 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1335 vchPubKey = keypool.vchPubKey;
1338 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1339 vchPubKey = pwallet->vchDefaultKey;
1342 assert(!vchPubKey.empty());
1346 void CReserveKey::KeepKey()
1349 pwallet->KeepKey(nIndex);
1354 void CReserveKey::ReturnKey()
1357 pwallet->ReturnKey(nIndex);