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)
104 CWalletDB walletdb(strWalletFile);
105 vchDefaultKey = GetKeyFromKeyPool();
106 walletdb.WriteDefaultKey(vchDefaultKey);
107 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
112 vWalletUpdated.push_back(hash);
114 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
115 WalletUpdateSpent(wtx);
123 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
125 uint256 hash = tx.GetHash();
126 bool fExisted = mapWallet.count(hash);
127 if (fExisted && !fUpdate) return false;
128 if (fExisted || IsMine(tx) || IsFromMe(tx))
130 CWalletTx wtx(this,tx);
131 // Get merkle branch if transaction was found in a block
133 wtx.SetMerkleBranch(pblock);
134 return AddToWallet(wtx);
137 WalletUpdateSpent(tx);
141 bool CWallet::EraseFromWallet(uint256 hash)
145 CRITICAL_BLOCK(cs_mapWallet)
147 if (mapWallet.erase(hash))
148 CWalletDB(strWalletFile).EraseTx(hash);
154 bool CWallet::IsMine(const CTxIn &txin) const
156 CRITICAL_BLOCK(cs_mapWallet)
158 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
159 if (mi != mapWallet.end())
161 const CWalletTx& prev = (*mi).second;
162 if (txin.prevout.n < prev.vout.size())
163 if (IsMine(prev.vout[txin.prevout.n]))
170 int64 CWallet::GetDebit(const CTxIn &txin) const
172 CRITICAL_BLOCK(cs_mapWallet)
174 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
175 if (mi != mapWallet.end())
177 const CWalletTx& prev = (*mi).second;
178 if (txin.prevout.n < prev.vout.size())
179 if (IsMine(prev.vout[txin.prevout.n]))
180 return prev.vout[txin.prevout.n].nValue;
186 int64 CWalletTx::GetTxTime() const
188 if (!fTimeReceivedIsTxTime && hashBlock != 0)
190 // If we did not receive the transaction directly, we rely on the block's
191 // time to figure out when it happened. We use the median over a range
192 // of blocks to try to filter out inaccurate block times.
193 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
194 if (mi != mapBlockIndex.end())
196 CBlockIndex* pindex = (*mi).second;
198 return pindex->GetMedianTime();
201 return nTimeReceived;
204 int CWalletTx::GetRequestCount() const
206 // Returns -1 if it wasn't being tracked
208 CRITICAL_BLOCK(pwallet->cs_mapRequestCount)
215 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
216 if (mi != pwallet->mapRequestCount.end())
217 nRequests = (*mi).second;
222 // Did anyone request this transaction?
223 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
224 if (mi != pwallet->mapRequestCount.end())
226 nRequests = (*mi).second;
228 // How about the block it's in?
229 if (nRequests == 0 && hashBlock != 0)
231 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
232 if (mi != pwallet->mapRequestCount.end())
233 nRequests = (*mi).second;
235 nRequests = 1; // If it's in someone else's block it must have got out
243 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
244 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
246 nGeneratedImmature = nGeneratedMature = nFee = 0;
247 listReceived.clear();
249 strSentAccount = strFromAccount;
253 if (GetBlocksToMaturity() > 0)
254 nGeneratedImmature = pwallet->GetCredit(*this);
256 nGeneratedMature = GetCredit();
261 int64 nDebit = GetDebit();
262 if (nDebit > 0) // debit>0 means we signed/sent this transaction
264 int64 nValueOut = GetValueOut();
265 nFee = nDebit - nValueOut;
268 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
269 // but non-standard clients might (so return a list of address/amount pairs)
270 BOOST_FOREACH(const CTxOut& txout, vout)
274 vector<unsigned char> vchPubKey;
275 if (ExtractHash160(txout.scriptPubKey, hash160))
276 address = Hash160ToAddress(hash160);
277 else if (ExtractPubKey(txout.scriptPubKey, NULL, vchPubKey))
278 address = PubKeyToAddress(vchPubKey);
281 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
282 this->GetHash().ToString().c_str());
283 address = " unknown ";
286 // Don't report 'change' txouts
287 if (nDebit > 0 && pwallet->IsChange(txout))
291 listSent.push_back(make_pair(address, txout.nValue));
293 if (pwallet->IsMine(txout))
294 listReceived.push_back(make_pair(address, txout.nValue));
299 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
300 int64& nSent, int64& nFee) const
302 nGenerated = nReceived = nSent = nFee = 0;
304 int64 allGeneratedImmature, allGeneratedMature, allFee;
305 allGeneratedImmature = allGeneratedMature = allFee = 0;
306 string strSentAccount;
307 list<pair<string, int64> > listReceived;
308 list<pair<string, int64> > listSent;
309 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
311 if (strAccount == "")
312 nGenerated = allGeneratedMature;
313 if (strAccount == strSentAccount)
315 BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
319 CRITICAL_BLOCK(pwallet->cs_mapAddressBook)
321 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
323 if (pwallet->mapAddressBook.count(r.first))
325 map<string, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
326 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
327 nReceived += r.second;
329 else if (strAccount.empty())
331 nReceived += r.second;
337 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
341 const int COPY_DEPTH = 3;
342 if (SetMerkleBranch() < COPY_DEPTH)
344 vector<uint256> vWorkQueue;
345 BOOST_FOREACH(const CTxIn& txin, vin)
346 vWorkQueue.push_back(txin.prevout.hash);
348 // This critsect is OK because txdb is already open
349 CRITICAL_BLOCK(pwallet->cs_mapWallet)
351 map<uint256, const CMerkleTx*> mapWalletPrev;
352 set<uint256> setAlreadyDone;
353 for (int i = 0; i < vWorkQueue.size(); i++)
355 uint256 hash = vWorkQueue[i];
356 if (setAlreadyDone.count(hash))
358 setAlreadyDone.insert(hash);
361 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
362 if (mi != pwallet->mapWallet.end())
365 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
366 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
368 else if (mapWalletPrev.count(hash))
370 tx = *mapWalletPrev[hash];
372 else if (!fClient && txdb.ReadDiskTx(hash, tx))
378 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
382 int nDepth = tx.SetMerkleBranch();
383 vtxPrev.push_back(tx);
385 if (nDepth < COPY_DEPTH)
386 BOOST_FOREACH(const CTxIn& txin, tx.vin)
387 vWorkQueue.push_back(txin.prevout.hash);
392 reverse(vtxPrev.begin(), vtxPrev.end());
395 bool CWalletTx::WriteToDisk()
397 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
400 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
404 CBlockIndex* pindex = pindexStart;
405 CRITICAL_BLOCK(cs_mapWallet)
410 block.ReadFromDisk(pindex, true);
411 BOOST_FOREACH(CTransaction& tx, block.vtx)
413 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
416 pindex = pindex->pnext;
422 void CWallet::ReacceptWalletTransactions()
426 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
429 vector<CDiskTxPos> vMissingTx;
430 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
432 CWalletTx& wtx = item.second;
433 if (wtx.IsCoinBase() && wtx.IsSpent(0))
437 bool fUpdated = false;
438 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
440 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
441 if (txindex.vSpent.size() != wtx.vout.size())
443 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
446 for (int i = 0; i < txindex.vSpent.size(); i++)
450 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
454 vMissingTx.push_back(txindex.vSpent[i]);
459 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
466 // Reaccept any txes of ours that aren't already in a block
467 if (!wtx.IsCoinBase())
468 wtx.AcceptWalletTransaction(txdb, false);
471 if (!vMissingTx.empty())
473 // TODO: optimize this to scan just part of the block chain?
474 if (ScanForWalletTransactions(pindexGenesisBlock))
475 fRepeat = true; // Found missing transactions: re-do Reaccept.
480 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
482 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
484 if (!tx.IsCoinBase())
486 uint256 hash = tx.GetHash();
487 if (!txdb.ContainsTx(hash))
488 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
493 uint256 hash = GetHash();
494 if (!txdb.ContainsTx(hash))
496 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
497 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
502 void CWalletTx::RelayWalletTransaction()
505 RelayWalletTransaction(txdb);
508 void CWallet::ResendWalletTransactions()
510 // Do this infrequently and randomly to avoid giving away
511 // that these are our transactions.
512 static int64 nNextTime;
513 if (GetTime() < nNextTime)
515 bool fFirst = (nNextTime == 0);
516 nNextTime = GetTime() + GetRand(30 * 60);
520 // Only do it if there's been a new block since last time
521 static int64 nLastTime;
522 if (nTimeBestReceived < nLastTime)
524 nLastTime = GetTime();
526 // Rebroadcast any of our txes that aren't in a block yet
527 printf("ResendWalletTransactions()\n");
529 CRITICAL_BLOCK(cs_mapWallet)
531 // Sort them in chronological order
532 multimap<unsigned int, CWalletTx*> mapSorted;
533 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
535 CWalletTx& wtx = item.second;
536 // Don't rebroadcast until it's had plenty of time that
537 // it should have gotten in already by now.
538 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
539 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
541 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
543 CWalletTx& wtx = *item.second;
544 wtx.RelayWalletTransaction(txdb);
554 //////////////////////////////////////////////////////////////////////////////
560 int64 CWallet::GetBalance() const
562 int64 nStart = GetTimeMillis();
565 CRITICAL_BLOCK(cs_mapWallet)
567 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
569 const CWalletTx* pcoin = &(*it).second;
570 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
572 nTotal += pcoin->GetAvailableCredit();
576 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
581 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
586 // List of values less than target
587 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
588 coinLowestLarger.first = INT64_MAX;
589 coinLowestLarger.second.first = NULL;
590 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
591 int64 nTotalLower = 0;
593 CRITICAL_BLOCK(cs_mapWallet)
595 vector<const CWalletTx*> vCoins;
596 vCoins.reserve(mapWallet.size());
597 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
598 vCoins.push_back(&(*it).second);
599 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
601 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
603 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
606 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
609 int nDepth = pcoin->GetDepthInMainChain();
610 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
613 for (int i = 0; i < pcoin->vout.size(); i++)
615 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
618 int64 n = pcoin->vout[i].nValue;
623 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
625 if (n == nTargetValue)
627 setCoinsRet.insert(coin.second);
628 nValueRet += coin.first;
631 else if (n < nTargetValue + CENT)
633 vValue.push_back(coin);
636 else if (n < coinLowestLarger.first)
638 coinLowestLarger = coin;
644 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
646 for (int i = 0; i < vValue.size(); ++i)
648 setCoinsRet.insert(vValue[i].second);
649 nValueRet += vValue[i].first;
654 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
656 if (coinLowestLarger.second.first == NULL)
658 setCoinsRet.insert(coinLowestLarger.second);
659 nValueRet += coinLowestLarger.first;
663 if (nTotalLower >= nTargetValue + CENT)
664 nTargetValue += CENT;
666 // Solve subset sum by stochastic approximation
667 sort(vValue.rbegin(), vValue.rend());
668 vector<char> vfIncluded;
669 vector<char> vfBest(vValue.size(), true);
670 int64 nBest = nTotalLower;
672 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
674 vfIncluded.assign(vValue.size(), false);
676 bool fReachedTarget = false;
677 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
679 for (int i = 0; i < vValue.size(); i++)
681 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
683 nTotal += vValue[i].first;
684 vfIncluded[i] = true;
685 if (nTotal >= nTargetValue)
687 fReachedTarget = true;
693 nTotal -= vValue[i].first;
694 vfIncluded[i] = false;
701 // If the next larger is still closer, return it
702 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
704 setCoinsRet.insert(coinLowestLarger.second);
705 nValueRet += coinLowestLarger.first;
708 for (int i = 0; i < vValue.size(); i++)
711 setCoinsRet.insert(vValue[i].second);
712 nValueRet += vValue[i].first;
716 printf("SelectCoins() best subset: ");
717 for (int i = 0; i < vValue.size(); i++)
719 printf("%s ", FormatMoney(vValue[i].first).c_str());
720 printf("total %s\n", FormatMoney(nBest).c_str());
726 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
728 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
729 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
730 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
736 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
739 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
745 if (vecSend.empty() || nValue < 0)
748 wtxNew.pwallet = this;
750 CRITICAL_BLOCK(cs_main)
752 // txdb must be opened before the mapWallet lock
754 CRITICAL_BLOCK(cs_mapWallet)
756 nFeeRet = nTransactionFee;
761 wtxNew.fFromMe = true;
763 int64 nTotalValue = nValue + nFeeRet;
764 double dPriority = 0;
765 // vouts to the payees
766 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
767 wtxNew.vout.push_back(CTxOut(s.second, s.first));
769 // Choose coins to use
770 set<pair<const CWalletTx*,unsigned int> > setCoins;
772 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
774 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
776 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
777 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
780 // Fill a vout back to self with any change
781 int64 nChange = nValueIn - nTotalValue;
784 // Note: We use a new key here to keep it from being obvious which side is the change.
785 // The drawback is that by not reusing a previous key, the change may be lost if a
786 // backup is restored, if the backup doesn't have the new private key for the change.
787 // If we reused the old key, it would be possible to add code to look for and
788 // rediscover unknown transactions that were written with keys of ours to recover
789 // post-backup change.
791 // Reserve a new key pair from key pool
792 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
793 assert(mapKeys.count(vchPubKey));
795 // Fill a vout to ourself, using same address type as the payment
796 CScript scriptChange;
797 if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
798 scriptChange.SetBitcoinAddress(vchPubKey);
800 scriptChange << vchPubKey << OP_CHECKSIG;
802 // Insert change txn at random position:
803 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
804 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
807 reservekey.ReturnKey();
810 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
811 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
815 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
816 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
820 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
821 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
825 // Check that enough fee is included
826 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
827 bool fAllowFree = CTransaction::AllowFree(dPriority);
828 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
829 if (nFeeRet < max(nPayFee, nMinFee))
831 nFeeRet = max(nPayFee, nMinFee);
835 // Fill vtxPrev by copying from previous transactions vtxPrev
836 wtxNew.AddSupportingTransactions(txdb);
837 wtxNew.fTimeReceivedIsTxTime = true;
846 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
848 vector< pair<CScript, int64> > vecSend;
849 vecSend.push_back(make_pair(scriptPubKey, nValue));
850 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
853 // Call after CreateTransaction unless you want to abort
854 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
856 CRITICAL_BLOCK(cs_main)
858 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
859 CRITICAL_BLOCK(cs_mapWallet)
861 // This is only to keep the database open to defeat the auto-flush for the
862 // duration of this scope. This is the only place where this optimization
863 // maybe makes sense; please don't do it anywhere else.
864 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
866 // Take key pair from key pool so it won't be used again
867 reservekey.KeepKey();
869 // Add tx to wallet, because if it has change it's also ours,
870 // otherwise just for transaction history.
873 // Mark old coins as spent
874 set<CWalletTx*> setCoins;
875 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
877 CWalletTx &coin = mapWallet[txin.prevout.hash];
879 coin.MarkSpent(txin.prevout.n);
881 vWalletUpdated.push_back(coin.GetHash());
888 // Track how many getdata requests our transaction gets
889 CRITICAL_BLOCK(cs_mapRequestCount)
890 mapRequestCount[wtxNew.GetHash()] = 0;
893 if (!wtxNew.AcceptToMemoryPool())
895 // This must not fail. The transaction has already been signed and recorded.
896 printf("CommitTransaction() : Error: Transaction not valid");
899 wtxNew.RelayWalletTransaction();
908 // requires cs_main lock
909 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
911 CReserveKey reservekey(this);
913 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
916 if (nValue + nFeeRequired > GetBalance())
917 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());
919 strError = _("Error: Transaction creation failed ");
920 printf("SendMoney() : %s", strError.c_str());
924 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
927 if (!CommitTransaction(wtxNew, reservekey))
928 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.");
936 // requires cs_main lock
937 string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
941 return _("Invalid amount");
942 if (nValue + nTransactionFee > GetBalance())
943 return _("Insufficient funds");
945 // Parse bitcoin address
946 CScript scriptPubKey;
947 if (!scriptPubKey.SetBitcoinAddress(strAddress))
948 return _("Invalid bitcoin address");
950 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
956 bool CWallet::LoadWallet(bool& fFirstRunRet)
960 fFirstRunRet = false;
961 if (!CWalletDB(strWalletFile,"cr+").LoadWallet(this))
963 fFirstRunRet = vchDefaultKey.empty();
965 if (!mapKeys.count(vchDefaultKey))
967 // Create new default key
968 RandAddSeedPerfmon();
970 vchDefaultKey = GetKeyFromKeyPool();
971 if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))
973 CWalletDB(strWalletFile).WriteDefaultKey(vchDefaultKey);
976 CreateThread(ThreadFlushWalletDB, &strWalletFile);
980 void CWallet::PrintWallet(const CBlock& block)
982 CRITICAL_BLOCK(cs_mapWallet)
984 if (mapWallet.count(block.vtx[0].GetHash()))
986 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
987 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
993 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
995 CRITICAL_BLOCK(cs_mapWallet)
997 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
998 if (mi != mapWallet.end())
1007 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1009 if (!pwallet->fFileBacked)
1011 strWalletFileOut = pwallet->strWalletFile;
1015 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1018 keypool.vchPubKey.clear();
1019 CRITICAL_BLOCK(cs_main)
1020 CRITICAL_BLOCK(cs_mapWallet)
1021 CRITICAL_BLOCK(cs_setKeyPool)
1023 CWalletDB walletdb(strWalletFile);
1026 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1027 while (setKeyPool.size() < nTargetSize+1)
1030 if (!setKeyPool.empty())
1031 nEnd = *(--setKeyPool.end()) + 1;
1032 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1033 throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");
1034 setKeyPool.insert(nEnd);
1035 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1038 // Get the oldest key
1039 assert(!setKeyPool.empty());
1040 nIndex = *(setKeyPool.begin());
1041 setKeyPool.erase(setKeyPool.begin());
1042 if (!walletdb.ReadPool(nIndex, keypool))
1043 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1044 if (!mapKeys.count(keypool.vchPubKey))
1045 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1046 assert(!keypool.vchPubKey.empty());
1047 printf("keypool reserve %"PRI64d"\n", nIndex);
1051 void CWallet::KeepKey(int64 nIndex)
1053 // Remove from key pool
1056 CWalletDB walletdb(strWalletFile);
1057 CRITICAL_BLOCK(cs_main)
1059 walletdb.ErasePool(nIndex);
1062 printf("keypool keep %"PRI64d"\n", nIndex);
1065 void CWallet::ReturnKey(int64 nIndex)
1067 // Return to key pool
1068 CRITICAL_BLOCK(cs_setKeyPool)
1069 setKeyPool.insert(nIndex);
1070 printf("keypool return %"PRI64d"\n", nIndex);
1073 bool CWallet::SetAddressBookName(const std::string& strAddress, const std::string& strName)
1077 if(CWalletDB(strWalletFile).WriteName(strAddress, strName))
1079 CRITICAL_BLOCK(cs_mapAddressBook)
1080 mapAddressBook[strAddress] = strName;
1089 bool CWallet::EraseAddressBookName(const std::string& strAddress)
1093 if(CWalletDB(strWalletFile).EraseName(strAddress))
1095 CRITICAL_BLOCK(cs_mapAddressBook)
1096 mapAddressBook.erase(strAddress);
1106 std::string CWallet::GetDefaultAddress()
1110 std::vector<unsigned char> vchPubKey;
1111 if (CWalletDB(strWalletFile, "r").ReadDefaultKey(vchPubKey))
1113 return PubKeyToAddress(vchPubKey);
1121 bool CWallet::SetDefaultAddress(const std::string& strAddress)
1124 if (!AddressToHash160(strAddress, hash160))
1126 if (!mapPubKeys.count(hash160))
1128 return CWalletDB(strWalletFile).WriteDefaultKey(mapPubKeys[hash160]);
1132 vector<unsigned char> CWallet::GetKeyFromKeyPool()
1136 ReserveKeyFromKeyPool(nIndex, keypool);
1138 return keypool.vchPubKey;
1141 int64 CWallet::GetOldestKeyPoolTime()
1145 ReserveKeyFromKeyPool(nIndex, keypool);
1147 return keypool.nTime;
1150 vector<unsigned char> CReserveKey::GetReservedKey()
1155 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1156 vchPubKey = keypool.vchPubKey;
1158 assert(!vchPubKey.empty());
1162 void CReserveKey::KeepKey()
1165 pwallet->KeepKey(nIndex);
1170 void CReserveKey::ReturnKey()
1173 pwallet->ReturnKey(nIndex);