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