Handle unspendable inputs correctly.
[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(false)).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(false);
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(false)).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(false);
1038         }
1039     }
1040
1041     return nTotal;
1042 }
1043
1044 void CWallet::GetBalance(int64 &nTotal, int64 &nWatchOnly) const
1045 {
1046     {
1047         LOCK(cs_wallet);
1048         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1049         {
1050             const CWalletTx* pcoin = &(*it).second;
1051             if (pcoin->IsTrusted()) {
1052                 nWatchOnly += pcoin->GetAvailableCredit(true);
1053                 nTotal += pcoin->GetAvailableCredit(false);
1054             }
1055         }
1056     }
1057 }
1058
1059 int64 CWallet::GetUnconfirmedBalance() 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->IsFinal() || !pcoin->IsTrusted())
1068                 nTotal += pcoin->GetAvailableCredit(false);
1069         }
1070     }
1071     return nTotal;
1072 }
1073
1074 int64 CWallet::GetImmatureBalance() const
1075 {
1076     int64 nTotal = 0;
1077     {
1078         LOCK(cs_wallet);
1079         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1080         {
1081             const CWalletTx& pcoin = (*it).second;
1082             if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1083                 nTotal += GetCredit(pcoin);
1084         }
1085     }
1086     return nTotal;
1087 }
1088
1089 // populate vCoins with vector of spendable COutputs
1090 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1091 {
1092     vCoins.clear();
1093
1094     {
1095         LOCK(cs_wallet);
1096         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1097         {
1098             const CWalletTx* pcoin = &(*it).second;
1099
1100             if (!pcoin->IsFinal())
1101                 continue;
1102
1103             if (fOnlyConfirmed && !pcoin->IsTrusted())
1104                 continue;
1105
1106             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1107                 continue;
1108
1109             if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1110                 continue;
1111
1112             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1113                 isminetype mine = IsMine(pcoin->vout[i]);
1114                 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && 
1115                     pcoin->vout[i].nValue >= nMinimumInputValue &&
1116                     (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1117                 {
1118                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1119                 }
1120             }
1121         }
1122     }
1123 }
1124
1125 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1126 {
1127     vCoins.clear();
1128
1129     {
1130         LOCK(cs_wallet);
1131         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1132         {
1133             const CWalletTx* pcoin = &(*it).second;
1134
1135             if (!pcoin->IsFinal())
1136                 continue;
1137
1138             if(pcoin->GetDepthInMainChain() < nConf)
1139                 continue;
1140
1141             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1142                 isminetype mine = IsMine(pcoin->vout[i]);
1143
1144                 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && pcoin->vout[i].nValue >= nMinimumInputValue)
1145                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1146             }
1147         }
1148     }
1149 }
1150
1151 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1152                                   vector<char>& vfBest, int64& nBest, int iterations = 1000)
1153 {
1154     vector<char> vfIncluded;
1155
1156     vfBest.assign(vValue.size(), true);
1157     nBest = nTotalLower;
1158
1159     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1160     {
1161         vfIncluded.assign(vValue.size(), false);
1162         int64 nTotal = 0;
1163         bool fReachedTarget = false;
1164         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1165         {
1166             for (unsigned int i = 0; i < vValue.size(); i++)
1167             {
1168                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1169                 {
1170                     nTotal += vValue[i].first;
1171                     vfIncluded[i] = true;
1172                     if (nTotal >= nTargetValue)
1173                     {
1174                         fReachedTarget = true;
1175                         if (nTotal < nBest)
1176                         {
1177                             nBest = nTotal;
1178                             vfBest = vfIncluded;
1179                         }
1180                         nTotal -= vValue[i].first;
1181                         vfIncluded[i] = false;
1182                     }
1183                 }
1184             }
1185         }
1186     }
1187 }
1188
1189 // ppcoin: total coins staked (non-spendable until maturity)
1190 int64 CWallet::GetStake() const
1191 {
1192     int64 nTotal = 0;
1193     LOCK(cs_wallet);
1194     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1195     {
1196         const CWalletTx* pcoin = &(*it).second;
1197         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1198             nTotal += CWallet::GetCredit(*pcoin);
1199     }
1200     return nTotal;
1201 }
1202
1203 int64 CWallet::GetNewMint() const
1204 {
1205     int64 nTotal = 0;
1206     LOCK(cs_wallet);
1207     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1208     {
1209         const CWalletTx* pcoin = &(*it).second;
1210         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1211             nTotal += CWallet::GetCredit(*pcoin);
1212     }
1213     return nTotal;
1214 }
1215
1216 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
1217 {
1218     setCoinsRet.clear();
1219     nValueRet = 0;
1220
1221     // List of values less than target
1222     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1223     coinLowestLarger.first = std::numeric_limits<int64>::max();
1224     coinLowestLarger.second.first = NULL;
1225     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1226     int64 nTotalLower = 0;
1227
1228     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1229
1230     BOOST_FOREACH(const COutput &output, vCoins)
1231     {
1232         if (!output.fSpendable)
1233             continue;
1234
1235         const CWalletTx *pcoin = output.tx;
1236
1237         if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1238             continue;
1239
1240         int i = output.i;
1241
1242         // Follow the timestamp rules
1243         if (pcoin->nTime > nSpendTime)
1244             continue;
1245
1246         int64 n = pcoin->vout[i].nValue;
1247
1248         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1249
1250         if (n == nTargetValue)
1251         {
1252             setCoinsRet.insert(coin.second);
1253             nValueRet += coin.first;
1254             return true;
1255         }
1256         else if (n < nTargetValue + CENT)
1257         {
1258             vValue.push_back(coin);
1259             nTotalLower += n;
1260         }
1261         else if (n < coinLowestLarger.first)
1262         {
1263             coinLowestLarger = coin;
1264         }
1265     }
1266
1267     if (nTotalLower == nTargetValue)
1268     {
1269         for (unsigned int i = 0; i < vValue.size(); ++i)
1270         {
1271             setCoinsRet.insert(vValue[i].second);
1272             nValueRet += vValue[i].first;
1273         }
1274         return true;
1275     }
1276
1277     if (nTotalLower < nTargetValue)
1278     {
1279         if (coinLowestLarger.second.first == NULL)
1280             return false;
1281         setCoinsRet.insert(coinLowestLarger.second);
1282         nValueRet += coinLowestLarger.first;
1283         return true;
1284     }
1285
1286     // Solve subset sum by stochastic approximation
1287     sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1288     vector<char> vfBest;
1289     int64 nBest;
1290
1291     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1292     if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1293         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1294
1295     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1296     //                                   or the next bigger coin is closer), return the bigger coin
1297     if (coinLowestLarger.second.first &&
1298         ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1299     {
1300         setCoinsRet.insert(coinLowestLarger.second);
1301         nValueRet += coinLowestLarger.first;
1302     }
1303     else {
1304         for (unsigned int i = 0; i < vValue.size(); i++)
1305             if (vfBest[i])
1306             {
1307                 setCoinsRet.insert(vValue[i].second);
1308                 nValueRet += vValue[i].first;
1309             }
1310
1311         if (fDebug && GetBoolArg("-printpriority"))
1312         {
1313             //// debug print
1314             printf("SelectCoins() best subset: ");
1315             for (unsigned int i = 0; i < vValue.size(); i++)
1316                 if (vfBest[i])
1317                     printf("%s ", FormatMoney(vValue[i].first).c_str());
1318             printf("total %s\n", FormatMoney(nBest).c_str());
1319         }
1320     }
1321
1322     return true;
1323 }
1324
1325 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1326 {
1327     vector<COutput> vCoins;
1328     AvailableCoins(vCoins, true, coinControl);
1329
1330     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1331     if (coinControl && coinControl->HasSelected())
1332     {
1333         BOOST_FOREACH(const COutput& out, vCoins)
1334         {
1335             if(!out.fSpendable)
1336                 continue;
1337             nValueRet += out.tx->vout[out.i].nValue;
1338             setCoinsRet.insert(make_pair(out.tx, out.i));
1339         }
1340         return (nValueRet >= nTargetValue);
1341     }
1342
1343     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1344             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1345             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1346 }
1347
1348 // Select some coins without random shuffle or best subset approximation
1349 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1350 {
1351     vector<COutput> vCoins;
1352     AvailableCoinsMinConf(vCoins, nMinConf);
1353
1354     setCoinsRet.clear();
1355     nValueRet = 0;
1356
1357     BOOST_FOREACH(COutput output, vCoins)
1358     {
1359         if(!output.fSpendable)
1360             continue;
1361         const CWalletTx *pcoin = output.tx;
1362         int i = output.i;
1363
1364         // Stop if we've chosen enough inputs
1365         if (nValueRet >= nTargetValue)
1366             break;
1367
1368         // Follow the timestamp rules
1369         if (pcoin->nTime > nSpendTime)
1370             continue;
1371
1372         int64 n = pcoin->vout[i].nValue;
1373
1374         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1375
1376         if (n >= nTargetValue)
1377         {
1378             // If input value is greater or equal to target then simply insert
1379             //    it into the current subset and exit
1380             setCoinsRet.insert(coin.second);
1381             nValueRet += coin.first;
1382             break;
1383         }
1384         else if (n < nTargetValue + CENT)
1385         {
1386             setCoinsRet.insert(coin.second);
1387             nValueRet += coin.first;
1388         }
1389     }
1390
1391     return true;
1392 }
1393
1394 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1395 {
1396     int64 nValue = 0;
1397     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1398     {
1399         if (nValue < 0)
1400             return false;
1401         nValue += s.second;
1402     }
1403     if (vecSend.empty() || nValue < 0)
1404         return false;
1405
1406     wtxNew.BindWallet(this);
1407
1408     {
1409         LOCK2(cs_main, cs_wallet);
1410         // txdb must be opened before the mapWallet lock
1411         CTxDB txdb("r");
1412         {
1413             nFeeRet = nTransactionFee;
1414             while (true)
1415             {
1416                 wtxNew.vin.clear();
1417                 wtxNew.vout.clear();
1418                 wtxNew.fFromMe = true;
1419
1420                 int64 nTotalValue = nValue + nFeeRet;
1421                 double dPriority = 0;
1422                 // vouts to the payees
1423                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1424                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1425
1426                 // Choose coins to use
1427                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1428                 int64 nValueIn = 0;
1429                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1430                     return false;
1431                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1432                 {
1433                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1434                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1435                 }
1436
1437                 int64 nChange = nValueIn - nValue - nFeeRet;
1438                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1439                 // or until nChange becomes zero
1440                 // NOTE: this depends on the exact behaviour of GetMinFee
1441                 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1442                 {
1443                     if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1444                     {
1445                         int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1446                         nChange -= nMoveToFee;
1447                         nFeeRet += nMoveToFee;
1448                     }
1449
1450                     // sub-cent change is moved to fee
1451                     if (nChange > 0 && nChange < CENT)
1452                     {
1453                         nFeeRet += nChange;
1454                         nChange = 0;
1455                     }
1456                 }
1457
1458                 if (nChange > 0)
1459                 {
1460                     // Fill a vout to ourself
1461                     // TODO: pass in scriptChange instead of reservekey so
1462                     // change transaction isn't always pay-to-bitcoin-address
1463                     CScript scriptChange;
1464
1465                     // coin control: send change to custom address
1466                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1467                         scriptChange.SetDestination(coinControl->destChange);
1468
1469                     // no coin control: send change to newly generated address
1470                     else
1471                     {
1472                         // Note: We use a new key here to keep it from being obvious which side is the change.
1473                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1474                         //  backup is restored, if the backup doesn't have the new private key for the change.
1475                         //  If we reused the old key, it would be possible to add code to look for and
1476                         //  rediscover unknown transactions that were written with keys of ours to recover
1477                         //  post-backup change.
1478
1479                         // Reserve a new key pair from key pool
1480                         CPubKey vchPubKey = reservekey.GetReservedKey();
1481
1482                         scriptChange.SetDestination(vchPubKey.GetID());
1483                     }
1484
1485                     // Insert change txn at random position:
1486                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1487                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1488                 }
1489                 else
1490                     reservekey.ReturnKey();
1491
1492                 // Fill vin
1493                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1494                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1495
1496                 // Sign
1497                 int nIn = 0;
1498                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1499                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1500                         return false;
1501
1502                 // Limit size
1503                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1504                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1505                     return false;
1506                 dPriority /= nBytes;
1507
1508                 // Check that enough fee is included
1509                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1510                 bool fAllowFree = CTransaction::AllowFree(dPriority);
1511
1512                 // Disable free transactions until 1 July 2014
1513                 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1514                 {
1515                     fAllowFree = false;
1516                 }
1517
1518                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1519
1520                 if (nFeeRet < max(nPayFee, nMinFee))
1521                 {
1522                     nFeeRet = max(nPayFee, nMinFee);
1523                     continue;
1524                 }
1525
1526                 // Fill vtxPrev by copying from previous transactions vtxPrev
1527                 wtxNew.AddSupportingTransactions(txdb);
1528                 wtxNew.fTimeReceivedIsTxTime = true;
1529
1530                 break;
1531             }
1532         }
1533     }
1534     return true;
1535 }
1536
1537 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1538 {
1539     vector< pair<CScript, int64> > vecSend;
1540     vecSend.push_back(make_pair(scriptPubKey, nValue));
1541     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1542 }
1543
1544 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1545 {
1546     int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1547
1548     // If time weight is lower or equal to zero then weight is zero.
1549     if (nTimeWeight <= 0)
1550     {
1551         nWeight = 0;
1552         return;
1553     }
1554
1555     CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1556     nWeight = bnCoinDayWeight.getuint64();
1557 }
1558
1559
1560 // NovaCoin: get current stake weight
1561 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1562 {
1563     // Choose coins to use
1564     int64 nBalance = GetBalance();
1565     int64 nReserveBalance = 0;
1566
1567     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1568     {
1569         error("GetStakeWeight : invalid reserve balance amount");
1570         return false;
1571     }
1572
1573     if (nBalance <= nReserveBalance)
1574         return false;
1575
1576     vector<const CWalletTx*> vwtxPrev;
1577
1578 /*
1579  * TODO: performance comparison
1580
1581     static set<pair<const CWalletTx*,unsigned int> > setCoins;
1582     static uint256 hashPrevBlock;
1583     static int64 nValueIn = 0;
1584
1585     // Cache outputs unless best block changed
1586     if (hashPrevBlock != pindexBest->GetBlockHash())
1587     {
1588         if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1589             return false;
1590
1591         if (setCoins.empty())
1592             return false;
1593
1594         hashPrevBlock == pindexBest->GetBlockHash();
1595     }
1596 */
1597
1598     set<pair<const CWalletTx*,unsigned int> > setCoins;
1599     int64 nValueIn = 0;
1600
1601     if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1602         return false;
1603
1604     if (setCoins.empty())
1605         return false;
1606
1607     CTxDB txdb("r");
1608     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1609     {
1610         CTxIndex txindex;
1611         {
1612             LOCK2(cs_main, cs_wallet);
1613             if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1614                 continue;
1615         }
1616
1617         int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1618         CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1619
1620         // Weight is greater than zero
1621         if (nTimeWeight > 0)
1622         {
1623             nWeight += bnCoinDayWeight.getuint64();
1624         }
1625
1626         // Weight is greater than zero, but the maximum value isn't reached yet
1627         if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1628         {
1629             nMinWeight += bnCoinDayWeight.getuint64();
1630         }
1631
1632         // Maximum weight was reached
1633         if (nTimeWeight == nStakeMaxAge)
1634         {
1635             nMaxWeight += bnCoinDayWeight.getuint64();
1636         }
1637     }
1638
1639     return true;
1640 }
1641
1642 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1643 {
1644     // The following combine threshold is important to security
1645     // Should not be adjusted if you don't understand the consequences
1646     int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1647
1648     CBigNum bnTargetPerCoinDay;
1649     bnTargetPerCoinDay.SetCompact(nBits);
1650
1651     txNew.vin.clear();
1652     txNew.vout.clear();
1653
1654     // Mark coin stake transaction
1655     CScript scriptEmpty;
1656     scriptEmpty.clear();
1657     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1658
1659     // Choose coins to use
1660     int64 nBalance = GetBalance();
1661     int64 nReserveBalance = 0;
1662
1663     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1664         return error("CreateCoinStake : invalid reserve balance amount");
1665
1666     if (nBalance <= nReserveBalance)
1667         return false;
1668
1669     vector<const CWalletTx*> vwtxPrev;
1670
1671 /*
1672  * TODO: performance comparison
1673
1674     static set<pair<const CWalletTx*,unsigned int> > setCoins;
1675     static uint256 hashPrevBlock;
1676     static int64 nValueIn = 0;
1677
1678     // Cache outputs unless best block changed
1679     if (hashPrevBlock != pindexBest->GetBlockHash())
1680     {
1681         if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1682             return false;
1683
1684         if (setCoins.empty())
1685             return false;
1686
1687         hashPrevBlock == pindexBest->GetBlockHash();
1688     }
1689 */
1690
1691     set<pair<const CWalletTx*,unsigned int> > setCoins;
1692     int64 nValueIn = 0;
1693
1694     // Select coins with suitable depth
1695     if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1696         return false;
1697
1698     if (setCoins.empty())
1699         return false;
1700
1701     int64 nCredit = 0;
1702     CScript scriptPubKeyKernel;
1703     CTxDB txdb("r");
1704     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1705     {
1706         CTxIndex txindex;
1707         {
1708             LOCK2(cs_main, cs_wallet);
1709             if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1710                 continue;
1711         }
1712
1713         // Read block header
1714         CBlock block;
1715         {
1716             LOCK2(cs_main, cs_wallet);
1717             if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1718                 continue;
1719         }
1720
1721         static int nMaxStakeSearchInterval = 60;
1722         if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1723             continue; // only count coins meeting min age requirement
1724
1725         bool fKernelFound = false;
1726         for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1727         {
1728             // Search backward in time from the given txNew timestamp 
1729             // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1730             uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1731             COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1732             if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1733             {
1734                 // Found a kernel
1735                 if (fDebug && GetBoolArg("-printcoinstake"))
1736                     printf("CreateCoinStake : kernel found\n");
1737                 vector<valtype> vSolutions;
1738                 txnouttype whichType;
1739                 CScript scriptPubKeyOut;
1740                 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1741                 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1742                 {
1743                     if (fDebug && GetBoolArg("-printcoinstake"))
1744                         printf("CreateCoinStake : failed to parse kernel\n");
1745                     break;
1746                 }
1747                 if (fDebug && GetBoolArg("-printcoinstake"))
1748                     printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1749                 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1750                 {
1751                     if (fDebug && GetBoolArg("-printcoinstake"))
1752                         printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1753                     break;  // only support pay to public key and pay to address
1754                 }
1755                 if (whichType == TX_PUBKEYHASH) // pay to address type
1756                 {
1757                     // convert to pay to public key type
1758                     if (!keystore.GetKey(uint160(vSolutions[0]), key))
1759                     {
1760                         if (fDebug && GetBoolArg("-printcoinstake"))
1761                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1762                         break;  // unable to find corresponding public key
1763                     }
1764                     scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1765                 }
1766                 if (whichType == TX_PUBKEY)
1767                 {
1768                     valtype& vchPubKey = vSolutions[0];
1769                     if (!keystore.GetKey(Hash160(vchPubKey), key))
1770                     {
1771                         if (fDebug && GetBoolArg("-printcoinstake"))
1772                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1773                         break;  // unable to find corresponding public key
1774                     }
1775
1776                 if (key.GetPubKey() != vchPubKey)
1777                 {
1778                     if (fDebug && GetBoolArg("-printcoinstake"))
1779                         printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1780                         break; // keys mismatch
1781                     }
1782
1783                     scriptPubKeyOut = scriptPubKeyKernel;
1784                 }
1785
1786                 txNew.nTime -= n;
1787                 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1788                 nCredit += pcoin.first->vout[pcoin.second].nValue;
1789                 vwtxPrev.push_back(pcoin.first);
1790                 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1791
1792                 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1793                     txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1794                 if (fDebug && GetBoolArg("-printcoinstake"))
1795                     printf("CreateCoinStake : added kernel type=%d\n", whichType);
1796                 fKernelFound = true;
1797                 break;
1798             }
1799         }
1800
1801         if (fKernelFound || fShutdown)
1802             break; // if kernel is found stop searching
1803     }
1804
1805     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1806         return false;
1807
1808     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1809     {
1810         // Attempt to add more inputs
1811         // Only add coins of the same key/address as kernel
1812         if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1813             && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1814         {
1815             int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1816
1817             // Stop adding more inputs if already too many inputs
1818             if (txNew.vin.size() >= 100)
1819                 break;
1820             // Stop adding more inputs if value is already pretty significant
1821             if (nCredit > nCombineThreshold)
1822                 break;
1823             // Stop adding inputs if reached reserve limit
1824             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1825                 break;
1826             // Do not add additional significant input
1827             if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1828                 continue;
1829             // Do not add input that is still too young
1830             if (nTimeWeight < nStakeMaxAge)
1831                 continue;
1832
1833             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1834             nCredit += pcoin.first->vout[pcoin.second].nValue;
1835             vwtxPrev.push_back(pcoin.first);
1836         }
1837     }
1838
1839     // Calculate coin age reward
1840     {
1841         uint64 nCoinAge;
1842         CTxDB txdb("r");
1843         if (!txNew.GetCoinAge(txdb, nCoinAge))
1844             return error("CreateCoinStake : failed to calculate coin age");
1845         nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1846     }
1847
1848     int64 nMinFee = 0;
1849     while (true)
1850     {
1851         // Set output amount
1852         if (txNew.vout.size() == 3)
1853         {
1854             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1855             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1856         }
1857         else
1858             txNew.vout[1].nValue = nCredit - nMinFee;
1859
1860         // Sign
1861         int nIn = 0;
1862         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1863         {
1864             if (!SignSignature(*this, *pcoin, txNew, nIn++))
1865                 return error("CreateCoinStake : failed to sign coinstake");
1866         }
1867
1868         // Limit size
1869         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1870         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1871             return error("CreateCoinStake : exceeded coinstake size limit");
1872
1873         // Check enough fee is paid
1874         if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
1875         {
1876             nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
1877             continue; // try signing again
1878         }
1879         else
1880         {
1881             if (fDebug && GetBoolArg("-printfee"))
1882                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1883             break;
1884         }
1885     }
1886
1887     // Successfully generated coinstake
1888     return true;
1889 }
1890
1891
1892 // Call after CreateTransaction unless you want to abort
1893 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1894 {
1895     {
1896         LOCK2(cs_main, cs_wallet);
1897         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1898         {
1899             // This is only to keep the database open to defeat the auto-flush for the
1900             // duration of this scope.  This is the only place where this optimization
1901             // maybe makes sense; please don't do it anywhere else.
1902             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1903
1904             // Take key pair from key pool so it won't be used again
1905             reservekey.KeepKey();
1906
1907             // Add tx to wallet, because if it has change it's also ours,
1908             // otherwise just for transaction history.
1909             AddToWallet(wtxNew);
1910
1911             // Mark old coins as spent
1912             set<CWalletTx*> setCoins;
1913             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1914             {
1915                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1916                 coin.BindWallet(this);
1917                 coin.MarkSpent(txin.prevout.n);
1918                 coin.WriteToDisk();
1919                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1920             }
1921
1922             if (fFileBacked)
1923                 delete pwalletdb;
1924         }
1925
1926         // Track how many getdata requests our transaction gets
1927         mapRequestCount[wtxNew.GetHash()] = 0;
1928
1929         // Broadcast
1930         if (!wtxNew.AcceptToMemoryPool())
1931         {
1932             // This must not fail. The transaction has already been signed and recorded.
1933             printf("CommitTransaction() : Error: Transaction not valid");
1934             return false;
1935         }
1936         wtxNew.RelayWalletTransaction();
1937     }
1938     return true;
1939 }
1940
1941
1942
1943
1944 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1945 {
1946     CReserveKey reservekey(this);
1947     int64 nFeeRequired;
1948
1949     if (IsLocked())
1950     {
1951         string strError = _("Error: Wallet locked, unable to create transaction  ");
1952         printf("SendMoney() : %s", strError.c_str());
1953         return strError;
1954     }
1955     if (fWalletUnlockMintOnly)
1956     {
1957         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1958         printf("SendMoney() : %s", strError.c_str());
1959         return strError;
1960     }
1961     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1962     {
1963         string strError;
1964         if (nValue + nFeeRequired > GetBalance())
1965             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());
1966         else
1967             strError = _("Error: Transaction creation failed  ");
1968         printf("SendMoney() : %s", strError.c_str());
1969         return strError;
1970     }
1971
1972     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1973         return "ABORTED";
1974
1975     if (!CommitTransaction(wtxNew, reservekey))
1976         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.");
1977
1978     return "";
1979 }
1980
1981
1982
1983 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1984 {
1985     // Check amount
1986     if (nValue <= 0)
1987         return _("Invalid amount");
1988     if (nValue + nTransactionFee > GetBalance())
1989         return _("Insufficient funds");
1990
1991     // Parse Bitcoin address
1992     CScript scriptPubKey;
1993     scriptPubKey.SetDestination(address);
1994
1995     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1996 }
1997
1998
1999
2000
2001 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2002 {
2003     if (!fFileBacked)
2004         return DB_LOAD_OK;
2005     fFirstRunRet = false;
2006     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2007     if (nLoadWalletRet == DB_NEED_REWRITE)
2008     {
2009         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2010         {
2011             setKeyPool.clear();
2012             // Note: can't top-up keypool here, because wallet is locked.
2013             // User will be prompted to unlock wallet the next operation
2014             // the requires a new key.
2015         }
2016     }
2017
2018     if (nLoadWalletRet != DB_LOAD_OK)
2019         return nLoadWalletRet;
2020     fFirstRunRet = !vchDefaultKey.IsValid();
2021
2022     NewThread(ThreadFlushWalletDB, &strWalletFile);
2023     return DB_LOAD_OK;
2024 }
2025
2026
2027 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2028 {
2029     std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2030     mapAddressBook[address] = strName;
2031     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2032     if (!fFileBacked)
2033         return false;
2034     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2035 }
2036
2037 bool CWallet::DelAddressBookName(const CTxDestination& address)
2038 {
2039     mapAddressBook.erase(address);
2040     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2041     if (!fFileBacked)
2042         return false;
2043     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2044 }
2045
2046
2047 void CWallet::PrintWallet(const CBlock& block)
2048 {
2049     {
2050         LOCK(cs_wallet);
2051         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2052         {
2053             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2054             printf("    mine:  %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(false));
2055         }
2056         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2057         {
2058             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2059             printf("    stake: %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(false));
2060          }
2061
2062     }
2063     printf("\n");
2064 }
2065
2066 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2067 {
2068     {
2069         LOCK(cs_wallet);
2070         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2071         if (mi != mapWallet.end())
2072         {
2073             wtx = (*mi).second;
2074             return true;
2075         }
2076     }
2077     return false;
2078 }
2079
2080 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2081 {
2082     if (fFileBacked)
2083     {
2084         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2085             return false;
2086     }
2087     vchDefaultKey = vchPubKey;
2088     return true;
2089 }
2090
2091 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2092 {
2093     if (!pwallet->fFileBacked)
2094         return false;
2095     strWalletFileOut = pwallet->strWalletFile;
2096     return true;
2097 }
2098
2099 //
2100 // Mark old keypool keys as used,
2101 // and generate all new keys
2102 //
2103 bool CWallet::NewKeyPool()
2104 {
2105     {
2106         LOCK(cs_wallet);
2107         CWalletDB walletdb(strWalletFile);
2108         BOOST_FOREACH(int64 nIndex, setKeyPool)
2109             walletdb.ErasePool(nIndex);
2110         setKeyPool.clear();
2111
2112         if (IsLocked())
2113             return false;
2114
2115         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2116         for (int i = 0; i < nKeys; i++)
2117         {
2118             int64 nIndex = i+1;
2119             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2120             setKeyPool.insert(nIndex);
2121         }
2122         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2123     }
2124     return true;
2125 }
2126
2127 bool CWallet::TopUpKeyPool(unsigned int nSize)
2128 {
2129     {
2130         LOCK(cs_wallet);
2131
2132         if (IsLocked())
2133             return false;
2134
2135         CWalletDB walletdb(strWalletFile);
2136
2137         // Top up key pool
2138         unsigned int nTargetSize;
2139         if (nSize > 0)
2140             nTargetSize = nSize;
2141         else
2142             nTargetSize = max(GetArg("-keypool", 100), 0LL);
2143
2144         while (setKeyPool.size() < (nTargetSize + 1))
2145         {
2146             int64 nEnd = 1;
2147             if (!setKeyPool.empty())
2148                 nEnd = *(--setKeyPool.end()) + 1;
2149             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2150                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2151             setKeyPool.insert(nEnd);
2152             printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2153         }
2154     }
2155     return true;
2156 }
2157
2158 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2159 {
2160     nIndex = -1;
2161     keypool.vchPubKey = CPubKey();
2162     {
2163         LOCK(cs_wallet);
2164
2165         if (!IsLocked())
2166             TopUpKeyPool();
2167
2168         // Get the oldest key
2169         if(setKeyPool.empty())
2170             return;
2171
2172         CWalletDB walletdb(strWalletFile);
2173
2174         nIndex = *(setKeyPool.begin());
2175         setKeyPool.erase(setKeyPool.begin());
2176         if (!walletdb.ReadPool(nIndex, keypool))
2177             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2178         if (!HaveKey(keypool.vchPubKey.GetID()))
2179             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2180         assert(keypool.vchPubKey.IsValid());
2181         if (fDebug && GetBoolArg("-printkeypool"))
2182             printf("keypool reserve %"PRI64d"\n", nIndex);
2183     }
2184 }
2185
2186 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2187 {
2188     {
2189         LOCK2(cs_main, cs_wallet);
2190         CWalletDB walletdb(strWalletFile);
2191
2192         int64 nIndex = 1 + *(--setKeyPool.end());
2193         if (!walletdb.WritePool(nIndex, keypool))
2194             throw runtime_error("AddReserveKey() : writing added key failed");
2195         setKeyPool.insert(nIndex);
2196         return nIndex;
2197     }
2198     return -1;
2199 }
2200
2201 void CWallet::KeepKey(int64 nIndex)
2202 {
2203     // Remove from key pool
2204     if (fFileBacked)
2205     {
2206         CWalletDB walletdb(strWalletFile);
2207         walletdb.ErasePool(nIndex);
2208     }
2209     if(fDebug)
2210         printf("keypool keep %"PRI64d"\n", nIndex);
2211 }
2212
2213 void CWallet::ReturnKey(int64 nIndex)
2214 {
2215     // Return to key pool
2216     {
2217         LOCK(cs_wallet);
2218         setKeyPool.insert(nIndex);
2219     }
2220     if(fDebug)
2221         printf("keypool return %"PRI64d"\n", nIndex);
2222 }
2223
2224 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2225 {
2226     int64 nIndex = 0;
2227     CKeyPool keypool;
2228     {
2229         LOCK(cs_wallet);
2230         ReserveKeyFromKeyPool(nIndex, keypool);
2231         if (nIndex == -1)
2232         {
2233             if (fAllowReuse && vchDefaultKey.IsValid())
2234             {
2235                 result = vchDefaultKey;
2236                 return true;
2237             }
2238             if (IsLocked()) return false;
2239             result = GenerateNewKey();
2240             return true;
2241         }
2242         KeepKey(nIndex);
2243         result = keypool.vchPubKey;
2244     }
2245     return true;
2246 }
2247
2248 int64 CWallet::GetOldestKeyPoolTime()
2249 {
2250     int64 nIndex = 0;
2251     CKeyPool keypool;
2252     ReserveKeyFromKeyPool(nIndex, keypool);
2253     if (nIndex == -1)
2254         return GetTime();
2255     ReturnKey(nIndex);
2256     return keypool.nTime;
2257 }
2258
2259 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2260 {
2261     map<CTxDestination, int64> balances;
2262
2263     {
2264         LOCK(cs_wallet);
2265         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2266         {
2267             CWalletTx *pcoin = &walletEntry.second;
2268
2269             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2270                 continue;
2271
2272             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2273                 continue;
2274
2275             int nDepth = pcoin->GetDepthInMainChain();
2276             if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2277                 continue;
2278
2279             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2280             {
2281                 CTxDestination addr;
2282                 if (!IsMine(pcoin->vout[i]))
2283                     continue;
2284                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2285                     continue;
2286
2287                 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2288
2289                 if (!balances.count(addr))
2290                     balances[addr] = 0;
2291                 balances[addr] += n;
2292             }
2293         }
2294     }
2295
2296     return balances;
2297 }
2298
2299 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2300 {
2301     set< set<CTxDestination> > groupings;
2302     set<CTxDestination> grouping;
2303
2304     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2305     {
2306         CWalletTx *pcoin = &walletEntry.second;
2307
2308         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2309         {
2310             // group all input addresses with each other
2311             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2312             {
2313                 CTxDestination address;
2314                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2315                     continue;
2316                 grouping.insert(address);
2317             }
2318
2319             // group change with input addresses
2320             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2321                 if (IsChange(txout))
2322                 {
2323                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2324                     CTxDestination txoutAddr;
2325                     if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2326                         continue;
2327                     grouping.insert(txoutAddr);
2328                 }
2329             groupings.insert(grouping);
2330             grouping.clear();
2331         }
2332
2333         // group lone addrs by themselves
2334         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2335             if (IsMine(pcoin->vout[i]))
2336             {
2337                 CTxDestination address;
2338                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2339                     continue;
2340                 grouping.insert(address);
2341                 groupings.insert(grouping);
2342                 grouping.clear();
2343             }
2344     }
2345
2346     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2347     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2348     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2349     {
2350         // make a set of all the groups hit by this new group
2351         set< set<CTxDestination>* > hits;
2352         map< CTxDestination, set<CTxDestination>* >::iterator it;
2353         BOOST_FOREACH(CTxDestination address, grouping)
2354             if ((it = setmap.find(address)) != setmap.end())
2355                 hits.insert((*it).second);
2356
2357         // merge all hit groups into a new single group and delete old groups
2358         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2359         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2360         {
2361             merged->insert(hit->begin(), hit->end());
2362             uniqueGroupings.erase(hit);
2363             delete hit;
2364         }
2365         uniqueGroupings.insert(merged);
2366
2367         // update setmap
2368         BOOST_FOREACH(CTxDestination element, *merged)
2369             setmap[element] = merged;
2370     }
2371
2372     set< set<CTxDestination> > ret;
2373     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2374     {
2375         ret.insert(*uniqueGrouping);
2376         delete uniqueGrouping;
2377     }
2378
2379     return ret;
2380 }
2381
2382 // ppcoin: check 'spent' consistency between wallet and txindex
2383 // ppcoin: fix wallet spent state according to txindex
2384 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2385 {
2386     nMismatchFound = 0;
2387     nBalanceInQuestion = 0;
2388
2389     LOCK(cs_wallet);
2390     vector<CWalletTx*> vCoins;
2391     vCoins.reserve(mapWallet.size());
2392     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2393         vCoins.push_back(&(*it).second);
2394
2395     CTxDB txdb("r");
2396     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2397     {
2398         // Find the corresponding transaction index
2399         CTxIndex txindex;
2400         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2401             continue;
2402         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2403         {
2404             if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2405             {
2406                 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2407                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2408                 nMismatchFound++;
2409                 nBalanceInQuestion += pcoin->vout[n].nValue;
2410                 if (!fCheckOnly)
2411                 {
2412                     pcoin->MarkUnspent(n);
2413                     pcoin->WriteToDisk();
2414                 }
2415             }
2416             else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2417             {
2418                 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2419                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2420                 nMismatchFound++;
2421                 nBalanceInQuestion += pcoin->vout[n].nValue;
2422                 if (!fCheckOnly)
2423                 {
2424                     pcoin->MarkSpent(n);
2425                     pcoin->WriteToDisk();
2426                 }
2427             }
2428
2429         }
2430
2431         if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2432         {
2433             printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2434             if (!fCheckOnly)
2435             {
2436                 EraseFromWallet(pcoin->GetHash());
2437             }
2438         }
2439     }
2440 }
2441
2442 // ppcoin: disable transaction (only for coinstake)
2443 void CWallet::DisableTransaction(const CTransaction &tx)
2444 {
2445     if (!tx.IsCoinStake() || !IsFromMe(tx))
2446         return; // only disconnecting coinstake requires marking input unspent
2447
2448     LOCK(cs_wallet);
2449     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2450     {
2451         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2452         if (mi != mapWallet.end())
2453         {
2454             CWalletTx& prev = (*mi).second;
2455             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2456             {
2457                 prev.MarkUnspent(txin.prevout.n);
2458                 prev.WriteToDisk();
2459             }
2460         }
2461     }
2462 }
2463
2464 CPubKey CReserveKey::GetReservedKey()
2465 {
2466     if (nIndex == -1)
2467     {
2468         CKeyPool keypool;
2469         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2470         if (nIndex != -1)
2471             vchPubKey = keypool.vchPubKey;
2472         else
2473         {
2474             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2475             vchPubKey = pwallet->vchDefaultKey;
2476         }
2477     }
2478     assert(vchPubKey.IsValid());
2479     return vchPubKey;
2480 }
2481
2482 void CReserveKey::KeepKey()
2483 {
2484     if (nIndex != -1)
2485         pwallet->KeepKey(nIndex);
2486     nIndex = -1;
2487     vchPubKey = CPubKey();
2488 }
2489
2490 void CReserveKey::ReturnKey()
2491 {
2492     if (nIndex != -1)
2493         pwallet->ReturnKey(nIndex);
2494     nIndex = -1;
2495     vchPubKey = CPubKey();
2496 }
2497
2498 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2499 {
2500     setAddress.clear();
2501
2502     CWalletDB walletdb(strWalletFile);
2503
2504     LOCK2(cs_main, cs_wallet);
2505     BOOST_FOREACH(const int64& id, setKeyPool)
2506     {
2507         CKeyPool keypool;
2508         if (!walletdb.ReadPool(id, keypool))
2509             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2510         assert(keypool.vchPubKey.IsValid());
2511         CKeyID keyID = keypool.vchPubKey.GetID();
2512         if (!HaveKey(keyID))
2513             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2514         setAddress.insert(keyID);
2515     }
2516 }
2517
2518 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2519 {
2520     {
2521         LOCK(cs_wallet);
2522         // Only notify UI if this transaction is in this wallet
2523         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2524         if (mi != mapWallet.end())
2525             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2526     }
2527 }
2528
2529 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2530     mapKeyBirth.clear();
2531
2532     // get birth times for keys with metadata
2533     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2534         if (it->second.nCreateTime)
2535             mapKeyBirth[it->first] = it->second.nCreateTime;
2536
2537     // map in which we'll infer heights of other keys
2538     CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2539     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2540     std::set<CKeyID> setKeys;
2541     GetKeys(setKeys);
2542     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2543         if (mapKeyBirth.count(keyid) == 0)
2544             mapKeyFirstBlock[keyid] = pindexMax;
2545     }
2546     setKeys.clear();
2547
2548     // if there are no such keys, we're done
2549     if (mapKeyFirstBlock.empty())
2550         return;
2551
2552     // find first block that affects those keys, if there are any left
2553     std::vector<CKeyID> vAffected;
2554     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2555         // iterate over all wallet transactions...
2556         const CWalletTx &wtx = (*it).second;
2557         std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2558         if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2559             // ... which are already in a block
2560             int nHeight = blit->second->nHeight;
2561             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2562                 // iterate over all their outputs
2563                 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2564                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2565                     // ... and all their affected keys
2566                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2567                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2568                         rit->second = blit->second;
2569                 }
2570                 vAffected.clear();
2571             }
2572         }
2573     }
2574
2575     // Extract block timestamps for those keys
2576     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2577         mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2578 }