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