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