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