New transaction fees scheme
[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 (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1398                 {
1399                     if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1400                     {
1401                         int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1402                         nChange -= nMoveToFee;
1403                         nFeeRet += nMoveToFee;
1404                     }
1405
1406                     // sub-cent change is moved to fee
1407                     if (nChange > 0 && nChange < CENT)
1408                     {
1409                         nFeeRet += nChange;
1410                         nChange = 0;
1411                     }
1412                 }
1413
1414                 if (nChange > 0)
1415                 {
1416                     // Fill a vout to ourself
1417                     // TODO: pass in scriptChange instead of reservekey so
1418                     // change transaction isn't always pay-to-bitcoin-address
1419                     CScript scriptChange;
1420
1421                     // coin control: send change to custom address
1422                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1423                         scriptChange.SetDestination(coinControl->destChange);
1424
1425                     // no coin control: send change to newly generated address
1426                     else
1427                     {
1428                         // Note: We use a new key here to keep it from being obvious which side is the change.
1429                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1430                         //  backup is restored, if the backup doesn't have the new private key for the change.
1431                         //  If we reused the old key, it would be possible to add code to look for and
1432                         //  rediscover unknown transactions that were written with keys of ours to recover
1433                         //  post-backup change.
1434
1435                         // Reserve a new key pair from key pool
1436                         CPubKey vchPubKey = reservekey.GetReservedKey();
1437
1438                         scriptChange.SetDestination(vchPubKey.GetID());
1439                     }
1440
1441                     // Insert change txn at random position:
1442                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1443                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1444                 }
1445                 else
1446                     reservekey.ReturnKey();
1447
1448                 // Fill vin
1449                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1450                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1451
1452                 // Sign
1453                 int nIn = 0;
1454                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1455                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1456                         return false;
1457
1458                 // Limit size
1459                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1460                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1461                     return false;
1462                 dPriority /= nBytes;
1463
1464                 // Check that enough fee is included
1465                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1466                 bool fAllowFree = CTransaction::AllowFree(dPriority);
1467
1468                 // Disable free transactions until 1 July 2014
1469                 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1470                 {
1471                     fAllowFree = false;
1472                 }
1473
1474                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1475
1476                 if (nFeeRet < max(nPayFee, nMinFee))
1477                 {
1478                     nFeeRet = max(nPayFee, nMinFee);
1479                     continue;
1480                 }
1481
1482                 // Fill vtxPrev by copying from previous transactions vtxPrev
1483                 wtxNew.AddSupportingTransactions(txdb);
1484                 wtxNew.fTimeReceivedIsTxTime = true;
1485
1486                 break;
1487             }
1488         }
1489     }
1490     return true;
1491 }
1492
1493 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1494 {
1495     vector< pair<CScript, int64> > vecSend;
1496     vecSend.push_back(make_pair(scriptPubKey, nValue));
1497     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1498 }
1499
1500 // NovaCoin: get current stake weight
1501 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1502 {
1503     // Choose coins to use
1504     int64 nBalance = GetBalance();
1505     int64 nReserveBalance = 0;
1506
1507     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1508     {
1509         error("GetStakeWeight : invalid reserve balance amount");
1510         return false;
1511     }
1512
1513     if (nBalance <= nReserveBalance)
1514         return false;
1515
1516     vector<const CWalletTx*> vwtxPrev;
1517
1518 /*
1519  * TODO: performance comparison
1520
1521     static set<pair<const CWalletTx*,unsigned int> > setCoins;
1522     static uint256 hashPrevBlock;
1523     static int64 nValueIn = 0;
1524
1525     // Cache outputs unless best block changed
1526     if (hashPrevBlock != pindexBest->GetBlockHash())
1527     {
1528         if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1529             return false;
1530
1531         if (setCoins.empty())
1532             return false;
1533
1534         hashPrevBlock == pindexBest->GetBlockHash();
1535     }
1536 */
1537
1538     set<pair<const CWalletTx*,unsigned int> > setCoins;
1539     int64 nValueIn = 0;
1540
1541     if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1542         return false;
1543
1544     if (setCoins.empty())
1545         return false;
1546
1547     CTxDB txdb("r");
1548     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1549     {
1550         CTxIndex txindex;
1551         {
1552             LOCK2(cs_main, cs_wallet);
1553             if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1554                 continue;
1555         }
1556
1557         int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1558         CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1559
1560         // Weight is greater than zero
1561         if (nTimeWeight > 0)
1562         {
1563             nWeight += bnCoinDayWeight.getuint64();
1564         }
1565
1566         // Weight is greater than zero, but the maximum value isn't reached yet
1567         if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1568         {
1569             nMinWeight += bnCoinDayWeight.getuint64();
1570         }
1571
1572         // Maximum weight was reached
1573         if (nTimeWeight == nStakeMaxAge)
1574         {
1575             nMaxWeight += bnCoinDayWeight.getuint64();
1576         }
1577     }
1578
1579     return true;
1580 }
1581
1582 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1583 {
1584     // The following combine threshold is important to security
1585     // Should not be adjusted if you don't understand the consequences
1586     int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1587
1588     CBigNum bnTargetPerCoinDay;
1589     bnTargetPerCoinDay.SetCompact(nBits);
1590
1591     txNew.vin.clear();
1592     txNew.vout.clear();
1593
1594     // Mark coin stake transaction
1595     CScript scriptEmpty;
1596     scriptEmpty.clear();
1597     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1598
1599     // Choose coins to use
1600     int64 nBalance = GetBalance();
1601     int64 nReserveBalance = 0;
1602
1603     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1604         return error("CreateCoinStake : invalid reserve balance amount");
1605
1606     if (nBalance <= nReserveBalance)
1607         return false;
1608
1609     vector<const CWalletTx*> vwtxPrev;
1610
1611 /*
1612  * TODO: performance comparison
1613
1614     static set<pair<const CWalletTx*,unsigned int> > setCoins;
1615     static uint256 hashPrevBlock;
1616     static int64 nValueIn = 0;
1617
1618     // Cache outputs unless best block changed
1619     if (hashPrevBlock != pindexBest->GetBlockHash())
1620     {
1621         if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1622             return false;
1623
1624         if (setCoins.empty())
1625             return false;
1626
1627         hashPrevBlock == pindexBest->GetBlockHash();
1628     }
1629 */
1630
1631     set<pair<const CWalletTx*,unsigned int> > setCoins;
1632     int64 nValueIn = 0;
1633
1634     // Select coins with suitable depth
1635     if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1636         return false;
1637
1638     if (setCoins.empty())
1639         return false;
1640
1641     int64 nCredit = 0;
1642     CScript scriptPubKeyKernel;
1643     CTxDB txdb("r");
1644     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1645     {
1646         CTxIndex txindex;
1647         {
1648             LOCK2(cs_main, cs_wallet);
1649             if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1650                 continue;
1651         }
1652
1653         // Read block header
1654         CBlock block;
1655         {
1656             LOCK2(cs_main, cs_wallet);
1657             if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1658                 continue;
1659         }
1660
1661         static int nMaxStakeSearchInterval = 60;
1662         if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1663             continue; // only count coins meeting min age requirement
1664
1665         bool fKernelFound = false;
1666         for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1667         {
1668             // Search backward in time from the given txNew timestamp 
1669             // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1670             uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1671             COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1672             if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1673             {
1674                 // Found a kernel
1675                 if (fDebug && GetBoolArg("-printcoinstake"))
1676                     printf("CreateCoinStake : kernel found\n");
1677                 vector<valtype> vSolutions;
1678                 txnouttype whichType;
1679                 CScript scriptPubKeyOut;
1680                 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1681                 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1682                 {
1683                     if (fDebug && GetBoolArg("-printcoinstake"))
1684                         printf("CreateCoinStake : failed to parse kernel\n");
1685                     break;
1686                 }
1687                 if (fDebug && GetBoolArg("-printcoinstake"))
1688                     printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1689                 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1690                 {
1691                     if (fDebug && GetBoolArg("-printcoinstake"))
1692                         printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1693                     break;  // only support pay to public key and pay to address
1694                 }
1695                 if (whichType == TX_PUBKEYHASH) // pay to address type
1696                 {
1697                     // convert to pay to public key type
1698                     if (!keystore.GetKey(uint160(vSolutions[0]), 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                     scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1705                 }
1706                 if (whichType == TX_PUBKEY)
1707                 {
1708                     valtype& vchPubKey = vSolutions[0];
1709                     if (!keystore.GetKey(Hash160(vchPubKey), key))
1710                     {
1711                         if (fDebug && GetBoolArg("-printcoinstake"))
1712                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1713                         break;  // unable to find corresponding public key
1714                     }
1715
1716                 if (key.GetPubKey() != vchPubKey)
1717                 {
1718                     if (fDebug && GetBoolArg("-printcoinstake"))
1719                         printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1720                         break; // keys mismatch
1721                     }
1722
1723                     scriptPubKeyOut = scriptPubKeyKernel;
1724                 }
1725
1726                 txNew.nTime -= n;
1727                 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1728                 nCredit += pcoin.first->vout[pcoin.second].nValue;
1729                 vwtxPrev.push_back(pcoin.first);
1730                 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1731
1732                 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1733                     txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1734                 if (fDebug && GetBoolArg("-printcoinstake"))
1735                     printf("CreateCoinStake : added kernel type=%d\n", whichType);
1736                 fKernelFound = true;
1737                 break;
1738             }
1739         }
1740
1741         if (fKernelFound || fShutdown)
1742             break; // if kernel is found stop searching
1743     }
1744
1745     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1746         return false;
1747
1748     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1749     {
1750         // Attempt to add more inputs
1751         // Only add coins of the same key/address as kernel
1752         if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1753             && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1754         {
1755             int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1756
1757             // Stop adding more inputs if already too many inputs
1758             if (txNew.vin.size() >= 100)
1759                 break;
1760             // Stop adding more inputs if value is already pretty significant
1761             if (nCredit > nCombineThreshold)
1762                 break;
1763             // Stop adding inputs if reached reserve limit
1764             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1765                 break;
1766             // Do not add additional significant input
1767             if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1768                 continue;
1769             // Do not add input that is still too young
1770             if (nTimeWeight < nStakeMaxAge)
1771                 continue;
1772
1773             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1774             nCredit += pcoin.first->vout[pcoin.second].nValue;
1775             vwtxPrev.push_back(pcoin.first);
1776         }
1777     }
1778
1779     // Calculate coin age reward
1780     {
1781         uint64 nCoinAge;
1782         CTxDB txdb("r");
1783         if (!txNew.GetCoinAge(txdb, nCoinAge))
1784             return error("CreateCoinStake : failed to calculate coin age");
1785         nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1786     }
1787
1788     int64 nMinFee = 0;
1789     while (true)
1790     {
1791         // Set output amount
1792         if (txNew.vout.size() == 3)
1793         {
1794             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1795             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1796         }
1797         else
1798             txNew.vout[1].nValue = nCredit - nMinFee;
1799
1800         // Sign
1801         int nIn = 0;
1802         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1803         {
1804             if (!SignSignature(*this, *pcoin, txNew, nIn++))
1805                 return error("CreateCoinStake : failed to sign coinstake");
1806         }
1807
1808         // Limit size
1809         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1810         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1811             return error("CreateCoinStake : exceeded coinstake size limit");
1812
1813         // Check enough fee is paid
1814         if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
1815         {
1816             nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
1817             continue; // try signing again
1818         }
1819         else
1820         {
1821             if (fDebug && GetBoolArg("-printfee"))
1822                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1823             break;
1824         }
1825     }
1826
1827     // Successfully generated coinstake
1828     return true;
1829 }
1830
1831
1832 // Call after CreateTransaction unless you want to abort
1833 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1834 {
1835     {
1836         LOCK2(cs_main, cs_wallet);
1837         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1838         {
1839             // This is only to keep the database open to defeat the auto-flush for the
1840             // duration of this scope.  This is the only place where this optimization
1841             // maybe makes sense; please don't do it anywhere else.
1842             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1843
1844             // Take key pair from key pool so it won't be used again
1845             reservekey.KeepKey();
1846
1847             // Add tx to wallet, because if it has change it's also ours,
1848             // otherwise just for transaction history.
1849             AddToWallet(wtxNew);
1850
1851             // Mark old coins as spent
1852             set<CWalletTx*> setCoins;
1853             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1854             {
1855                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1856                 coin.BindWallet(this);
1857                 coin.MarkSpent(txin.prevout.n);
1858                 coin.WriteToDisk();
1859                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1860             }
1861
1862             if (fFileBacked)
1863                 delete pwalletdb;
1864         }
1865
1866         // Track how many getdata requests our transaction gets
1867         mapRequestCount[wtxNew.GetHash()] = 0;
1868
1869         // Broadcast
1870         if (!wtxNew.AcceptToMemoryPool())
1871         {
1872             // This must not fail. The transaction has already been signed and recorded.
1873             printf("CommitTransaction() : Error: Transaction not valid");
1874             return false;
1875         }
1876         wtxNew.RelayWalletTransaction();
1877     }
1878     return true;
1879 }
1880
1881
1882
1883
1884 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1885 {
1886     CReserveKey reservekey(this);
1887     int64 nFeeRequired;
1888
1889     if (IsLocked())
1890     {
1891         string strError = _("Error: Wallet locked, unable to create transaction  ");
1892         printf("SendMoney() : %s", strError.c_str());
1893         return strError;
1894     }
1895     if (fWalletUnlockMintOnly)
1896     {
1897         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1898         printf("SendMoney() : %s", strError.c_str());
1899         return strError;
1900     }
1901     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1902     {
1903         string strError;
1904         if (nValue + nFeeRequired > GetBalance())
1905             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());
1906         else
1907             strError = _("Error: Transaction creation failed  ");
1908         printf("SendMoney() : %s", strError.c_str());
1909         return strError;
1910     }
1911
1912     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1913         return "ABORTED";
1914
1915     if (!CommitTransaction(wtxNew, reservekey))
1916         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.");
1917
1918     return "";
1919 }
1920
1921
1922
1923 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1924 {
1925     // Check amount
1926     if (nValue <= 0)
1927         return _("Invalid amount");
1928     if (nValue + nTransactionFee > GetBalance())
1929         return _("Insufficient funds");
1930
1931     // Parse Bitcoin address
1932     CScript scriptPubKey;
1933     scriptPubKey.SetDestination(address);
1934
1935     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1936 }
1937
1938
1939
1940
1941 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1942 {
1943     if (!fFileBacked)
1944         return DB_LOAD_OK;
1945     fFirstRunRet = false;
1946     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1947     if (nLoadWalletRet == DB_NEED_REWRITE)
1948     {
1949         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1950         {
1951             setKeyPool.clear();
1952             // Note: can't top-up keypool here, because wallet is locked.
1953             // User will be prompted to unlock wallet the next operation
1954             // the requires a new key.
1955         }
1956     }
1957
1958     if (nLoadWalletRet != DB_LOAD_OK)
1959         return nLoadWalletRet;
1960     fFirstRunRet = !vchDefaultKey.IsValid();
1961
1962     NewThread(ThreadFlushWalletDB, &strWalletFile);
1963     return DB_LOAD_OK;
1964 }
1965
1966
1967 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1968 {
1969     std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1970     mapAddressBook[address] = strName;
1971     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1972     if (!fFileBacked)
1973         return false;
1974     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1975 }
1976
1977 bool CWallet::DelAddressBookName(const CTxDestination& address)
1978 {
1979     mapAddressBook.erase(address);
1980     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1981     if (!fFileBacked)
1982         return false;
1983     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1984 }
1985
1986
1987 void CWallet::PrintWallet(const CBlock& block)
1988 {
1989     {
1990         LOCK(cs_wallet);
1991         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1992         {
1993             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1994             printf("    mine:  %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1995         }
1996         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1997         {
1998             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1999             printf("    stake: %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2000          }
2001
2002     }
2003     printf("\n");
2004 }
2005
2006 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2007 {
2008     {
2009         LOCK(cs_wallet);
2010         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2011         if (mi != mapWallet.end())
2012         {
2013             wtx = (*mi).second;
2014             return true;
2015         }
2016     }
2017     return false;
2018 }
2019
2020 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2021 {
2022     if (fFileBacked)
2023     {
2024         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2025             return false;
2026     }
2027     vchDefaultKey = vchPubKey;
2028     return true;
2029 }
2030
2031 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2032 {
2033     if (!pwallet->fFileBacked)
2034         return false;
2035     strWalletFileOut = pwallet->strWalletFile;
2036     return true;
2037 }
2038
2039 //
2040 // Mark old keypool keys as used,
2041 // and generate all new keys
2042 //
2043 bool CWallet::NewKeyPool()
2044 {
2045     {
2046         LOCK(cs_wallet);
2047         CWalletDB walletdb(strWalletFile);
2048         BOOST_FOREACH(int64 nIndex, setKeyPool)
2049             walletdb.ErasePool(nIndex);
2050         setKeyPool.clear();
2051
2052         if (IsLocked())
2053             return false;
2054
2055         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2056         for (int i = 0; i < nKeys; i++)
2057         {
2058             int64 nIndex = i+1;
2059             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2060             setKeyPool.insert(nIndex);
2061         }
2062         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2063     }
2064     return true;
2065 }
2066
2067 bool CWallet::TopUpKeyPool(unsigned int nSize)
2068 {
2069     {
2070         LOCK(cs_wallet);
2071
2072         if (IsLocked())
2073             return false;
2074
2075         CWalletDB walletdb(strWalletFile);
2076
2077         // Top up key pool
2078         unsigned int nTargetSize;
2079         if (nSize > 0)
2080             nTargetSize = nSize;
2081         else
2082             nTargetSize = max(GetArg("-keypool", 100), 0LL);
2083
2084         while (setKeyPool.size() < (nTargetSize + 1))
2085         {
2086             int64 nEnd = 1;
2087             if (!setKeyPool.empty())
2088                 nEnd = *(--setKeyPool.end()) + 1;
2089             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2090                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2091             setKeyPool.insert(nEnd);
2092             printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2093         }
2094     }
2095     return true;
2096 }
2097
2098 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2099 {
2100     nIndex = -1;
2101     keypool.vchPubKey = CPubKey();
2102     {
2103         LOCK(cs_wallet);
2104
2105         if (!IsLocked())
2106             TopUpKeyPool();
2107
2108         // Get the oldest key
2109         if(setKeyPool.empty())
2110             return;
2111
2112         CWalletDB walletdb(strWalletFile);
2113
2114         nIndex = *(setKeyPool.begin());
2115         setKeyPool.erase(setKeyPool.begin());
2116         if (!walletdb.ReadPool(nIndex, keypool))
2117             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2118         if (!HaveKey(keypool.vchPubKey.GetID()))
2119             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2120         assert(keypool.vchPubKey.IsValid());
2121         if (fDebug && GetBoolArg("-printkeypool"))
2122             printf("keypool reserve %"PRI64d"\n", nIndex);
2123     }
2124 }
2125
2126 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2127 {
2128     {
2129         LOCK2(cs_main, cs_wallet);
2130         CWalletDB walletdb(strWalletFile);
2131
2132         int64 nIndex = 1 + *(--setKeyPool.end());
2133         if (!walletdb.WritePool(nIndex, keypool))
2134             throw runtime_error("AddReserveKey() : writing added key failed");
2135         setKeyPool.insert(nIndex);
2136         return nIndex;
2137     }
2138     return -1;
2139 }
2140
2141 void CWallet::KeepKey(int64 nIndex)
2142 {
2143     // Remove from key pool
2144     if (fFileBacked)
2145     {
2146         CWalletDB walletdb(strWalletFile);
2147         walletdb.ErasePool(nIndex);
2148     }
2149     if(fDebug)
2150         printf("keypool keep %"PRI64d"\n", nIndex);
2151 }
2152
2153 void CWallet::ReturnKey(int64 nIndex)
2154 {
2155     // Return to key pool
2156     {
2157         LOCK(cs_wallet);
2158         setKeyPool.insert(nIndex);
2159     }
2160     if(fDebug)
2161         printf("keypool return %"PRI64d"\n", nIndex);
2162 }
2163
2164 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2165 {
2166     int64 nIndex = 0;
2167     CKeyPool keypool;
2168     {
2169         LOCK(cs_wallet);
2170         ReserveKeyFromKeyPool(nIndex, keypool);
2171         if (nIndex == -1)
2172         {
2173             if (fAllowReuse && vchDefaultKey.IsValid())
2174             {
2175                 result = vchDefaultKey;
2176                 return true;
2177             }
2178             if (IsLocked()) return false;
2179             result = GenerateNewKey();
2180             return true;
2181         }
2182         KeepKey(nIndex);
2183         result = keypool.vchPubKey;
2184     }
2185     return true;
2186 }
2187
2188 int64 CWallet::GetOldestKeyPoolTime()
2189 {
2190     int64 nIndex = 0;
2191     CKeyPool keypool;
2192     ReserveKeyFromKeyPool(nIndex, keypool);
2193     if (nIndex == -1)
2194         return GetTime();
2195     ReturnKey(nIndex);
2196     return keypool.nTime;
2197 }
2198
2199 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2200 {
2201     map<CTxDestination, int64> balances;
2202
2203     {
2204         LOCK(cs_wallet);
2205         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2206         {
2207             CWalletTx *pcoin = &walletEntry.second;
2208
2209             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2210                 continue;
2211
2212             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2213                 continue;
2214
2215             int nDepth = pcoin->GetDepthInMainChain();
2216             if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2217                 continue;
2218
2219             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2220             {
2221                 CTxDestination addr;
2222                 if (!IsMine(pcoin->vout[i]))
2223                     continue;
2224                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2225                     continue;
2226
2227                 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2228
2229                 if (!balances.count(addr))
2230                     balances[addr] = 0;
2231                 balances[addr] += n;
2232             }
2233         }
2234     }
2235
2236     return balances;
2237 }
2238
2239 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2240 {
2241     set< set<CTxDestination> > groupings;
2242     set<CTxDestination> grouping;
2243
2244     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2245     {
2246         CWalletTx *pcoin = &walletEntry.second;
2247
2248         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2249         {
2250             // group all input addresses with each other
2251             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2252             {
2253                 CTxDestination address;
2254                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2255                     continue;
2256                 grouping.insert(address);
2257             }
2258
2259             // group change with input addresses
2260             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2261                 if (IsChange(txout))
2262                 {
2263                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2264                     CTxDestination txoutAddr;
2265                     if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2266                         continue;
2267                     grouping.insert(txoutAddr);
2268                 }
2269             groupings.insert(grouping);
2270             grouping.clear();
2271         }
2272
2273         // group lone addrs by themselves
2274         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2275             if (IsMine(pcoin->vout[i]))
2276             {
2277                 CTxDestination address;
2278                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2279                     continue;
2280                 grouping.insert(address);
2281                 groupings.insert(grouping);
2282                 grouping.clear();
2283             }
2284     }
2285
2286     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2287     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2288     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2289     {
2290         // make a set of all the groups hit by this new group
2291         set< set<CTxDestination>* > hits;
2292         map< CTxDestination, set<CTxDestination>* >::iterator it;
2293         BOOST_FOREACH(CTxDestination address, grouping)
2294             if ((it = setmap.find(address)) != setmap.end())
2295                 hits.insert((*it).second);
2296
2297         // merge all hit groups into a new single group and delete old groups
2298         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2299         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2300         {
2301             merged->insert(hit->begin(), hit->end());
2302             uniqueGroupings.erase(hit);
2303             delete hit;
2304         }
2305         uniqueGroupings.insert(merged);
2306
2307         // update setmap
2308         BOOST_FOREACH(CTxDestination element, *merged)
2309             setmap[element] = merged;
2310     }
2311
2312     set< set<CTxDestination> > ret;
2313     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2314     {
2315         ret.insert(*uniqueGrouping);
2316         delete uniqueGrouping;
2317     }
2318
2319     return ret;
2320 }
2321
2322 // ppcoin: check 'spent' consistency between wallet and txindex
2323 // ppcoin: fix wallet spent state according to txindex
2324 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2325 {
2326     nMismatchFound = 0;
2327     nBalanceInQuestion = 0;
2328
2329     LOCK(cs_wallet);
2330     vector<CWalletTx*> vCoins;
2331     vCoins.reserve(mapWallet.size());
2332     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2333         vCoins.push_back(&(*it).second);
2334
2335     CTxDB txdb("r");
2336     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2337     {
2338         // Find the corresponding transaction index
2339         CTxIndex txindex;
2340         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2341             continue;
2342         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2343         {
2344             if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2345             {
2346                 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2347                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2348                 nMismatchFound++;
2349                 nBalanceInQuestion += pcoin->vout[n].nValue;
2350                 if (!fCheckOnly)
2351                 {
2352                     pcoin->MarkUnspent(n);
2353                     pcoin->WriteToDisk();
2354                 }
2355             }
2356             else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2357             {
2358                 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2359                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2360                 nMismatchFound++;
2361                 nBalanceInQuestion += pcoin->vout[n].nValue;
2362                 if (!fCheckOnly)
2363                 {
2364                     pcoin->MarkSpent(n);
2365                     pcoin->WriteToDisk();
2366                 }
2367             }
2368         }
2369     }
2370 }
2371
2372 // ppcoin: disable transaction (only for coinstake)
2373 void CWallet::DisableTransaction(const CTransaction &tx)
2374 {
2375     if (!tx.IsCoinStake() || !IsFromMe(tx))
2376         return; // only disconnecting coinstake requires marking input unspent
2377
2378     LOCK(cs_wallet);
2379     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2380     {
2381         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2382         if (mi != mapWallet.end())
2383         {
2384             CWalletTx& prev = (*mi).second;
2385             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2386             {
2387                 prev.MarkUnspent(txin.prevout.n);
2388                 prev.WriteToDisk();
2389             }
2390         }
2391     }
2392 }
2393
2394 CPubKey CReserveKey::GetReservedKey()
2395 {
2396     if (nIndex == -1)
2397     {
2398         CKeyPool keypool;
2399         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2400         if (nIndex != -1)
2401             vchPubKey = keypool.vchPubKey;
2402         else
2403         {
2404             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2405             vchPubKey = pwallet->vchDefaultKey;
2406         }
2407     }
2408     assert(vchPubKey.IsValid());
2409     return vchPubKey;
2410 }
2411
2412 void CReserveKey::KeepKey()
2413 {
2414     if (nIndex != -1)
2415         pwallet->KeepKey(nIndex);
2416     nIndex = -1;
2417     vchPubKey = CPubKey();
2418 }
2419
2420 void CReserveKey::ReturnKey()
2421 {
2422     if (nIndex != -1)
2423         pwallet->ReturnKey(nIndex);
2424     nIndex = -1;
2425     vchPubKey = CPubKey();
2426 }
2427
2428 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2429 {
2430     setAddress.clear();
2431
2432     CWalletDB walletdb(strWalletFile);
2433
2434     LOCK2(cs_main, cs_wallet);
2435     BOOST_FOREACH(const int64& id, setKeyPool)
2436     {
2437         CKeyPool keypool;
2438         if (!walletdb.ReadPool(id, keypool))
2439             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2440         assert(keypool.vchPubKey.IsValid());
2441         CKeyID keyID = keypool.vchPubKey.GetID();
2442         if (!HaveKey(keyID))
2443             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2444         setAddress.insert(keyID);
2445     }
2446 }
2447
2448 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2449 {
2450     {
2451         LOCK(cs_wallet);
2452         // Only notify UI if this transaction is in this wallet
2453         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2454         if (mi != mapWallet.end())
2455             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2456     }
2457 }
2458
2459 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2460     mapKeyBirth.clear();
2461
2462     // get birth times for keys with metadata
2463     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2464         if (it->second.nCreateTime)
2465             mapKeyBirth[it->first] = it->second.nCreateTime;
2466
2467     // map in which we'll infer heights of other keys
2468     CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2469     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2470     std::set<CKeyID> setKeys;
2471     GetKeys(setKeys);
2472     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2473         if (mapKeyBirth.count(keyid) == 0)
2474             mapKeyFirstBlock[keyid] = pindexMax;
2475     }
2476     setKeys.clear();
2477
2478     // if there are no such keys, we're done
2479     if (mapKeyFirstBlock.empty())
2480         return;
2481
2482     // find first block that affects those keys, if there are any left
2483     std::vector<CKeyID> vAffected;
2484     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2485         // iterate over all wallet transactions...
2486         const CWalletTx &wtx = (*it).second;
2487         std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2488         if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2489             // ... which are already in a block
2490             int nHeight = blit->second->nHeight;
2491             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2492                 // iterate over all their outputs
2493                 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2494                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2495                     // ... and all their affected keys
2496                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2497                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2498                         rit->second = blit->second;
2499                 }
2500                 vAffected.clear();
2501             }
2502         }
2503     }
2504
2505     // Extract block timestamps for those keys
2506     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2507         mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2508 }