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