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