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 this->CKeyStore::AddKey(key);
23 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
26 void CWallet::WalletUpdateSpent(const CTransaction &tx)
28 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
29 // Update the wallet spent flag if it doesn't know due to wallet.dat being
30 // restored from backup or the user making copies of wallet.dat.
31 CRITICAL_BLOCK(cs_mapWallet)
33 BOOST_FOREACH(const CTxIn& txin, tx.vin)
35 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
36 if (mi != mapWallet.end())
38 CWalletTx& wtx = (*mi).second;
39 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
41 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
42 wtx.MarkSpent(txin.prevout.n);
44 vWalletUpdated.push_back(txin.prevout.hash);
51 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
53 uint256 hash = wtxIn.GetHash();
54 CRITICAL_BLOCK(cs_mapWallet)
56 // Inserts only if not already there, returns tx inserted or tx found
57 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
58 CWalletTx& wtx = (*ret.first).second;
60 bool fInsertedNew = ret.second;
62 wtx.nTimeReceived = GetAdjustedTime();
64 bool fUpdated = false;
68 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
70 wtx.hashBlock = wtxIn.hashBlock;
73 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
75 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
76 wtx.nIndex = wtxIn.nIndex;
79 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
81 wtx.fFromMe = wtxIn.fFromMe;
84 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
88 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
91 if (fInsertedNew || fUpdated)
92 if (!wtx.WriteToDisk())
95 // If default receiving address gets used, replace it with a new one
96 CScript scriptDefaultKey;
97 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
98 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
100 if (txout.scriptPubKey == scriptDefaultKey)
101 SetDefaultKey(GetKeyFromKeyPool());
105 vWalletUpdated.push_back(hash);
107 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
108 WalletUpdateSpent(wtx);
116 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
118 uint256 hash = tx.GetHash();
119 bool fExisted = mapWallet.count(hash);
120 if (fExisted && !fUpdate) return false;
121 if (fExisted || IsMine(tx) || IsFromMe(tx))
123 CWalletTx wtx(this,tx);
124 // Get merkle branch if transaction was found in a block
126 wtx.SetMerkleBranch(pblock);
127 return AddToWallet(wtx);
130 WalletUpdateSpent(tx);
134 bool CWallet::EraseFromWallet(uint256 hash)
138 CRITICAL_BLOCK(cs_mapWallet)
140 if (mapWallet.erase(hash))
141 CWalletDB(strWalletFile).EraseTx(hash);
147 bool CWallet::IsMine(const CTxIn &txin) const
149 CRITICAL_BLOCK(cs_mapWallet)
151 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
152 if (mi != mapWallet.end())
154 const CWalletTx& prev = (*mi).second;
155 if (txin.prevout.n < prev.vout.size())
156 if (IsMine(prev.vout[txin.prevout.n]))
163 int64 CWallet::GetDebit(const CTxIn &txin) const
165 CRITICAL_BLOCK(cs_mapWallet)
167 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
168 if (mi != mapWallet.end())
170 const CWalletTx& prev = (*mi).second;
171 if (txin.prevout.n < prev.vout.size())
172 if (IsMine(prev.vout[txin.prevout.n]))
173 return prev.vout[txin.prevout.n].nValue;
179 int64 CWalletTx::GetTxTime() const
181 if (!fTimeReceivedIsTxTime && hashBlock != 0)
183 // If we did not receive the transaction directly, we rely on the block's
184 // time to figure out when it happened. We use the median over a range
185 // of blocks to try to filter out inaccurate block times.
186 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
187 if (mi != mapBlockIndex.end())
189 CBlockIndex* pindex = (*mi).second;
191 return pindex->GetMedianTime();
194 return nTimeReceived;
197 int CWalletTx::GetRequestCount() const
199 // Returns -1 if it wasn't being tracked
201 CRITICAL_BLOCK(pwallet->cs_mapRequestCount)
208 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
209 if (mi != pwallet->mapRequestCount.end())
210 nRequests = (*mi).second;
215 // Did anyone request this transaction?
216 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
217 if (mi != pwallet->mapRequestCount.end())
219 nRequests = (*mi).second;
221 // How about the block it's in?
222 if (nRequests == 0 && hashBlock != 0)
224 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
225 if (mi != pwallet->mapRequestCount.end())
226 nRequests = (*mi).second;
228 nRequests = 1; // If it's in someone else's block it must have got out
236 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
237 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
239 nGeneratedImmature = nGeneratedMature = nFee = 0;
240 listReceived.clear();
242 strSentAccount = strFromAccount;
246 if (GetBlocksToMaturity() > 0)
247 nGeneratedImmature = pwallet->GetCredit(*this);
249 nGeneratedMature = GetCredit();
254 int64 nDebit = GetDebit();
255 if (nDebit > 0) // debit>0 means we signed/sent this transaction
257 int64 nValueOut = GetValueOut();
258 nFee = nDebit - nValueOut;
261 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
262 // but non-standard clients might (so return a list of address/amount pairs)
263 BOOST_FOREACH(const CTxOut& txout, vout)
267 vector<unsigned char> vchPubKey;
268 if (ExtractHash160(txout.scriptPubKey, hash160))
269 address = Hash160ToAddress(hash160);
270 else if (ExtractPubKey(txout.scriptPubKey, NULL, vchPubKey))
271 address = PubKeyToAddress(vchPubKey);
274 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
275 this->GetHash().ToString().c_str());
276 address = " unknown ";
279 // Don't report 'change' txouts
280 if (nDebit > 0 && pwallet->IsChange(txout))
284 listSent.push_back(make_pair(address, txout.nValue));
286 if (pwallet->IsMine(txout))
287 listReceived.push_back(make_pair(address, txout.nValue));
292 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
293 int64& nSent, int64& nFee) const
295 nGenerated = nReceived = nSent = nFee = 0;
297 int64 allGeneratedImmature, allGeneratedMature, allFee;
298 allGeneratedImmature = allGeneratedMature = allFee = 0;
299 string strSentAccount;
300 list<pair<string, int64> > listReceived;
301 list<pair<string, int64> > listSent;
302 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
304 if (strAccount == "")
305 nGenerated = allGeneratedMature;
306 if (strAccount == strSentAccount)
308 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
312 CRITICAL_BLOCK(pwallet->cs_mapAddressBook)
314 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
316 if (pwallet->mapAddressBook.count(r.first))
318 map<string, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
319 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
320 nReceived += r.second;
322 else if (strAccount.empty())
324 nReceived += r.second;
330 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
334 const int COPY_DEPTH = 3;
335 if (SetMerkleBranch() < COPY_DEPTH)
337 vector<uint256> vWorkQueue;
338 BOOST_FOREACH(const CTxIn& txin, vin)
339 vWorkQueue.push_back(txin.prevout.hash);
341 // This critsect is OK because txdb is already open
342 CRITICAL_BLOCK(pwallet->cs_mapWallet)
344 map<uint256, const CMerkleTx*> mapWalletPrev;
345 set<uint256> setAlreadyDone;
346 for (int i = 0; i < vWorkQueue.size(); i++)
348 uint256 hash = vWorkQueue[i];
349 if (setAlreadyDone.count(hash))
351 setAlreadyDone.insert(hash);
354 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
355 if (mi != pwallet->mapWallet.end())
358 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
359 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
361 else if (mapWalletPrev.count(hash))
363 tx = *mapWalletPrev[hash];
365 else if (!fClient && txdb.ReadDiskTx(hash, tx))
371 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
375 int nDepth = tx.SetMerkleBranch();
376 vtxPrev.push_back(tx);
378 if (nDepth < COPY_DEPTH)
379 BOOST_FOREACH(const CTxIn& txin, tx.vin)
380 vWorkQueue.push_back(txin.prevout.hash);
385 reverse(vtxPrev.begin(), vtxPrev.end());
388 bool CWalletTx::WriteToDisk()
390 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
393 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
397 CBlockIndex* pindex = pindexStart;
398 CRITICAL_BLOCK(cs_mapWallet)
403 block.ReadFromDisk(pindex, true);
404 BOOST_FOREACH(CTransaction& tx, block.vtx)
406 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
409 pindex = pindex->pnext;
415 void CWallet::ReacceptWalletTransactions()
419 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
422 vector<CDiskTxPos> vMissingTx;
423 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
425 CWalletTx& wtx = item.second;
426 if (wtx.IsCoinBase() && wtx.IsSpent(0))
430 bool fUpdated = false;
431 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
433 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
434 if (txindex.vSpent.size() != wtx.vout.size())
436 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
439 for (int i = 0; i < txindex.vSpent.size(); i++)
443 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
447 vMissingTx.push_back(txindex.vSpent[i]);
452 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
459 // Reaccept any txes of ours that aren't already in a block
460 if (!wtx.IsCoinBase())
461 wtx.AcceptWalletTransaction(txdb, false);
464 if (!vMissingTx.empty())
466 // TODO: optimize this to scan just part of the block chain?
467 if (ScanForWalletTransactions(pindexGenesisBlock))
468 fRepeat = true; // Found missing transactions: re-do Reaccept.
473 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
475 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
477 if (!tx.IsCoinBase())
479 uint256 hash = tx.GetHash();
480 if (!txdb.ContainsTx(hash))
481 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
486 uint256 hash = GetHash();
487 if (!txdb.ContainsTx(hash))
489 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
490 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
495 void CWalletTx::RelayWalletTransaction()
498 RelayWalletTransaction(txdb);
501 void CWallet::ResendWalletTransactions()
503 // Do this infrequently and randomly to avoid giving away
504 // that these are our transactions.
505 static int64 nNextTime;
506 if (GetTime() < nNextTime)
508 bool fFirst = (nNextTime == 0);
509 nNextTime = GetTime() + GetRand(30 * 60);
513 // Only do it if there's been a new block since last time
514 static int64 nLastTime;
515 if (nTimeBestReceived < nLastTime)
517 nLastTime = GetTime();
519 // Rebroadcast any of our txes that aren't in a block yet
520 printf("ResendWalletTransactions()\n");
522 CRITICAL_BLOCK(cs_mapWallet)
524 // Sort them in chronological order
525 multimap<unsigned int, CWalletTx*> mapSorted;
526 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
528 CWalletTx& wtx = item.second;
529 // Don't rebroadcast until it's had plenty of time that
530 // it should have gotten in already by now.
531 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
532 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
534 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
536 CWalletTx& wtx = *item.second;
537 wtx.RelayWalletTransaction(txdb);
547 //////////////////////////////////////////////////////////////////////////////
553 int64 CWallet::GetBalance() const
555 int64 nStart = GetTimeMillis();
558 CRITICAL_BLOCK(cs_mapWallet)
560 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
562 const CWalletTx* pcoin = &(*it).second;
563 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
565 nTotal += pcoin->GetAvailableCredit();
569 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
574 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
579 // List of values less than target
580 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
581 coinLowestLarger.first = INT64_MAX;
582 coinLowestLarger.second.first = NULL;
583 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
584 int64 nTotalLower = 0;
586 CRITICAL_BLOCK(cs_mapWallet)
588 vector<const CWalletTx*> vCoins;
589 vCoins.reserve(mapWallet.size());
590 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
591 vCoins.push_back(&(*it).second);
592 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
594 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
596 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
599 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
602 int nDepth = pcoin->GetDepthInMainChain();
603 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
606 for (int i = 0; i < pcoin->vout.size(); i++)
608 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
611 int64 n = pcoin->vout[i].nValue;
616 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
618 if (n == nTargetValue)
620 setCoinsRet.insert(coin.second);
621 nValueRet += coin.first;
624 else if (n < nTargetValue + CENT)
626 vValue.push_back(coin);
629 else if (n < coinLowestLarger.first)
631 coinLowestLarger = coin;
637 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
639 for (int i = 0; i < vValue.size(); ++i)
641 setCoinsRet.insert(vValue[i].second);
642 nValueRet += vValue[i].first;
647 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
649 if (coinLowestLarger.second.first == NULL)
651 setCoinsRet.insert(coinLowestLarger.second);
652 nValueRet += coinLowestLarger.first;
656 if (nTotalLower >= nTargetValue + CENT)
657 nTargetValue += CENT;
659 // Solve subset sum by stochastic approximation
660 sort(vValue.rbegin(), vValue.rend());
661 vector<char> vfIncluded;
662 vector<char> vfBest(vValue.size(), true);
663 int64 nBest = nTotalLower;
665 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
667 vfIncluded.assign(vValue.size(), false);
669 bool fReachedTarget = false;
670 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
672 for (int i = 0; i < vValue.size(); i++)
674 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
676 nTotal += vValue[i].first;
677 vfIncluded[i] = true;
678 if (nTotal >= nTargetValue)
680 fReachedTarget = true;
686 nTotal -= vValue[i].first;
687 vfIncluded[i] = false;
694 // If the next larger is still closer, return it
695 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
697 setCoinsRet.insert(coinLowestLarger.second);
698 nValueRet += coinLowestLarger.first;
701 for (int i = 0; i < vValue.size(); i++)
704 setCoinsRet.insert(vValue[i].second);
705 nValueRet += vValue[i].first;
709 printf("SelectCoins() best subset: ");
710 for (int i = 0; i < vValue.size(); i++)
712 printf("%s ", FormatMoney(vValue[i].first).c_str());
713 printf("total %s\n", FormatMoney(nBest).c_str());
719 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
721 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
722 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
723 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
729 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
732 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
738 if (vecSend.empty() || nValue < 0)
741 wtxNew.pwallet = this;
743 CRITICAL_BLOCK(cs_main)
745 // txdb must be opened before the mapWallet lock
747 CRITICAL_BLOCK(cs_mapWallet)
749 nFeeRet = nTransactionFee;
754 wtxNew.fFromMe = true;
756 int64 nTotalValue = nValue + nFeeRet;
757 double dPriority = 0;
758 // vouts to the payees
759 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
760 wtxNew.vout.push_back(CTxOut(s.second, s.first));
762 // Choose coins to use
763 set<pair<const CWalletTx*,unsigned int> > setCoins;
765 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
767 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
769 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
770 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
773 // Fill a vout back to self with any change
774 int64 nChange = nValueIn - nTotalValue;
777 // Note: We use a new key here to keep it from being obvious which side is the change.
778 // The drawback is that by not reusing a previous key, the change may be lost if a
779 // backup is restored, if the backup doesn't have the new private key for the change.
780 // If we reused the old key, it would be possible to add code to look for and
781 // rediscover unknown transactions that were written with keys of ours to recover
782 // post-backup change.
784 // Reserve a new key pair from key pool
785 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
786 assert(mapKeys.count(vchPubKey));
788 // Fill a vout to ourself, using same address type as the payment
789 CScript scriptChange;
790 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
791 scriptChange.SetBitcoinAddress(vchPubKey);
793 scriptChange << vchPubKey << OP_CHECKSIG;
795 // Insert change txn at random position:
796 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
797 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
800 reservekey.ReturnKey();
803 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
804 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
808 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
809 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
813 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
814 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
818 // Check that enough fee is included
819 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
820 bool fAllowFree = CTransaction::AllowFree(dPriority);
821 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
822 if (nFeeRet < max(nPayFee, nMinFee))
824 nFeeRet = max(nPayFee, nMinFee);
828 // Fill vtxPrev by copying from previous transactions vtxPrev
829 wtxNew.AddSupportingTransactions(txdb);
830 wtxNew.fTimeReceivedIsTxTime = true;
839 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
841 vector< pair<CScript, int64> > vecSend;
842 vecSend.push_back(make_pair(scriptPubKey, nValue));
843 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
846 // Call after CreateTransaction unless you want to abort
847 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
849 CRITICAL_BLOCK(cs_main)
851 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
852 CRITICAL_BLOCK(cs_mapWallet)
854 // This is only to keep the database open to defeat the auto-flush for the
855 // duration of this scope. This is the only place where this optimization
856 // maybe makes sense; please don't do it anywhere else.
857 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
859 // Take key pair from key pool so it won't be used again
860 reservekey.KeepKey();
862 // Add tx to wallet, because if it has change it's also ours,
863 // otherwise just for transaction history.
866 // Mark old coins as spent
867 set<CWalletTx*> setCoins;
868 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
870 CWalletTx &coin = mapWallet[txin.prevout.hash];
872 coin.MarkSpent(txin.prevout.n);
874 vWalletUpdated.push_back(coin.GetHash());
881 // Track how many getdata requests our transaction gets
882 CRITICAL_BLOCK(cs_mapRequestCount)
883 mapRequestCount[wtxNew.GetHash()] = 0;
886 if (!wtxNew.AcceptToMemoryPool())
888 // This must not fail. The transaction has already been signed and recorded.
889 printf("CommitTransaction() : Error: Transaction not valid");
892 wtxNew.RelayWalletTransaction();
901 // requires cs_main lock
902 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
904 CReserveKey reservekey(this);
906 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
909 if (nValue + nFeeRequired > GetBalance())
910 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());
912 strError = _("Error: Transaction creation failed ");
913 printf("SendMoney() : %s", strError.c_str());
917 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
920 if (!CommitTransaction(wtxNew, reservekey))
921 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.");
929 // requires cs_main lock
930 string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
934 return _("Invalid amount");
935 if (nValue + nTransactionFee > GetBalance())
936 return _("Insufficient funds");
938 // Parse bitcoin address
939 CScript scriptPubKey;
940 if (!scriptPubKey.SetBitcoinAddress(strAddress))
941 return _("Invalid bitcoin address");
943 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
949 bool CWallet::LoadWallet(bool& fFirstRunRet)
953 fFirstRunRet = false;
954 if (!CWalletDB(strWalletFile,"cr+").LoadWallet(this))
956 fFirstRunRet = vchDefaultKey.empty();
958 if (!mapKeys.count(vchDefaultKey))
960 // Create new default key
961 RandAddSeedPerfmon();
963 SetDefaultKey(GetKeyFromKeyPool());
964 if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))
968 CreateThread(ThreadFlushWalletDB, &strWalletFile);
973 bool CWallet::SetAddressBookName(const string& strAddress, const string& strName)
975 mapAddressBook[strAddress] = strName;
978 return CWalletDB(strWalletFile).WriteName(strAddress, strName);
981 bool CWallet::DelAddressBookName(const string& strAddress)
983 mapAddressBook.erase(strAddress);
986 return CWalletDB(strWalletFile).EraseName(strAddress);
990 void CWallet::PrintWallet(const CBlock& block)
992 CRITICAL_BLOCK(cs_mapWallet)
994 if (mapWallet.count(block.vtx[0].GetHash()))
996 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
997 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1003 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1005 CRITICAL_BLOCK(cs_mapWallet)
1007 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1008 if (mi != mapWallet.end())
1017 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1021 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1024 vchDefaultKey = vchPubKey;
1028 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1030 if (!pwallet->fFileBacked)
1032 strWalletFileOut = pwallet->strWalletFile;
1036 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1039 keypool.vchPubKey.clear();
1040 CRITICAL_BLOCK(cs_main)
1041 CRITICAL_BLOCK(cs_mapWallet)
1042 CRITICAL_BLOCK(cs_setKeyPool)
1044 CWalletDB walletdb(strWalletFile);
1047 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1048 while (setKeyPool.size() < nTargetSize+1)
1051 if (!setKeyPool.empty())
1052 nEnd = *(--setKeyPool.end()) + 1;
1053 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1054 throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");
1055 setKeyPool.insert(nEnd);
1056 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1059 // Get the oldest key
1060 assert(!setKeyPool.empty());
1061 nIndex = *(setKeyPool.begin());
1062 setKeyPool.erase(setKeyPool.begin());
1063 if (!walletdb.ReadPool(nIndex, keypool))
1064 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1065 if (!mapKeys.count(keypool.vchPubKey))
1066 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1067 assert(!keypool.vchPubKey.empty());
1068 printf("keypool reserve %"PRI64d"\n", nIndex);
1072 void CWallet::KeepKey(int64 nIndex)
1074 // Remove from key pool
1077 CWalletDB walletdb(strWalletFile);
1078 CRITICAL_BLOCK(cs_main)
1080 walletdb.ErasePool(nIndex);
1083 printf("keypool keep %"PRI64d"\n", nIndex);
1086 void CWallet::ReturnKey(int64 nIndex)
1088 // Return to key pool
1089 CRITICAL_BLOCK(cs_setKeyPool)
1090 setKeyPool.insert(nIndex);
1091 printf("keypool return %"PRI64d"\n", nIndex);
1094 vector<unsigned char> CWallet::GetKeyFromKeyPool()
1098 ReserveKeyFromKeyPool(nIndex, keypool);
1100 return keypool.vchPubKey;
1103 int64 CWallet::GetOldestKeyPoolTime()
1107 ReserveKeyFromKeyPool(nIndex, keypool);
1109 return keypool.nTime;
1112 vector<unsigned char> CReserveKey::GetReservedKey()
1117 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1118 vchPubKey = keypool.vchPubKey;
1120 assert(!vchPubKey.empty());
1124 void CReserveKey::KeepKey()
1127 pwallet->KeepKey(nIndex);
1132 void CReserveKey::ReturnKey()
1135 pwallet->ReturnKey(nIndex);