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