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