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