Use std::numeric_limits<> for typesafe INT_MAX/etc
[novacoin.git] / src / wallet.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "headers.h"
7 #include "db.h"
8 #include "crypter.h"
9
10 using namespace std;
11
12
13 //////////////////////////////////////////////////////////////////////////////
14 //
15 // mapWallet
16 //
17
18 bool CWallet::AddKey(const CKey& key)
19 {
20     if (!CCryptoKeyStore::AddKey(key))
21         return false;
22     if (!fFileBacked)
23         return true;
24     if (!IsCrypted())
25         return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
26     return true;
27 }
28
29 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
30 {
31     if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
32         return false;
33     if (!fFileBacked)
34         return true;
35     CRITICAL_BLOCK(cs_wallet)
36     {
37         if (pwalletdbEncryption)
38             return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
39         else
40             return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
41     }
42     return false;
43 }
44
45 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
46 {
47     if (!IsLocked())
48         return false;
49
50     CCrypter crypter;
51     CKeyingMaterial vMasterKey;
52
53     CRITICAL_BLOCK(cs_wallet)
54         BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
55         {
56             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
57                 return false;
58             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
59                 return false;
60             if (CCryptoKeyStore::Unlock(vMasterKey))
61                 return true;
62         }
63     return false;
64 }
65
66 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
67 {
68     bool fWasLocked = IsLocked();
69
70     CRITICAL_BLOCK(cs_wallet)
71     {
72         Lock();
73
74         CCrypter crypter;
75         CKeyingMaterial vMasterKey;
76         BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
77         {
78             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
79                 return false;
80             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
81                 return false;
82             if (CCryptoKeyStore::Unlock(vMasterKey))
83             {
84                 int64 nStartTime = GetTimeMillis();
85                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
86                 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
87
88                 nStartTime = GetTimeMillis();
89                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
90                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
91
92                 if (pMasterKey.second.nDeriveIterations < 25000)
93                     pMasterKey.second.nDeriveIterations = 25000;
94
95                 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
96
97                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
98                     return false;
99                 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
100                     return false;
101                 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
102                 if (fWasLocked)
103                     Lock();
104                 return true;
105             }
106         }
107     }
108
109     return false;
110 }
111
112
113 // This class implements an addrIncoming entry that causes pre-0.4
114 // clients to crash on startup if reading a private-key-encrypted wallet.
115 class CCorruptAddress
116 {
117 public:
118     IMPLEMENT_SERIALIZE
119     (
120         if (nType & SER_DISK)
121             READWRITE(nVersion);
122     )
123 };
124
125 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
126 {
127     if (IsCrypted())
128         return false;
129
130     CKeyingMaterial vMasterKey;
131     RandAddSeedPerfmon();
132
133     vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
134     RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
135
136     CMasterKey kMasterKey;
137
138     RandAddSeedPerfmon();
139     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
140     RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
141
142     CCrypter crypter;
143     int64 nStartTime = GetTimeMillis();
144     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
145     kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
146
147     nStartTime = GetTimeMillis();
148     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
149     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
150
151     if (kMasterKey.nDeriveIterations < 25000)
152         kMasterKey.nDeriveIterations = 25000;
153
154     printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
155
156     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
157         return false;
158     if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
159         return false;
160
161     CRITICAL_BLOCK(cs_wallet)
162     {
163         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
164         if (fFileBacked)
165         {
166             pwalletdbEncryption = new CWalletDB(strWalletFile);
167             pwalletdbEncryption->TxnBegin();
168             pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
169         }
170
171         if (!EncryptKeys(vMasterKey))
172         {
173             if (fFileBacked)
174                 pwalletdbEncryption->TxnAbort();
175             exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
176         }
177
178         if (fFileBacked)
179         {
180             CCorruptAddress corruptAddress;
181             pwalletdbEncryption->WriteSetting("addrIncoming", corruptAddress);
182             if (!pwalletdbEncryption->TxnCommit())
183                 exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
184
185             pwalletdbEncryption->Close();
186             pwalletdbEncryption = NULL;
187         }
188
189         Lock();
190         Unlock(strWalletPassphrase);
191         NewKeyPool();
192         Lock();
193
194         // Need to completely rewrite the wallet file; if we don't, bdb might keep
195         // bits of the unencrypted private key in slack space in the database file.
196         CDB::Rewrite(strWalletFile);
197     }
198
199     return true;
200 }
201
202 void CWallet::WalletUpdateSpent(const CTransaction &tx)
203 {
204     // Anytime a signature is successfully verified, it's proof the outpoint is spent.
205     // Update the wallet spent flag if it doesn't know due to wallet.dat being
206     // restored from backup or the user making copies of wallet.dat.
207     CRITICAL_BLOCK(cs_wallet)
208     {
209         BOOST_FOREACH(const CTxIn& txin, tx.vin)
210         {
211             map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
212             if (mi != mapWallet.end())
213             {
214                 CWalletTx& wtx = (*mi).second;
215                 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
216                 {
217                     printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
218                     wtx.MarkSpent(txin.prevout.n);
219                     wtx.WriteToDisk();
220                     vWalletUpdated.push_back(txin.prevout.hash);
221                 }
222             }
223         }
224     }
225 }
226
227 void CWallet::MarkDirty()
228 {
229     CRITICAL_BLOCK(cs_wallet)
230     {
231         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
232             item.second.MarkDirty();
233     }
234 }
235
236 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
237 {
238     uint256 hash = wtxIn.GetHash();
239     CRITICAL_BLOCK(cs_wallet)
240     {
241         // Inserts only if not already there, returns tx inserted or tx found
242         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
243         CWalletTx& wtx = (*ret.first).second;
244         wtx.BindWallet(this);
245         bool fInsertedNew = ret.second;
246         if (fInsertedNew)
247             wtx.nTimeReceived = GetAdjustedTime();
248
249         bool fUpdated = false;
250         if (!fInsertedNew)
251         {
252             // Merge
253             if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
254             {
255                 wtx.hashBlock = wtxIn.hashBlock;
256                 fUpdated = true;
257             }
258             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
259             {
260                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
261                 wtx.nIndex = wtxIn.nIndex;
262                 fUpdated = true;
263             }
264             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
265             {
266                 wtx.fFromMe = wtxIn.fFromMe;
267                 fUpdated = true;
268             }
269             fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
270         }
271
272         //// debug print
273         printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
274
275         // Write to disk
276         if (fInsertedNew || fUpdated)
277             if (!wtx.WriteToDisk())
278                 return false;
279 #ifndef QT_GUI
280         // If default receiving address gets used, replace it with a new one
281         CScript scriptDefaultKey;
282         scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
283         BOOST_FOREACH(const CTxOut& txout, wtx.vout)
284         {
285             if (txout.scriptPubKey == scriptDefaultKey)
286             {
287                 std::vector<unsigned char> newDefaultKey;
288                 if (GetKeyFromPool(newDefaultKey, false))
289                 {
290                     SetDefaultKey(newDefaultKey);
291                     SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
292                 }
293             }
294         }
295 #endif
296         // Notify UI
297         vWalletUpdated.push_back(hash);
298
299         // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
300         WalletUpdateSpent(wtx);
301     }
302
303     // Refresh UI
304     MainFrameRepaint();
305     return true;
306 }
307
308 // Add a transaction to the wallet, or update it.
309 // pblock is optional, but should be provided if the transaction is known to be in a block.
310 // If fUpdate is true, existing transactions will be updated.
311 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
312 {
313     uint256 hash = tx.GetHash();
314     CRITICAL_BLOCK(cs_wallet)
315     {
316         bool fExisted = mapWallet.count(hash);
317         if (fExisted && !fUpdate) return false;
318         if (fExisted || IsMine(tx) || IsFromMe(tx))
319         {
320             CWalletTx wtx(this,tx);
321             // Get merkle branch if transaction was found in a block
322             if (pblock)
323                 wtx.SetMerkleBranch(pblock);
324             return AddToWallet(wtx);
325         }
326         else
327             WalletUpdateSpent(tx);
328     }
329     return false;
330 }
331
332 bool CWallet::EraseFromWallet(uint256 hash)
333 {
334     if (!fFileBacked)
335         return false;
336     CRITICAL_BLOCK(cs_wallet)
337     {
338         if (mapWallet.erase(hash))
339             CWalletDB(strWalletFile).EraseTx(hash);
340     }
341     return true;
342 }
343
344
345 bool CWallet::IsMine(const CTxIn &txin) const
346 {
347     CRITICAL_BLOCK(cs_wallet)
348     {
349         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
350         if (mi != mapWallet.end())
351         {
352             const CWalletTx& prev = (*mi).second;
353             if (txin.prevout.n < prev.vout.size())
354                 if (IsMine(prev.vout[txin.prevout.n]))
355                     return true;
356         }
357     }
358     return false;
359 }
360
361 int64 CWallet::GetDebit(const CTxIn &txin) const
362 {
363     CRITICAL_BLOCK(cs_wallet)
364     {
365         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
366         if (mi != mapWallet.end())
367         {
368             const CWalletTx& prev = (*mi).second;
369             if (txin.prevout.n < prev.vout.size())
370                 if (IsMine(prev.vout[txin.prevout.n]))
371                     return prev.vout[txin.prevout.n].nValue;
372         }
373     }
374     return 0;
375 }
376
377 int64 CWalletTx::GetTxTime() const
378 {
379     return nTimeReceived;
380 }
381
382 int CWalletTx::GetRequestCount() const
383 {
384     // Returns -1 if it wasn't being tracked
385     int nRequests = -1;
386     CRITICAL_BLOCK(pwallet->cs_wallet)
387     {
388         if (IsCoinBase())
389         {
390             // Generated block
391             if (hashBlock != 0)
392             {
393                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
394                 if (mi != pwallet->mapRequestCount.end())
395                     nRequests = (*mi).second;
396             }
397         }
398         else
399         {
400             // Did anyone request this transaction?
401             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
402             if (mi != pwallet->mapRequestCount.end())
403             {
404                 nRequests = (*mi).second;
405
406                 // How about the block it's in?
407                 if (nRequests == 0 && hashBlock != 0)
408                 {
409                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
410                     if (mi != pwallet->mapRequestCount.end())
411                         nRequests = (*mi).second;
412                     else
413                         nRequests = 1; // If it's in someone else's block it must have got out
414                 }
415             }
416         }
417     }
418     return nRequests;
419 }
420
421 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
422                            list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
423 {
424     nGeneratedImmature = nGeneratedMature = nFee = 0;
425     listReceived.clear();
426     listSent.clear();
427     strSentAccount = strFromAccount;
428
429     if (IsCoinBase())
430     {
431         if (GetBlocksToMaturity() > 0)
432             nGeneratedImmature = pwallet->GetCredit(*this);
433         else
434             nGeneratedMature = GetCredit();
435         return;
436     }
437
438     // Compute fee:
439     int64 nDebit = GetDebit();
440     if (nDebit > 0) // debit>0 means we signed/sent this transaction
441     {
442         int64 nValueOut = GetValueOut();
443         nFee = nDebit - nValueOut;
444     }
445
446     // Sent/received.  Standard client will never generate a send-to-multiple-recipients,
447     // but non-standard clients might (so return a list of address/amount pairs)
448     BOOST_FOREACH(const CTxOut& txout, vout)
449     {
450         CBitcoinAddress address;
451         vector<unsigned char> vchPubKey;
452         if (!ExtractAddress(txout.scriptPubKey, NULL, address))
453         {
454             printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
455                    this->GetHash().ToString().c_str());
456             address = " unknown ";
457         }
458
459         // Don't report 'change' txouts
460         if (nDebit > 0 && pwallet->IsChange(txout))
461             continue;
462
463         if (nDebit > 0)
464             listSent.push_back(make_pair(address, txout.nValue));
465
466         if (pwallet->IsMine(txout))
467             listReceived.push_back(make_pair(address, txout.nValue));
468     }
469
470 }
471
472 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 
473                                   int64& nSent, int64& nFee) const
474 {
475     nGenerated = nReceived = nSent = nFee = 0;
476
477     int64 allGeneratedImmature, allGeneratedMature, allFee;
478     allGeneratedImmature = allGeneratedMature = allFee = 0;
479     string strSentAccount;
480     list<pair<CBitcoinAddress, int64> > listReceived;
481     list<pair<CBitcoinAddress, int64> > listSent;
482     GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
483
484     if (strAccount == "")
485         nGenerated = allGeneratedMature;
486     if (strAccount == strSentAccount)
487     {
488         BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
489             nSent += s.second;
490         nFee = allFee;
491     }
492     CRITICAL_BLOCK(pwallet->cs_wallet)
493     {
494         BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
495         {
496             if (pwallet->mapAddressBook.count(r.first))
497             {
498                 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
499                 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
500                     nReceived += r.second;
501             }
502             else if (strAccount.empty())
503             {
504                 nReceived += r.second;
505             }
506         }
507     }
508 }
509
510 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
511 {
512     vtxPrev.clear();
513
514     const int COPY_DEPTH = 3;
515     if (SetMerkleBranch() < COPY_DEPTH)
516     {
517         vector<uint256> vWorkQueue;
518         BOOST_FOREACH(const CTxIn& txin, vin)
519             vWorkQueue.push_back(txin.prevout.hash);
520
521         // This critsect is OK because txdb is already open
522         CRITICAL_BLOCK(pwallet->cs_wallet)
523         {
524             map<uint256, const CMerkleTx*> mapWalletPrev;
525             set<uint256> setAlreadyDone;
526             for (int i = 0; i < vWorkQueue.size(); i++)
527             {
528                 uint256 hash = vWorkQueue[i];
529                 if (setAlreadyDone.count(hash))
530                     continue;
531                 setAlreadyDone.insert(hash);
532
533                 CMerkleTx tx;
534                 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
535                 if (mi != pwallet->mapWallet.end())
536                 {
537                     tx = (*mi).second;
538                     BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
539                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
540                 }
541                 else if (mapWalletPrev.count(hash))
542                 {
543                     tx = *mapWalletPrev[hash];
544                 }
545                 else if (!fClient && txdb.ReadDiskTx(hash, tx))
546                 {
547                     ;
548                 }
549                 else
550                 {
551                     printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
552                     continue;
553                 }
554
555                 int nDepth = tx.SetMerkleBranch();
556                 vtxPrev.push_back(tx);
557
558                 if (nDepth < COPY_DEPTH)
559                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
560                         vWorkQueue.push_back(txin.prevout.hash);
561             }
562         }
563     }
564
565     reverse(vtxPrev.begin(), vtxPrev.end());
566 }
567
568 bool CWalletTx::WriteToDisk()
569 {
570     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
571 }
572
573 // Scan the block chain (starting in pindexStart) for transactions
574 // from or to us. If fUpdate is true, found transactions that already
575 // exist in the wallet will be updated.
576 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
577 {
578     int ret = 0;
579
580     CBlockIndex* pindex = pindexStart;
581     CRITICAL_BLOCK(cs_wallet)
582     {
583         while (pindex)
584         {
585             CBlock block;
586             block.ReadFromDisk(pindex, true);
587             BOOST_FOREACH(CTransaction& tx, block.vtx)
588             {
589                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
590                     ret++;
591             }
592             pindex = pindex->pnext;
593         }
594     }
595     return ret;
596 }
597
598 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
599 {
600     CTransaction tx;
601     tx.ReadFromDisk(COutPoint(hashTx, 0));
602     if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
603         return 1;
604     return 0;
605 }
606
607 void CWallet::ReacceptWalletTransactions()
608 {
609     CTxDB txdb("r");
610     bool fRepeat = true;
611     while (fRepeat) CRITICAL_BLOCK(cs_wallet)
612     {
613         fRepeat = false;
614         vector<CDiskTxPos> vMissingTx;
615         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
616         {
617             CWalletTx& wtx = item.second;
618             if (wtx.IsCoinBase() && wtx.IsSpent(0))
619                 continue;
620
621             CTxIndex txindex;
622             bool fUpdated = false;
623             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
624             {
625                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
626                 if (txindex.vSpent.size() != wtx.vout.size())
627                 {
628                     printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
629                     continue;
630                 }
631                 for (int i = 0; i < txindex.vSpent.size(); i++)
632                 {
633                     if (wtx.IsSpent(i))
634                         continue;
635                     if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
636                     {
637                         wtx.MarkSpent(i);
638                         fUpdated = true;
639                         vMissingTx.push_back(txindex.vSpent[i]);
640                     }
641                 }
642                 if (fUpdated)
643                 {
644                     printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
645                     wtx.MarkDirty();
646                     wtx.WriteToDisk();
647                 }
648             }
649             else
650             {
651                 // Reaccept any txes of ours that aren't already in a block
652                 if (!wtx.IsCoinBase())
653                     wtx.AcceptWalletTransaction(txdb, false);
654             }
655         }
656         if (!vMissingTx.empty())
657         {
658             // TODO: optimize this to scan just part of the block chain?
659             if (ScanForWalletTransactions(pindexGenesisBlock))
660                 fRepeat = true;  // Found missing transactions: re-do Reaccept.
661         }
662     }
663 }
664
665 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
666 {
667     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
668     {
669         if (!tx.IsCoinBase())
670         {
671             uint256 hash = tx.GetHash();
672             if (!txdb.ContainsTx(hash))
673                 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
674         }
675     }
676     if (!IsCoinBase())
677     {
678         uint256 hash = GetHash();
679         if (!txdb.ContainsTx(hash))
680         {
681             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
682             RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
683         }
684     }
685 }
686
687 void CWalletTx::RelayWalletTransaction()
688 {
689    CTxDB txdb("r");
690    RelayWalletTransaction(txdb);
691 }
692
693 void CWallet::ResendWalletTransactions()
694 {
695     // Do this infrequently and randomly to avoid giving away
696     // that these are our transactions.
697     static int64 nNextTime;
698     if (GetTime() < nNextTime)
699         return;
700     bool fFirst = (nNextTime == 0);
701     nNextTime = GetTime() + GetRand(30 * 60);
702     if (fFirst)
703         return;
704
705     // Only do it if there's been a new block since last time
706     static int64 nLastTime;
707     if (nTimeBestReceived < nLastTime)
708         return;
709     nLastTime = GetTime();
710
711     // Rebroadcast any of our txes that aren't in a block yet
712     printf("ResendWalletTransactions()\n");
713     CTxDB txdb("r");
714     CRITICAL_BLOCK(cs_wallet)
715     {
716         // Sort them in chronological order
717         multimap<unsigned int, CWalletTx*> mapSorted;
718         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
719         {
720             CWalletTx& wtx = item.second;
721             // Don't rebroadcast until it's had plenty of time that
722             // it should have gotten in already by now.
723             if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
724                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
725         }
726         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
727         {
728             CWalletTx& wtx = *item.second;
729             wtx.RelayWalletTransaction(txdb);
730         }
731     }
732 }
733
734
735
736
737
738
739 //////////////////////////////////////////////////////////////////////////////
740 //
741 // Actions
742 //
743
744
745 int64 CWallet::GetBalance() const
746 {
747     int64 nTotal = 0;
748     CRITICAL_BLOCK(cs_wallet)
749     {
750         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
751         {
752             const CWalletTx* pcoin = &(*it).second;
753             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
754                 continue;
755             nTotal += pcoin->GetAvailableCredit();
756         }
757     }
758
759     return nTotal;
760 }
761
762 int64 CWallet::GetUnconfirmedBalance() const
763 {
764     int64 nTotal = 0;
765     CRITICAL_BLOCK(cs_wallet)
766     {
767         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
768         {
769             const CWalletTx* pcoin = &(*it).second;
770             if (pcoin->IsFinal() && pcoin->IsConfirmed())
771                 continue;
772             nTotal += pcoin->GetAvailableCredit();
773         }
774     }
775     return nTotal;
776 }
777
778 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
779 {
780     setCoinsRet.clear();
781     nValueRet = 0;
782
783     // List of values less than target
784     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
785     coinLowestLarger.first = std::numeric_limits<int64>::max();
786     coinLowestLarger.second.first = NULL;
787     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
788     int64 nTotalLower = 0;
789
790     CRITICAL_BLOCK(cs_wallet)
791     {
792        vector<const CWalletTx*> vCoins;
793        vCoins.reserve(mapWallet.size());
794        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
795            vCoins.push_back(&(*it).second);
796        random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
797
798        BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
799        {
800             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
801                 continue;
802
803             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
804                 continue;
805
806             int nDepth = pcoin->GetDepthInMainChain();
807             if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
808                 continue;
809
810             for (int i = 0; i < pcoin->vout.size(); i++)
811             {
812                 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
813                     continue;
814
815                 int64 n = pcoin->vout[i].nValue;
816
817                 if (n <= 0)
818                     continue;
819
820                 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
821
822                 if (n == nTargetValue)
823                 {
824                     setCoinsRet.insert(coin.second);
825                     nValueRet += coin.first;
826                     return true;
827                 }
828                 else if (n < nTargetValue + CENT)
829                 {
830                     vValue.push_back(coin);
831                     nTotalLower += n;
832                 }
833                 else if (n < coinLowestLarger.first)
834                 {
835                     coinLowestLarger = coin;
836                 }
837             }
838         }
839     }
840
841     if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
842     {
843         for (int i = 0; i < vValue.size(); ++i)
844         {
845             setCoinsRet.insert(vValue[i].second);
846             nValueRet += vValue[i].first;
847         }
848         return true;
849     }
850
851     if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
852     {
853         if (coinLowestLarger.second.first == NULL)
854             return false;
855         setCoinsRet.insert(coinLowestLarger.second);
856         nValueRet += coinLowestLarger.first;
857         return true;
858     }
859
860     if (nTotalLower >= nTargetValue + CENT)
861         nTargetValue += CENT;
862
863     // Solve subset sum by stochastic approximation
864     sort(vValue.rbegin(), vValue.rend());
865     vector<char> vfIncluded;
866     vector<char> vfBest(vValue.size(), true);
867     int64 nBest = nTotalLower;
868
869     for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
870     {
871         vfIncluded.assign(vValue.size(), false);
872         int64 nTotal = 0;
873         bool fReachedTarget = false;
874         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
875         {
876             for (int i = 0; i < vValue.size(); i++)
877             {
878                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
879                 {
880                     nTotal += vValue[i].first;
881                     vfIncluded[i] = true;
882                     if (nTotal >= nTargetValue)
883                     {
884                         fReachedTarget = true;
885                         if (nTotal < nBest)
886                         {
887                             nBest = nTotal;
888                             vfBest = vfIncluded;
889                         }
890                         nTotal -= vValue[i].first;
891                         vfIncluded[i] = false;
892                     }
893                 }
894             }
895         }
896     }
897
898     // If the next larger is still closer, return it
899     if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
900     {
901         setCoinsRet.insert(coinLowestLarger.second);
902         nValueRet += coinLowestLarger.first;
903     }
904     else {
905         for (int i = 0; i < vValue.size(); i++)
906             if (vfBest[i])
907             {
908                 setCoinsRet.insert(vValue[i].second);
909                 nValueRet += vValue[i].first;
910             }
911
912         //// debug print
913         printf("SelectCoins() best subset: ");
914         for (int i = 0; i < vValue.size(); i++)
915             if (vfBest[i])
916                 printf("%s ", FormatMoney(vValue[i].first).c_str());
917         printf("total %s\n", FormatMoney(nBest).c_str());
918     }
919
920     return true;
921 }
922
923 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
924 {
925     return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
926             SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
927             SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
928 }
929
930
931
932
933 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
934 {
935     int64 nValue = 0;
936     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
937     {
938         if (nValue < 0)
939             return false;
940         nValue += s.second;
941     }
942     if (vecSend.empty() || nValue < 0)
943         return false;
944
945     wtxNew.BindWallet(this);
946
947     CRITICAL_BLOCK(cs_main)
948     CRITICAL_BLOCK(cs_wallet)
949     {
950         // txdb must be opened before the mapWallet lock
951         CTxDB txdb("r");
952         {
953             nFeeRet = nTransactionFee;
954             loop
955             {
956                 wtxNew.vin.clear();
957                 wtxNew.vout.clear();
958                 wtxNew.fFromMe = true;
959
960                 int64 nTotalValue = nValue + nFeeRet;
961                 double dPriority = 0;
962                 // vouts to the payees
963                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
964                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
965
966                 // Choose coins to use
967                 set<pair<const CWalletTx*,unsigned int> > setCoins;
968                 int64 nValueIn = 0;
969                 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
970                     return false;
971                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
972                 {
973                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
974                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
975                 }
976
977                 int64 nChange = nValueIn - nValue - nFeeRet;
978                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
979                 // or until nChange becomes zero
980                 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
981                 {
982                     int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
983                     nChange -= nMoveToFee;
984                     nFeeRet += nMoveToFee;
985                 }
986
987                 if (nChange > 0)
988                 {
989                     // Note: We use a new key here to keep it from being obvious which side is the change.
990                     //  The drawback is that by not reusing a previous key, the change may be lost if a
991                     //  backup is restored, if the backup doesn't have the new private key for the change.
992                     //  If we reused the old key, it would be possible to add code to look for and
993                     //  rediscover unknown transactions that were written with keys of ours to recover
994                     //  post-backup change.
995
996                     // Reserve a new key pair from key pool
997                     vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
998                     // assert(mapKeys.count(vchPubKey));
999
1000                     // Fill a vout to ourself, using same address type as the payment
1001                     CScript scriptChange;
1002                     if (vecSend[0].first.GetBitcoinAddress().IsValid())
1003                         scriptChange.SetBitcoinAddress(vchPubKey);
1004                     else
1005                         scriptChange << vchPubKey << OP_CHECKSIG;
1006
1007                     // Insert change txn at random position:
1008                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1009                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1010                 }
1011                 else
1012                     reservekey.ReturnKey();
1013
1014                 // Fill vin
1015                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1016                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1017
1018                 // Sign
1019                 int nIn = 0;
1020                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1021                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1022                         return false;
1023
1024                 // Limit size
1025                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1026                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1027                     return false;
1028                 dPriority /= nBytes;
1029
1030                 // Check that enough fee is included
1031                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1032                 bool fAllowFree = CTransaction::AllowFree(dPriority);
1033                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
1034                 if (nFeeRet < max(nPayFee, nMinFee))
1035                 {
1036                     nFeeRet = max(nPayFee, nMinFee);
1037                     continue;
1038                 }
1039
1040                 // Fill vtxPrev by copying from previous transactions vtxPrev
1041                 wtxNew.AddSupportingTransactions(txdb);
1042                 wtxNew.fTimeReceivedIsTxTime = true;
1043
1044                 break;
1045             }
1046         }
1047     }
1048     return true;
1049 }
1050
1051 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1052 {
1053     vector< pair<CScript, int64> > vecSend;
1054     vecSend.push_back(make_pair(scriptPubKey, nValue));
1055     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1056 }
1057
1058 // Call after CreateTransaction unless you want to abort
1059 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1060 {
1061     CRITICAL_BLOCK(cs_main)
1062     CRITICAL_BLOCK(cs_wallet)
1063     {
1064         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1065         {
1066             // This is only to keep the database open to defeat the auto-flush for the
1067             // duration of this scope.  This is the only place where this optimization
1068             // maybe makes sense; please don't do it anywhere else.
1069             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1070
1071             // Take key pair from key pool so it won't be used again
1072             reservekey.KeepKey();
1073
1074             // Add tx to wallet, because if it has change it's also ours,
1075             // otherwise just for transaction history.
1076             AddToWallet(wtxNew);
1077
1078             // Mark old coins as spent
1079             set<CWalletTx*> setCoins;
1080             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1081             {
1082                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1083                 coin.BindWallet(this);
1084                 coin.MarkSpent(txin.prevout.n);
1085                 coin.WriteToDisk();
1086                 vWalletUpdated.push_back(coin.GetHash());
1087             }
1088
1089             if (fFileBacked)
1090                 delete pwalletdb;
1091         }
1092
1093         // Track how many getdata requests our transaction gets
1094         mapRequestCount[wtxNew.GetHash()] = 0;
1095
1096         // Broadcast
1097         if (!wtxNew.AcceptToMemoryPool())
1098         {
1099             // This must not fail. The transaction has already been signed and recorded.
1100             printf("CommitTransaction() : Error: Transaction not valid");
1101             return false;
1102         }
1103         wtxNew.RelayWalletTransaction();
1104     }
1105     MainFrameRepaint();
1106     return true;
1107 }
1108
1109
1110
1111
1112 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1113 {
1114     CReserveKey reservekey(this);
1115     int64 nFeeRequired;
1116
1117     if (IsLocked())
1118     {
1119         string strError = _("Error: Wallet locked, unable to create transaction  ");
1120         printf("SendMoney() : %s", strError.c_str());
1121         return strError;
1122     }
1123     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1124     {
1125         string strError;
1126         if (nValue + nFeeRequired > GetBalance())
1127             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());
1128         else
1129             strError = _("Error: Transaction creation failed  ");
1130         printf("SendMoney() : %s", strError.c_str());
1131         return strError;
1132     }
1133
1134     if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1135         return "ABORTED";
1136
1137     if (!CommitTransaction(wtxNew, reservekey))
1138         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.");
1139
1140     MainFrameRepaint();
1141     return "";
1142 }
1143
1144
1145
1146 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1147 {
1148     // Check amount
1149     if (nValue <= 0)
1150         return _("Invalid amount");
1151     if (nValue + nTransactionFee > GetBalance())
1152         return _("Insufficient funds");
1153
1154     // Parse bitcoin address
1155     CScript scriptPubKey;
1156     scriptPubKey.SetBitcoinAddress(address);
1157
1158     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1159 }
1160
1161
1162
1163
1164 int CWallet::LoadWallet(bool& fFirstRunRet)
1165 {
1166     if (!fFileBacked)
1167         return false;
1168     fFirstRunRet = false;
1169     int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1170     if (nLoadWalletRet == DB_NEED_REWRITE)
1171     {
1172         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1173         {
1174             setKeyPool.clear();
1175             // Note: can't top-up keypool here, because wallet is locked.
1176             // User will be prompted to unlock wallet the next operation
1177             // the requires a new key.
1178         }
1179         nLoadWalletRet = DB_NEED_REWRITE;
1180     }
1181
1182     if (nLoadWalletRet != DB_LOAD_OK)
1183         return nLoadWalletRet;
1184     fFirstRunRet = vchDefaultKey.empty();
1185
1186     if (!HaveKey(Hash160(vchDefaultKey)))
1187     {
1188         // Create new keyUser and set as default key
1189         RandAddSeedPerfmon();
1190
1191         std::vector<unsigned char> newDefaultKey;
1192         if (!GetKeyFromPool(newDefaultKey, false))
1193             return DB_LOAD_FAIL;
1194         SetDefaultKey(newDefaultKey);
1195         if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""))
1196             return DB_LOAD_FAIL;
1197     }
1198
1199     CreateThread(ThreadFlushWalletDB, &strWalletFile);
1200     return DB_LOAD_OK;
1201 }
1202
1203
1204 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1205 {
1206     mapAddressBook[address] = strName;
1207     if (!fFileBacked)
1208         return false;
1209     return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1210 }
1211
1212 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1213 {
1214     mapAddressBook.erase(address);
1215     if (!fFileBacked)
1216         return false;
1217     return CWalletDB(strWalletFile).EraseName(address.ToString());
1218 }
1219
1220
1221 void CWallet::PrintWallet(const CBlock& block)
1222 {
1223     CRITICAL_BLOCK(cs_wallet)
1224     {
1225         if (mapWallet.count(block.vtx[0].GetHash()))
1226         {
1227             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1228             printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1229         }
1230     }
1231     printf("\n");
1232 }
1233
1234 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1235 {
1236     CRITICAL_BLOCK(cs_wallet)
1237     {
1238         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1239         if (mi != mapWallet.end())
1240         {
1241             wtx = (*mi).second;
1242             return true;
1243         }
1244     }
1245     return false;
1246 }
1247
1248 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1249 {
1250     if (fFileBacked)
1251     {
1252         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1253             return false;
1254     }
1255     vchDefaultKey = vchPubKey;
1256     return true;
1257 }
1258
1259 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1260 {
1261     if (!pwallet->fFileBacked)
1262         return false;
1263     strWalletFileOut = pwallet->strWalletFile;
1264     return true;
1265 }
1266
1267 //
1268 // Mark old keypool keys as used,
1269 // and generate all new keys
1270 //
1271 bool CWallet::NewKeyPool()
1272 {
1273     CRITICAL_BLOCK(cs_wallet)
1274     {
1275         CWalletDB walletdb(strWalletFile);
1276         BOOST_FOREACH(int64 nIndex, setKeyPool)
1277             walletdb.ErasePool(nIndex);
1278         setKeyPool.clear();
1279
1280         if (IsLocked())
1281             return false;
1282
1283         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1284         for (int i = 0; i < nKeys; i++)
1285         {
1286             int64 nIndex = i+1;
1287             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1288             setKeyPool.insert(nIndex);
1289         }
1290         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1291     }
1292     return true;
1293 }
1294
1295 bool CWallet::TopUpKeyPool()
1296 {
1297     CRITICAL_BLOCK(cs_wallet)
1298     {
1299         if (IsLocked())
1300             return false;
1301
1302         CWalletDB walletdb(strWalletFile);
1303
1304         // Top up key pool
1305         int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1306         while (setKeyPool.size() < nTargetSize+1)
1307         {
1308             int64 nEnd = 1;
1309             if (!setKeyPool.empty())
1310                 nEnd = *(--setKeyPool.end()) + 1;
1311             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1312                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1313             setKeyPool.insert(nEnd);
1314             printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1315         }
1316     }
1317     return true;
1318 }
1319
1320 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1321 {
1322     nIndex = -1;
1323     keypool.vchPubKey.clear();
1324     CRITICAL_BLOCK(cs_wallet)
1325     {
1326         if (!IsLocked())
1327             TopUpKeyPool();
1328
1329         // Get the oldest key
1330         if(setKeyPool.empty())
1331             return;
1332
1333         CWalletDB walletdb(strWalletFile);
1334
1335         nIndex = *(setKeyPool.begin());
1336         setKeyPool.erase(setKeyPool.begin());
1337         if (!walletdb.ReadPool(nIndex, keypool))
1338             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1339         if (!HaveKey(Hash160(keypool.vchPubKey)))
1340             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1341         assert(!keypool.vchPubKey.empty());
1342         printf("keypool reserve %"PRI64d"\n", nIndex);
1343     }
1344 }
1345
1346 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1347 {
1348     CRITICAL_BLOCK(cs_main)
1349     CRITICAL_BLOCK(cs_wallet)
1350     {
1351         CWalletDB walletdb(strWalletFile);
1352
1353         int64 nIndex = 1 + *(--setKeyPool.end());
1354         if (!walletdb.WritePool(nIndex, keypool))
1355             throw runtime_error("AddReserveKey() : writing added key failed");
1356         setKeyPool.insert(nIndex);
1357         return nIndex;
1358     }
1359     return -1;
1360 }
1361
1362 void CWallet::KeepKey(int64 nIndex)
1363 {
1364     // Remove from key pool
1365     if (fFileBacked)
1366     {
1367         CWalletDB walletdb(strWalletFile);
1368         walletdb.ErasePool(nIndex);
1369     }
1370     printf("keypool keep %"PRI64d"\n", nIndex);
1371 }
1372
1373 void CWallet::ReturnKey(int64 nIndex)
1374 {
1375     // Return to key pool
1376     CRITICAL_BLOCK(cs_wallet)
1377         setKeyPool.insert(nIndex);
1378     printf("keypool return %"PRI64d"\n", nIndex);
1379 }
1380
1381 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1382 {
1383     int64 nIndex = 0;
1384     CKeyPool keypool;
1385     CRITICAL_BLOCK(cs_wallet)
1386     {
1387         ReserveKeyFromKeyPool(nIndex, keypool);
1388         if (nIndex == -1)
1389         {
1390             if (fAllowReuse && !vchDefaultKey.empty())
1391             {
1392                 result = vchDefaultKey;
1393                 return true;
1394             }
1395             if (IsLocked()) return false;
1396             result = GenerateNewKey();
1397             return true;
1398         }
1399         KeepKey(nIndex);
1400         result = keypool.vchPubKey;
1401     }
1402     return true;
1403 }
1404
1405 int64 CWallet::GetOldestKeyPoolTime()
1406 {
1407     int64 nIndex = 0;
1408     CKeyPool keypool;
1409     ReserveKeyFromKeyPool(nIndex, keypool);
1410     if (nIndex == -1)
1411         return GetTime();
1412     ReturnKey(nIndex);
1413     return keypool.nTime;
1414 }
1415
1416 vector<unsigned char> CReserveKey::GetReservedKey()
1417 {
1418     if (nIndex == -1)
1419     {
1420         CKeyPool keypool;
1421         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1422         if (nIndex != -1)
1423             vchPubKey = keypool.vchPubKey;
1424         else
1425         {
1426             printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1427             vchPubKey = pwallet->vchDefaultKey;
1428         }
1429     }
1430     assert(!vchPubKey.empty());
1431     return vchPubKey;
1432 }
1433
1434 void CReserveKey::KeepKey()
1435 {
1436     if (nIndex != -1)
1437         pwallet->KeepKey(nIndex);
1438     nIndex = -1;
1439     vchPubKey.clear();
1440 }
1441
1442 void CReserveKey::ReturnKey()
1443 {
1444     if (nIndex != -1)
1445         pwallet->ReturnKey(nIndex);
1446     nIndex = -1;
1447     vchPubKey.clear();
1448 }
1449
1450 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1451 {
1452     setAddress.clear();
1453
1454     CWalletDB walletdb(strWalletFile);
1455
1456     CRITICAL_BLOCK(cs_main)
1457     CRITICAL_BLOCK(cs_wallet)
1458     BOOST_FOREACH(const int64& id, setKeyPool)
1459     {
1460         CKeyPool keypool;
1461         if (!walletdb.ReadPool(id, keypool))
1462             throw runtime_error("GetAllReserveKeyHashes() : read failed");
1463         CBitcoinAddress address(keypool.vchPubKey);
1464         assert(!keypool.vchPubKey.empty());
1465         if (!HaveKey(address))
1466             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1467         setAddress.insert(address);
1468     }
1469 }