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