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