Show unconfirmed balance on overview page
[novacoin.git] / src / wallet.cpp
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.
4
5 #include "headers.h"
6 #include "db.h"
7 #include "cryptopp/sha.h"
8
9 using namespace std;
10
11
12
13 //////////////////////////////////////////////////////////////////////////////
14 //
15 // mapWallet
16 //
17
18 bool CWallet::AddKey(const CKey& key)
19 {
20     this->CKeyStore::AddKey(key);
21     if (!fFileBacked)
22         return true;
23     return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
24 }
25
26 void CWallet::WalletUpdateSpent(const CTransaction &tx)
27 {
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)
32     {
33         BOOST_FOREACH(const CTxIn& txin, tx.vin)
34         {
35             map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
36             if (mi != mapWallet.end())
37             {
38                 CWalletTx& wtx = (*mi).second;
39                 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
40                 {
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);
43                     wtx.WriteToDisk();
44                     vWalletUpdated.push_back(txin.prevout.hash);
45                 }
46             }
47         }
48     }
49 }
50
51 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
52 {
53     uint256 hash = wtxIn.GetHash();
54     CRITICAL_BLOCK(cs_mapWallet)
55     {
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;
59         wtx.pwallet = this;
60         bool fInsertedNew = ret.second;
61         if (fInsertedNew)
62             wtx.nTimeReceived = GetAdjustedTime();
63
64         bool fUpdated = false;
65         if (!fInsertedNew)
66         {
67             // Merge
68             if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
69             {
70                 wtx.hashBlock = wtxIn.hashBlock;
71                 fUpdated = true;
72             }
73             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
74             {
75                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
76                 wtx.nIndex = wtxIn.nIndex;
77                 fUpdated = true;
78             }
79             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
80             {
81                 wtx.fFromMe = wtxIn.fFromMe;
82                 fUpdated = true;
83             }
84             fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
85         }
86
87         //// debug print
88         printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
89
90         // Write to disk
91         if (fInsertedNew || fUpdated)
92             if (!wtx.WriteToDisk())
93                 return false;
94 #ifndef QT_GUI
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)
99         {
100             if (txout.scriptPubKey == scriptDefaultKey)
101                 SetDefaultKey(GetKeyFromKeyPool());
102         }
103 #endif
104         // Notify UI
105         vWalletUpdated.push_back(hash);
106
107         // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
108         WalletUpdateSpent(wtx);
109     }
110
111     // Refresh UI
112     MainFrameRepaint();
113     return true;
114 }
115
116 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
117 {
118     uint256 hash = tx.GetHash();
119     bool fExisted = mapWallet.count(hash);
120     if (fExisted && !fUpdate) return false;
121     if (fExisted || IsMine(tx) || IsFromMe(tx))
122     {
123         CWalletTx wtx(this,tx);
124         // Get merkle branch if transaction was found in a block
125         if (pblock)
126             wtx.SetMerkleBranch(pblock);
127         return AddToWallet(wtx);
128     }
129     else
130         WalletUpdateSpent(tx);
131     return false;
132 }
133
134 bool CWallet::EraseFromWallet(uint256 hash)
135 {
136     if (!fFileBacked)
137         return false;
138     CRITICAL_BLOCK(cs_mapWallet)
139     {
140         if (mapWallet.erase(hash))
141             CWalletDB(strWalletFile).EraseTx(hash);
142     }
143     return true;
144 }
145
146
147 bool CWallet::IsMine(const CTxIn &txin) const
148 {
149     CRITICAL_BLOCK(cs_mapWallet)
150     {
151         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
152         if (mi != mapWallet.end())
153         {
154             const CWalletTx& prev = (*mi).second;
155             if (txin.prevout.n < prev.vout.size())
156                 if (IsMine(prev.vout[txin.prevout.n]))
157                     return true;
158         }
159     }
160     return false;
161 }
162
163 int64 CWallet::GetDebit(const CTxIn &txin) const
164 {
165     CRITICAL_BLOCK(cs_mapWallet)
166     {
167         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
168         if (mi != mapWallet.end())
169         {
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;
174         }
175     }
176     return 0;
177 }
178
179 int64 CWalletTx::GetTxTime() const
180 {
181     if (!fTimeReceivedIsTxTime && hashBlock != 0)
182     {
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())
188         {
189             CBlockIndex* pindex = (*mi).second;
190             if (pindex)
191                 return pindex->GetMedianTime();
192         }
193     }
194     return nTimeReceived;
195 }
196
197 int CWalletTx::GetRequestCount() const
198 {
199     // Returns -1 if it wasn't being tracked
200     int nRequests = -1;
201     CRITICAL_BLOCK(pwallet->cs_mapRequestCount)
202     {
203         if (IsCoinBase())
204         {
205             // Generated block
206             if (hashBlock != 0)
207             {
208                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
209                 if (mi != pwallet->mapRequestCount.end())
210                     nRequests = (*mi).second;
211             }
212         }
213         else
214         {
215             // Did anyone request this transaction?
216             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
217             if (mi != pwallet->mapRequestCount.end())
218             {
219                 nRequests = (*mi).second;
220
221                 // How about the block it's in?
222                 if (nRequests == 0 && hashBlock != 0)
223                 {
224                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
225                     if (mi != pwallet->mapRequestCount.end())
226                         nRequests = (*mi).second;
227                     else
228                         nRequests = 1; // If it's in someone else's block it must have got out
229                 }
230             }
231         }
232     }
233     return nRequests;
234 }
235
236 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
237                            list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
238 {
239     nGeneratedImmature = nGeneratedMature = nFee = 0;
240     listReceived.clear();
241     listSent.clear();
242     strSentAccount = strFromAccount;
243
244     if (IsCoinBase())
245     {
246         if (GetBlocksToMaturity() > 0)
247             nGeneratedImmature = pwallet->GetCredit(*this);
248         else
249             nGeneratedMature = GetCredit();
250         return;
251     }
252
253     // Compute fee:
254     int64 nDebit = GetDebit();
255     if (nDebit > 0) // debit>0 means we signed/sent this transaction
256     {
257         int64 nValueOut = GetValueOut();
258         nFee = nDebit - nValueOut;
259     }
260
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)
264     {
265         string address;
266         uint160 hash160;
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);
272         else
273         {
274             printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
275                    this->GetHash().ToString().c_str());
276             address = " unknown ";
277         }
278
279         // Don't report 'change' txouts
280         if (nDebit > 0 && pwallet->IsChange(txout))
281             continue;
282
283         if (nDebit > 0)
284             listSent.push_back(make_pair(address, txout.nValue));
285
286         if (pwallet->IsMine(txout))
287             listReceived.push_back(make_pair(address, txout.nValue));
288     }
289
290 }
291
292 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 
293                                   int64& nSent, int64& nFee) const
294 {
295     nGenerated = nReceived = nSent = nFee = 0;
296
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);
303
304     if (strAccount == "")
305         nGenerated = allGeneratedMature;
306     if (strAccount == strSentAccount)
307     {
308         BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
309             nSent += s.second;
310         nFee = allFee;
311     }
312     CRITICAL_BLOCK(pwallet->cs_mapAddressBook)
313     {
314         BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
315         {
316             if (pwallet->mapAddressBook.count(r.first))
317             {
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;
321             }
322             else if (strAccount.empty())
323             {
324                 nReceived += r.second;
325             }
326         }
327     }
328 }
329
330 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
331 {
332     vtxPrev.clear();
333
334     const int COPY_DEPTH = 3;
335     if (SetMerkleBranch() < COPY_DEPTH)
336     {
337         vector<uint256> vWorkQueue;
338         BOOST_FOREACH(const CTxIn& txin, vin)
339             vWorkQueue.push_back(txin.prevout.hash);
340
341         // This critsect is OK because txdb is already open
342         CRITICAL_BLOCK(pwallet->cs_mapWallet)
343         {
344             map<uint256, const CMerkleTx*> mapWalletPrev;
345             set<uint256> setAlreadyDone;
346             for (int i = 0; i < vWorkQueue.size(); i++)
347             {
348                 uint256 hash = vWorkQueue[i];
349                 if (setAlreadyDone.count(hash))
350                     continue;
351                 setAlreadyDone.insert(hash);
352
353                 CMerkleTx tx;
354                 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
355                 if (mi != pwallet->mapWallet.end())
356                 {
357                     tx = (*mi).second;
358                     BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
359                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
360                 }
361                 else if (mapWalletPrev.count(hash))
362                 {
363                     tx = *mapWalletPrev[hash];
364                 }
365                 else if (!fClient && txdb.ReadDiskTx(hash, tx))
366                 {
367                     ;
368                 }
369                 else
370                 {
371                     printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
372                     continue;
373                 }
374
375                 int nDepth = tx.SetMerkleBranch();
376                 vtxPrev.push_back(tx);
377
378                 if (nDepth < COPY_DEPTH)
379                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
380                         vWorkQueue.push_back(txin.prevout.hash);
381             }
382         }
383     }
384
385     reverse(vtxPrev.begin(), vtxPrev.end());
386 }
387
388 bool CWalletTx::WriteToDisk()
389 {
390     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
391 }
392
393 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
394 {
395     int ret = 0;
396
397     CBlockIndex* pindex = pindexStart;
398     CRITICAL_BLOCK(cs_mapWallet)
399     {
400         while (pindex)
401         {
402             CBlock block;
403             block.ReadFromDisk(pindex, true);
404             BOOST_FOREACH(CTransaction& tx, block.vtx)
405             {
406                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
407                     ret++;
408             }
409             pindex = pindex->pnext;
410         }
411     }
412     return ret;
413 }
414
415 void CWallet::ReacceptWalletTransactions()
416 {
417     CTxDB txdb("r");
418     bool fRepeat = true;
419     while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
420     {
421         fRepeat = false;
422         vector<CDiskTxPos> vMissingTx;
423         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
424         {
425             CWalletTx& wtx = item.second;
426             if (wtx.IsCoinBase() && wtx.IsSpent(0))
427                 continue;
428
429             CTxIndex txindex;
430             bool fUpdated = false;
431             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
432             {
433                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
434                 if (txindex.vSpent.size() != wtx.vout.size())
435                 {
436                     printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
437                     continue;
438                 }
439                 for (int i = 0; i < txindex.vSpent.size(); i++)
440                 {
441                     if (wtx.IsSpent(i))
442                         continue;
443                     if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
444                     {
445                         wtx.MarkSpent(i);
446                         fUpdated = true;
447                         vMissingTx.push_back(txindex.vSpent[i]);
448                     }
449                 }
450                 if (fUpdated)
451                 {
452                     printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
453                     wtx.MarkDirty();
454                     wtx.WriteToDisk();
455                 }
456             }
457             else
458             {
459                 // Reaccept any txes of ours that aren't already in a block
460                 if (!wtx.IsCoinBase())
461                     wtx.AcceptWalletTransaction(txdb, false);
462             }
463         }
464         if (!vMissingTx.empty())
465         {
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.
469         }
470     }
471 }
472
473 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
474 {
475     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
476     {
477         if (!tx.IsCoinBase())
478         {
479             uint256 hash = tx.GetHash();
480             if (!txdb.ContainsTx(hash))
481                 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
482         }
483     }
484     if (!IsCoinBase())
485     {
486         uint256 hash = GetHash();
487         if (!txdb.ContainsTx(hash))
488         {
489             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
490             RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
491         }
492     }
493 }
494
495 void CWalletTx::RelayWalletTransaction()
496 {
497    CTxDB txdb("r");
498    RelayWalletTransaction(txdb);
499 }
500
501 void CWallet::ResendWalletTransactions()
502 {
503     // Do this infrequently and randomly to avoid giving away
504     // that these are our transactions.
505     static int64 nNextTime;
506     if (GetTime() < nNextTime)
507         return;
508     bool fFirst = (nNextTime == 0);
509     nNextTime = GetTime() + GetRand(30 * 60);
510     if (fFirst)
511         return;
512
513     // Only do it if there's been a new block since last time
514     static int64 nLastTime;
515     if (nTimeBestReceived < nLastTime)
516         return;
517     nLastTime = GetTime();
518
519     // Rebroadcast any of our txes that aren't in a block yet
520     printf("ResendWalletTransactions()\n");
521     CTxDB txdb("r");
522     CRITICAL_BLOCK(cs_mapWallet)
523     {
524         // Sort them in chronological order
525         multimap<unsigned int, CWalletTx*> mapSorted;
526         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
527         {
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));
533         }
534         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
535         {
536             CWalletTx& wtx = *item.second;
537             wtx.RelayWalletTransaction(txdb);
538         }
539     }
540 }
541
542
543
544
545
546
547 //////////////////////////////////////////////////////////////////////////////
548 //
549 // Actions
550 //
551
552
553 int64 CWallet::GetBalance() const
554 {
555     int64 nStart = GetTimeMillis();
556
557     int64 nTotal = 0;
558     CRITICAL_BLOCK(cs_mapWallet)
559     {
560         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
561         {
562             const CWalletTx* pcoin = &(*it).second;
563             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
564                 continue;
565             nTotal += pcoin->GetAvailableCredit();
566         }
567     }
568
569     //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
570     return nTotal;
571 }
572
573 int64 CWallet::GetUnconfirmedBalance() const
574 {
575     int64 nTotal = 0;
576     CRITICAL_BLOCK(cs_mapWallet)
577     {
578         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
579         {
580             const CWalletTx* pcoin = &(*it).second;
581             if (pcoin->IsFinal() && pcoin->IsConfirmed())
582                 continue;
583             nTotal += pcoin->GetAvailableCredit();
584         }
585     }
586     return nTotal;
587 }
588
589 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
590 {
591     setCoinsRet.clear();
592     nValueRet = 0;
593
594     // List of values less than target
595     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
596     coinLowestLarger.first = INT64_MAX;
597     coinLowestLarger.second.first = NULL;
598     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
599     int64 nTotalLower = 0;
600
601     CRITICAL_BLOCK(cs_mapWallet)
602     {
603        vector<const CWalletTx*> vCoins;
604        vCoins.reserve(mapWallet.size());
605        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
606            vCoins.push_back(&(*it).second);
607        random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
608
609        BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
610        {
611             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
612                 continue;
613
614             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
615                 continue;
616
617             int nDepth = pcoin->GetDepthInMainChain();
618             if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
619                 continue;
620
621             for (int i = 0; i < pcoin->vout.size(); i++)
622             {
623                 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
624                     continue;
625
626                 int64 n = pcoin->vout[i].nValue;
627
628                 if (n <= 0)
629                     continue;
630
631                 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
632
633                 if (n == nTargetValue)
634                 {
635                     setCoinsRet.insert(coin.second);
636                     nValueRet += coin.first;
637                     return true;
638                 }
639                 else if (n < nTargetValue + CENT)
640                 {
641                     vValue.push_back(coin);
642                     nTotalLower += n;
643                 }
644                 else if (n < coinLowestLarger.first)
645                 {
646                     coinLowestLarger = coin;
647                 }
648             }
649         }
650     }
651
652     if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
653     {
654         for (int i = 0; i < vValue.size(); ++i)
655         {
656             setCoinsRet.insert(vValue[i].second);
657             nValueRet += vValue[i].first;
658         }
659         return true;
660     }
661
662     if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
663     {
664         if (coinLowestLarger.second.first == NULL)
665             return false;
666         setCoinsRet.insert(coinLowestLarger.second);
667         nValueRet += coinLowestLarger.first;
668         return true;
669     }
670
671     if (nTotalLower >= nTargetValue + CENT)
672         nTargetValue += CENT;
673
674     // Solve subset sum by stochastic approximation
675     sort(vValue.rbegin(), vValue.rend());
676     vector<char> vfIncluded;
677     vector<char> vfBest(vValue.size(), true);
678     int64 nBest = nTotalLower;
679
680     for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
681     {
682         vfIncluded.assign(vValue.size(), false);
683         int64 nTotal = 0;
684         bool fReachedTarget = false;
685         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
686         {
687             for (int i = 0; i < vValue.size(); i++)
688             {
689                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
690                 {
691                     nTotal += vValue[i].first;
692                     vfIncluded[i] = true;
693                     if (nTotal >= nTargetValue)
694                     {
695                         fReachedTarget = true;
696                         if (nTotal < nBest)
697                         {
698                             nBest = nTotal;
699                             vfBest = vfIncluded;
700                         }
701                         nTotal -= vValue[i].first;
702                         vfIncluded[i] = false;
703                     }
704                 }
705             }
706         }
707     }
708
709     // If the next larger is still closer, return it
710     if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
711     {
712         setCoinsRet.insert(coinLowestLarger.second);
713         nValueRet += coinLowestLarger.first;
714     }
715     else {
716         for (int i = 0; i < vValue.size(); i++)
717             if (vfBest[i])
718             {
719                 setCoinsRet.insert(vValue[i].second);
720                 nValueRet += vValue[i].first;
721             }
722
723         //// debug print
724         printf("SelectCoins() best subset: ");
725         for (int i = 0; i < vValue.size(); i++)
726             if (vfBest[i])
727                 printf("%s ", FormatMoney(vValue[i].first).c_str());
728         printf("total %s\n", FormatMoney(nBest).c_str());
729     }
730
731     return true;
732 }
733
734 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
735 {
736     return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
737             SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
738             SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
739 }
740
741
742
743
744 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
745 {
746     int64 nValue = 0;
747     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
748     {
749         if (nValue < 0)
750             return false;
751         nValue += s.second;
752     }
753     if (vecSend.empty() || nValue < 0)
754         return false;
755
756     wtxNew.pwallet = this;
757
758     CRITICAL_BLOCK(cs_main)
759     {
760         // txdb must be opened before the mapWallet lock
761         CTxDB txdb("r");
762         CRITICAL_BLOCK(cs_mapWallet)
763         {
764             nFeeRet = nTransactionFee;
765             loop
766             {
767                 wtxNew.vin.clear();
768                 wtxNew.vout.clear();
769                 wtxNew.fFromMe = true;
770
771                 int64 nTotalValue = nValue + nFeeRet;
772                 double dPriority = 0;
773                 // vouts to the payees
774                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
775                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
776
777                 // Choose coins to use
778                 set<pair<const CWalletTx*,unsigned int> > setCoins;
779                 int64 nValueIn = 0;
780                 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
781                     return false;
782                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
783                 {
784                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
785                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
786                 }
787
788                 // Fill a vout back to self with any change
789                 int64 nChange = nValueIn - nTotalValue;
790                 if (nChange >= CENT)
791                 {
792                     // Note: We use a new key here to keep it from being obvious which side is the change.
793                     //  The drawback is that by not reusing a previous key, the change may be lost if a
794                     //  backup is restored, if the backup doesn't have the new private key for the change.
795                     //  If we reused the old key, it would be possible to add code to look for and
796                     //  rediscover unknown transactions that were written with keys of ours to recover
797                     //  post-backup change.
798
799                     // Reserve a new key pair from key pool
800                     vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
801                     assert(mapKeys.count(vchPubKey));
802
803                     // Fill a vout to ourself, using same address type as the payment
804                     CScript scriptChange;
805                     if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
806                         scriptChange.SetBitcoinAddress(vchPubKey);
807                     else
808                         scriptChange << vchPubKey << OP_CHECKSIG;
809
810                     // Insert change txn at random position:
811                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
812                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
813                 }
814                 else
815                     reservekey.ReturnKey();
816
817                 // Fill vin
818                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
819                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
820
821                 // Sign
822                 int nIn = 0;
823                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
824                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
825                         return false;
826
827                 // Limit size
828                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
829                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
830                     return false;
831                 dPriority /= nBytes;
832
833                 // Check that enough fee is included
834                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
835                 bool fAllowFree = CTransaction::AllowFree(dPriority);
836                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
837                 if (nFeeRet < max(nPayFee, nMinFee))
838                 {
839                     nFeeRet = max(nPayFee, nMinFee);
840                     continue;
841                 }
842
843                 // Fill vtxPrev by copying from previous transactions vtxPrev
844                 wtxNew.AddSupportingTransactions(txdb);
845                 wtxNew.fTimeReceivedIsTxTime = true;
846
847                 break;
848             }
849         }
850     }
851     return true;
852 }
853
854 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
855 {
856     vector< pair<CScript, int64> > vecSend;
857     vecSend.push_back(make_pair(scriptPubKey, nValue));
858     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
859 }
860
861 // Call after CreateTransaction unless you want to abort
862 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
863 {
864     CRITICAL_BLOCK(cs_main)
865     {
866         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
867         CRITICAL_BLOCK(cs_mapWallet)
868         {
869             // This is only to keep the database open to defeat the auto-flush for the
870             // duration of this scope.  This is the only place where this optimization
871             // maybe makes sense; please don't do it anywhere else.
872             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
873
874             // Take key pair from key pool so it won't be used again
875             reservekey.KeepKey();
876
877             // Add tx to wallet, because if it has change it's also ours,
878             // otherwise just for transaction history.
879             AddToWallet(wtxNew);
880
881             // Mark old coins as spent
882             set<CWalletTx*> setCoins;
883             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
884             {
885                 CWalletTx &coin = mapWallet[txin.prevout.hash];
886                 coin.pwallet = this;
887                 coin.MarkSpent(txin.prevout.n);
888                 coin.WriteToDisk();
889                 vWalletUpdated.push_back(coin.GetHash());
890             }
891
892             if (fFileBacked)
893                 delete pwalletdb;
894         }
895
896         // Track how many getdata requests our transaction gets
897         CRITICAL_BLOCK(cs_mapRequestCount)
898             mapRequestCount[wtxNew.GetHash()] = 0;
899
900         // Broadcast
901         if (!wtxNew.AcceptToMemoryPool())
902         {
903             // This must not fail. The transaction has already been signed and recorded.
904             printf("CommitTransaction() : Error: Transaction not valid");
905             return false;
906         }
907         wtxNew.RelayWalletTransaction();
908     }
909     MainFrameRepaint();
910     return true;
911 }
912
913
914
915
916 // requires cs_main lock
917 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
918 {
919     CReserveKey reservekey(this);
920     int64 nFeeRequired;
921     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
922     {
923         string strError;
924         if (nValue + nFeeRequired > GetBalance())
925             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());
926         else
927             strError = _("Error: Transaction creation failed  ");
928         printf("SendMoney() : %s", strError.c_str());
929         return strError;
930     }
931
932     if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
933         return "ABORTED";
934
935     if (!CommitTransaction(wtxNew, reservekey))
936         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.");
937
938     MainFrameRepaint();
939     return "";
940 }
941
942
943
944 // requires cs_main lock
945 string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
946 {
947     // Check amount
948     if (nValue <= 0)
949         return _("Invalid amount");
950     if (nValue + nTransactionFee > GetBalance())
951         return _("Insufficient funds");
952
953     // Parse bitcoin address
954     CScript scriptPubKey;
955     if (!scriptPubKey.SetBitcoinAddress(strAddress))
956         return _("Invalid bitcoin address");
957
958     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
959 }
960
961
962
963
964 bool CWallet::LoadWallet(bool& fFirstRunRet)
965 {
966     if (!fFileBacked)
967         return false;
968     fFirstRunRet = false;
969     if (!CWalletDB(strWalletFile,"cr+").LoadWallet(this))
970         return false;
971     fFirstRunRet = vchDefaultKey.empty();
972
973     if (!mapKeys.count(vchDefaultKey))
974     {
975         // Create new default key
976         RandAddSeedPerfmon();
977
978         SetDefaultKey(GetKeyFromKeyPool());
979         if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))
980             return false;
981     }
982
983     CreateThread(ThreadFlushWalletDB, &strWalletFile);
984     return true;
985 }
986
987
988 bool CWallet::SetAddressBookName(const string& strAddress, const string& strName)
989 {
990     mapAddressBook[strAddress] = strName;
991     if (!fFileBacked)
992         return false;
993     return CWalletDB(strWalletFile).WriteName(strAddress, strName);
994 }
995
996 bool CWallet::DelAddressBookName(const string& strAddress)
997 {
998     mapAddressBook.erase(strAddress);
999     if (!fFileBacked)
1000         return false;
1001     return CWalletDB(strWalletFile).EraseName(strAddress);
1002 }
1003
1004
1005 void CWallet::PrintWallet(const CBlock& block)
1006 {
1007     CRITICAL_BLOCK(cs_mapWallet)
1008     {
1009         if (mapWallet.count(block.vtx[0].GetHash()))
1010         {
1011             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1012             printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1013         }
1014     }
1015     printf("\n");
1016 }
1017
1018 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1019 {
1020     CRITICAL_BLOCK(cs_mapWallet)
1021     {
1022         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1023         if (mi != mapWallet.end())
1024         {
1025             wtx = (*mi).second;
1026             return true;
1027         }
1028     }
1029     return false;
1030 }
1031
1032 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1033 {
1034     if (fFileBacked)
1035     {
1036         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1037             return false;
1038     }
1039     vchDefaultKey = vchPubKey;
1040     return true;
1041 }
1042
1043 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1044 {
1045     if (!pwallet->fFileBacked)
1046         return false;
1047     strWalletFileOut = pwallet->strWalletFile;
1048     return true;
1049 }
1050
1051 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1052 {
1053     nIndex = -1;
1054     keypool.vchPubKey.clear();
1055     CRITICAL_BLOCK(cs_main)
1056     CRITICAL_BLOCK(cs_mapWallet)
1057     CRITICAL_BLOCK(cs_setKeyPool)
1058     {
1059         CWalletDB walletdb(strWalletFile);
1060
1061         // Top up key pool
1062         int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1063         while (setKeyPool.size() < nTargetSize+1)
1064         {
1065             int64 nEnd = 1;
1066             if (!setKeyPool.empty())
1067                 nEnd = *(--setKeyPool.end()) + 1;
1068             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1069                 throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");
1070             setKeyPool.insert(nEnd);
1071             printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1072         }
1073
1074         // Get the oldest key
1075         assert(!setKeyPool.empty());
1076         nIndex = *(setKeyPool.begin());
1077         setKeyPool.erase(setKeyPool.begin());
1078         if (!walletdb.ReadPool(nIndex, keypool))
1079             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1080         if (!mapKeys.count(keypool.vchPubKey))
1081             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1082         assert(!keypool.vchPubKey.empty());
1083         printf("keypool reserve %"PRI64d"\n", nIndex);
1084     }
1085 }
1086
1087 void CWallet::KeepKey(int64 nIndex)
1088 {
1089     // Remove from key pool
1090     if (fFileBacked)
1091     {
1092         CWalletDB walletdb(strWalletFile);
1093         CRITICAL_BLOCK(cs_main)
1094         {
1095             walletdb.ErasePool(nIndex);
1096         }
1097     }
1098     printf("keypool keep %"PRI64d"\n", nIndex);
1099 }
1100
1101 void CWallet::ReturnKey(int64 nIndex)
1102 {
1103     // Return to key pool
1104     CRITICAL_BLOCK(cs_setKeyPool)
1105         setKeyPool.insert(nIndex);
1106     printf("keypool return %"PRI64d"\n", nIndex);
1107 }
1108
1109 vector<unsigned char> CWallet::GetKeyFromKeyPool()
1110 {
1111     int64 nIndex = 0;
1112     CKeyPool keypool;
1113     ReserveKeyFromKeyPool(nIndex, keypool);
1114     KeepKey(nIndex);
1115     return keypool.vchPubKey;
1116 }
1117
1118 int64 CWallet::GetOldestKeyPoolTime()
1119 {
1120     int64 nIndex = 0;
1121     CKeyPool keypool;
1122     ReserveKeyFromKeyPool(nIndex, keypool);
1123     ReturnKey(nIndex);
1124     return keypool.nTime;
1125 }
1126
1127 vector<unsigned char> CReserveKey::GetReservedKey()
1128 {
1129     if (nIndex == -1)
1130     {
1131         CKeyPool keypool;
1132         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1133         vchPubKey = keypool.vchPubKey;
1134     }
1135     assert(!vchPubKey.empty());
1136     return vchPubKey;
1137 }
1138
1139 void CReserveKey::KeepKey()
1140 {
1141     if (nIndex != -1)
1142         pwallet->KeepKey(nIndex);
1143     nIndex = -1;
1144     vchPubKey.clear();
1145 }
1146
1147 void CReserveKey::ReturnKey()
1148 {
1149     if (nIndex != -1)
1150         pwallet->ReturnKey(nIndex);
1151     nIndex = -1;
1152     vchPubKey.clear();
1153 }
1154