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