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