Remove remainings of of sha512+scrypt key derivation
[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;
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, uint32_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     unsigned int nTimeTx, nBlockTime;
1880     COutPoint prevoutStake;
1881     CoinsSet::value_type kernelcoin;
1882
1883     if (ScanForStakeKernelHash(mapMeta, nBits, txNew.nTime, nSearchInterval, kernelcoin, nTimeTx, nBlockTime, nKernelsTried, nCoinDaysTried))
1884     {
1885         // Found a kernel
1886         if (fDebug && GetBoolArg("-printcoinstake"))
1887             printf("CreateCoinStake : kernel found\n");
1888         vector<valtype> vSolutions;
1889         txnouttype whichType;
1890         CScript scriptPubKeyOut;
1891         scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1892         if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1893         {
1894             if (fDebug && GetBoolArg("-printcoinstake"))
1895                 printf("CreateCoinStake : failed to parse kernel\n");
1896             return false;
1897         }
1898         if (fDebug && GetBoolArg("-printcoinstake"))
1899             printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1900         if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1901         {
1902             if (fDebug && GetBoolArg("-printcoinstake"))
1903                 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1904             return false;  // only support pay to public key and pay to address
1905         }
1906         if (whichType == TX_PUBKEYHASH) // pay to address type
1907         {
1908             // convert to pay to public key type
1909             if (!keystore.GetKey(uint160(vSolutions[0]), key))
1910             {
1911                 if (fDebug && GetBoolArg("-printcoinstake"))
1912                     printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1913                 return false;  // unable to find corresponding public key
1914             }
1915             scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1916         }
1917         if (whichType == TX_PUBKEY)
1918         {
1919             valtype& vchPubKey = vSolutions[0];
1920             if (!keystore.GetKey(Hash160(vchPubKey), key))
1921             {
1922                 if (fDebug && GetBoolArg("-printcoinstake"))
1923                     printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1924                 return false;  // unable to find corresponding public key
1925             }
1926             if (key.GetPubKey() != vchPubKey)
1927             {
1928                 if (fDebug && GetBoolArg("-printcoinstake"))
1929                     printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1930                 return false; // keys mismatch
1931             }
1932
1933             scriptPubKeyOut = scriptPubKeyKernel;
1934         }
1935
1936         txNew.nTime = nTimeTx;
1937         txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
1938         nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
1939         vwtxPrev.push_back(kernelcoin.first);
1940         txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1941
1942         if (GetWeight((int64_t)nBlockTime, (int64_t)txNew.nTime) < nStakeMaxAge)
1943             txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1944         if (fDebug && GetBoolArg("-printcoinstake"))
1945             printf("CreateCoinStake : added kernel type=%d\n", whichType);
1946     }
1947
1948     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1949         return false;
1950
1951     // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1952     for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
1953     {
1954         // Get coin
1955         CoinsSet::value_type pcoin = meta_item->second.first.second;
1956
1957         // Attempt to add more inputs
1958         // Only add coins of the same key/address as kernel
1959         if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1960             && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1961         {
1962             int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime);
1963
1964             // Stop adding more inputs if already too many inputs
1965             if (txNew.vin.size() >= 100)
1966                 break;
1967             // Stop adding more inputs if value is already pretty significant
1968             if (nCredit > nCombineThreshold)
1969                 break;
1970             // Stop adding inputs if reached reserve limit
1971             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1972                 break;
1973             // Do not add additional significant input
1974             if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1975                 continue;
1976             // Do not add input that is still too young
1977             if (nTimeWeight < nStakeMaxAge)
1978                 continue;
1979
1980             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1981             nCredit += pcoin.first->vout[pcoin.second].nValue;
1982             vwtxPrev.push_back(pcoin.first);
1983         }
1984     }
1985
1986     // Calculate coin age reward
1987     {
1988         uint64_t nCoinAge;
1989         CTxDB txdb("r");
1990         if (!txNew.GetCoinAge(txdb, nCoinAge))
1991             return error("CreateCoinStake : failed to calculate coin age");
1992         
1993         int64_t nReward = GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1994         // Refuse to create mint that has zero or negative reward
1995         if(nReward <= 0)
1996             return false;
1997     
1998         nCredit += nReward;
1999     }
2000
2001     int64_t nMinFee = 0;
2002     while (true)
2003     {
2004         // Set output amount
2005         if (txNew.vout.size() == 3)
2006         {
2007             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2008             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2009         }
2010         else
2011             txNew.vout[1].nValue = nCredit - nMinFee;
2012
2013         // Sign
2014         int nIn = 0;
2015         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2016         {
2017             if (!SignSignature(*this, *pcoin, txNew, nIn++))
2018                 return error("CreateCoinStake : failed to sign coinstake");
2019         }
2020
2021         // Limit size
2022         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2023         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2024             return error("CreateCoinStake : exceeded coinstake size limit");
2025
2026         // Check enough fee is paid
2027         if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2028         {
2029             nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2030             continue; // try signing again
2031         }
2032         else
2033         {
2034             if (fDebug && GetBoolArg("-printfee"))
2035                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2036             break;
2037         }
2038     }
2039
2040     // Successfully generated coinstake
2041     return true;
2042 }
2043
2044
2045 // Call after CreateTransaction unless you want to abort
2046 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2047 {
2048     {
2049         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2050
2051         // Track how many getdata requests our transaction gets
2052         mapRequestCount[wtxNew.GetHash()] = 0;
2053
2054         // Try to broadcast before saving
2055         if (!wtxNew.AcceptToMemoryPool())
2056         {
2057             // This must not fail. The transaction has already been signed.
2058             printf("CommitTransaction() : Error: Transaction not valid");
2059             return false;
2060         }
2061
2062         wtxNew.RelayWalletTransaction();
2063
2064         {
2065             LOCK2(cs_main, cs_wallet);
2066
2067             // This is only to keep the database open to defeat the auto-flush for the
2068             // duration of this scope.  This is the only place where this optimization
2069             // maybe makes sense; please don't do it anywhere else.
2070             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2071
2072             // Take key pair from key pool so it won't be used again
2073             reservekey.KeepKey();
2074
2075             // Add tx to wallet, because if it has change it's also ours,
2076             // otherwise just for transaction history.
2077             AddToWallet(wtxNew);
2078
2079             // Mark old coins as spent
2080             set<CWalletTx*> setCoins;
2081             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2082             {
2083                 CWalletTx &coin = mapWallet[txin.prevout.hash];
2084                 coin.BindWallet(this);
2085                 coin.MarkSpent(txin.prevout.n);
2086                 coin.WriteToDisk();
2087                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2088                 vMintingWalletUpdated.push_back(coin.GetHash());
2089             }
2090
2091             if (fFileBacked)
2092                 delete pwalletdb;
2093         }
2094     }
2095     return true;
2096 }
2097
2098
2099
2100
2101 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2102 {
2103     CReserveKey reservekey(this);
2104     int64_t nFeeRequired;
2105
2106     if (IsLocked())
2107     {
2108         string strError = _("Error: Wallet locked, unable to create transaction  ");
2109         printf("SendMoney() : %s", strError.c_str());
2110         return strError;
2111     }
2112     if (fWalletUnlockMintOnly)
2113     {
2114         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2115         printf("SendMoney() : %s", strError.c_str());
2116         return strError;
2117     }
2118     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2119     {
2120         string strError;
2121         if (nValue + nFeeRequired > GetBalance())
2122             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());
2123         else
2124             strError = _("Error: Transaction creation failed  ");
2125         printf("SendMoney() : %s", strError.c_str());
2126         return strError;
2127     }
2128
2129     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2130         return "ABORTED";
2131
2132     if (!CommitTransaction(wtxNew, reservekey))
2133         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.");
2134
2135     return "";
2136 }
2137
2138
2139
2140 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2141 {
2142     // Check amount
2143     if (nValue <= 0)
2144         return _("Invalid amount");
2145     if (nValue + nTransactionFee > GetBalance())
2146         return _("Insufficient funds");
2147
2148     // Parse Bitcoin address
2149     CScript scriptPubKey;
2150     scriptPubKey.SetDestination(address);
2151
2152     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2153 }
2154
2155
2156
2157
2158 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2159 {
2160     if (!fFileBacked)
2161         return DB_LOAD_OK;
2162     fFirstRunRet = false;
2163     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2164     if (nLoadWalletRet == DB_NEED_REWRITE)
2165     {
2166         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2167         {
2168             setKeyPool.clear();
2169             // Note: can't top-up keypool here, because wallet is locked.
2170             // User will be prompted to unlock wallet the next operation
2171             // the requires a new key.
2172         }
2173     }
2174
2175     if (nLoadWalletRet != DB_LOAD_OK)
2176         return nLoadWalletRet;
2177     fFirstRunRet = !vchDefaultKey.IsValid();
2178
2179     NewThread(ThreadFlushWalletDB, &strWalletFile);
2180     return DB_LOAD_OK;
2181 }
2182
2183
2184 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2185 {
2186     std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2187     mapAddressBook[address] = strName;
2188     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2189     if (!fFileBacked)
2190         return false;
2191     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2192 }
2193
2194 bool CWallet::DelAddressBookName(const CTxDestination& address)
2195 {
2196     mapAddressBook.erase(address);
2197     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2198     if (!fFileBacked)
2199         return false;
2200     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2201 }
2202
2203
2204 void CWallet::PrintWallet(const CBlock& block)
2205 {
2206     {
2207         LOCK(cs_wallet);
2208         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2209         {
2210             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2211             printf("    PoS: %d  %d  %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2212         }
2213         else if (mapWallet.count(block.vtx[0].GetHash()))
2214         {
2215             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2216             printf("    PoW:  %d  %d  %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2217         }
2218     }
2219     printf("\n");
2220 }
2221
2222 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2223 {
2224     {
2225         LOCK(cs_wallet);
2226         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2227         if (mi != mapWallet.end())
2228         {
2229             wtx = (*mi).second;
2230             return true;
2231         }
2232     }
2233     return false;
2234 }
2235
2236 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2237 {
2238     if (fFileBacked)
2239     {
2240         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2241             return false;
2242     }
2243     vchDefaultKey = vchPubKey;
2244     return true;
2245 }
2246
2247 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2248 {
2249     if (!pwallet->fFileBacked)
2250         return false;
2251     strWalletFileOut = pwallet->strWalletFile;
2252     return true;
2253 }
2254
2255 //
2256 // Mark old keypool keys as used,
2257 // and generate all new keys
2258 //
2259 bool CWallet::NewKeyPool()
2260 {
2261     {
2262         LOCK(cs_wallet);
2263         CWalletDB walletdb(strWalletFile);
2264         BOOST_FOREACH(int64_t nIndex, setKeyPool)
2265             walletdb.ErasePool(nIndex);
2266         setKeyPool.clear();
2267
2268         if (IsLocked())
2269             return false;
2270
2271         int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
2272         for (int i = 0; i < nKeys; i++)
2273         {
2274             int64_t nIndex = i+1;
2275             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2276             setKeyPool.insert(nIndex);
2277         }
2278         printf("CWallet::NewKeyPool wrote %" PRId64 " new keys\n", nKeys);
2279     }
2280     return true;
2281 }
2282
2283 bool CWallet::TopUpKeyPool(unsigned int nSize)
2284 {
2285     {
2286         LOCK(cs_wallet);
2287
2288         if (IsLocked())
2289             return false;
2290
2291         CWalletDB walletdb(strWalletFile);
2292
2293         // Top up key pool
2294         unsigned int nTargetSize;
2295         if (nSize > 0)
2296             nTargetSize = nSize;
2297         else
2298             nTargetSize = max<unsigned int>(GetArg("-keypool", 100), 0LL);
2299
2300         while (setKeyPool.size() < (nTargetSize + 1))
2301         {
2302             int64_t nEnd = 1;
2303             if (!setKeyPool.empty())
2304                 nEnd = *(--setKeyPool.end()) + 1;
2305             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2306                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2307             setKeyPool.insert(nEnd);
2308             printf("keypool added key %" PRId64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2309         }
2310     }
2311     return true;
2312 }
2313
2314 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2315 {
2316     nIndex = -1;
2317     keypool.vchPubKey = CPubKey();
2318     {
2319         LOCK(cs_wallet);
2320
2321         if (!IsLocked())
2322             TopUpKeyPool();
2323
2324         // Get the oldest key
2325         if(setKeyPool.empty())
2326             return;
2327
2328         CWalletDB walletdb(strWalletFile);
2329
2330         nIndex = *(setKeyPool.begin());
2331         setKeyPool.erase(setKeyPool.begin());
2332         if (!walletdb.ReadPool(nIndex, keypool))
2333             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2334         if (!HaveKey(keypool.vchPubKey.GetID()))
2335             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2336         assert(keypool.vchPubKey.IsValid());
2337         if (fDebug && GetBoolArg("-printkeypool"))
2338             printf("keypool reserve %" PRId64 "\n", nIndex);
2339     }
2340 }
2341
2342 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2343 {
2344     {
2345         LOCK2(cs_main, cs_wallet);
2346         CWalletDB walletdb(strWalletFile);
2347
2348         int64_t nIndex = 1 + *(--setKeyPool.end());
2349         if (!walletdb.WritePool(nIndex, keypool))
2350             throw runtime_error("AddReserveKey() : writing added key failed");
2351         setKeyPool.insert(nIndex);
2352         return nIndex;
2353     }
2354     return -1;
2355 }
2356
2357 void CWallet::KeepKey(int64_t nIndex)
2358 {
2359     // Remove from key pool
2360     if (fFileBacked)
2361     {
2362         CWalletDB walletdb(strWalletFile);
2363         walletdb.ErasePool(nIndex);
2364     }
2365     if(fDebug)
2366         printf("keypool keep %" PRId64 "\n", nIndex);
2367 }
2368
2369 void CWallet::ReturnKey(int64_t nIndex)
2370 {
2371     // Return to key pool
2372     {
2373         LOCK(cs_wallet);
2374         setKeyPool.insert(nIndex);
2375     }
2376     if(fDebug)
2377         printf("keypool return %" PRId64 "\n", nIndex);
2378 }
2379
2380 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2381 {
2382     int64_t nIndex = 0;
2383     CKeyPool keypool;
2384     {
2385         LOCK(cs_wallet);
2386         ReserveKeyFromKeyPool(nIndex, keypool);
2387         if (nIndex == -1)
2388         {
2389             if (fAllowReuse && vchDefaultKey.IsValid())
2390             {
2391                 result = vchDefaultKey;
2392                 return true;
2393             }
2394             if (IsLocked()) return false;
2395             result = GenerateNewKey();
2396             return true;
2397         }
2398         KeepKey(nIndex);
2399         result = keypool.vchPubKey;
2400     }
2401     return true;
2402 }
2403
2404 int64_t CWallet::GetOldestKeyPoolTime()
2405 {
2406     int64_t nIndex = 0;
2407     CKeyPool keypool;
2408     ReserveKeyFromKeyPool(nIndex, keypool);
2409     if (nIndex == -1)
2410         return GetTime();
2411     ReturnKey(nIndex);
2412     return keypool.nTime;
2413 }
2414
2415 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2416 {
2417     map<CTxDestination, int64_t> balances;
2418
2419     {
2420         LOCK(cs_wallet);
2421         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2422         {
2423             CWalletTx *pcoin = &walletEntry.second;
2424
2425             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2426                 continue;
2427
2428             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2429                 continue;
2430
2431             int nDepth = pcoin->GetDepthInMainChain();
2432             if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2433                 continue;
2434
2435             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2436             {
2437                 CTxDestination addr;
2438                 if (!IsMine(pcoin->vout[i]))
2439                     continue;
2440                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2441                     continue;
2442
2443                 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2444
2445                 if (!balances.count(addr))
2446                     balances[addr] = 0;
2447                 balances[addr] += n;
2448             }
2449         }
2450     }
2451
2452     return balances;
2453 }
2454
2455 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2456 {
2457     set< set<CTxDestination> > groupings;
2458     set<CTxDestination> grouping;
2459
2460     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2461     {
2462         CWalletTx *pcoin = &walletEntry.second;
2463
2464         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2465         {
2466             // group all input addresses with each other
2467             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2468             {
2469                 CTxDestination address;
2470                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2471                     continue;
2472                 grouping.insert(address);
2473             }
2474
2475             // group change with input addresses
2476             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2477                 if (IsChange(txout))
2478                 {
2479                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2480                     CTxDestination txoutAddr;
2481                     if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2482                         continue;
2483                     grouping.insert(txoutAddr);
2484                 }
2485             groupings.insert(grouping);
2486             grouping.clear();
2487         }
2488
2489         // group lone addrs by themselves
2490         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2491             if (IsMine(pcoin->vout[i]))
2492             {
2493                 CTxDestination address;
2494                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2495                     continue;
2496                 grouping.insert(address);
2497                 groupings.insert(grouping);
2498                 grouping.clear();
2499             }
2500     }
2501
2502     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2503     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2504     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2505     {
2506         // make a set of all the groups hit by this new group
2507         set< set<CTxDestination>* > hits;
2508         map< CTxDestination, set<CTxDestination>* >::iterator it;
2509         BOOST_FOREACH(CTxDestination address, grouping)
2510             if ((it = setmap.find(address)) != setmap.end())
2511                 hits.insert((*it).second);
2512
2513         // merge all hit groups into a new single group and delete old groups
2514         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2515         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2516         {
2517             merged->insert(hit->begin(), hit->end());
2518             uniqueGroupings.erase(hit);
2519             delete hit;
2520         }
2521         uniqueGroupings.insert(merged);
2522
2523         // update setmap
2524         BOOST_FOREACH(CTxDestination element, *merged)
2525             setmap[element] = merged;
2526     }
2527
2528     set< set<CTxDestination> > ret;
2529     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2530     {
2531         ret.insert(*uniqueGrouping);
2532         delete uniqueGrouping;
2533     }
2534
2535     return ret;
2536 }
2537
2538 // ppcoin: check 'spent' consistency between wallet and txindex
2539 // ppcoin: fix wallet spent state according to txindex
2540 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2541 {
2542     nMismatchFound = 0;
2543     nBalanceInQuestion = 0;
2544
2545     LOCK(cs_wallet);
2546     vector<CWalletTx*> vCoins;
2547     vCoins.reserve(mapWallet.size());
2548     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2549         vCoins.push_back(&(*it).second);
2550
2551     CTxDB txdb("r");
2552     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2553     {
2554         // Find the corresponding transaction index
2555         CTxIndex txindex;
2556         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2557             continue;
2558         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2559         {
2560             if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2561             {
2562                 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2563                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2564                 nMismatchFound++;
2565                 nBalanceInQuestion += pcoin->vout[n].nValue;
2566                 if (!fCheckOnly)
2567                 {
2568                     pcoin->MarkUnspent(n);
2569                     pcoin->WriteToDisk();
2570                 }
2571             }
2572             else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2573             {
2574                 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2575                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2576                 nMismatchFound++;
2577                 nBalanceInQuestion += pcoin->vout[n].nValue;
2578                 if (!fCheckOnly)
2579                 {
2580                     pcoin->MarkSpent(n);
2581                     pcoin->WriteToDisk();
2582                 }
2583             }
2584
2585         }
2586
2587         if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2588         {
2589             printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2590             if (!fCheckOnly)
2591             {
2592                 EraseFromWallet(pcoin->GetHash());
2593             }
2594         }
2595     }
2596 }
2597
2598 // ppcoin: disable transaction (only for coinstake)
2599 void CWallet::DisableTransaction(const CTransaction &tx)
2600 {
2601     if (!tx.IsCoinStake() || !IsFromMe(tx))
2602         return; // only disconnecting coinstake requires marking input unspent
2603
2604     LOCK(cs_wallet);
2605     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2606     {
2607         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2608         if (mi != mapWallet.end())
2609         {
2610             CWalletTx& prev = (*mi).second;
2611             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2612             {
2613                 prev.MarkUnspent(txin.prevout.n);
2614                 prev.WriteToDisk();
2615             }
2616         }
2617     }
2618 }
2619
2620 CPubKey CReserveKey::GetReservedKey()
2621 {
2622     if (nIndex == -1)
2623     {
2624         CKeyPool keypool;
2625         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2626         if (nIndex != -1)
2627             vchPubKey = keypool.vchPubKey;
2628         else
2629         {
2630             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2631             vchPubKey = pwallet->vchDefaultKey;
2632         }
2633     }
2634     assert(vchPubKey.IsValid());
2635     return vchPubKey;
2636 }
2637
2638 void CReserveKey::KeepKey()
2639 {
2640     if (nIndex != -1)
2641         pwallet->KeepKey(nIndex);
2642     nIndex = -1;
2643     vchPubKey = CPubKey();
2644 }
2645
2646 void CReserveKey::ReturnKey()
2647 {
2648     if (nIndex != -1)
2649         pwallet->ReturnKey(nIndex);
2650     nIndex = -1;
2651     vchPubKey = CPubKey();
2652 }
2653
2654 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2655 {
2656     setAddress.clear();
2657
2658     CWalletDB walletdb(strWalletFile);
2659
2660     LOCK2(cs_main, cs_wallet);
2661     BOOST_FOREACH(const int64_t& id, setKeyPool)
2662     {
2663         CKeyPool keypool;
2664         if (!walletdb.ReadPool(id, keypool))
2665             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2666         assert(keypool.vchPubKey.IsValid());
2667         CKeyID keyID = keypool.vchPubKey.GetID();
2668         if (!HaveKey(keyID))
2669             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2670         setAddress.insert(keyID);
2671     }
2672 }
2673
2674 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2675 {
2676     {
2677         LOCK(cs_wallet);
2678         // Only notify UI if this transaction is in this wallet
2679         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2680         if (mi != mapWallet.end())
2681         {
2682             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2683             vMintingWalletUpdated.push_back(hashTx);
2684         }
2685     }
2686 }
2687
2688 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2689     mapKeyBirth.clear();
2690
2691     // get birth times for keys with metadata
2692     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2693         if (it->second.nCreateTime)
2694             mapKeyBirth[it->first] = it->second.nCreateTime;
2695
2696     // map in which we'll infer heights of other keys
2697     CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2698     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2699     std::set<CKeyID> setKeys;
2700     GetKeys(setKeys);
2701     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2702         if (mapKeyBirth.count(keyid) == 0)
2703             mapKeyFirstBlock[keyid] = pindexMax;
2704     }
2705     setKeys.clear();
2706
2707     // if there are no such keys, we're done
2708     if (mapKeyFirstBlock.empty())
2709         return;
2710
2711     // find first block that affects those keys, if there are any left
2712     std::vector<CKeyID> vAffected;
2713     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2714         // iterate over all wallet transactions...
2715         const CWalletTx &wtx = (*it).second;
2716         std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2717         if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2718             // ... which are already in a block
2719             int nHeight = blit->second->nHeight;
2720             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2721                 // iterate over all their outputs
2722                 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2723                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2724                     // ... and all their affected keys
2725                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2726                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2727                         rit->second = blit->second;
2728                 }
2729                 vAffected.clear();
2730             }
2731         }
2732     }
2733
2734     // Extract block timestamps for those keys
2735     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2736         mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2737 }
2738
2739 void CWallet::ClearOrphans()
2740 {
2741     list<uint256> orphans;
2742
2743     LOCK(cs_wallet);
2744     for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2745     {
2746         const CWalletTx *wtx = &(*it).second;
2747         if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2748         {
2749             orphans.push_back(wtx->GetHash());
2750         }
2751     }
2752
2753     for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2754         EraseFromWallet(*it);
2755 }