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