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