Update to 0.3.0 (New upstream + new RPC calls)
[novacoin.git] / src / wallet.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2013 The PPCoin developers
4 // Copyright (c) 2013 NovaCoin Developers
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7
8 #include "wallet.h"
9 #include "walletdb.h"
10 #include "crypter.h"
11 #include "ui_interface.h"
12 #include "kernel.h"
13
14 using namespace std;
15
16
17 //////////////////////////////////////////////////////////////////////////////
18 //
19 // mapWallet
20 //
21
22 std::vector<unsigned char> CWallet::GenerateNewKey(bool bCompressed = true)
23 {
24     bool fCompressed = bCompressed ? CanSupportFeature(FEATURE_COMPRPUBKEY) : false; // default to compressed public keys if we want 0.6.0 wallets
25
26     RandAddSeedPerfmon();
27     CKey key;
28     key.MakeNewKey(fCompressed);
29
30     // Compressed public keys were introduced in version 0.6.0
31     if (fCompressed)
32         SetMinVersion(FEATURE_COMPRPUBKEY);
33
34     if (!AddKey(key))
35         throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
36     return key.GetPubKey();
37 }
38
39 bool CWallet::AddKey(const CKey& key)
40 {
41     if (!CCryptoKeyStore::AddKey(key))
42         return false;
43     if (!fFileBacked)
44         return true;
45     if (!IsCrypted())
46         return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
47     return true;
48 }
49
50 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
51 {
52     if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
53         return false;
54     if (!fFileBacked)
55         return true;
56     {
57         LOCK(cs_wallet);
58         if (pwalletdbEncryption)
59             return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
60         else
61             return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
62     }
63     return false;
64 }
65
66 bool CWallet::AddCScript(const CScript& redeemScript)
67 {
68     if (!CCryptoKeyStore::AddCScript(redeemScript))
69         return false;
70     if (!fFileBacked)
71         return true;
72     return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
73 }
74
75 // ppcoin: optional setting to unlock wallet for block minting only;
76 //         serves to disable the trivial sendmoney when OS account compromised
77 bool fWalletUnlockMintOnly = false;
78
79 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
80 {
81     if (!IsLocked())
82         return false;
83
84     CCrypter crypter;
85     CKeyingMaterial vMasterKey;
86
87     {
88         LOCK(cs_wallet);
89         BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
90         {
91             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
92                 return false;
93             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
94                 return false;
95             if (CCryptoKeyStore::Unlock(vMasterKey))
96                 return true;
97         }
98     }
99     return false;
100 }
101
102 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
103 {
104     bool fWasLocked = IsLocked();
105
106     {
107         LOCK(cs_wallet);
108         Lock();
109
110         CCrypter crypter;
111         CKeyingMaterial vMasterKey;
112         BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
113         {
114             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
115                 return false;
116             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
117                 return false;
118             if (CCryptoKeyStore::Unlock(vMasterKey))
119             {
120                 int64 nStartTime = GetTimeMillis();
121                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
122                 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
123
124                 nStartTime = GetTimeMillis();
125                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
126                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
127
128                 if (pMasterKey.second.nDeriveIterations < 25000)
129                     pMasterKey.second.nDeriveIterations = 25000;
130
131                 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
132
133                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
134                     return false;
135                 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
136                     return false;
137                 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
138                 if (fWasLocked)
139                     Lock();
140                 return true;
141             }
142         }
143     }
144
145     return false;
146 }
147
148 void CWallet::SetBestChain(const CBlockLocator& loc)
149 {
150     CWalletDB walletdb(strWalletFile);
151     walletdb.WriteBestBlock(loc);
152 }
153
154 // This class implements an addrIncoming entry that causes pre-0.4
155 // clients to crash on startup if reading a private-key-encrypted wallet.
156 class CCorruptAddress
157 {
158 public:
159     IMPLEMENT_SERIALIZE
160     (
161         if (nType & SER_DISK)
162             READWRITE(nVersion);
163     )
164 };
165
166 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
167 {
168     if (nWalletVersion >= nVersion)
169         return true;
170
171     // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
172     if (fExplicit && nVersion > nWalletMaxVersion)
173             nVersion = FEATURE_LATEST;
174
175     nWalletVersion = nVersion;
176
177     if (nVersion > nWalletMaxVersion)
178         nWalletMaxVersion = nVersion;
179
180     if (fFileBacked)
181     {
182         CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
183         if (nWalletVersion >= 40000)
184         {
185             // Versions prior to 0.4.0 did not support the "minversion" record.
186             // Use a CCorruptAddress to make them crash instead.
187             CCorruptAddress corruptAddress;
188             pwalletdb->WriteSetting("addrIncoming", corruptAddress);
189         }
190         if (nWalletVersion > 40000)
191             pwalletdb->WriteMinVersion(nWalletVersion);
192         if (!pwalletdbIn)
193             delete pwalletdb;
194     }
195
196     return true;
197 }
198
199 bool CWallet::SetMaxVersion(int nVersion)
200 {
201     // cannot downgrade below current version
202     if (nWalletVersion > nVersion)
203         return false;
204
205     nWalletMaxVersion = nVersion;
206
207     return true;
208 }
209
210 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
211 {
212     if (IsCrypted())
213         return false;
214
215     CKeyingMaterial vMasterKey;
216     RandAddSeedPerfmon();
217
218     vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
219     RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
220
221     CMasterKey kMasterKey;
222
223     RandAddSeedPerfmon();
224     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
225     RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
226
227     CCrypter crypter;
228     int64 nStartTime = GetTimeMillis();
229     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
230     kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
231
232     nStartTime = GetTimeMillis();
233     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
234     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
235
236     if (kMasterKey.nDeriveIterations < 25000)
237         kMasterKey.nDeriveIterations = 25000;
238
239     printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
240
241     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
242         return false;
243     if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
244         return false;
245
246     {
247         LOCK(cs_wallet);
248         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
249         if (fFileBacked)
250         {
251             pwalletdbEncryption = new CWalletDB(strWalletFile);
252             if (!pwalletdbEncryption->TxnBegin())
253                 return false;
254             pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
255         }
256
257         if (!EncryptKeys(vMasterKey))
258         {
259             if (fFileBacked)
260                 pwalletdbEncryption->TxnAbort();
261             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.
262         }
263
264         // Encryption was introduced in version 0.4.0
265         SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
266
267         if (fFileBacked)
268         {
269             if (!pwalletdbEncryption->TxnCommit())
270                 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.
271
272             delete pwalletdbEncryption;
273             pwalletdbEncryption = NULL;
274         }
275
276         Lock();
277         Unlock(strWalletPassphrase);
278         NewKeyPool();
279         Lock();
280
281         // Need to completely rewrite the wallet file; if we don't, bdb might keep
282         // bits of the unencrypted private key in slack space in the database file.
283         CDB::Rewrite(strWalletFile);
284     }
285
286     return true;
287 }
288
289 void CWallet::WalletUpdateSpent(const CTransaction &tx)
290 {
291     // Anytime a signature is successfully verified, it's proof the outpoint is spent.
292     // Update the wallet spent flag if it doesn't know due to wallet.dat being
293     // restored from backup or the user making copies of wallet.dat.
294     {
295         LOCK(cs_wallet);
296         BOOST_FOREACH(const CTxIn& txin, tx.vin)
297         {
298             map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
299             if (mi != mapWallet.end())
300             {
301                 CWalletTx& wtx = (*mi).second;
302                 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
303                 {
304                     printf("WalletUpdateSpent found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
305                     wtx.MarkSpent(txin.prevout.n);
306                     wtx.WriteToDisk();
307                     vWalletUpdated.push_back(txin.prevout.hash);
308                 }
309             }
310         }
311     }
312 }
313
314 void CWallet::MarkDirty()
315 {
316     {
317         LOCK(cs_wallet);
318         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
319             item.second.MarkDirty();
320     }
321 }
322
323 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
324 {
325     uint256 hash = wtxIn.GetHash();
326     {
327         LOCK(cs_wallet);
328         // Inserts only if not already there, returns tx inserted or tx found
329         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
330         CWalletTx& wtx = (*ret.first).second;
331         wtx.BindWallet(this);
332         bool fInsertedNew = ret.second;
333         if (fInsertedNew)
334             wtx.nTimeReceived = GetAdjustedTime();
335
336         bool fUpdated = false;
337         if (!fInsertedNew)
338         {
339             // Merge
340             if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
341             {
342                 wtx.hashBlock = wtxIn.hashBlock;
343                 fUpdated = true;
344             }
345             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
346             {
347                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
348                 wtx.nIndex = wtxIn.nIndex;
349                 fUpdated = true;
350             }
351             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
352             {
353                 wtx.fFromMe = wtxIn.fFromMe;
354                 fUpdated = true;
355             }
356             fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
357         }
358
359         //// debug print
360         printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
361
362         // Write to disk
363         if (fInsertedNew || fUpdated)
364             if (!wtx.WriteToDisk())
365                 return false;
366 #ifndef QT_GUI
367         // If default receiving address gets used, replace it with a new one
368         CScript scriptDefaultKey;
369         scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
370         BOOST_FOREACH(const CTxOut& txout, wtx.vout)
371         {
372             if (txout.scriptPubKey == scriptDefaultKey)
373             {
374                 std::vector<unsigned char> newDefaultKey;
375                 if (GetKeyFromPool(newDefaultKey, false))
376                 {
377                     SetDefaultKey(newDefaultKey);
378                     SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
379                 }
380             }
381         }
382 #endif
383         // Notify UI
384         vWalletUpdated.push_back(hash);
385
386         // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
387         WalletUpdateSpent(wtx);
388     }
389
390     // Refresh UI
391     MainFrameRepaint();
392     return true;
393 }
394
395 // Add a transaction to the wallet, or update it.
396 // pblock is optional, but should be provided if the transaction is known to be in a block.
397 // If fUpdate is true, existing transactions will be updated.
398 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
399 {
400     uint256 hash = tx.GetHash();
401     {
402         LOCK(cs_wallet);
403         bool fExisted = mapWallet.count(hash);
404         if (fExisted && !fUpdate) return false;
405         if (fExisted || IsMine(tx) || IsFromMe(tx))
406         {
407             CWalletTx wtx(this,tx);
408             // Get merkle branch if transaction was found in a block
409             if (pblock)
410                 wtx.SetMerkleBranch(pblock);
411             return AddToWallet(wtx);
412         }
413         else
414             WalletUpdateSpent(tx);
415     }
416     return false;
417 }
418
419 bool CWallet::EraseFromWallet(uint256 hash)
420 {
421     if (!fFileBacked)
422         return false;
423     {
424         LOCK(cs_wallet);
425         if (mapWallet.erase(hash))
426             CWalletDB(strWalletFile).EraseTx(hash);
427     }
428     return true;
429 }
430
431
432 bool CWallet::IsMine(const CTxIn &txin) const
433 {
434     {
435         LOCK(cs_wallet);
436         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
437         if (mi != mapWallet.end())
438         {
439             const CWalletTx& prev = (*mi).second;
440             if (txin.prevout.n < prev.vout.size())
441                 if (IsMine(prev.vout[txin.prevout.n]))
442                     return true;
443         }
444     }
445     return false;
446 }
447
448 int64 CWallet::GetDebit(const CTxIn &txin) const
449 {
450     {
451         LOCK(cs_wallet);
452         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
453         if (mi != mapWallet.end())
454         {
455             const CWalletTx& prev = (*mi).second;
456             if (txin.prevout.n < prev.vout.size())
457                 if (IsMine(prev.vout[txin.prevout.n]))
458                     return prev.vout[txin.prevout.n].nValue;
459         }
460     }
461     return 0;
462 }
463
464 bool CWallet::IsChange(const CTxOut& txout) const
465 {
466     CBitcoinAddress address;
467
468     // TODO: fix handling of 'change' outputs. The assumption is that any
469     // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
470     // is change. That assumption is likely to break when we implement multisignature
471     // wallets that return change back into a multi-signature-protected address;
472     // a better way of identifying which outputs are 'the send' and which are
473     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
474     // which output, if any, was change).
475     if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
476     {
477         LOCK(cs_wallet);
478         if (!mapAddressBook.count(address))
479             return true;
480     }
481     return false;
482 }
483
484 int64 CWalletTx::GetTxTime() const
485 {
486     return nTimeReceived;
487 }
488
489 int CWalletTx::GetRequestCount() const
490 {
491     // Returns -1 if it wasn't being tracked
492     int nRequests = -1;
493     {
494         LOCK(pwallet->cs_wallet);
495         if (IsCoinBase() || IsCoinStake())
496         {
497             // Generated block
498             if (hashBlock != 0)
499             {
500                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
501                 if (mi != pwallet->mapRequestCount.end())
502                     nRequests = (*mi).second;
503             }
504         }
505         else
506         {
507             // Did anyone request this transaction?
508             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
509             if (mi != pwallet->mapRequestCount.end())
510             {
511                 nRequests = (*mi).second;
512
513                 // How about the block it's in?
514                 if (nRequests == 0 && hashBlock != 0)
515                 {
516                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
517                     if (mi != pwallet->mapRequestCount.end())
518                         nRequests = (*mi).second;
519                     else
520                         nRequests = 1; // If it's in someone else's block it must have got out
521                 }
522             }
523         }
524     }
525     return nRequests;
526 }
527
528 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
529                            list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
530 {
531     nGeneratedImmature = nGeneratedMature = nFee = 0;
532     listReceived.clear();
533     listSent.clear();
534     strSentAccount = strFromAccount;
535
536     if (IsCoinBase() || IsCoinStake())
537     {
538         if (GetBlocksToMaturity() > 0)
539             nGeneratedImmature = pwallet->GetCredit(*this);
540         else
541             nGeneratedMature = GetCredit();
542         return;
543     }
544
545     // Compute fee:
546     int64 nDebit = GetDebit();
547     if (nDebit > 0) // debit>0 means we signed/sent this transaction
548     {
549         int64 nValueOut = GetValueOut();
550         nFee = nDebit - nValueOut;
551     }
552
553     // Sent/received.
554     BOOST_FOREACH(const CTxOut& txout, vout)
555     {
556         CBitcoinAddress address;
557         vector<unsigned char> vchPubKey;
558         if (!ExtractAddress(txout.scriptPubKey, address))
559         {
560             printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
561                    this->GetHash().ToString().c_str());
562             address = " unknown ";
563         }
564
565         // Don't report 'change' txouts
566         if (nDebit > 0 && pwallet->IsChange(txout))
567             continue;
568
569         if (nDebit > 0)
570             listSent.push_back(make_pair(address, txout.nValue));
571
572         if (pwallet->IsMine(txout))
573             listReceived.push_back(make_pair(address, txout.nValue));
574     }
575
576 }
577
578 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 
579                                   int64& nSent, int64& nFee) const
580 {
581     nGenerated = nReceived = nSent = nFee = 0;
582
583     int64 allGeneratedImmature, allGeneratedMature, allFee;
584     allGeneratedImmature = allGeneratedMature = allFee = 0;
585     string strSentAccount;
586     list<pair<CBitcoinAddress, int64> > listReceived;
587     list<pair<CBitcoinAddress, int64> > listSent;
588     GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
589
590     if (strAccount == "")
591         nGenerated = allGeneratedMature;
592     if (strAccount == strSentAccount)
593     {
594         BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
595             nSent += s.second;
596         nFee = allFee;
597     }
598     {
599         LOCK(pwallet->cs_wallet);
600         BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
601         {
602             if (pwallet->mapAddressBook.count(r.first))
603             {
604                 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
605                 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
606                     nReceived += r.second;
607             }
608             else if (strAccount.empty())
609             {
610                 nReceived += r.second;
611             }
612         }
613     }
614 }
615
616 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
617 {
618     vtxPrev.clear();
619
620     const int COPY_DEPTH = 3;
621     if (SetMerkleBranch() < COPY_DEPTH)
622     {
623         vector<uint256> vWorkQueue;
624         BOOST_FOREACH(const CTxIn& txin, vin)
625             vWorkQueue.push_back(txin.prevout.hash);
626
627         // This critsect is OK because txdb is already open
628         {
629             LOCK(pwallet->cs_wallet);
630             map<uint256, const CMerkleTx*> mapWalletPrev;
631             set<uint256> setAlreadyDone;
632             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
633             {
634                 uint256 hash = vWorkQueue[i];
635                 if (setAlreadyDone.count(hash))
636                     continue;
637                 setAlreadyDone.insert(hash);
638
639                 CMerkleTx tx;
640                 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
641                 if (mi != pwallet->mapWallet.end())
642                 {
643                     tx = (*mi).second;
644                     BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
645                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
646                 }
647                 else if (mapWalletPrev.count(hash))
648                 {
649                     tx = *mapWalletPrev[hash];
650                 }
651                 else if (!fClient && txdb.ReadDiskTx(hash, tx))
652                 {
653                     ;
654                 }
655                 else
656                 {
657                     printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
658                     continue;
659                 }
660
661                 int nDepth = tx.SetMerkleBranch();
662                 vtxPrev.push_back(tx);
663
664                 if (nDepth < COPY_DEPTH)
665                 {
666                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
667                         vWorkQueue.push_back(txin.prevout.hash);
668                 }
669             }
670         }
671     }
672
673     reverse(vtxPrev.begin(), vtxPrev.end());
674 }
675
676 bool CWalletTx::WriteToDisk()
677 {
678     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
679 }
680
681 // Scan the block chain (starting in pindexStart) for transactions
682 // from or to us. If fUpdate is true, found transactions that already
683 // exist in the wallet will be updated.
684 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
685 {
686     int ret = 0;
687
688     CBlockIndex* pindex = pindexStart;
689     {
690         LOCK(cs_wallet);
691         while (pindex)
692         {
693             CBlock block;
694             block.ReadFromDisk(pindex, true);
695             BOOST_FOREACH(CTransaction& tx, block.vtx)
696             {
697                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
698                     ret++;
699             }
700             pindex = pindex->pnext;
701         }
702     }
703     return ret;
704 }
705
706 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
707 {
708     CTransaction tx;
709     tx.ReadFromDisk(COutPoint(hashTx, 0));
710     if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
711         return 1;
712     return 0;
713 }
714
715 void CWallet::ReacceptWalletTransactions()
716 {
717     CTxDB txdb("r");
718     bool fRepeat = true;
719     while (fRepeat)
720     {
721         LOCK(cs_wallet);
722         fRepeat = false;
723         vector<CDiskTxPos> vMissingTx;
724         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
725         {
726             CWalletTx& wtx = item.second;
727             if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
728                 continue;
729
730             CTxIndex txindex;
731             bool fUpdated = false;
732             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
733             {
734                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
735                 if (txindex.vSpent.size() != wtx.vout.size())
736                 {
737                     printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
738                     continue;
739                 }
740                 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
741                 {
742                     if (wtx.IsSpent(i))
743                         continue;
744                     if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
745                     {
746                         wtx.MarkSpent(i);
747                         fUpdated = true;
748                         vMissingTx.push_back(txindex.vSpent[i]);
749                     }
750                 }
751                 if (fUpdated)
752                 {
753                     printf("ReacceptWalletTransactions found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
754                     wtx.MarkDirty();
755                     wtx.WriteToDisk();
756                 }
757             }
758             else
759             {
760                 // Reaccept any txes of ours that aren't already in a block
761                 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
762                     wtx.AcceptWalletTransaction(txdb, false);
763             }
764         }
765         if (!vMissingTx.empty())
766         {
767             // TODO: optimize this to scan just part of the block chain?
768             if (ScanForWalletTransactions(pindexGenesisBlock))
769                 fRepeat = true;  // Found missing transactions: re-do Reaccept.
770         }
771     }
772 }
773
774 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
775 {
776     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
777     {
778         if (!(tx.IsCoinBase() || tx.IsCoinStake()))
779         {
780             uint256 hash = tx.GetHash();
781             if (!txdb.ContainsTx(hash))
782                 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
783         }
784     }
785     if (!(IsCoinBase() || IsCoinStake()))
786     {
787         uint256 hash = GetHash();
788         if (!txdb.ContainsTx(hash))
789         {
790             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
791             RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
792         }
793     }
794 }
795
796 void CWalletTx::RelayWalletTransaction()
797 {
798    CTxDB txdb("r");
799    RelayWalletTransaction(txdb);
800 }
801
802 void CWallet::ResendWalletTransactions()
803 {
804     // Do this infrequently and randomly to avoid giving away
805     // that these are our transactions.
806     static int64 nNextTime;
807     if (GetTime() < nNextTime)
808         return;
809     bool fFirst = (nNextTime == 0);
810     nNextTime = GetTime() + GetRand(30 * 60);
811     if (fFirst)
812         return;
813
814     // Only do it if there's been a new block since last time
815     static int64 nLastTime;
816     if (nTimeBestReceived < nLastTime)
817         return;
818     nLastTime = GetTime();
819
820     // Rebroadcast any of our txes that aren't in a block yet
821     printf("ResendWalletTransactions()\n");
822     CTxDB txdb("r");
823     {
824         LOCK(cs_wallet);
825         // Sort them in chronological order
826         multimap<unsigned int, CWalletTx*> mapSorted;
827         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
828         {
829             CWalletTx& wtx = item.second;
830             // Don't rebroadcast until it's had plenty of time that
831             // it should have gotten in already by now.
832             if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
833                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
834         }
835         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
836         {
837             CWalletTx& wtx = *item.second;
838             if (wtx.CheckTransaction())
839                 wtx.RelayWalletTransaction(txdb);
840             else
841                 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
842         }
843     }
844 }
845
846
847
848
849
850
851 //////////////////////////////////////////////////////////////////////////////
852 //
853 // Actions
854 //
855
856
857 int64 CWallet::GetBalance() const
858 {
859     int64 nTotal = 0;
860     {
861         LOCK(cs_wallet);
862         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
863         {
864             const CWalletTx* pcoin = &(*it).second;
865             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
866                 continue;
867             nTotal += pcoin->GetAvailableCredit();
868         }
869     }
870
871     return nTotal;
872 }
873
874 int64 CWallet::GetUnconfirmedBalance() const
875 {
876     int64 nTotal = 0;
877     {
878         LOCK(cs_wallet);
879         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
880         {
881             const CWalletTx* pcoin = &(*it).second;
882             if (pcoin->IsFinal() && pcoin->IsConfirmed())
883                 continue;
884             nTotal += pcoin->GetAvailableCredit();
885         }
886     }
887     return nTotal;
888 }
889
890 // ppcoin: total coins staked (non-spendable until maturity)
891 int64 CWallet::GetStake() const
892 {
893     int64 nTotal = 0;
894     LOCK(cs_wallet);
895     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
896     {
897         const CWalletTx* pcoin = &(*it).second;
898         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
899             nTotal += CWallet::GetCredit(*pcoin);
900     }
901     return nTotal;
902 }
903
904 int64 CWallet::GetNewMint() const
905 {
906     int64 nTotal = 0;
907     LOCK(cs_wallet);
908     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
909     {
910         const CWalletTx* pcoin = &(*it).second;
911         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
912             nTotal += CWallet::GetCredit(*pcoin);
913     }
914     return nTotal;
915 }
916
917
918 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
919 {
920     setCoinsRet.clear();
921     nValueRet = 0;
922
923     // List of values less than target
924     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
925     coinLowestLarger.first = std::numeric_limits<int64>::max();
926     coinLowestLarger.second.first = NULL;
927     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
928     int64 nTotalLower = 0;
929
930     {
931        LOCK(cs_wallet);
932        vector<const CWalletTx*> vCoins;
933        vCoins.reserve(mapWallet.size());
934        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
935            vCoins.push_back(&(*it).second);
936        random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
937
938        BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
939        {
940             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
941                 continue;
942
943             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
944                 continue;
945
946             int nDepth = pcoin->GetDepthInMainChain();
947             if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
948                 continue;
949
950             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
951             {
952                 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
953                     continue;
954
955                 if (pcoin->nTime > nSpendTime)
956                     continue;  // ppcoin: timestamp must not exceed spend time
957
958                 int64 n = pcoin->vout[i].nValue;
959
960                 if (n <= 0)
961                     continue;
962
963                 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
964
965                 if (n == nTargetValue)
966                 {
967                     setCoinsRet.insert(coin.second);
968                     nValueRet += coin.first;
969                     return true;
970                 }
971                 else if (n < nTargetValue + CENT)
972                 {
973                     vValue.push_back(coin);
974                     nTotalLower += n;
975                 }
976                 else if (n < coinLowestLarger.first)
977                 {
978                     coinLowestLarger = coin;
979                 }
980             }
981         }
982     }
983
984     if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
985     {
986         for (unsigned int i = 0; i < vValue.size(); ++i)
987         {
988             setCoinsRet.insert(vValue[i].second);
989             nValueRet += vValue[i].first;
990         }
991         return true;
992     }
993
994     if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
995     {
996         if (coinLowestLarger.second.first == NULL)
997             return false;
998         setCoinsRet.insert(coinLowestLarger.second);
999         nValueRet += coinLowestLarger.first;
1000         return true;
1001     }
1002
1003     if (nTotalLower >= nTargetValue + CENT)
1004         nTargetValue += CENT;
1005
1006     // Solve subset sum by stochastic approximation
1007     sort(vValue.rbegin(), vValue.rend());
1008     vector<char> vfIncluded;
1009     vector<char> vfBest(vValue.size(), true);
1010     int64 nBest = nTotalLower;
1011
1012     for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
1013     {
1014         vfIncluded.assign(vValue.size(), false);
1015         int64 nTotal = 0;
1016         bool fReachedTarget = false;
1017         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1018         {
1019             for (unsigned int i = 0; i < vValue.size(); i++)
1020             {
1021                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1022                 {
1023                     nTotal += vValue[i].first;
1024                     vfIncluded[i] = true;
1025                     if (nTotal >= nTargetValue)
1026                     {
1027                         fReachedTarget = true;
1028                         if (nTotal < nBest)
1029                         {
1030                             nBest = nTotal;
1031                             vfBest = vfIncluded;
1032                         }
1033                         nTotal -= vValue[i].first;
1034                         vfIncluded[i] = false;
1035                     }
1036                 }
1037             }
1038         }
1039     }
1040
1041     // If the next larger is still closer, return it
1042     if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
1043     {
1044         setCoinsRet.insert(coinLowestLarger.second);
1045         nValueRet += coinLowestLarger.first;
1046     }
1047     else {
1048         for (unsigned int i = 0; i < vValue.size(); i++)
1049             if (vfBest[i])
1050             {
1051                 setCoinsRet.insert(vValue[i].second);
1052                 nValueRet += vValue[i].first;
1053             }
1054
1055         //// debug print
1056         if (fDebug && GetBoolArg("-printselectcoin"))
1057         {
1058             printf("SelectCoins() best subset: ");
1059             for (unsigned int i = 0; i < vValue.size(); i++)
1060                 if (vfBest[i])
1061                     printf("%s ", FormatMoney(vValue[i].first).c_str());
1062             printf("total %s\n", FormatMoney(nBest).c_str());
1063         }
1064     }
1065
1066     return true;
1067 }
1068
1069 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1070 {
1071     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
1072             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
1073             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
1074 }
1075
1076
1077
1078
1079 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1080 {
1081     int64 nValue = 0;
1082     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1083     {
1084         if (nValue < 0)
1085             return false;
1086         nValue += s.second;
1087     }
1088     if (vecSend.empty() || nValue < 0)
1089         return false;
1090
1091     wtxNew.BindWallet(this);
1092
1093     {
1094         LOCK2(cs_main, cs_wallet);
1095         // txdb must be opened before the mapWallet lock
1096         CTxDB txdb("r");
1097         {
1098             nFeeRet = nTransactionFee;
1099             loop
1100             {
1101                 wtxNew.vin.clear();
1102                 wtxNew.vout.clear();
1103                 wtxNew.fFromMe = true;
1104
1105                 int64 nTotalValue = nValue + nFeeRet;
1106                 double dPriority = 0;
1107                 // vouts to the payees
1108                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1109                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1110
1111                 // Choose coins to use
1112                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1113                 int64 nValueIn = 0;
1114                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1115                     return false;
1116                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1117                 {
1118                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1119                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1120                 }
1121
1122                 int64 nChange = nValueIn - nValue - nFeeRet;
1123                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1124                 // or until nChange becomes zero
1125                 // NOTE: this depends on the exact behaviour of GetMinFee
1126                 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1127                 {
1128                     int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1129                     nChange -= nMoveToFee;
1130                     nFeeRet += nMoveToFee;
1131                 }
1132
1133                 // ppcoin: sub-cent change is moved to fee
1134                 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1135                 {
1136                     nFeeRet += nChange;
1137                     nChange = 0;
1138                 }
1139
1140                 if (nChange > 0)
1141                 {
1142                     // Note: We use a new key here to keep it from being obvious which side is the change.
1143                     //  The drawback is that by not reusing a previous key, the change may be lost if a
1144                     //  backup is restored, if the backup doesn't have the new private key for the change.
1145                     //  If we reused the old key, it would be possible to add code to look for and
1146                     //  rediscover unknown transactions that were written with keys of ours to recover
1147                     //  post-backup change.
1148
1149                     // Reserve a new key pair from key pool
1150                     vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1151                     // assert(mapKeys.count(vchPubKey));
1152
1153                     // Fill a vout to ourself
1154                     // TODO: pass in scriptChange instead of reservekey so
1155                     // change transaction isn't always pay-to-bitcoin-address
1156                     CScript scriptChange;
1157                     scriptChange.SetBitcoinAddress(vchPubKey);
1158
1159                     // Insert change txn at random position:
1160                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1161                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1162                 }
1163                 else
1164                     reservekey.ReturnKey();
1165
1166                 // Fill vin
1167                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1168                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1169
1170                 // Sign
1171                 int nIn = 0;
1172                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1173                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1174                         return false;
1175
1176                 // Limit size
1177                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1178                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1179                     return false;
1180                 dPriority /= nBytes;
1181
1182                 // Check that enough fee is included
1183                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1184                 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1185                 if (nFeeRet < max(nPayFee, nMinFee))
1186                 {
1187                     nFeeRet = max(nPayFee, nMinFee);
1188                     continue;
1189                 }
1190
1191                 // Fill vtxPrev by copying from previous transactions vtxPrev
1192                 wtxNew.AddSupportingTransactions(txdb);
1193                 wtxNew.fTimeReceivedIsTxTime = true;
1194
1195                 break;
1196             }
1197         }
1198     }
1199     return true;
1200 }
1201
1202 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1203 {
1204     vector< pair<CScript, int64> > vecSend;
1205     vecSend.push_back(make_pair(scriptPubKey, nValue));
1206     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1207 }
1208
1209 // ppcoin: create coin stake transaction
1210 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew)
1211 {
1212     // The following split & combine thresholds are important to security
1213     // Should not be adjusted if you don't understand the consequences
1214     static unsigned int nStakeSplitAge = (60 * 60 * 24 * 90);
1215     int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1216
1217     CBigNum bnTargetPerCoinDay;
1218     bnTargetPerCoinDay.SetCompact(nBits);
1219
1220     LOCK2(cs_main, cs_wallet);
1221     txNew.vin.clear();
1222     txNew.vout.clear();
1223     // Mark coin stake transaction
1224     CScript scriptEmpty;
1225     scriptEmpty.clear();
1226     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1227     // Choose coins to use
1228     int64 nBalance = GetBalance();
1229     int64 nReserveBalance = 0;
1230     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1231         return error("CreateCoinStake : invalid reserve balance amount");
1232     if (nBalance <= nReserveBalance)
1233         return false;
1234     set<pair<const CWalletTx*,unsigned int> > setCoins;
1235     vector<const CWalletTx*> vwtxPrev;
1236     int64 nValueIn = 0;
1237     if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
1238         return false;
1239     if (setCoins.empty())
1240         return false;
1241     int64 nCredit = 0;
1242     CScript scriptPubKeyKernel;
1243     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1244     {
1245         CTxDB txdb("r");
1246         CTxIndex txindex;
1247         if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1248             continue;
1249
1250         // Read block header
1251         CBlock block;
1252         if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1253             continue;
1254         static int nMaxStakeSearchInterval = 60;
1255         if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1256             continue; // only count coins meeting min age requirement
1257
1258         bool fKernelFound = false;
1259         for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1260         {
1261             // Search backward in time from the given txNew timestamp 
1262             // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1263             uint256 hashProofOfStake = 0;
1264             COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1265             if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake))
1266             {
1267                 // Found a kernel
1268                 if (fDebug && GetBoolArg("-printcoinstake"))
1269                     printf("CreateCoinStake : kernel found\n");
1270                 vector<valtype> vSolutions;
1271                 txnouttype whichType;
1272                 CScript scriptPubKeyOut;
1273                 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1274                 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1275                 {
1276                     if (fDebug && GetBoolArg("-printcoinstake"))
1277                         printf("CreateCoinStake : failed to parse kernel\n", whichType);
1278                     break;
1279                 }
1280                 if (fDebug && GetBoolArg("-printcoinstake"))
1281                     printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1282                 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1283                 {
1284                     if (fDebug && GetBoolArg("-printcoinstake"))
1285                         printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1286                     break;  // only support pay to public key and pay to address
1287                 }
1288                 if (whichType == TX_PUBKEYHASH) // pay to address type
1289                 {
1290                     // convert to pay to public key type
1291                     CKey key;
1292                     if (!keystore.GetKey(uint160(vSolutions[0]), key))
1293                     {
1294                         if (fDebug && GetBoolArg("-printcoinstake"))
1295                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1296                         break;  // unable to find corresponding public key
1297                     }
1298                     scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1299                 }
1300                 else
1301                     scriptPubKeyOut = scriptPubKeyKernel;
1302
1303                 txNew.nTime -= n; 
1304                 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1305                 nCredit += pcoin.first->vout[pcoin.second].nValue;
1306                 vwtxPrev.push_back(pcoin.first);
1307                 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1308                 if (block.GetBlockTime() + nStakeSplitAge > txNew.nTime)
1309                     txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1310                 if (fDebug && GetBoolArg("-printcoinstake"))
1311                     printf("CreateCoinStake : added kernel type=%d\n", whichType);
1312                 fKernelFound = true;
1313                 break;
1314             }
1315         }
1316         if (fKernelFound || fShutdown)
1317             break; // if kernel is found stop searching
1318     }
1319     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1320         return false;
1321     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1322     {
1323         // Attempt to add more inputs
1324         // Only add coins of the same key/address as kernel
1325         if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1326             && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1327         {
1328             // Stop adding more inputs if already too many inputs
1329             if (txNew.vin.size() >= 100)
1330                 break;
1331             // Stop adding more inputs if value is already pretty significant
1332             if (nCredit > nCombineThreshold)
1333                 break;
1334             // Stop adding inputs if reached reserve limit
1335             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1336                 break;
1337             // Do not add additional significant input
1338             if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1339                 continue;
1340             // Do not add input that is still too young
1341             if (pcoin.first->nTime + STAKE_MAX_AGE > txNew.nTime)
1342                 continue;
1343             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1344             nCredit += pcoin.first->vout[pcoin.second].nValue;
1345             vwtxPrev.push_back(pcoin.first);
1346         }
1347     }
1348     // Calculate coin age reward
1349     {
1350         uint64 nCoinAge;
1351         CTxDB txdb("r");
1352         if (!txNew.GetCoinAge(txdb, nCoinAge))
1353             return error("CreateCoinStake : failed to calculate coin age");
1354         nCredit += GetProofOfStakeReward(nCoinAge);
1355     }
1356
1357     int64 nMinFee = 0;
1358     loop
1359     {
1360         // Set output amount
1361         if (txNew.vout.size() == 3)
1362         {
1363             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1364             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1365         }
1366         else
1367             txNew.vout[1].nValue = nCredit - nMinFee;
1368
1369         // Sign
1370         int nIn = 0;
1371         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1372         {
1373             if (!SignSignature(*this, *pcoin, txNew, nIn++))
1374                 return error("CreateCoinStake : failed to sign coinstake");
1375         }
1376
1377         // Limit size
1378         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1379         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1380             return error("CreateCoinStake : exceeded coinstake size limit");
1381
1382         // Check enough fee is paid
1383         if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1384         {
1385             nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1386             continue; // try signing again
1387         }
1388         else
1389         {
1390             if (fDebug && GetBoolArg("-printfee"))
1391                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1392             break;
1393         }
1394     }
1395
1396     // Successfully generated coinstake
1397     return true;
1398 }
1399
1400 // Call after CreateTransaction unless you want to abort
1401 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1402 {
1403     {
1404         LOCK2(cs_main, cs_wallet);
1405         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1406         {
1407             // This is only to keep the database open to defeat the auto-flush for the
1408             // duration of this scope.  This is the only place where this optimization
1409             // maybe makes sense; please don't do it anywhere else.
1410             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1411
1412             // Take key pair from key pool so it won't be used again
1413             reservekey.KeepKey();
1414
1415             // Add tx to wallet, because if it has change it's also ours,
1416             // otherwise just for transaction history.
1417             AddToWallet(wtxNew);
1418
1419             // Mark old coins as spent
1420             set<CWalletTx*> setCoins;
1421             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1422             {
1423                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1424                 coin.BindWallet(this);
1425                 coin.MarkSpent(txin.prevout.n);
1426                 coin.WriteToDisk();
1427                 vWalletUpdated.push_back(coin.GetHash());
1428             }
1429
1430             if (fFileBacked)
1431                 delete pwalletdb;
1432         }
1433
1434         // Track how many getdata requests our transaction gets
1435         mapRequestCount[wtxNew.GetHash()] = 0;
1436
1437         // Broadcast
1438         if (!wtxNew.AcceptToMemoryPool())
1439         {
1440             // This must not fail. The transaction has already been signed and recorded.
1441             printf("CommitTransaction() : Error: Transaction not valid");
1442             return false;
1443         }
1444         wtxNew.RelayWalletTransaction();
1445     }
1446     MainFrameRepaint();
1447     return true;
1448 }
1449
1450
1451
1452
1453 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1454 {
1455     CReserveKey reservekey(this);
1456     int64 nFeeRequired;
1457
1458     if (IsLocked())
1459     {
1460         string strError = _("Error: Wallet locked, unable to create transaction  ");
1461         printf("SendMoney() : %s", strError.c_str());
1462         return strError;
1463     }
1464     if (fWalletUnlockMintOnly)
1465     {
1466         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1467         printf("SendMoney() : %s", strError.c_str());
1468         return strError;
1469     }
1470     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1471     {
1472         string strError;
1473         if (nValue + nFeeRequired > GetBalance())
1474             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());
1475         else
1476             strError = _("Error: Transaction creation failed  ");
1477         printf("SendMoney() : %s", strError.c_str());
1478         return strError;
1479     }
1480
1481     if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1482         return "ABORTED";
1483
1484     if (!CommitTransaction(wtxNew, reservekey))
1485         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.");
1486
1487     MainFrameRepaint();
1488     return "";
1489 }
1490
1491
1492
1493 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1494 {
1495     // Check amount
1496     if (nValue <= 0)
1497         return _("Invalid amount");
1498     if (nValue + nTransactionFee > GetBalance())
1499         return _("Insufficient funds");
1500
1501     // Parse bitcoin address
1502     CScript scriptPubKey;
1503     scriptPubKey.SetBitcoinAddress(address);
1504
1505     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1506 }
1507
1508
1509
1510
1511 int CWallet::LoadWallet(bool& fFirstRunRet)
1512 {
1513     if (!fFileBacked)
1514         return false;
1515     fFirstRunRet = false;
1516     int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1517     if (nLoadWalletRet == DB_NEED_REWRITE)
1518     {
1519         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1520         {
1521             setKeyPool.clear();
1522             // Note: can't top-up keypool here, because wallet is locked.
1523             // User will be prompted to unlock wallet the next operation
1524             // the requires a new key.
1525         }
1526         nLoadWalletRet = DB_NEED_REWRITE;
1527     }
1528
1529     if (nLoadWalletRet != DB_LOAD_OK)
1530         return nLoadWalletRet;
1531     fFirstRunRet = vchDefaultKey.empty();
1532
1533     CreateThread(ThreadFlushWalletDB, &strWalletFile);
1534     return DB_LOAD_OK;
1535 }
1536
1537
1538 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1539 {
1540     mapAddressBook[address] = strName;
1541     AddressBookRepaint();
1542     if (!fFileBacked)
1543         return false;
1544     return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1545 }
1546
1547 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1548 {
1549     mapAddressBook.erase(address);
1550     AddressBookRepaint();
1551     if (!fFileBacked)
1552         return false;
1553     return CWalletDB(strWalletFile).EraseName(address.ToString());
1554 }
1555
1556
1557 void CWallet::PrintWallet(const CBlock& block)
1558 {
1559     {
1560         LOCK(cs_wallet);
1561         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1562         {
1563             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1564             printf("    mine:  %d  %d  %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1565         }
1566         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1567         {
1568             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1569             printf("    stake: %d  %d  %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1570         }
1571     }
1572     printf("\n");
1573 }
1574
1575 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1576 {
1577     {
1578         LOCK(cs_wallet);
1579         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1580         if (mi != mapWallet.end())
1581         {
1582             wtx = (*mi).second;
1583             return true;
1584         }
1585     }
1586     return false;
1587 }
1588
1589 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1590 {
1591     if (fFileBacked)
1592     {
1593         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1594             return false;
1595     }
1596     vchDefaultKey = vchPubKey;
1597     return true;
1598 }
1599
1600 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1601 {
1602     if (!pwallet->fFileBacked)
1603         return false;
1604     strWalletFileOut = pwallet->strWalletFile;
1605     return true;
1606 }
1607
1608 //
1609 // Mark old keypool keys as used,
1610 // and generate all new keys
1611 //
1612 bool CWallet::NewKeyPool()
1613 {
1614     {
1615         LOCK(cs_wallet);
1616         CWalletDB walletdb(strWalletFile);
1617         BOOST_FOREACH(int64 nIndex, setKeyPool)
1618             walletdb.ErasePool(nIndex);
1619         setKeyPool.clear();
1620
1621         if (IsLocked())
1622             return false;
1623
1624         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1625         for (int i = 0; i < nKeys; i++)
1626         {
1627             int64 nIndex = i+1;
1628             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1629             setKeyPool.insert(nIndex);
1630         }
1631         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1632     }
1633     return true;
1634 }
1635
1636 bool CWallet::TopUpKeyPool()
1637 {
1638     {
1639         LOCK(cs_wallet);
1640
1641         if (IsLocked())
1642             return false;
1643
1644         CWalletDB walletdb(strWalletFile);
1645
1646         // Top up key pool
1647         unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1648         while (setKeyPool.size() < (nTargetSize + 1))
1649         {
1650             int64 nEnd = 1;
1651             if (!setKeyPool.empty())
1652                 nEnd = *(--setKeyPool.end()) + 1;
1653             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1654                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1655             setKeyPool.insert(nEnd);
1656             printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1657         }
1658     }
1659     return true;
1660 }
1661
1662 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1663 {
1664     nIndex = -1;
1665     keypool.vchPubKey.clear();
1666     {
1667         LOCK(cs_wallet);
1668
1669         if (!IsLocked())
1670             TopUpKeyPool();
1671
1672         // Get the oldest key
1673         if(setKeyPool.empty())
1674             return;
1675
1676         CWalletDB walletdb(strWalletFile);
1677
1678         nIndex = *(setKeyPool.begin());
1679         setKeyPool.erase(setKeyPool.begin());
1680         if (!walletdb.ReadPool(nIndex, keypool))
1681             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1682         if (!HaveKey(Hash160(keypool.vchPubKey)))
1683             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1684         assert(!keypool.vchPubKey.empty());
1685         if (fDebug && GetBoolArg("-printkeypool"))
1686             printf("keypool reserve %"PRI64d"\n", nIndex);
1687     }
1688 }
1689
1690 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1691 {
1692     {
1693         LOCK2(cs_main, cs_wallet);
1694         CWalletDB walletdb(strWalletFile);
1695
1696         int64 nIndex = 1 + *(--setKeyPool.end());
1697         if (!walletdb.WritePool(nIndex, keypool))
1698             throw runtime_error("AddReserveKey() : writing added key failed");
1699         setKeyPool.insert(nIndex);
1700         return nIndex;
1701     }
1702     return -1;
1703 }
1704
1705 void CWallet::KeepKey(int64 nIndex)
1706 {
1707     // Remove from key pool
1708     if (fFileBacked)
1709     {
1710         CWalletDB walletdb(strWalletFile);
1711         walletdb.ErasePool(nIndex);
1712     }
1713     printf("keypool keep %"PRI64d"\n", nIndex);
1714 }
1715
1716 void CWallet::ReturnKey(int64 nIndex)
1717 {
1718     // Return to key pool
1719     {
1720         LOCK(cs_wallet);
1721         setKeyPool.insert(nIndex);
1722     }
1723     if (fDebug && GetBoolArg("-printkeypool"))
1724         printf("keypool return %"PRI64d"\n", nIndex);
1725 }
1726
1727 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1728 {
1729     int64 nIndex = 0;
1730     CKeyPool keypool;
1731     {
1732         LOCK(cs_wallet);
1733         ReserveKeyFromKeyPool(nIndex, keypool);
1734         if (nIndex == -1)
1735         {
1736             if (fAllowReuse && !vchDefaultKey.empty())
1737             {
1738                 result = vchDefaultKey;
1739                 return true;
1740             }
1741             if (IsLocked()) return false;
1742             result = GenerateNewKey();
1743             return true;
1744         }
1745         KeepKey(nIndex);
1746         result = keypool.vchPubKey;
1747     }
1748     return true;
1749 }
1750
1751 int64 CWallet::GetOldestKeyPoolTime()
1752 {
1753     int64 nIndex = 0;
1754     CKeyPool keypool;
1755     ReserveKeyFromKeyPool(nIndex, keypool);
1756     if (nIndex == -1)
1757         return GetTime();
1758     ReturnKey(nIndex);
1759     return keypool.nTime;
1760 }
1761
1762 // ppcoin: check 'spent' consistency between wallet and txindex
1763 // ppcoin: fix wallet spent state according to txindex
1764 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
1765 {
1766     nMismatchFound = 0;
1767     nBalanceInQuestion = 0;
1768
1769     LOCK(cs_wallet);
1770     vector<CWalletTx*> vCoins;
1771     vCoins.reserve(mapWallet.size());
1772     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1773         vCoins.push_back(&(*it).second);
1774
1775     CTxDB txdb("r");
1776     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
1777     {
1778         // Find the corresponding transaction index
1779         CTxIndex txindex;
1780         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1781             continue;
1782         for (int n=0; n < pcoin->vout.size(); n++)
1783         {
1784             if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1785             {
1786                 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
1787                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
1788                 nMismatchFound++;
1789                 nBalanceInQuestion += pcoin->vout[n].nValue;
1790                 if (!fCheckOnly)
1791                 {
1792                     pcoin->MarkUnspent(n);
1793                     pcoin->WriteToDisk();
1794                 }
1795             }
1796             else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1797             {
1798                 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
1799                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
1800                 nMismatchFound++;
1801                 nBalanceInQuestion += pcoin->vout[n].nValue;
1802                 if (!fCheckOnly)
1803                 {
1804                     pcoin->MarkSpent(n);
1805                     pcoin->WriteToDisk();
1806                 }
1807             }
1808         }
1809     }
1810 }
1811
1812 // ppcoin: disable transaction (only for coinstake)
1813 void CWallet::DisableTransaction(const CTransaction &tx)
1814 {
1815     if (!tx.IsCoinStake() || !IsFromMe(tx))
1816         return; // only disconnecting coinstake requires marking input unspent
1817
1818     LOCK(cs_wallet);
1819     BOOST_FOREACH(const CTxIn& txin, tx.vin)
1820     {
1821         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
1822         if (mi != mapWallet.end())
1823         {
1824             CWalletTx& prev = (*mi).second;
1825             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
1826             {
1827                 prev.MarkUnspent(txin.prevout.n);
1828                 prev.WriteToDisk();
1829             }
1830         }
1831     }
1832 }
1833
1834 vector<unsigned char> CReserveKey::GetReservedKey()
1835 {
1836     if (nIndex == -1)
1837     {
1838         CKeyPool keypool;
1839         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1840         if (nIndex != -1)
1841             vchPubKey = keypool.vchPubKey;
1842         else
1843         {
1844             printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1845             vchPubKey = pwallet->vchDefaultKey;
1846         }
1847     }
1848     assert(!vchPubKey.empty());
1849     return vchPubKey;
1850 }
1851
1852 void CReserveKey::KeepKey()
1853 {
1854     if (nIndex != -1)
1855         pwallet->KeepKey(nIndex);
1856     nIndex = -1;
1857     vchPubKey.clear();
1858 }
1859
1860 void CReserveKey::ReturnKey()
1861 {
1862     if (nIndex != -1)
1863         pwallet->ReturnKey(nIndex);
1864     nIndex = -1;
1865     vchPubKey.clear();
1866 }
1867
1868 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1869 {
1870     setAddress.clear();
1871
1872     CWalletDB walletdb(strWalletFile);
1873
1874     LOCK2(cs_main, cs_wallet);
1875     BOOST_FOREACH(const int64& id, setKeyPool)
1876     {
1877         CKeyPool keypool;
1878         if (!walletdb.ReadPool(id, keypool))
1879             throw runtime_error("GetAllReserveKeyHashes() : read failed");
1880         CBitcoinAddress address(keypool.vchPubKey);
1881         assert(!keypool.vchPubKey.empty());
1882         if (!HaveKey(address))
1883             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1884         setAddress.insert(address);
1885     }
1886 }