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