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