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