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