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