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