PUBKEY_PAIR_ADDRESS / PUBKEY_PAIR_ADDRESS_TEST
[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()
1156 {
1157     // Do this infrequently and randomly to avoid giving away
1158     // that these are our transactions.
1159     static int64_t nNextTime = GetRand(GetTime() + 30 * 60);
1160     if (GetTime() < nNextTime)
1161         return;
1162     bool fFirst = (nNextTime == 0);
1163     nNextTime = GetTime() + GetRand(30 * 60);
1164     if (fFirst)
1165         return;
1166
1167     // Only do it if there's been a new block since last time
1168     static int64_t nLastTime = 0;
1169     if (nTimeBestReceived < nLastTime)
1170         return;
1171     nLastTime = GetTime();
1172
1173     // Rebroadcast any of our txes that aren't in a block yet
1174     printf("ResendWalletTransactions()\n");
1175     CTxDB txdb("r");
1176     {
1177         LOCK(cs_wallet);
1178         // Sort them in chronological order
1179         multimap<unsigned int, CWalletTx*> mapSorted;
1180         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1181         {
1182             CWalletTx& wtx = item.second;
1183             // Don't rebroadcast until it's had plenty of time that
1184             // it should have gotten in already by now.
1185             if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1186                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1187         }
1188         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1189         {
1190             CWalletTx& wtx = *item.second;
1191             if (wtx.CheckTransaction())
1192                 wtx.RelayWalletTransaction(txdb);
1193             else
1194                 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1195         }
1196     }
1197 }
1198
1199
1200
1201
1202
1203
1204 //////////////////////////////////////////////////////////////////////////////
1205 //
1206 // Actions
1207 //
1208
1209
1210 int64_t CWallet::GetBalance() const
1211 {
1212     int64_t nTotal = 0;
1213     {
1214         LOCK(cs_wallet);
1215         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1216         {
1217             const CWalletTx* pcoin = &(*it).second;
1218             if (pcoin->IsTrusted())
1219                 nTotal += pcoin->GetAvailableCredit();
1220         }
1221     }
1222
1223     return nTotal;
1224 }
1225
1226 int64_t CWallet::GetWatchOnlyBalance() const
1227 {
1228     int64_t nTotal = 0;
1229     {
1230         LOCK(cs_wallet);
1231         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1232         {
1233             const CWalletTx* pcoin = &(*it).second;
1234             if (pcoin->IsTrusted())
1235                 nTotal += pcoin->GetAvailableWatchCredit();
1236         }
1237     }
1238
1239     return nTotal;
1240 }
1241
1242 int64_t CWallet::GetUnconfirmedBalance() const
1243 {
1244     int64_t nTotal = 0;
1245     {
1246         LOCK(cs_wallet);
1247         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1248         {
1249             const CWalletTx* pcoin = &(*it).second;
1250             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1251                 nTotal += pcoin->GetAvailableCredit();
1252         }
1253     }
1254     return nTotal;
1255 }
1256
1257 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1258 {
1259     int64_t nTotal = 0;
1260     {
1261         LOCK(cs_wallet);
1262         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1263         {
1264             const CWalletTx* pcoin = &(*it).second;
1265             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1266                 nTotal += pcoin->GetAvailableWatchCredit();
1267         }
1268     }
1269     return nTotal;
1270 }
1271
1272 int64_t CWallet::GetImmatureBalance() const
1273 {
1274     int64_t nTotal = 0;
1275     {
1276         LOCK(cs_wallet);
1277         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1278         {
1279             const CWalletTx* pcoin = &(*it).second;
1280             nTotal += pcoin->GetImmatureCredit();
1281         }
1282     }
1283     return nTotal;
1284 }
1285
1286 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1287 {
1288     int64_t nTotal = 0;
1289     {
1290         LOCK(cs_wallet);
1291         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1292         {
1293             const CWalletTx* pcoin = &(*it).second;
1294             nTotal += pcoin->GetImmatureWatchOnlyCredit();
1295         }
1296     }
1297     return nTotal;
1298 }
1299
1300 // populate vCoins with vector of spendable COutputs
1301 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1302 {
1303     vCoins.clear();
1304
1305     {
1306         LOCK(cs_wallet);
1307         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1308         {
1309             const CWalletTx* pcoin = &(*it).second;
1310
1311             if (!pcoin->IsFinal())
1312                 continue;
1313
1314             if (fOnlyConfirmed && !pcoin->IsTrusted())
1315                 continue;
1316
1317             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1318                 continue;
1319
1320             if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1321                 continue;
1322
1323             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1324                 isminetype mine = IsMine(pcoin->vout[i]);
1325                 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && 
1326                     pcoin->vout[i].nValue >= nMinimumInputValue &&
1327                     (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1328                 {
1329                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1330                 }
1331             }
1332         }
1333     }
1334 }
1335
1336 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1337 {
1338     vCoins.clear();
1339
1340     {
1341         LOCK(cs_wallet);
1342         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1343         {
1344             const CWalletTx* pcoin = &(*it).second;
1345
1346             if (!pcoin->IsFinal())
1347                 continue;
1348
1349             if(pcoin->GetDepthInMainChain() < nConf)
1350                 continue;
1351
1352             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1353                 isminetype mine = IsMine(pcoin->vout[i]);
1354
1355                 // ignore coin if it was already spent or we don't own it
1356                 if (pcoin->IsSpent(i) || mine == MINE_NO)
1357                     continue;
1358
1359                 // if coin value is between required limits then add new item to vector
1360                 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1361                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1362             }
1363         }
1364     }
1365 }
1366
1367 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1368                                   vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1369 {
1370     vector<char> vfIncluded;
1371
1372     vfBest.assign(vValue.size(), true);
1373     nBest = nTotalLower;
1374
1375     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1376     {
1377         vfIncluded.assign(vValue.size(), false);
1378         int64_t nTotal = 0;
1379         bool fReachedTarget = false;
1380         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1381         {
1382             for (unsigned int i = 0; i < vValue.size(); i++)
1383             {
1384                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1385                 {
1386                     nTotal += vValue[i].first;
1387                     vfIncluded[i] = true;
1388                     if (nTotal >= nTargetValue)
1389                     {
1390                         fReachedTarget = true;
1391                         if (nTotal < nBest)
1392                         {
1393                             nBest = nTotal;
1394                             vfBest = vfIncluded;
1395                         }
1396                         nTotal -= vValue[i].first;
1397                         vfIncluded[i] = false;
1398                     }
1399                 }
1400             }
1401         }
1402     }
1403 }
1404
1405 int64_t CWallet::GetStake() const
1406 {
1407     int64_t nTotal = 0;
1408     LOCK(cs_wallet);
1409     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1410     {
1411         const CWalletTx* pcoin = &(*it).second;
1412         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1413             nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1414     }
1415     return nTotal;
1416 }
1417
1418 int64_t CWallet::GetWatchOnlyStake() const
1419 {
1420     int64_t nTotal = 0;
1421     LOCK(cs_wallet);
1422     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1423     {
1424         const CWalletTx* pcoin = &(*it).second;
1425         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1426             nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1427     }
1428     return nTotal;
1429 }
1430
1431 int64_t CWallet::GetNewMint() const
1432 {
1433     int64_t nTotal = 0;
1434     LOCK(cs_wallet);
1435     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1436     {
1437         const CWalletTx* pcoin = &(*it).second;
1438         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1439             nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1440     }
1441     return nTotal;
1442 }
1443
1444 int64_t CWallet::GetWatchOnlyNewMint() const
1445 {
1446     int64_t nTotal = 0;
1447     LOCK(cs_wallet);
1448     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1449     {
1450         const CWalletTx* pcoin = &(*it).second;
1451         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1452             nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1453     }
1454     return nTotal;
1455 }
1456
1457 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
1458 {
1459     setCoinsRet.clear();
1460     nValueRet = 0;
1461
1462     // List of values less than target
1463     pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1464     coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1465     coinLowestLarger.second.first = NULL;
1466     vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1467     int64_t nTotalLower = 0;
1468
1469     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1470
1471     BOOST_FOREACH(const COutput &output, vCoins)
1472     {
1473         if (!output.fSpendable)
1474             continue;
1475
1476         const CWalletTx *pcoin = output.tx;
1477
1478         if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1479             continue;
1480
1481         int i = output.i;
1482
1483         // Follow the timestamp rules
1484         if (pcoin->nTime > nSpendTime)
1485             continue;
1486
1487         int64_t n = pcoin->vout[i].nValue;
1488
1489         pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1490
1491         if (n == nTargetValue)
1492         {
1493             setCoinsRet.insert(coin.second);
1494             nValueRet += coin.first;
1495             return true;
1496         }
1497         else if (n < nTargetValue + CENT)
1498         {
1499             vValue.push_back(coin);
1500             nTotalLower += n;
1501         }
1502         else if (n < coinLowestLarger.first)
1503         {
1504             coinLowestLarger = coin;
1505         }
1506     }
1507
1508     if (nTotalLower == nTargetValue)
1509     {
1510         for (unsigned int i = 0; i < vValue.size(); ++i)
1511         {
1512             setCoinsRet.insert(vValue[i].second);
1513             nValueRet += vValue[i].first;
1514         }
1515         return true;
1516     }
1517
1518     if (nTotalLower < nTargetValue)
1519     {
1520         if (coinLowestLarger.second.first == NULL)
1521             return false;
1522         setCoinsRet.insert(coinLowestLarger.second);
1523         nValueRet += coinLowestLarger.first;
1524         return true;
1525     }
1526
1527     // Solve subset sum by stochastic approximation
1528     sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1529     vector<char> vfBest;
1530     int64_t nBest;
1531
1532     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1533     if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1534         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1535
1536     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1537     //                                   or the next bigger coin is closer), return the bigger coin
1538     if (coinLowestLarger.second.first &&
1539         ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1540     {
1541         setCoinsRet.insert(coinLowestLarger.second);
1542         nValueRet += coinLowestLarger.first;
1543     }
1544     else {
1545         for (unsigned int i = 0; i < vValue.size(); i++)
1546             if (vfBest[i])
1547             {
1548                 setCoinsRet.insert(vValue[i].second);
1549                 nValueRet += vValue[i].first;
1550             }
1551
1552         if (fDebug && GetBoolArg("-printpriority"))
1553         {
1554             //// debug print
1555             printf("SelectCoins() best subset: ");
1556             for (unsigned int i = 0; i < vValue.size(); i++)
1557                 if (vfBest[i])
1558                     printf("%s ", FormatMoney(vValue[i].first).c_str());
1559             printf("total %s\n", FormatMoney(nBest).c_str());
1560         }
1561     }
1562
1563     return true;
1564 }
1565
1566 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1567 {
1568     vector<COutput> vCoins;
1569     AvailableCoins(vCoins, true, coinControl);
1570
1571     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1572     if (coinControl && coinControl->HasSelected())
1573     {
1574         BOOST_FOREACH(const COutput& out, vCoins)
1575         {
1576             if(!out.fSpendable)
1577                 continue;
1578             nValueRet += out.tx->vout[out.i].nValue;
1579             setCoinsRet.insert(make_pair(out.tx, out.i));
1580         }
1581         return (nValueRet >= nTargetValue);
1582     }
1583
1584     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1585             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1586             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1587 }
1588
1589 // Select some coins without random shuffle or best subset approximation
1590 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
1591 {
1592     vector<COutput> vCoins;
1593     AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1594
1595     setCoinsRet.clear();
1596     nValueRet = 0;
1597
1598     BOOST_FOREACH(COutput output, vCoins)
1599     {
1600         if(!output.fSpendable)
1601             continue;
1602         const CWalletTx *pcoin = output.tx;
1603         int i = output.i;
1604
1605         // Ignore immature coins
1606         if (pcoin->GetBlocksToMaturity() > 0)
1607             continue;
1608
1609         // Stop if we've chosen enough inputs
1610         if (nValueRet >= nTargetValue)
1611             break;
1612
1613         // Follow the timestamp rules
1614         if (pcoin->nTime > nSpendTime)
1615             continue;
1616
1617         int64_t n = pcoin->vout[i].nValue;
1618
1619         pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1620
1621         if (n >= nTargetValue)
1622         {
1623             // If input value is greater or equal to target then simply insert
1624             //    it into the current subset and exit
1625             setCoinsRet.insert(coin.second);
1626             nValueRet += coin.first;
1627             break;
1628         }
1629         else if (n < nTargetValue + CENT)
1630         {
1631             setCoinsRet.insert(coin.second);
1632             nValueRet += coin.first;
1633         }
1634     }
1635
1636     return true;
1637 }
1638
1639 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1640 {
1641     int64_t nValue = 0;
1642     BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1643     {
1644         if (nValue < 0)
1645             return false;
1646         nValue += s.second;
1647     }
1648     if (vecSend.empty() || nValue < 0)
1649         return false;
1650
1651     wtxNew.BindWallet(this);
1652
1653     {
1654         LOCK2(cs_main, cs_wallet);
1655         // txdb must be opened before the mapWallet lock
1656         CTxDB txdb("r");
1657         {
1658             nFeeRet = nTransactionFee;
1659             while (true)
1660             {
1661                 wtxNew.vin.clear();
1662                 wtxNew.vout.clear();
1663                 wtxNew.fFromMe = true;
1664
1665                 int64_t nTotalValue = nValue + nFeeRet;
1666                 double dPriority = 0;
1667                 // vouts to the payees
1668                 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1669                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1670
1671                 // Choose coins to use
1672                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1673                 int64_t nValueIn = 0;
1674                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1675                     return false;
1676                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1677                 {
1678                     int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1679                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1680                 }
1681
1682                 int64_t nChange = nValueIn - nValue - nFeeRet;
1683                 if (nChange > 0)
1684                 {
1685                     // Fill a vout to ourself
1686                     // TODO: pass in scriptChange instead of reservekey so
1687                     // change transaction isn't always pay-to-bitcoin-address
1688                     CScript scriptChange;
1689
1690                     // coin control: send change to custom address
1691                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1692                         scriptChange.SetDestination(coinControl->destChange);
1693
1694                     // no coin control: send change to newly generated address
1695                     else
1696                     {
1697                         // Note: We use a new key here to keep it from being obvious which side is the change.
1698                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1699                         //  backup is restored, if the backup doesn't have the new private key for the change.
1700                         //  If we reused the old key, it would be possible to add code to look for and
1701                         //  rediscover unknown transactions that were written with keys of ours to recover
1702                         //  post-backup change.
1703
1704                         // Reserve a new key pair from key pool
1705                         CPubKey vchPubKey = reservekey.GetReservedKey();
1706
1707                         scriptChange.SetDestination(vchPubKey.GetID());
1708                     }
1709
1710                     // Insert change txn at random position:
1711                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1712                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1713                 }
1714                 else
1715                     reservekey.ReturnKey();
1716
1717                 // Fill vin
1718                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1719                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1720
1721                 // Sign
1722                 int nIn = 0;
1723                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1724                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1725                         return false;
1726
1727                 // Limit size
1728                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1729                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1730                     return false;
1731                 dPriority /= nBytes;
1732
1733                 // Check that enough fee is included
1734                 bool fAllowFree = CTransaction::AllowFree(dPriority);
1735                 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1736                 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1737
1738                 if (nFeeRet < max(nPayFee, nMinFee))
1739                 {
1740                     nFeeRet = max(nPayFee, nMinFee);
1741                     continue;
1742                 }
1743
1744                 // Fill vtxPrev by copying from previous transactions vtxPrev
1745                 wtxNew.AddSupportingTransactions(txdb);
1746                 wtxNew.fTimeReceivedIsTxTime = true;
1747
1748                 break;
1749             }
1750         }
1751     }
1752     return true;
1753 }
1754
1755 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1756 {
1757     vector< pair<CScript, int64_t> > vecSend;
1758     vecSend.push_back(make_pair(scriptPubKey, nValue));
1759     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1760 }
1761
1762 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1763 {
1764     int64_t nTimeWeight = GetWeight(nTime, GetTime());
1765
1766     // If time weight is lower or equal to zero then weight is zero.
1767     if (nTimeWeight <= 0)
1768     {
1769         nWeight = 0;
1770         return;
1771     }
1772
1773     CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
1774     nWeight = bnCoinDayWeight.getuint64();
1775 }
1776
1777 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1778 {
1779     int64_t nBalance = GetBalance();
1780
1781     if (nAmount > nBalance)
1782         return false;
1783
1784     listMerged.clear();
1785     int64_t nValueIn = 0;
1786     set<pair<const CWalletTx*,unsigned int> > setCoins;
1787
1788     // Simple coins selection - no randomization
1789     if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1790         return false;
1791
1792     if (setCoins.empty())
1793         return false;
1794
1795     CWalletTx wtxNew;
1796     vector<const CWalletTx*> vwtxPrev;
1797
1798     // Reserve a new key pair from key pool
1799     CReserveKey reservekey(this);
1800     CPubKey vchPubKey = reservekey.GetReservedKey();
1801
1802     // Output script
1803     CScript scriptOutput;
1804     scriptOutput.SetDestination(vchPubKey.GetID());
1805
1806     // Insert output
1807     wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1808
1809     double dWeight = 0;
1810     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1811     {
1812         int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1813
1814         // Add current coin to inputs list and add its credit to transaction output
1815         wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1816         wtxNew.vout[0].nValue += nCredit;
1817         vwtxPrev.push_back(pcoin.first);
1818
1819 /*
1820         // Replaced with estimation for performance purposes
1821
1822         for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1823             const CWalletTx *txin = vwtxPrev[i];
1824
1825             // Sign scripts to get actual transaction size for fee calculation
1826             if (!SignSignature(*this, *txin, wtxNew, i))
1827                 return false;
1828         }
1829 */
1830
1831         // Assuming that average scriptsig size is 110 bytes
1832         int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1833         dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1834
1835         double dFinalPriority = dWeight /= nBytes;
1836         bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1837
1838         // Get actual transaction fee according to its estimated size and priority
1839         int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1840
1841         // Prepare transaction for commit if sum is enough ot its size is too big
1842         if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1843         {
1844             wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1845
1846             for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1847                 const CWalletTx *txin = vwtxPrev[i];
1848
1849                 // Sign all scripts
1850                 if (!SignSignature(*this, *txin, wtxNew, i))
1851                     return false;
1852             }
1853
1854             // Try to commit, return false on failure
1855             if (!CommitTransaction(wtxNew, reservekey))
1856                 return false;
1857
1858             listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1859
1860             dWeight = 0;  // Reset all temporary values
1861             vwtxPrev.clear();
1862             wtxNew.SetNull();
1863             wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1864         }
1865     }
1866
1867     // Create transactions if there are some unhandled coins left
1868     if (wtxNew.vout[0].nValue > 0) {
1869         int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1870
1871         double dFinalPriority = dWeight /= nBytes;
1872         bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1873
1874         // Get actual transaction fee according to its size and priority
1875         int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1876
1877         wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1878
1879         if (wtxNew.vout[0].nValue <= 0)
1880             return false;
1881
1882         for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1883             const CWalletTx *txin = vwtxPrev[i];
1884
1885             // Sign all scripts again
1886             if (!SignSignature(*this, *txin, wtxNew, i))
1887                 return false;
1888         }
1889
1890         // Try to commit, return false on failure
1891         if (!CommitTransaction(wtxNew, reservekey))
1892             return false;
1893
1894         listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1895     }
1896
1897     return true;
1898 }
1899
1900 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
1901 {
1902     CWalletTx wtx;
1903     if (!GetTransaction(hashTx, wtx))
1904         return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
1905
1906     vector<valtype> vSolutions;
1907     txnouttype whichType;
1908     CScript scriptPubKeyOut;
1909     CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
1910     if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1911         return error("CreateCoinStake : failed to parse kernel\n");
1912
1913     if (fDebug && GetBoolArg("-printcoinstake"))
1914         printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1915
1916     if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1917         return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
1918
1919     if (whichType == TX_PUBKEYHASH) // pay to address type
1920     {
1921         // convert to pay to public key type
1922         if (!GetKey(uint160(vSolutions[0]), key))
1923             return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1924
1925         scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1926     }
1927     if (whichType == TX_PUBKEY)
1928     {
1929         valtype& vchPubKey = vSolutions[0];
1930         if (!GetKey(Hash160(vchPubKey), key))
1931             return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1932         if (key.GetPubKey() != vchPubKey)
1933             return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
1934         scriptPubKeyOut = scriptPubKeyKernel;
1935     }
1936
1937     // The following combine threshold is important to security
1938     // Should not be adjusted if you don't understand the consequences
1939     int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1940
1941     int64_t nBalance = GetBalance();
1942     int64_t nCredit = wtx.vout[nOut].nValue;
1943
1944     txNew.vin.clear();
1945     txNew.vout.clear();
1946
1947     // List of constake dependencies
1948     vector<const CWalletTx*> vwtxPrev;
1949     vwtxPrev.push_back(&wtx);
1950
1951     // Set generation time, and kernel input
1952     txNew.nTime = nGenerationTime;
1953     txNew.vin.push_back(CTxIn(hashTx, nOut));
1954
1955     // Mark coin stake transaction with empty vout[0]
1956     CScript scriptEmpty;
1957     scriptEmpty.clear();
1958     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1959
1960     if (fDebug && GetBoolArg("-printcoinstake"))
1961         printf("CreateCoinStake : added kernel type=%d\n", whichType);
1962
1963     int64_t nValueIn = 0;
1964     CoinsSet setCoins;
1965     if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1966         return false;
1967
1968     if (setCoins.empty())
1969         return false;
1970
1971     bool fDontSplitCoins = false;
1972     if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
1973     {
1974         // Only one output for old kernel inputs
1975         txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1976
1977         // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
1978         //
1979         // * Value is higher than 0.01 NVC;
1980         // * Only add inputs of the same key/address as kernel;
1981         // * Input hash and kernel parent hash should be different.
1982         for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1983         {
1984             // Stop adding more inputs if already too many inputs
1985             if (txNew.vin.size() >= 100)
1986                 break;
1987             // Stop adding more inputs if value is already pretty significant
1988             if (nCredit > nCombineThreshold)
1989                 break;
1990             // Stop adding inputs if reached reserve limit
1991             if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
1992                 break;
1993
1994             int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
1995
1996             // Do not add input that is still too young
1997             if (nTimeWeight < nStakeMaxAge)
1998                 continue;
1999             // Do not add input if key/address is not the same as kernel
2000             if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2001                 continue;
2002             // Do not add input if parents are the same
2003             if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2004                 continue;
2005             // Do not add additional significant input
2006             if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2007                 continue;
2008
2009             txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2010             nCredit += pcoin->first->vout[pcoin->second].nValue;
2011             vwtxPrev.push_back(pcoin->first);
2012         }
2013
2014         fDontSplitCoins = true;
2015     }
2016     else
2017     {
2018         int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2019
2020         if (fDebug && GetBoolArg("-printcoinstake"))
2021             printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2022
2023         if (nCredit > nSplitThreshold)
2024         {
2025             // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2026             txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2027             txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2028
2029             if (fDebug && GetBoolArg("-printcoinstake"))
2030                 printf("CreateCoinStake : splitting coinstake\n");
2031         }
2032         else
2033         {
2034             txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2035             fDontSplitCoins = true;
2036         }
2037     }
2038
2039     // Calculate coin age reward
2040     uint64_t nCoinAge;
2041     CTxDB txdb("r");
2042     if (!txNew.GetCoinAge(txdb, nCoinAge))
2043         return error("CreateCoinStake : failed to calculate coin age\n");
2044     nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2045
2046     int64_t nMinFee = 0;
2047     while (true)
2048     {
2049         // Set output amount
2050         if (fDontSplitCoins)
2051             txNew.vout[1].nValue = nCredit - nMinFee;
2052         else
2053         {
2054             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2055             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2056         }
2057
2058         // Sign
2059         int nIn = 0;
2060         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2061         {
2062             if (!SignSignature(*this, *pcoin, txNew, nIn++))
2063                 return error("CreateCoinStake : failed to sign coinstake\n");
2064         }
2065
2066         // Limit size
2067         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2068         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2069             return error("CreateCoinStake : exceeded coinstake size limit\n");
2070
2071         // Check enough fee is paid
2072         if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2073         {
2074             nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2075             continue; // try signing again
2076         }
2077         else
2078         {
2079             if (fDebug && GetBoolArg("-printfee"))
2080                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2081             break;
2082         }
2083     }
2084
2085     // Successfully created coinstake
2086     return true;
2087 }
2088
2089 // Call after CreateTransaction unless you want to abort
2090 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2091 {
2092     {
2093         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2094
2095         // Track how many getdata requests our transaction gets
2096         mapRequestCount[wtxNew.GetHash()] = 0;
2097
2098         // Try to broadcast before saving
2099         if (!wtxNew.AcceptToMemoryPool())
2100         {
2101             // This must not fail. The transaction has already been signed.
2102             printf("CommitTransaction() : Error: Transaction not valid");
2103             return false;
2104         }
2105
2106         wtxNew.RelayWalletTransaction();
2107
2108         {
2109             LOCK2(cs_main, cs_wallet);
2110
2111             // This is only to keep the database open to defeat the auto-flush for the
2112             // duration of this scope.  This is the only place where this optimization
2113             // maybe makes sense; please don't do it anywhere else.
2114             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2115
2116             // Take key pair from key pool so it won't be used again
2117             reservekey.KeepKey();
2118
2119             // Add tx to wallet, because if it has change it's also ours,
2120             // otherwise just for transaction history.
2121             AddToWallet(wtxNew);
2122
2123             // Mark old coins as spent
2124             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2125             {
2126                 CWalletTx &coin = mapWallet[txin.prevout.hash];
2127                 coin.BindWallet(this);
2128                 coin.MarkSpent(txin.prevout.n);
2129                 coin.WriteToDisk();
2130                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2131                 vMintingWalletUpdated.push_back(coin.GetHash());
2132             }
2133
2134             if (fFileBacked)
2135                 delete pwalletdb;
2136         }
2137     }
2138     return true;
2139 }
2140
2141
2142
2143
2144 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2145 {
2146     // Check amount
2147     if (nValue <= 0)
2148         return _("Invalid amount");
2149     if (nValue + nTransactionFee > GetBalance())
2150         return _("Insufficient funds");
2151
2152     CReserveKey reservekey(this);
2153     int64_t nFeeRequired;
2154
2155     if (IsLocked())
2156     {
2157         string strError = _("Error: Wallet locked, unable to create transaction  ");
2158         printf("SendMoney() : %s", strError.c_str());
2159         return strError;
2160     }
2161     if (fWalletUnlockMintOnly)
2162     {
2163         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2164         printf("SendMoney() : %s", strError.c_str());
2165         return strError;
2166     }
2167     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2168     {
2169         string strError;
2170         if (nValue + nFeeRequired > GetBalance())
2171             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());
2172         else
2173             strError = _("Error: Transaction creation failed  ");
2174         printf("SendMoney() : %s", strError.c_str());
2175         return strError;
2176     }
2177
2178     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2179         return "ABORTED";
2180
2181     if (!CommitTransaction(wtxNew, reservekey))
2182         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.");
2183
2184     return "";
2185 }
2186
2187 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2188 {
2189     if (!fFileBacked)
2190         return DB_LOAD_OK;
2191     fFirstRunRet = false;
2192     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2193     if (nLoadWalletRet == DB_NEED_REWRITE)
2194     {
2195         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2196         {
2197             setKeyPool.clear();
2198             // Note: can't top-up keypool here, because wallet is locked.
2199             // User will be prompted to unlock wallet the next operation
2200             // the requires a new key.
2201         }
2202     }
2203
2204     if (nLoadWalletRet != DB_LOAD_OK)
2205         return nLoadWalletRet;
2206     fFirstRunRet = !vchDefaultKey.IsValid();
2207
2208     NewThread(ThreadFlushWalletDB, &strWalletFile);
2209     return DB_LOAD_OK;
2210 }
2211
2212 DBErrors CWallet::ZapWalletTx()
2213 {
2214     if (!fFileBacked)
2215         return DB_LOAD_OK;
2216     DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2217     if (nZapWalletTxRet == DB_NEED_REWRITE)
2218     {
2219         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2220         {
2221             LOCK(cs_wallet);
2222             setKeyPool.clear();
2223             // Note: can't top-up keypool here, because wallet is locked.
2224             // User will be prompted to unlock wallet the next operation
2225             // the requires a new key.
2226         }
2227     }
2228
2229     if (nZapWalletTxRet != DB_LOAD_OK)
2230         return nZapWalletTxRet;
2231
2232     return DB_LOAD_OK;
2233 }
2234
2235 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2236 {
2237     std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2238     mapAddressBook[address] = strName;
2239     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2240     if (!fFileBacked)
2241         return false;
2242     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2243 }
2244
2245 bool CWallet::DelAddressBookName(const CTxDestination& address)
2246 {
2247     mapAddressBook.erase(address);
2248     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2249     if (!fFileBacked)
2250         return false;
2251     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2252 }
2253
2254
2255 void CWallet::PrintWallet(const CBlock& block)
2256 {
2257     {
2258         LOCK(cs_wallet);
2259         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2260         {
2261             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2262             printf("    PoS: %d  %d  %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2263         }
2264         else if (mapWallet.count(block.vtx[0].GetHash()))
2265         {
2266             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2267             printf("    PoW:  %d  %d  %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2268         }
2269     }
2270     printf("\n");
2271 }
2272
2273 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2274 {
2275     {
2276         LOCK(cs_wallet);
2277         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2278         if (mi != mapWallet.end())
2279         {
2280             wtx = (*mi).second;
2281             return true;
2282         }
2283     }
2284     return false;
2285 }
2286
2287 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2288 {
2289     if (fFileBacked)
2290     {
2291         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2292             return false;
2293     }
2294     vchDefaultKey = vchPubKey;
2295     return true;
2296 }
2297
2298 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2299 {
2300     if (!pwallet->fFileBacked)
2301         return false;
2302     strWalletFileOut = pwallet->strWalletFile;
2303     return true;
2304 }
2305
2306 //
2307 // Mark old keypool keys as used,
2308 // and generate all new keys
2309 //
2310 bool CWallet::NewKeyPool(unsigned int nSize)
2311 {
2312     {
2313         LOCK(cs_wallet);
2314         CWalletDB walletdb(strWalletFile);
2315         BOOST_FOREACH(int64_t nIndex, setKeyPool)
2316             walletdb.ErasePool(nIndex);
2317         setKeyPool.clear();
2318
2319         if (IsLocked())
2320             return false;
2321
2322         uint64_t nKeys;
2323         if (nSize > 0)
2324             nKeys = nSize;
2325         else
2326             nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2327
2328         for (uint64_t i = 0; i < nKeys; i++)
2329         {
2330             uint64_t nIndex = i+1;
2331             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2332             setKeyPool.insert(nIndex);
2333         }
2334         printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2335     }
2336     return true;
2337 }
2338
2339 bool CWallet::TopUpKeyPool(unsigned int nSize)
2340 {
2341     {
2342         LOCK(cs_wallet);
2343
2344         if (IsLocked())
2345             return false;
2346
2347         CWalletDB walletdb(strWalletFile);
2348
2349         // Top up key pool
2350         uint64_t nTargetSize;
2351         if (nSize > 0)
2352             nTargetSize = nSize;
2353         else
2354             nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2355
2356         while (setKeyPool.size() < (nTargetSize + 1))
2357         {
2358             uint64_t nEnd = 1;
2359             if (!setKeyPool.empty())
2360                 nEnd = *(--setKeyPool.end()) + 1;
2361             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2362                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2363             setKeyPool.insert(nEnd);
2364             printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2365         }
2366     }
2367     return true;
2368 }
2369
2370 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2371 {
2372     nIndex = -1;
2373     keypool.vchPubKey = CPubKey();
2374     {
2375         LOCK(cs_wallet);
2376
2377         if (!IsLocked())
2378             TopUpKeyPool();
2379
2380         // Get the oldest key
2381         if(setKeyPool.empty())
2382             return;
2383
2384         CWalletDB walletdb(strWalletFile);
2385
2386         nIndex = *(setKeyPool.begin());
2387         setKeyPool.erase(setKeyPool.begin());
2388         if (!walletdb.ReadPool(nIndex, keypool))
2389             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2390         if (!HaveKey(keypool.vchPubKey.GetID()))
2391             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2392         assert(keypool.vchPubKey.IsValid());
2393         if (fDebug && GetBoolArg("-printkeypool"))
2394             printf("keypool reserve %" PRId64 "\n", nIndex);
2395     }
2396 }
2397
2398 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2399 {
2400     {
2401         LOCK2(cs_main, cs_wallet);
2402         CWalletDB walletdb(strWalletFile);
2403
2404         int64_t nIndex = 1 + *(--setKeyPool.end());
2405         if (!walletdb.WritePool(nIndex, keypool))
2406             throw runtime_error("AddReserveKey() : writing added key failed");
2407         setKeyPool.insert(nIndex);
2408         return nIndex;
2409     }
2410     return -1;
2411 }
2412
2413 void CWallet::KeepKey(int64_t nIndex)
2414 {
2415     // Remove from key pool
2416     if (fFileBacked)
2417     {
2418         CWalletDB walletdb(strWalletFile);
2419         walletdb.ErasePool(nIndex);
2420     }
2421     if(fDebug)
2422         printf("keypool keep %" PRId64 "\n", nIndex);
2423 }
2424
2425 void CWallet::ReturnKey(int64_t nIndex)
2426 {
2427     // Return to key pool
2428     {
2429         LOCK(cs_wallet);
2430         setKeyPool.insert(nIndex);
2431     }
2432     if(fDebug)
2433         printf("keypool return %" PRId64 "\n", nIndex);
2434 }
2435
2436 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2437 {
2438     int64_t nIndex = 0;
2439     CKeyPool keypool;
2440     {
2441         LOCK(cs_wallet);
2442         ReserveKeyFromKeyPool(nIndex, keypool);
2443         if (nIndex == -1)
2444         {
2445             if (fAllowReuse && vchDefaultKey.IsValid())
2446             {
2447                 result = vchDefaultKey;
2448                 return true;
2449             }
2450             if (IsLocked()) return false;
2451             result = GenerateNewKey();
2452             return true;
2453         }
2454         KeepKey(nIndex);
2455         result = keypool.vchPubKey;
2456     }
2457     return true;
2458 }
2459
2460 int64_t CWallet::GetOldestKeyPoolTime()
2461 {
2462     int64_t nIndex = 0;
2463     CKeyPool keypool;
2464     ReserveKeyFromKeyPool(nIndex, keypool);
2465     if (nIndex == -1)
2466         return GetTime();
2467     ReturnKey(nIndex);
2468     return keypool.nTime;
2469 }
2470
2471 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2472 {
2473     map<CTxDestination, int64_t> balances;
2474
2475     {
2476         LOCK(cs_wallet);
2477         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2478         {
2479             CWalletTx *pcoin = &walletEntry.second;
2480
2481             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2482                 continue;
2483
2484             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2485                 continue;
2486
2487             int nDepth = pcoin->GetDepthInMainChain();
2488             if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2489                 continue;
2490
2491             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2492             {
2493                 CTxDestination addr;
2494                 if (!IsMine(pcoin->vout[i]))
2495                     continue;
2496                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2497                     continue;
2498
2499                 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2500
2501                 if (!balances.count(addr))
2502                     balances[addr] = 0;
2503                 balances[addr] += n;
2504             }
2505         }
2506     }
2507
2508     return balances;
2509 }
2510
2511 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2512 {
2513     set< set<CTxDestination> > groupings;
2514     set<CTxDestination> grouping;
2515
2516     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2517     {
2518         CWalletTx *pcoin = &walletEntry.second;
2519
2520         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2521         {
2522             // group all input addresses with each other
2523             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2524             {
2525                 CTxDestination address;
2526                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2527                     continue;
2528                 grouping.insert(address);
2529             }
2530
2531             // group change with input addresses
2532             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2533                 if (IsChange(txout))
2534                 {
2535                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2536                     CTxDestination txoutAddr;
2537                     if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2538                         continue;
2539                     grouping.insert(txoutAddr);
2540                 }
2541             groupings.insert(grouping);
2542             grouping.clear();
2543         }
2544
2545         // group lone addrs by themselves
2546         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2547             if (IsMine(pcoin->vout[i]))
2548             {
2549                 CTxDestination address;
2550                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2551                     continue;
2552                 grouping.insert(address);
2553                 groupings.insert(grouping);
2554                 grouping.clear();
2555             }
2556     }
2557
2558     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2559     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2560     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2561     {
2562         // make a set of all the groups hit by this new group
2563         set< set<CTxDestination>* > hits;
2564         map< CTxDestination, set<CTxDestination>* >::iterator it;
2565         BOOST_FOREACH(CTxDestination address, grouping)
2566             if ((it = setmap.find(address)) != setmap.end())
2567                 hits.insert((*it).second);
2568
2569         // merge all hit groups into a new single group and delete old groups
2570         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2571         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2572         {
2573             merged->insert(hit->begin(), hit->end());
2574             uniqueGroupings.erase(hit);
2575             delete hit;
2576         }
2577         uniqueGroupings.insert(merged);
2578
2579         // update setmap
2580         BOOST_FOREACH(CTxDestination element, *merged)
2581             setmap[element] = merged;
2582     }
2583
2584     set< set<CTxDestination> > ret;
2585     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2586     {
2587         ret.insert(*uniqueGrouping);
2588         delete uniqueGrouping;
2589     }
2590
2591     return ret;
2592 }
2593
2594 // ppcoin: check 'spent' consistency between wallet and txindex
2595 // ppcoin: fix wallet spent state according to txindex
2596 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2597 {
2598     nMismatchFound = 0;
2599     nBalanceInQuestion = 0;
2600
2601     LOCK(cs_wallet);
2602     vector<CWalletTx*> vCoins;
2603     vCoins.reserve(mapWallet.size());
2604     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2605         vCoins.push_back(&(*it).second);
2606
2607     CTxDB txdb("r");
2608     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2609     {
2610         // Find the corresponding transaction index
2611         CTxIndex txindex;
2612         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2613             continue;
2614         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2615         {
2616             if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2617             {
2618                 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
2619                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2620                 nMismatchFound++;
2621                 nBalanceInQuestion += pcoin->vout[n].nValue;
2622                 if (!fCheckOnly)
2623                 {
2624                     pcoin->MarkUnspent(n);
2625                     pcoin->WriteToDisk();
2626                 }
2627             }
2628             else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2629             {
2630                 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
2631                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2632                 nMismatchFound++;
2633                 nBalanceInQuestion += pcoin->vout[n].nValue;
2634                 if (!fCheckOnly)
2635                 {
2636                     pcoin->MarkSpent(n);
2637                     pcoin->WriteToDisk();
2638                 }
2639             }
2640
2641         }
2642
2643         if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2644         {
2645             printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2646             if (!fCheckOnly)
2647             {
2648                 EraseFromWallet(pcoin->GetHash());
2649             }
2650         }
2651     }
2652 }
2653
2654 // ppcoin: disable transaction (only for coinstake)
2655 void CWallet::DisableTransaction(const CTransaction &tx)
2656 {
2657     if (!tx.IsCoinStake() || !IsFromMe(tx))
2658         return; // only disconnecting coinstake requires marking input unspent
2659
2660     LOCK(cs_wallet);
2661     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2662     {
2663         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2664         if (mi != mapWallet.end())
2665         {
2666             CWalletTx& prev = (*mi).second;
2667             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2668             {
2669                 prev.MarkUnspent(txin.prevout.n);
2670                 prev.WriteToDisk();
2671             }
2672         }
2673     }
2674 }
2675
2676 CPubKey CReserveKey::GetReservedKey()
2677 {
2678     if (nIndex == -1)
2679     {
2680         CKeyPool keypool;
2681         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2682         if (nIndex != -1)
2683             vchPubKey = keypool.vchPubKey;
2684         else
2685         {
2686             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2687             vchPubKey = pwallet->vchDefaultKey;
2688         }
2689     }
2690     assert(vchPubKey.IsValid());
2691     return vchPubKey;
2692 }
2693
2694 void CReserveKey::KeepKey()
2695 {
2696     if (nIndex != -1)
2697         pwallet->KeepKey(nIndex);
2698     nIndex = -1;
2699     vchPubKey = CPubKey();
2700 }
2701
2702 void CReserveKey::ReturnKey()
2703 {
2704     if (nIndex != -1)
2705         pwallet->ReturnKey(nIndex);
2706     nIndex = -1;
2707     vchPubKey = CPubKey();
2708 }
2709
2710 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2711 {
2712     setAddress.clear();
2713
2714     CWalletDB walletdb(strWalletFile);
2715
2716     LOCK2(cs_main, cs_wallet);
2717     BOOST_FOREACH(const int64_t& id, setKeyPool)
2718     {
2719         CKeyPool keypool;
2720         if (!walletdb.ReadPool(id, keypool))
2721             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2722         assert(keypool.vchPubKey.IsValid());
2723         CKeyID keyID = keypool.vchPubKey.GetID();
2724         if (!HaveKey(keyID))
2725             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2726         setAddress.insert(keyID);
2727     }
2728 }
2729
2730 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2731 {
2732     {
2733         LOCK(cs_wallet);
2734         // Only notify UI if this transaction is in this wallet
2735         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2736         if (mi != mapWallet.end())
2737         {
2738             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2739             vMintingWalletUpdated.push_back(hashTx);
2740         }
2741     }
2742 }
2743
2744 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2745     mapKeyBirth.clear();
2746
2747     // get birth times for keys with metadata
2748     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2749         if (it->second.nCreateTime)
2750             mapKeyBirth[it->first] = it->second.nCreateTime;
2751
2752     // map in which we'll infer heights of other keys
2753     CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2754     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2755     std::set<CKeyID> setKeys;
2756     GetKeys(setKeys);
2757     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2758         if (mapKeyBirth.count(keyid) == 0)
2759             mapKeyFirstBlock[keyid] = pindexMax;
2760     }
2761     setKeys.clear();
2762
2763     // if there are no such keys, we're done
2764     if (mapKeyFirstBlock.empty())
2765         return;
2766
2767     // find first block that affects those keys, if there are any left
2768     std::vector<CKeyID> vAffected;
2769     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2770         // iterate over all wallet transactions...
2771         const CWalletTx &wtx = (*it).second;
2772         std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2773         if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2774             // ... which are already in a block
2775             int nHeight = blit->second->nHeight;
2776             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2777                 // iterate over all their outputs
2778                 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2779                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2780                     // ... and all their affected keys
2781                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2782                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2783                         rit->second = blit->second;
2784                 }
2785                 vAffected.clear();
2786             }
2787         }
2788     }
2789
2790     // Extract block timestamps for those keys
2791     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2792         mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2793 }
2794
2795 void CWallet::ClearOrphans()
2796 {
2797     list<uint256> orphans;
2798
2799     LOCK(cs_wallet);
2800     for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2801     {
2802         const CWalletTx *wtx = &(*it).second;
2803         if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2804         {
2805             orphans.push_back(wtx->GetHash());
2806         }
2807     }
2808
2809     for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2810         EraseFromWallet(*it);
2811 }
2812
2813 bool CWallet::ExtractAddress(const CScript& scriptPubKey, std::string& addressRet)
2814 {
2815     vector<valtype> vSolutions;
2816     txnouttype whichType;
2817     if (!Solver(scriptPubKey, whichType, vSolutions))
2818         return false;
2819
2820     if (whichType == TX_PUBKEY)
2821     {
2822         addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID()).ToString();
2823         return true;
2824     }
2825     if (whichType == TX_PUBKEY_DROP)
2826     {
2827         // Pay-to-Pubkey-R
2828         CMalleableKeyView view;
2829         if (!CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
2830             return false;
2831
2832         addressRet = CBitcoinAddress(view.GetMalleablePubKey()).ToString();
2833         return true;
2834     }
2835     else if (whichType == TX_PUBKEYHASH)
2836     {
2837         addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0]))).ToString();
2838         return true;
2839     }
2840     else if (whichType == TX_SCRIPTHASH)
2841     {
2842         addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0]))).ToString();
2843         return true;
2844     }
2845     // Multisig txns have more than one address...
2846     return false;
2847 }