7b43f95e54c0c41e52b934bd6e067d6d7b2dff19
[novacoin.git] / src / wallet.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "txdb.h"
7 #include "wallet.h"
8 #include "walletdb.h"
9 #include "crypter.h"
10 #include "ui_interface.h"
11 #include "base58.h"
12 #include "kernel.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <openssl/bio.h>
16
17 #include "main.h"
18
19 using namespace std;
20 extern int64_t nReserveBalance;
21
22 //////////////////////////////////////////////////////////////////////////////
23 //
24 // mapWallet
25 //
26
27 struct CompareValueOnly
28 {
29     bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
30                     const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
31     {
32         return t1.first < t2.first;
33     }
34 };
35
36 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 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
814 {
815     {
816         LOCK(cs_wallet);
817         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
818         if (mi != mapWallet.end())
819         {
820             const CWalletTx& prev = (*mi).second;
821             if (txin.prevout.n < prev.vout.size())
822                 if (IsMine(prev.vout[txin.prevout.n]) & filter)
823                     return prev.vout[txin.prevout.n].nValue;
824         }
825     }
826     return 0;
827 }
828
829 isminetype CWallet::IsMine(const CTxOut& txout) const
830 {
831     return ::IsMine(*this, txout.scriptPubKey);
832 }
833
834 int64_t CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
835 {
836     if (!MoneyRange(txout.nValue))
837         throw std::runtime_error("CWallet::GetCredit() : value out of range");
838     return (IsMine(txout) & filter ? txout.nValue : 0);
839 }
840
841 bool CWallet::IsChange(const CTxOut& txout) const
842 {
843     // TODO: fix handling of 'change' outputs. The assumption is that any
844     // payment to a script that is ours, but isn't in the address book
845     // is change. That assumption is likely to break when we implement multisignature
846     // wallets that return change back into a multi-signature-protected address;
847     // a better way of identifying which outputs are 'the send' and which are
848     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
849     // which output, if any, was change).
850     if (::IsMine(*this, txout.scriptPubKey))
851     {
852         CTxDestination address;
853         if (!ExtractDestination(txout.scriptPubKey, address))
854             return true;
855
856         LOCK(cs_wallet);
857         if (!mapAddressBook.count(address))
858             return true;
859     }
860     return false;
861 }
862
863 int64_t CWallet::GetChange(const CTxOut& txout) const
864 {
865     if (!MoneyRange(txout.nValue))
866         throw std::runtime_error("CWallet::GetChange() : value out of range");
867     return (IsChange(txout) ? txout.nValue : 0);
868 }
869
870 bool CWallet::IsMine(const CTransaction& tx) const
871 {
872     BOOST_FOREACH(const CTxOut& txout, tx.vout)
873         if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
874             return true;
875     return false;
876 }
877
878 bool CWallet::IsFromMe(const CTransaction& tx) const
879 {
880     return (GetDebit(tx, MINE_ALL) > 0);
881 }
882
883 int64_t CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
884 {
885     int64_t nDebit = 0;
886     BOOST_FOREACH(const CTxIn& txin, tx.vin)
887     {
888         nDebit += GetDebit(txin, filter);
889         if (!MoneyRange(nDebit))
890             throw std::runtime_error("CWallet::GetDebit() : value out of range");
891     }
892     return nDebit;
893 }
894
895 int64_t CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
896 {
897     int64_t nCredit = 0;
898     BOOST_FOREACH(const CTxOut& txout, tx.vout)
899     {
900         nCredit += GetCredit(txout, filter);
901         if (!MoneyRange(nCredit))
902             throw std::runtime_error("CWallet::GetCredit() : value out of range");
903     }
904     return nCredit;
905 }
906
907 int64_t CWallet::GetChange(const CTransaction& tx) const
908 {
909     int64_t nChange = 0;
910     BOOST_FOREACH(const CTxOut& txout, tx.vout)
911     {
912         nChange += GetChange(txout);
913         if (!MoneyRange(nChange))
914             throw std::runtime_error("CWallet::GetChange() : value out of range");
915     }
916     return nChange;
917 }
918
919 int64_t CWalletTx::GetTxTime() const
920 {
921     return nTime;
922 }
923
924 int CWalletTx::GetRequestCount() const
925 {
926     // Returns -1 if it wasn't being tracked
927     int nRequests = -1;
928     {
929         LOCK(pwallet->cs_wallet);
930         if (IsCoinBase() || IsCoinStake())
931         {
932             // Generated block
933             if (hashBlock != 0)
934             {
935                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
936                 if (mi != pwallet->mapRequestCount.end())
937                     nRequests = (*mi).second;
938             }
939         }
940         else
941         {
942             // Did anyone request this transaction?
943             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
944             if (mi != pwallet->mapRequestCount.end())
945             {
946                 nRequests = (*mi).second;
947
948                 // How about the block it's in?
949                 if (nRequests == 0 && hashBlock != 0)
950                 {
951                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
952                     if (mi != pwallet->mapRequestCount.end())
953                         nRequests = (*mi).second;
954                     else
955                         nRequests = 1; // If it's in someone else's block it must have got out
956                 }
957             }
958         }
959     }
960     return nRequests;
961 }
962
963 bool CWalletTx::InMempool() const
964 {
965     LOCK(mempool.cs);
966     if (mempool.exists(GetHash())) {
967         return true;
968     }
969     return false;
970 }
971
972 bool CWalletTx::IsTrusted() const
973 {
974     // Quick answer in most cases
975     if (!IsFinal())
976         return false;
977     int nDepth = GetDepthInMainChain();
978     if (nDepth >= 1)
979         return true;
980     if (nDepth < 0)
981         return false;
982     if (!fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
983         return false;
984
985     // Don't trust unconfirmed transactions from us unless they are in the mempool.
986     if (!InMempool())
987         return false;
988
989     // Trusted if all inputs are from us and are in the mempool:
990     BOOST_FOREACH(const CTxIn& txin, vin)
991     {
992         // Transactions not sent by us: not trusted
993         const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
994         if (parent == NULL)
995             return false;
996         const CTxOut& parentOut = parent->vout[txin.prevout.n];
997         if (pwallet->IsMine(parentOut) != MINE_SPENDABLE)
998             return false;
999     }
1000     return true;
1001 }
1002
1003 int64_t CWalletTx::GetDebit(const isminefilter& filter) const
1004 {
1005     if (vin.empty())
1006         return 0;
1007
1008     int64_t nDebit = 0;
1009     if (filter & MINE_SPENDABLE)
1010     {
1011         if (fDebitCached)
1012             nDebit += nDebitCached;
1013         else
1014         {
1015             nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
1016             fDebitCached = true;
1017             nDebit += nDebitCached;
1018         }
1019     }
1020     if (filter & MINE_WATCH_ONLY)
1021     {
1022         if (fWatchDebitCached)
1023             nDebit += nWatchDebitCached;
1024         else
1025         {
1026             nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
1027             fWatchDebitCached = true;
1028             nDebit += nWatchDebitCached;
1029         }
1030     }
1031     return nDebit;
1032 }
1033
1034 int64_t CWalletTx::GetCredit(const isminefilter& filter) const
1035 {
1036     // Must wait until coinbase is safely deep enough in the chain before valuing it
1037     if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1038         return 0;
1039
1040     int64_t credit = 0;
1041     if (filter & MINE_SPENDABLE)
1042     {
1043         // GetBalance can assume transactions in mapWallet won't change
1044         if (fCreditCached)
1045             credit += nCreditCached;
1046         else
1047         {
1048             nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1049             fCreditCached = true;
1050             credit += nCreditCached;
1051         }
1052     }
1053     if (filter & MINE_WATCH_ONLY)
1054     {
1055         if (fWatchCreditCached)
1056             credit += nWatchCreditCached;
1057         else
1058         {
1059             nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1060             fWatchCreditCached = true;
1061             credit += nWatchCreditCached;
1062         }
1063     }
1064     return credit;
1065 }
1066
1067 int64_t CWalletTx::GetImmatureCredit(bool fUseCache) const
1068 {
1069     if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1070     {
1071         if (fUseCache && fImmatureCreditCached)
1072             return nImmatureCreditCached;
1073         nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1074         fImmatureCreditCached = true;
1075         return nImmatureCreditCached;
1076     }
1077
1078     return 0;
1079 }
1080
1081 int64_t CWalletTx::GetImmatureWatchOnlyCredit(bool fUseCache) const
1082 {
1083     if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1084     {
1085         if (fUseCache && fImmatureWatchCreditCached)
1086             return nImmatureWatchCreditCached;
1087         nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1088         fImmatureWatchCreditCached = true;
1089         return nImmatureWatchCreditCached;
1090     }
1091
1092     return 0;
1093 }
1094
1095
1096 int64_t CWalletTx::GetAvailableCredit(bool fUseCache) const
1097 {
1098     // Must wait until coinbase is safely deep enough in the chain before valuing it
1099     if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1100         return 0;
1101
1102     if (fUseCache) {
1103         if (fAvailableCreditCached)
1104             return nAvailableCreditCached;
1105     }
1106
1107     int64_t nCredit = 0;
1108     for (unsigned int i = 0; i < vout.size(); i++)
1109     {
1110         if (!IsSpent(i))
1111         {
1112             const CTxOut &txout = vout[i];
1113             nCredit += pwallet->GetCredit(txout, MINE_SPENDABLE);
1114             if (!MoneyRange(nCredit))
1115                 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1116         }
1117     }
1118
1119     nAvailableCreditCached = nCredit;
1120     fAvailableCreditCached = true;
1121
1122     return nCredit;
1123 }
1124
1125 int64_t CWalletTx::GetAvailableWatchCredit(bool fUseCache) const
1126 {
1127     // Must wait until coinbase is safely deep enough in the chain before valuing it
1128     if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1129         return 0;
1130
1131     if (fUseCache) {
1132         if (fAvailableWatchCreditCached)
1133             return nAvailableWatchCreditCached;
1134     }
1135
1136     int64_t nCredit = 0;
1137     for (unsigned int i = 0; i < vout.size(); i++)
1138     {
1139         if (!IsSpent(i))
1140         {
1141             const CTxOut &txout = vout[i];
1142             nCredit += pwallet->GetCredit(txout, MINE_WATCH_ONLY);
1143             if (!MoneyRange(nCredit))
1144                 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1145         }
1146     }
1147
1148     nAvailableWatchCreditCached = nCredit;
1149     fAvailableWatchCreditCached = true;
1150
1151     return nCredit;
1152 }
1153
1154 int64_t CWalletTx::GetChange() const
1155 {
1156     if (fChangeCached)
1157         return nChangeCached;
1158     nChangeCached = pwallet->GetChange(*this);
1159     fChangeCached = true;
1160     return nChangeCached;
1161 }
1162
1163 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
1164                            list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
1165 {
1166     nGeneratedImmature = nGeneratedMature = nFee = 0;
1167     listReceived.clear();
1168     listSent.clear();
1169     strSentAccount = strFromAccount;
1170
1171     if (IsCoinBase() || IsCoinStake())
1172     {
1173         if (GetBlocksToMaturity() > 0)
1174             nGeneratedImmature = pwallet->GetCredit(*this, filter);
1175         else
1176             nGeneratedMature = GetCredit(filter);
1177         return;
1178     }
1179
1180     // Compute fee:
1181     int64_t nDebit = GetDebit(filter);
1182     if (nDebit > 0) // debit>0 means we signed/sent this transaction
1183     {
1184         int64_t nValueOut = GetValueOut();
1185         nFee = nDebit - nValueOut;
1186     }
1187
1188     // Sent/received.
1189     BOOST_FOREACH(const CTxOut& txout, vout)
1190     {
1191         isminetype fIsMine = pwallet->IsMine(txout);
1192         // Only need to handle txouts if AT LEAST one of these is true:
1193         //   1) they debit from us (sent)
1194         //   2) the output is to us (received)
1195         if (nDebit > 0)
1196         {
1197             // Don't report 'change' txouts
1198             if (pwallet->IsChange(txout))
1199                 continue;
1200         }
1201         else if (!(fIsMine & filter))
1202             continue;
1203
1204         // In either case, we need to get the destination address
1205         CBitcoinAddress address;
1206         if (!ExtractAddress(*pwallet, txout.scriptPubKey, address))
1207         {
1208             printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1209                    this->GetHash().ToString().c_str());
1210             address = CBitcoinAddress();
1211         }
1212
1213         // If we are debited by the transaction, add the output as a "sent" entry
1214         if (nDebit > 0)
1215             listSent.push_back(make_pair(address, txout.nValue));
1216
1217         // If we are receiving the output, add it as a "received" entry
1218         if (fIsMine & filter)
1219             listReceived.push_back(make_pair(address, txout.nValue));
1220     }
1221
1222 }
1223
1224 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
1225                                   int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
1226 {
1227     nGenerated = nReceived = nSent = nFee = 0;
1228
1229     int64_t allGeneratedImmature, allGeneratedMature, allFee;
1230     allGeneratedImmature = allGeneratedMature = allFee = 0;
1231     string strSentAccount;
1232     list<pair<CBitcoinAddress, int64_t> > listReceived;
1233     list<pair<CBitcoinAddress, int64_t> > listSent;
1234     GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
1235
1236     if (strAccount.empty())
1237         nGenerated = allGeneratedMature;
1238     if (strAccount == strSentAccount)
1239     {
1240         BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& s, listSent)
1241             nSent += s.second;
1242         nFee = allFee;
1243     }
1244     {
1245         LOCK(pwallet->cs_wallet);
1246         BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& r, listReceived)
1247         {
1248             if (pwallet->mapAddressBook.count(r.first))
1249             {
1250                 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
1251                 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
1252                     nReceived += r.second;
1253             }
1254             else if (strAccount.empty())
1255             {
1256                 nReceived += r.second;
1257             }
1258         }
1259     }
1260 }
1261
1262 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
1263 {
1264     vtxPrev.clear();
1265
1266     const int COPY_DEPTH = 3;
1267     if (SetMerkleBranch() < COPY_DEPTH)
1268     {
1269         vector<uint256> vWorkQueue;
1270         BOOST_FOREACH(const CTxIn& txin, vin)
1271             vWorkQueue.push_back(txin.prevout.hash);
1272
1273         // This critsect is OK because txdb is already open
1274         {
1275             LOCK(pwallet->cs_wallet);
1276             map<uint256, const CMerkleTx*> mapWalletPrev;
1277             set<uint256> setAlreadyDone;
1278             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1279             {
1280                 uint256 hash = vWorkQueue[i];
1281                 if (setAlreadyDone.count(hash))
1282                     continue;
1283                 setAlreadyDone.insert(hash);
1284
1285                 CMerkleTx tx;
1286                 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
1287                 if (mi != pwallet->mapWallet.end())
1288                 {
1289                     tx = (*mi).second;
1290                     BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
1291                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1292                 }
1293                 else if (mapWalletPrev.count(hash))
1294                 {
1295                     tx = *mapWalletPrev[hash];
1296                 }
1297                 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1298                 {
1299                     ;
1300                 }
1301                 else
1302                 {
1303                     printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1304                     continue;
1305                 }
1306
1307                 int nDepth = tx.SetMerkleBranch();
1308                 vtxPrev.push_back(tx);
1309
1310                 if (nDepth < COPY_DEPTH)
1311                 {
1312                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
1313                         vWorkQueue.push_back(txin.prevout.hash);
1314                 }
1315             }
1316         }
1317     }
1318
1319     reverse(vtxPrev.begin(), vtxPrev.end());
1320 }
1321
1322 bool CWalletTx::WriteToDisk()
1323 {
1324     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1325 }
1326
1327 // Scan the block chain (starting in pindexStart) for transactions
1328 // from or to us. If fUpdate is true, found transactions that already
1329 // exist in the wallet will be updated.
1330 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1331 {
1332     int ret = 0;
1333
1334     CBlockIndex* pindex = pindexStart;
1335     {
1336         LOCK(cs_wallet);
1337         while (pindex)
1338         {
1339             CBlock block;
1340             block.ReadFromDisk(pindex, true);
1341             BOOST_FOREACH(CTransaction& tx, block.vtx)
1342             {
1343                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1344                     ret++;
1345             }
1346             pindex = pindex->pnext;
1347         }
1348     }
1349     return ret;
1350 }
1351
1352 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1353 {
1354     CTransaction tx;
1355     tx.ReadFromDisk(COutPoint(hashTx, 0));
1356     if (AddToWalletIfInvolvingMe(tx, NULL, true))
1357         return 1;
1358     return 0;
1359 }
1360
1361 void CWallet::ReacceptWalletTransactions()
1362 {
1363     CTxDB txdb("r");
1364     bool fRepeat = true;
1365     while (fRepeat)
1366     {
1367         LOCK(cs_wallet);
1368         fRepeat = false;
1369         vector<CDiskTxPos> vMissingTx;
1370         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1371         {
1372             CWalletTx& wtx = item.second;
1373             if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1374                 continue;
1375
1376             CTxIndex txindex;
1377             bool fUpdated = false;
1378             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1379             {
1380                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1381                 if (txindex.vSpent.size() != wtx.vout.size())
1382                 {
1383                     printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1384                     continue;
1385                 }
1386                 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1387                 {
1388                     if (wtx.IsSpent(i))
1389                         continue;
1390                     if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1391                     {
1392                         wtx.MarkSpent(i);
1393                         fUpdated = true;
1394                         vMissingTx.push_back(txindex.vSpent[i]);
1395                     }
1396                 }
1397                 if (fUpdated)
1398                 {
1399                     printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1400                     wtx.MarkDirty();
1401                     wtx.WriteToDisk();
1402                 }
1403             }
1404             else
1405             {
1406                 // Re-accept any txes of ours that aren't already in a block
1407                 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1408                     wtx.AcceptWalletTransaction(txdb, false);
1409             }
1410         }
1411         if (!vMissingTx.empty())
1412         {
1413             // TODO: optimize this to scan just part of the block chain?
1414             if (ScanForWalletTransactions(pindexGenesisBlock))
1415                 fRepeat = true;  // Found missing transactions: re-do re-accept.
1416         }
1417     }
1418 }
1419
1420 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1421 {
1422     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1423     {
1424         if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1425         {
1426             uint256 hash = tx.GetHash();
1427             if (!txdb.ContainsTx(hash))
1428                 RelayTransaction((CTransaction)tx, hash);
1429         }
1430     }
1431     if (!(IsCoinBase() || IsCoinStake()))
1432     {
1433         uint256 hash = GetHash();
1434         if (!txdb.ContainsTx(hash))
1435         {
1436             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1437             RelayTransaction((CTransaction)*this, hash);
1438         }
1439     }
1440 }
1441
1442 void CWalletTx::RelayWalletTransaction()
1443 {
1444    CTxDB txdb("r");
1445    RelayWalletTransaction(txdb);
1446 }
1447
1448 void CWallet::ResendWalletTransactions(bool fForceResend)
1449 {
1450     if (!fForceResend) {
1451         // Do this infrequently and randomly to avoid giving away
1452         // that these are our transactions.
1453         static int64_t nNextTime = GetRand(GetTime() + 30 * 60);
1454         if (GetTime() < nNextTime)
1455             return;
1456         bool fFirst = (nNextTime == 0);
1457         nNextTime = GetTime() + GetRand(30 * 60);
1458         if (fFirst)
1459             return;
1460
1461         // Only do it if there's been a new block since last time
1462         static int64_t nLastTime = 0;
1463         if (nTimeBestReceived < nLastTime)
1464             return;
1465         nLastTime = GetTime();
1466     }
1467
1468     // Rebroadcast any of our txes that aren't in a block yet
1469     printf("ResendWalletTransactions()\n");
1470     CTxDB txdb("r");
1471     {
1472         LOCK(cs_wallet);
1473         // Sort them in chronological order
1474         multimap<unsigned int, CWalletTx*> mapSorted;
1475         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1476         {
1477             CWalletTx& wtx = item.second;
1478             // Don't rebroadcast until it's had plenty of time that
1479             // it should have gotten in already by now.
1480             if (fForceResend || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1481                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1482         }
1483         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1484         {
1485             CWalletTx& wtx = *item.second;
1486             if (wtx.CheckTransaction())
1487                 wtx.RelayWalletTransaction(txdb);
1488             else
1489                 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1490         }
1491     }
1492 }
1493
1494
1495
1496
1497
1498
1499 //////////////////////////////////////////////////////////////////////////////
1500 //
1501 // Actions
1502 //
1503
1504
1505 int64_t CWallet::GetBalance() const
1506 {
1507     int64_t nTotal = 0;
1508     {
1509         LOCK(cs_wallet);
1510         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1511         {
1512             const CWalletTx* pcoin = &(*it).second;
1513             if (pcoin->IsTrusted())
1514                 nTotal += pcoin->GetAvailableCredit();
1515         }
1516     }
1517
1518     return nTotal;
1519 }
1520
1521 int64_t CWallet::GetWatchOnlyBalance() const
1522 {
1523     int64_t nTotal = 0;
1524     {
1525         LOCK(cs_wallet);
1526         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1527         {
1528             const CWalletTx* pcoin = &(*it).second;
1529             if (pcoin->IsTrusted())
1530                 nTotal += pcoin->GetAvailableWatchCredit();
1531         }
1532     }
1533
1534     return nTotal;
1535 }
1536
1537 int64_t CWallet::GetUnconfirmedBalance() const
1538 {
1539     int64_t nTotal = 0;
1540     {
1541         LOCK(cs_wallet);
1542         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1543         {
1544             const CWalletTx* pcoin = &(*it).second;
1545             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1546                 nTotal += pcoin->GetAvailableCredit();
1547         }
1548     }
1549     return nTotal;
1550 }
1551
1552 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1553 {
1554     int64_t nTotal = 0;
1555     {
1556         LOCK(cs_wallet);
1557         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1558         {
1559             const CWalletTx* pcoin = &(*it).second;
1560             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1561                 nTotal += pcoin->GetAvailableWatchCredit();
1562         }
1563     }
1564     return nTotal;
1565 }
1566
1567 int64_t CWallet::GetImmatureBalance() const
1568 {
1569     int64_t nTotal = 0;
1570     {
1571         LOCK(cs_wallet);
1572         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1573         {
1574             const CWalletTx* pcoin = &(*it).second;
1575             nTotal += pcoin->GetImmatureCredit();
1576         }
1577     }
1578     return nTotal;
1579 }
1580
1581 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1582 {
1583     int64_t nTotal = 0;
1584     {
1585         LOCK(cs_wallet);
1586         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1587         {
1588             const CWalletTx* pcoin = &(*it).second;
1589             nTotal += pcoin->GetImmatureWatchOnlyCredit();
1590         }
1591     }
1592     return nTotal;
1593 }
1594
1595 // populate vCoins with vector of spendable COutputs
1596 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1597 {
1598     vCoins.clear();
1599
1600     {
1601         LOCK(cs_wallet);
1602         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1603         {
1604             const CWalletTx* pcoin = &(*it).second;
1605
1606             if (!pcoin->IsFinal())
1607                 continue;
1608
1609             if (fOnlyConfirmed && !pcoin->IsTrusted())
1610                 continue;
1611
1612             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1613                 continue;
1614
1615             if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1616                 continue;
1617
1618             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1619                 isminetype mine = IsMine(pcoin->vout[i]);
1620                 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && 
1621                     pcoin->vout[i].nValue >= nMinimumInputValue &&
1622                     (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1623                 {
1624                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1625                 }
1626             }
1627         }
1628     }
1629 }
1630
1631 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1632 {
1633     vCoins.clear();
1634
1635     {
1636         LOCK(cs_wallet);
1637         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1638         {
1639             const CWalletTx* pcoin = &(*it).second;
1640
1641             if (!pcoin->IsFinal())
1642                 continue;
1643
1644             if(pcoin->GetDepthInMainChain() < nConf)
1645                 continue;
1646
1647             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1648                 isminetype mine = IsMine(pcoin->vout[i]);
1649
1650                 // ignore coin if it was already spent or we don't own it
1651                 if (pcoin->IsSpent(i) || mine == MINE_NO)
1652                     continue;
1653
1654                 // if coin value is between required limits then add new item to vector
1655                 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1656                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1657             }
1658         }
1659     }
1660 }
1661
1662 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1663                                   vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1664 {
1665     vector<char> vfIncluded;
1666
1667     vfBest.assign(vValue.size(), true);
1668     nBest = nTotalLower;
1669
1670     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1671     {
1672         vfIncluded.assign(vValue.size(), false);
1673         int64_t nTotal = 0;
1674         bool fReachedTarget = false;
1675         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1676         {
1677             for (unsigned int i = 0; i < vValue.size(); i++)
1678             {
1679                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1680                 {
1681                     nTotal += vValue[i].first;
1682                     vfIncluded[i] = true;
1683                     if (nTotal >= nTargetValue)
1684                     {
1685                         fReachedTarget = true;
1686                         if (nTotal < nBest)
1687                         {
1688                             nBest = nTotal;
1689                             vfBest = vfIncluded;
1690                         }
1691                         nTotal -= vValue[i].first;
1692                         vfIncluded[i] = false;
1693                     }
1694                 }
1695             }
1696         }
1697     }
1698 }
1699
1700 int64_t CWallet::GetStake() const
1701 {
1702     int64_t nTotal = 0;
1703     LOCK(cs_wallet);
1704     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1705     {
1706         const CWalletTx* pcoin = &(*it).second;
1707         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1708             nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1709     }
1710     return nTotal;
1711 }
1712
1713 int64_t CWallet::GetWatchOnlyStake() const
1714 {
1715     int64_t nTotal = 0;
1716     LOCK(cs_wallet);
1717     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1718     {
1719         const CWalletTx* pcoin = &(*it).second;
1720         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1721             nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1722     }
1723     return nTotal;
1724 }
1725
1726 int64_t CWallet::GetNewMint() const
1727 {
1728     int64_t nTotal = 0;
1729     LOCK(cs_wallet);
1730     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1731     {
1732         const CWalletTx* pcoin = &(*it).second;
1733         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1734             nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1735     }
1736     return nTotal;
1737 }
1738
1739 int64_t CWallet::GetWatchOnlyNewMint() const
1740 {
1741     int64_t nTotal = 0;
1742     LOCK(cs_wallet);
1743     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1744     {
1745         const CWalletTx* pcoin = &(*it).second;
1746         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1747             nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1748     }
1749     return nTotal;
1750 }
1751
1752 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
1753 {
1754     setCoinsRet.clear();
1755     nValueRet = 0;
1756
1757     // List of values less than target
1758     pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1759     coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1760     coinLowestLarger.second.first = NULL;
1761     vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1762     int64_t nTotalLower = 0;
1763
1764     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1765
1766     BOOST_FOREACH(const COutput &output, vCoins)
1767     {
1768         if (!output.fSpendable)
1769             continue;
1770
1771         const CWalletTx *pcoin = output.tx;
1772
1773         if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1774             continue;
1775
1776         int i = output.i;
1777
1778         // Follow the timestamp rules
1779         if (pcoin->nTime > nSpendTime)
1780             continue;
1781
1782         int64_t n = pcoin->vout[i].nValue;
1783
1784         pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1785
1786         if (n == nTargetValue)
1787         {
1788             setCoinsRet.insert(coin.second);
1789             nValueRet += coin.first;
1790             return true;
1791         }
1792         else if (n < nTargetValue + CENT)
1793         {
1794             vValue.push_back(coin);
1795             nTotalLower += n;
1796         }
1797         else if (n < coinLowestLarger.first)
1798         {
1799             coinLowestLarger = coin;
1800         }
1801     }
1802
1803     if (nTotalLower == nTargetValue)
1804     {
1805         for (unsigned int i = 0; i < vValue.size(); ++i)
1806         {
1807             setCoinsRet.insert(vValue[i].second);
1808             nValueRet += vValue[i].first;
1809         }
1810         return true;
1811     }
1812
1813     if (nTotalLower < nTargetValue)
1814     {
1815         if (coinLowestLarger.second.first == NULL)
1816             return false;
1817         setCoinsRet.insert(coinLowestLarger.second);
1818         nValueRet += coinLowestLarger.first;
1819         return true;
1820     }
1821
1822     // Solve subset sum by stochastic approximation
1823     sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1824     vector<char> vfBest;
1825     int64_t nBest;
1826
1827     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1828     if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1829         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1830
1831     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1832     //                                   or the next bigger coin is closer), return the bigger coin
1833     if (coinLowestLarger.second.first &&
1834         ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1835     {
1836         setCoinsRet.insert(coinLowestLarger.second);
1837         nValueRet += coinLowestLarger.first;
1838     }
1839     else {
1840         for (unsigned int i = 0; i < vValue.size(); i++)
1841             if (vfBest[i])
1842             {
1843                 setCoinsRet.insert(vValue[i].second);
1844                 nValueRet += vValue[i].first;
1845             }
1846
1847         if (fDebug && GetBoolArg("-printpriority"))
1848         {
1849             //// debug print
1850             printf("SelectCoins() best subset: ");
1851             for (unsigned int i = 0; i < vValue.size(); i++)
1852                 if (vfBest[i])
1853                     printf("%s ", FormatMoney(vValue[i].first).c_str());
1854             printf("total %s\n", FormatMoney(nBest).c_str());
1855         }
1856     }
1857
1858     return true;
1859 }
1860
1861 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1862 {
1863     vector<COutput> vCoins;
1864     AvailableCoins(vCoins, true, coinControl);
1865
1866     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1867     if (coinControl && coinControl->HasSelected())
1868     {
1869         BOOST_FOREACH(const COutput& out, vCoins)
1870         {
1871             if(!out.fSpendable)
1872                 continue;
1873             nValueRet += out.tx->vout[out.i].nValue;
1874             setCoinsRet.insert(make_pair(out.tx, out.i));
1875         }
1876         return (nValueRet >= nTargetValue);
1877     }
1878
1879     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1880             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1881             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1882 }
1883
1884 // Select some coins without random shuffle or best subset approximation
1885 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
1886 {
1887     vector<COutput> vCoins;
1888     AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1889
1890     setCoinsRet.clear();
1891     nValueRet = 0;
1892
1893     BOOST_FOREACH(COutput output, vCoins)
1894     {
1895         if(!output.fSpendable)
1896             continue;
1897         const CWalletTx *pcoin = output.tx;
1898         int i = output.i;
1899
1900         // Ignore immature coins
1901         if (pcoin->GetBlocksToMaturity() > 0)
1902             continue;
1903
1904         // Stop if we've chosen enough inputs
1905         if (nValueRet >= nTargetValue)
1906             break;
1907
1908         // Follow the timestamp rules
1909         if (pcoin->nTime > nSpendTime)
1910             continue;
1911
1912         int64_t n = pcoin->vout[i].nValue;
1913
1914         pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1915
1916         if (n >= nTargetValue)
1917         {
1918             // If input value is greater or equal to target then simply insert
1919             //    it into the current subset and exit
1920             setCoinsRet.insert(coin.second);
1921             nValueRet += coin.first;
1922             break;
1923         }
1924         else if (n < nTargetValue + CENT)
1925         {
1926             setCoinsRet.insert(coin.second);
1927             nValueRet += coin.first;
1928         }
1929     }
1930
1931     return true;
1932 }
1933
1934 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1935 {
1936     int64_t nValue = 0;
1937     BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1938     {
1939         if (nValue < 0)
1940             return false;
1941         nValue += s.second;
1942     }
1943     if (vecSend.empty() || nValue < 0)
1944         return false;
1945
1946     wtxNew.BindWallet(this);
1947
1948     {
1949         LOCK2(cs_main, cs_wallet);
1950         // txdb must be opened before the mapWallet lock
1951         CTxDB txdb("r");
1952         {
1953             nFeeRet = nTransactionFee;
1954             for ( ; ; )
1955             {
1956                 wtxNew.vin.clear();
1957                 wtxNew.vout.clear();
1958                 wtxNew.fFromMe = true;
1959
1960                 int64_t nTotalValue = nValue + nFeeRet;
1961                 double dPriority = 0;
1962                 // vouts to the payees
1963                 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1964                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1965
1966                 // Choose coins to use
1967                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1968                 int64_t nValueIn = 0;
1969                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1970                     return false;
1971                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1972                 {
1973                     int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1974                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1975                 }
1976
1977                 int64_t nChange = nValueIn - nValue - nFeeRet;
1978                 if (nChange > 0)
1979                 {
1980                     // Fill a vout to ourself
1981                     // TODO: pass in scriptChange instead of reservekey so
1982                     // change transaction isn't always pay-to-bitcoin-address
1983                     CScript scriptChange;
1984
1985                     // coin control: send change to custom address
1986                     if (coinControl && coinControl->destChange.IsValid())
1987                         scriptChange.SetAddress(coinControl->destChange);
1988
1989                     // no coin control: send change to newly generated address
1990                     else
1991                     {
1992                         // Note: We use a new key here to keep it from being obvious which side is the change.
1993                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1994                         //  backup is restored, if the backup doesn't have the new private key for the change.
1995                         //  If we reused the old key, it would be possible to add code to look for and
1996                         //  rediscover unknown transactions that were written with keys of ours to recover
1997                         //  post-backup change.
1998
1999                         // Reserve a new key pair from key pool
2000                         CPubKey vchPubKey = reservekey.GetReservedKey();
2001
2002                         scriptChange.SetDestination(vchPubKey.GetID());
2003                     }
2004
2005                     // Insert change txn at random position:
2006                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
2007                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
2008                 }
2009                 else
2010                     reservekey.ReturnKey();
2011
2012                 // Fill vin
2013                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2014                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
2015
2016                 // Sign
2017                 int nIn = 0;
2018                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2019                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
2020                         return false;
2021
2022                 // Limit size
2023                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
2024                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2025                     return false;
2026                 dPriority /= nBytes;
2027
2028                 // Check that enough fee is included
2029                 bool fAllowFree = CTransaction::AllowFree(dPriority);
2030                 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
2031                 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2032
2033                 if (nFeeRet < max(nPayFee, nMinFee))
2034                 {
2035                     nFeeRet = max(nPayFee, nMinFee);
2036                     continue;
2037                 }
2038
2039                 // Fill vtxPrev by copying from previous transactions vtxPrev
2040                 wtxNew.AddSupportingTransactions(txdb);
2041                 wtxNew.fTimeReceivedIsTxTime = true;
2042
2043                 break;
2044             }
2045         }
2046     }
2047     return true;
2048 }
2049
2050 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2051 {
2052     vector< pair<CScript, int64_t> > vecSend;
2053     vecSend.push_back(make_pair(scriptPubKey, nValue));
2054     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
2055 }
2056
2057 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
2058 {
2059     int64_t nTimeWeight = GetWeight(nTime, GetTime());
2060
2061     // If time weight is lower or equal to zero then weight is zero.
2062     if (nTimeWeight <= 0)
2063     {
2064         nWeight = 0;
2065         return;
2066     }
2067
2068     CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
2069     nWeight = bnCoinDayWeight.getuint64();
2070 }
2071
2072 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
2073 {
2074     int64_t nBalance = GetBalance();
2075
2076     if (nAmount > nBalance)
2077         return false;
2078
2079     listMerged.clear();
2080     int64_t nValueIn = 0;
2081     set<pair<const CWalletTx*,unsigned int> > setCoins;
2082
2083     // Simple coins selection - no randomization
2084     if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
2085         return false;
2086
2087     if (setCoins.empty())
2088         return false;
2089
2090     CWalletTx wtxNew;
2091     vector<const CWalletTx*> vwtxPrev;
2092
2093     // Reserve a new key pair from key pool
2094     CReserveKey reservekey(this);
2095     CPubKey vchPubKey = reservekey.GetReservedKey();
2096
2097     // Output script
2098     CScript scriptOutput;
2099     scriptOutput.SetDestination(vchPubKey.GetID());
2100
2101     // Insert output
2102     wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2103
2104     double dWeight = 0;
2105     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2106     {
2107         int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
2108
2109         // Add current coin to inputs list and add its credit to transaction output
2110         wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2111         wtxNew.vout[0].nValue += nCredit;
2112         vwtxPrev.push_back(pcoin.first);
2113
2114 /*
2115         // Replaced with estimation for performance purposes
2116
2117         for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2118             const CWalletTx *txin = vwtxPrev[i];
2119
2120             // Sign scripts to get actual transaction size for fee calculation
2121             if (!SignSignature(*this, *txin, wtxNew, i))
2122                 return false;
2123         }
2124 */
2125
2126         // Assuming that average scriptsig size is 110 bytes
2127         int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2128         dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
2129
2130         double dFinalPriority = dWeight /= nBytes;
2131         bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2132
2133         // Get actual transaction fee according to its estimated size and priority
2134         int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2135
2136         // Prepare transaction for commit if sum is enough ot its size is too big
2137         if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
2138         {
2139             wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2140
2141             for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2142                 const CWalletTx *txin = vwtxPrev[i];
2143
2144                 // Sign all scripts
2145                 if (!SignSignature(*this, *txin, wtxNew, i))
2146                     return false;
2147             }
2148
2149             // Try to commit, return false on failure
2150             if (!CommitTransaction(wtxNew, reservekey))
2151                 return false;
2152
2153             listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2154
2155             dWeight = 0;  // Reset all temporary values
2156             vwtxPrev.clear();
2157             wtxNew.SetNull();
2158             wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2159         }
2160     }
2161
2162     // Create transactions if there are some unhandled coins left
2163     if (wtxNew.vout[0].nValue > 0) {
2164         int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2165
2166         double dFinalPriority = dWeight /= nBytes;
2167         bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2168
2169         // Get actual transaction fee according to its size and priority
2170         int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2171
2172         wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2173
2174         if (wtxNew.vout[0].nValue <= 0)
2175             return false;
2176
2177         for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2178             const CWalletTx *txin = vwtxPrev[i];
2179
2180             // Sign all scripts again
2181             if (!SignSignature(*this, *txin, wtxNew, i))
2182                 return false;
2183         }
2184
2185         // Try to commit, return false on failure
2186         if (!CommitTransaction(wtxNew, reservekey))
2187             return false;
2188
2189         listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2190     }
2191
2192     return true;
2193 }
2194
2195 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
2196 {
2197     CWalletTx wtx;
2198     if (!GetTransaction(hashTx, wtx))
2199         return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
2200
2201     vector<valtype> vSolutions;
2202     txnouttype whichType;
2203     CScript scriptPubKeyOut;
2204     CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
2205     if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
2206         return error("CreateCoinStake : failed to parse kernel\n");
2207
2208     if (fDebug && GetBoolArg("-printcoinstake"))
2209         printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
2210
2211     if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
2212         return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
2213
2214     if (whichType == TX_PUBKEYHASH) // pay to address type
2215     {
2216         // convert to pay to public key type
2217         if (!GetKey(uint160(vSolutions[0]), key))
2218             return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2219
2220         scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
2221     }
2222     if (whichType == TX_PUBKEY)
2223     {
2224         valtype& vchPubKey = vSolutions[0];
2225         if (!GetKey(Hash160(vchPubKey), key))
2226             return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2227         if (key.GetPubKey() != vchPubKey)
2228             return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
2229         scriptPubKeyOut = scriptPubKeyKernel;
2230     }
2231
2232     // The following combine threshold is important to security
2233     // Should not be adjusted if you don't understand the consequences
2234     int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
2235
2236     int64_t nBalance = GetBalance();
2237     int64_t nCredit = wtx.vout[nOut].nValue;
2238
2239     txNew.vin.clear();
2240     txNew.vout.clear();
2241
2242     // List of constake dependencies
2243     vector<const CWalletTx*> vwtxPrev;
2244     vwtxPrev.push_back(&wtx);
2245
2246     // Set generation time, and kernel input
2247     txNew.nTime = nGenerationTime;
2248     txNew.vin.push_back(CTxIn(hashTx, nOut));
2249
2250     // Mark coin stake transaction with empty vout[0]
2251     CScript scriptEmpty;
2252     scriptEmpty.clear();
2253     txNew.vout.push_back(CTxOut(0, scriptEmpty));
2254
2255     if (fDebug && GetBoolArg("-printcoinstake"))
2256         printf("CreateCoinStake : added kernel type=%d\n", whichType);
2257
2258     int64_t nValueIn = 0;
2259     CoinsSet setCoins;
2260     if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
2261         return false;
2262
2263     if (setCoins.empty())
2264         return false;
2265
2266     bool fDontSplitCoins = false;
2267     if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
2268     {
2269         // Only one output for old kernel inputs
2270         txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2271
2272         // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
2273         //
2274         // * Value is higher than 0.01 NVC;
2275         // * Only add inputs of the same key/address as kernel;
2276         // * Input hash and kernel parent hash should be different.
2277         for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
2278         {
2279             // Stop adding more inputs if already too many inputs
2280             if (txNew.vin.size() >= 100)
2281                 break;
2282             // Stop adding more inputs if value is already pretty significant
2283             if (nCredit > nCombineThreshold)
2284                 break;
2285             // Stop adding inputs if reached reserve limit
2286             if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
2287                 break;
2288
2289             int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
2290
2291             // Do not add input that is still too young
2292             if (nTimeWeight < nStakeMaxAge)
2293                 continue;
2294             // Do not add input if key/address is not the same as kernel
2295             if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2296                 continue;
2297             // Do not add input if parents are the same
2298             if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2299                 continue;
2300             // Do not add additional significant input
2301             if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2302                 continue;
2303
2304             txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2305             nCredit += pcoin->first->vout[pcoin->second].nValue;
2306             vwtxPrev.push_back(pcoin->first);
2307         }
2308
2309         fDontSplitCoins = true;
2310     }
2311     else
2312     {
2313         int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2314
2315         if (fDebug && GetBoolArg("-printcoinstake"))
2316             printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2317
2318         if (nCredit > nSplitThreshold)
2319         {
2320             // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2321             txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2322             txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2323
2324             if (fDebug && GetBoolArg("-printcoinstake"))
2325                 printf("CreateCoinStake : splitting coinstake\n");
2326         }
2327         else
2328         {
2329             txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2330             fDontSplitCoins = true;
2331         }
2332     }
2333
2334     // Calculate coin age reward
2335     uint64_t nCoinAge;
2336     CTxDB txdb("r");
2337     if (!txNew.GetCoinAge(txdb, nCoinAge))
2338         return error("CreateCoinStake : failed to calculate coin age\n");
2339     nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2340
2341     int64_t nMinFee = 0;
2342     for ( ; ; )
2343     {
2344         // Set output amount
2345         if (fDontSplitCoins)
2346             txNew.vout[1].nValue = nCredit - nMinFee;
2347         else
2348         {
2349             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2350             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2351         }
2352
2353         // Sign
2354         int nIn = 0;
2355         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2356         {
2357             if (!SignSignature(*this, *pcoin, txNew, nIn++))
2358                 return error("CreateCoinStake : failed to sign coinstake\n");
2359         }
2360
2361         // Limit size
2362         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2363         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2364             return error("CreateCoinStake : exceeded coinstake size limit\n");
2365
2366         // Check enough fee is paid
2367         if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2368         {
2369             nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2370             continue; // try signing again
2371         }
2372         else
2373         {
2374             if (fDebug && GetBoolArg("-printfee"))
2375                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2376             break;
2377         }
2378     }
2379
2380     // Successfully created coinstake
2381     return true;
2382 }
2383
2384 // Call after CreateTransaction unless you want to abort
2385 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2386 {
2387     {
2388         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2389
2390         // Track how many getdata requests our transaction gets
2391         mapRequestCount[wtxNew.GetHash()] = 0;
2392
2393         // Try to broadcast before saving
2394         if (!wtxNew.AcceptToMemoryPool())
2395         {
2396             // This must not fail. The transaction has already been signed.
2397             printf("CommitTransaction() : Error: Transaction not valid");
2398             return false;
2399         }
2400
2401         wtxNew.RelayWalletTransaction();
2402
2403         {
2404             LOCK2(cs_main, cs_wallet);
2405
2406             // This is only to keep the database open to defeat the auto-flush for the
2407             // duration of this scope.  This is the only place where this optimization
2408             // maybe makes sense; please don't do it anywhere else.
2409             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2410
2411             // Take key pair from key pool so it won't be used again
2412             reservekey.KeepKey();
2413
2414             // Add tx to wallet, because if it has change it's also ours,
2415             // otherwise just for transaction history.
2416             AddToWallet(wtxNew);
2417
2418             // Mark old coins as spent
2419             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2420             {
2421                 CWalletTx &coin = mapWallet[txin.prevout.hash];
2422                 coin.BindWallet(this);
2423                 coin.MarkSpent(txin.prevout.n);
2424                 coin.WriteToDisk();
2425                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2426                 vMintingWalletUpdated.push_back(coin.GetHash());
2427             }
2428
2429             if (fFileBacked)
2430                 delete pwalletdb;
2431         }
2432     }
2433     return true;
2434 }
2435
2436
2437
2438
2439 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2440 {
2441     // Check amount
2442     if (nValue <= 0)
2443         return _("Invalid amount");
2444     if (nValue + nTransactionFee > GetBalance())
2445         return _("Insufficient funds");
2446
2447     CReserveKey reservekey(this);
2448     int64_t nFeeRequired;
2449
2450     if (IsLocked())
2451     {
2452         string strError = _("Error: Wallet locked, unable to create transaction  ");
2453         printf("SendMoney() : %s", strError.c_str());
2454         return strError;
2455     }
2456     if (fWalletUnlockMintOnly)
2457     {
2458         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2459         printf("SendMoney() : %s", strError.c_str());
2460         return strError;
2461     }
2462     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2463     {
2464         string strError;
2465         if (nValue + nFeeRequired > GetBalance())
2466             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());
2467         else
2468             strError = _("Error: Transaction creation failed  ");
2469         printf("SendMoney() : %s", strError.c_str());
2470         return strError;
2471     }
2472
2473     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2474         return "ABORTED";
2475
2476     if (!CommitTransaction(wtxNew, reservekey))
2477         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.");
2478
2479     return "";
2480 }
2481
2482 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2483 {
2484     if (!fFileBacked)
2485         return DB_LOAD_OK;
2486     fFirstRunRet = false;
2487     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2488     if (nLoadWalletRet == DB_NEED_REWRITE)
2489     {
2490         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2491         {
2492             setKeyPool.clear();
2493             // Note: can't top-up keypool here, because wallet is locked.
2494             // User will be prompted to unlock wallet the next operation
2495             // the requires a new key.
2496         }
2497     }
2498
2499     if (nLoadWalletRet != DB_LOAD_OK)
2500         return nLoadWalletRet;
2501     fFirstRunRet = !vchDefaultKey.IsValid();
2502
2503     NewThread(ThreadFlushWalletDB, &strWalletFile);
2504     return DB_LOAD_OK;
2505 }
2506
2507 DBErrors CWallet::ZapWalletTx()
2508 {
2509     if (!fFileBacked)
2510         return DB_LOAD_OK;
2511     DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2512     if (nZapWalletTxRet == DB_NEED_REWRITE)
2513     {
2514         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2515         {
2516             LOCK(cs_wallet);
2517             setKeyPool.clear();
2518             // Note: can't top-up keypool here, because wallet is locked.
2519             // User will be prompted to unlock wallet the next operation
2520             // the requires a new key.
2521         }
2522     }
2523
2524     if (nZapWalletTxRet != DB_LOAD_OK)
2525         return nZapWalletTxRet;
2526
2527     return DB_LOAD_OK;
2528 }
2529
2530 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2531 {
2532     return SetAddressBookName(CBitcoinAddress(address), strName);
2533 }
2534
2535 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
2536 {
2537     std::map<CBitcoinAddress, string>::iterator mi = mapAddressBook.find(address);
2538     mapAddressBook[address] = strName;
2539     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2540     if (!fFileBacked)
2541         return false;
2542     return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
2543 }
2544
2545 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
2546 {
2547     mapAddressBook.erase(address);
2548     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2549     if (!fFileBacked)
2550         return false;
2551     return CWalletDB(strWalletFile).EraseName(address.ToString());
2552 }
2553
2554
2555 void CWallet::PrintWallet(const CBlock& block)
2556 {
2557     {
2558         LOCK(cs_wallet);
2559         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2560         {
2561             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2562             printf("    PoS: %d  %d  %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2563         }
2564         else if (mapWallet.count(block.vtx[0].GetHash()))
2565         {
2566             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2567             printf("    PoW:  %d  %d  %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2568         }
2569     }
2570     printf("\n");
2571 }
2572
2573 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2574 {
2575     {
2576         LOCK(cs_wallet);
2577         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2578         if (mi != mapWallet.end())
2579         {
2580             wtx = (*mi).second;
2581             return true;
2582         }
2583     }
2584     return false;
2585 }
2586
2587 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2588 {
2589     if (fFileBacked)
2590     {
2591         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2592             return false;
2593     }
2594     vchDefaultKey = vchPubKey;
2595     return true;
2596 }
2597
2598 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2599 {
2600     if (!pwallet->fFileBacked)
2601         return false;
2602     strWalletFileOut = pwallet->strWalletFile;
2603     return true;
2604 }
2605
2606 //
2607 // Mark old keypool keys as used,
2608 // and generate all new keys
2609 //
2610 bool CWallet::NewKeyPool(unsigned int nSize)
2611 {
2612     {
2613         LOCK(cs_wallet);
2614         CWalletDB walletdb(strWalletFile);
2615         BOOST_FOREACH(int64_t nIndex, setKeyPool)
2616             walletdb.ErasePool(nIndex);
2617         setKeyPool.clear();
2618
2619         if (IsLocked())
2620             return false;
2621
2622         uint64_t nKeys;
2623         if (nSize > 0)
2624             nKeys = nSize;
2625         else
2626             nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2627
2628         for (uint64_t i = 0; i < nKeys; i++)
2629         {
2630             uint64_t nIndex = i+1;
2631             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2632             setKeyPool.insert(nIndex);
2633         }
2634         printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2635     }
2636     return true;
2637 }
2638
2639 bool CWallet::TopUpKeyPool(unsigned int nSize)
2640 {
2641     {
2642         LOCK(cs_wallet);
2643
2644         if (IsLocked())
2645             return false;
2646
2647         CWalletDB walletdb(strWalletFile);
2648
2649         // Top up key pool
2650         uint64_t nTargetSize;
2651         if (nSize > 0)
2652             nTargetSize = nSize;
2653         else
2654             nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2655
2656         while (setKeyPool.size() < (nTargetSize + 1))
2657         {
2658             uint64_t nEnd = 1;
2659             if (!setKeyPool.empty())
2660                 nEnd = *(--setKeyPool.end()) + 1;
2661             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2662                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2663             setKeyPool.insert(nEnd);
2664             printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2665         }
2666     }
2667     return true;
2668 }
2669
2670 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2671 {
2672     nIndex = -1;
2673     keypool.vchPubKey = CPubKey();
2674     {
2675         LOCK(cs_wallet);
2676
2677         if (!IsLocked())
2678             TopUpKeyPool();
2679
2680         // Get the oldest key
2681         if(setKeyPool.empty())
2682             return;
2683
2684         CWalletDB walletdb(strWalletFile);
2685
2686         nIndex = *(setKeyPool.begin());
2687         setKeyPool.erase(setKeyPool.begin());
2688         if (!walletdb.ReadPool(nIndex, keypool))
2689             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2690         if (!HaveKey(keypool.vchPubKey.GetID()))
2691             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2692         assert(keypool.vchPubKey.IsValid());
2693         if (fDebug && GetBoolArg("-printkeypool"))
2694             printf("keypool reserve %" PRId64 "\n", nIndex);
2695     }
2696 }
2697
2698 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2699 {
2700     {
2701         LOCK2(cs_main, cs_wallet);
2702         CWalletDB walletdb(strWalletFile);
2703
2704         int64_t nIndex = 1 + *(--setKeyPool.end());
2705         if (!walletdb.WritePool(nIndex, keypool))
2706             throw runtime_error("AddReserveKey() : writing added key failed");
2707         setKeyPool.insert(nIndex);
2708         return nIndex;
2709     }
2710     return -1;
2711 }
2712
2713 void CWallet::KeepKey(int64_t nIndex)
2714 {
2715     // Remove from key pool
2716     if (fFileBacked)
2717     {
2718         CWalletDB walletdb(strWalletFile);
2719         walletdb.ErasePool(nIndex);
2720     }
2721     if(fDebug)
2722         printf("keypool keep %" PRId64 "\n", nIndex);
2723 }
2724
2725 void CWallet::ReturnKey(int64_t nIndex)
2726 {
2727     // Return to key pool
2728     {
2729         LOCK(cs_wallet);
2730         setKeyPool.insert(nIndex);
2731     }
2732     if(fDebug)
2733         printf("keypool return %" PRId64 "\n", nIndex);
2734 }
2735
2736 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2737 {
2738     int64_t nIndex = 0;
2739     CKeyPool keypool;
2740     {
2741         LOCK(cs_wallet);
2742         ReserveKeyFromKeyPool(nIndex, keypool);
2743         if (nIndex == -1)
2744         {
2745             if (fAllowReuse && vchDefaultKey.IsValid())
2746             {
2747                 result = vchDefaultKey;
2748                 return true;
2749             }
2750             if (IsLocked()) return false;
2751             result = GenerateNewKey();
2752             return true;
2753         }
2754         KeepKey(nIndex);
2755         result = keypool.vchPubKey;
2756     }
2757     return true;
2758 }
2759
2760 int64_t CWallet::GetOldestKeyPoolTime()
2761 {
2762     int64_t nIndex = 0;
2763     CKeyPool keypool;
2764     ReserveKeyFromKeyPool(nIndex, keypool);
2765     if (nIndex == -1)
2766         return GetTime();
2767     ReturnKey(nIndex);
2768     return keypool.nTime;
2769 }
2770
2771 std::map<CBitcoinAddress, int64_t> CWallet::GetAddressBalances()
2772 {
2773     map<CBitcoinAddress, int64_t> balances;
2774
2775     {
2776         LOCK(cs_wallet);
2777         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2778         {
2779             CWalletTx *pcoin = &walletEntry.second;
2780
2781             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2782                 continue;
2783
2784             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2785                 continue;
2786
2787             int nDepth = pcoin->GetDepthInMainChain();
2788             if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2789                 continue;
2790
2791             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2792             {
2793                 CBitcoinAddress addr;
2794                 if (!IsMine(pcoin->vout[i]))
2795                     continue;
2796                 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, addr))
2797                     continue;
2798
2799                 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2800
2801                 if (!balances.count(addr))
2802                     balances[addr] = 0;
2803                 balances[addr] += n;
2804             }
2805         }
2806     }
2807
2808     return balances;
2809 }
2810
2811 set< set<CBitcoinAddress> > CWallet::GetAddressGroupings()
2812 {
2813     set< set<CBitcoinAddress> > groupings;
2814     set<CBitcoinAddress> grouping;
2815
2816     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2817     {
2818         CWalletTx *pcoin = &walletEntry.second;
2819
2820         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2821         {
2822             // group all input addresses with each other
2823             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2824             {
2825                 CBitcoinAddress address;
2826                 if(!ExtractAddress(*this, mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2827                     continue;
2828                 grouping.insert(address);
2829             }
2830
2831             // group change with input addresses
2832             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2833                 if (IsChange(txout))
2834                 {
2835                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2836                     CBitcoinAddress txoutAddr;
2837                     if(!ExtractAddress(*this, txout.scriptPubKey, txoutAddr))
2838                         continue;
2839                     grouping.insert(txoutAddr);
2840                 }
2841             groupings.insert(grouping);
2842             grouping.clear();
2843         }
2844
2845         // group lone addrs by themselves
2846         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2847             if (IsMine(pcoin->vout[i]))
2848             {
2849                 CBitcoinAddress address;
2850                 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, address))
2851                     continue;
2852                 grouping.insert(address);
2853                 groupings.insert(grouping);
2854                 grouping.clear();
2855             }
2856     }
2857
2858     set< set<CBitcoinAddress>* > uniqueGroupings; // a set of pointers to groups of addresses
2859     map< CBitcoinAddress, set<CBitcoinAddress>* > setmap;  // map addresses to the unique group containing it
2860     BOOST_FOREACH(set<CBitcoinAddress> grouping, groupings)
2861     {
2862         // make a set of all the groups hit by this new group
2863         set< set<CBitcoinAddress>* > hits;
2864         map< CBitcoinAddress, set<CBitcoinAddress>* >::iterator it;
2865         BOOST_FOREACH(CBitcoinAddress address, grouping)
2866             if ((it = setmap.find(address)) != setmap.end())
2867                 hits.insert((*it).second);
2868
2869         // merge all hit groups into a new single group and delete old groups
2870         set<CBitcoinAddress>* merged = new set<CBitcoinAddress>(grouping);
2871         BOOST_FOREACH(set<CBitcoinAddress>* hit, hits)
2872         {
2873             merged->insert(hit->begin(), hit->end());
2874             uniqueGroupings.erase(hit);
2875             delete hit;
2876         }
2877         uniqueGroupings.insert(merged);
2878
2879         // update setmap
2880         BOOST_FOREACH(CBitcoinAddress element, *merged)
2881             setmap[element] = merged;
2882     }
2883
2884     set< set<CBitcoinAddress> > ret;
2885     BOOST_FOREACH(set<CBitcoinAddress>* uniqueGrouping, uniqueGroupings)
2886     {
2887         ret.insert(*uniqueGrouping);
2888         delete uniqueGrouping;
2889     }
2890
2891     return ret;
2892 }
2893
2894 // ppcoin: check 'spent' consistency between wallet and txindex
2895 // ppcoin: fix wallet spent state according to txindex
2896 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2897 {
2898     nMismatchFound = 0;
2899     nBalanceInQuestion = 0;
2900
2901     LOCK(cs_wallet);
2902     vector<CWalletTx*> vCoins;
2903     vCoins.reserve(mapWallet.size());
2904     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2905         vCoins.push_back(&(*it).second);
2906
2907     CTxDB txdb("r");
2908     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2909     {
2910         // Find the corresponding transaction index
2911         CTxIndex txindex;
2912         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2913             continue;
2914         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2915         {
2916             if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2917             {
2918                 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
2919                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2920                 nMismatchFound++;
2921                 nBalanceInQuestion += pcoin->vout[n].nValue;
2922                 if (!fCheckOnly)
2923                 {
2924                     pcoin->MarkUnspent(n);
2925                     pcoin->WriteToDisk();
2926                 }
2927             }
2928             else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2929             {
2930                 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
2931                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2932                 nMismatchFound++;
2933                 nBalanceInQuestion += pcoin->vout[n].nValue;
2934                 if (!fCheckOnly)
2935                 {
2936                     pcoin->MarkSpent(n);
2937                     pcoin->WriteToDisk();
2938                 }
2939             }
2940
2941         }
2942
2943         if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2944         {
2945             printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2946             if (!fCheckOnly)
2947             {
2948                 EraseFromWallet(pcoin->GetHash());
2949             }
2950         }
2951     }
2952 }
2953
2954 // ppcoin: disable transaction (only for coinstake)
2955 void CWallet::DisableTransaction(const CTransaction &tx)
2956 {
2957     if (!tx.IsCoinStake() || !IsFromMe(tx))
2958         return; // only disconnecting coinstake requires marking input unspent
2959
2960     LOCK(cs_wallet);
2961     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2962     {
2963         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2964         if (mi != mapWallet.end())
2965         {
2966             CWalletTx& prev = (*mi).second;
2967             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2968             {
2969                 prev.MarkUnspent(txin.prevout.n);
2970                 prev.WriteToDisk();
2971             }
2972         }
2973     }
2974 }
2975
2976 CPubKey CReserveKey::GetReservedKey()
2977 {
2978     if (nIndex == -1)
2979     {
2980         CKeyPool keypool;
2981         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2982         if (nIndex != -1)
2983             vchPubKey = keypool.vchPubKey;
2984         else
2985         {
2986             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2987             vchPubKey = pwallet->vchDefaultKey;
2988         }
2989     }
2990     assert(vchPubKey.IsValid());
2991     return vchPubKey;
2992 }
2993
2994 void CReserveKey::KeepKey()
2995 {
2996     if (nIndex != -1)
2997         pwallet->KeepKey(nIndex);
2998     nIndex = -1;
2999     vchPubKey = CPubKey();
3000 }
3001
3002 void CReserveKey::ReturnKey()
3003 {
3004     if (nIndex != -1)
3005         pwallet->ReturnKey(nIndex);
3006     nIndex = -1;
3007     vchPubKey = CPubKey();
3008 }
3009
3010 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3011 {
3012     setAddress.clear();
3013
3014     CWalletDB walletdb(strWalletFile);
3015
3016     LOCK2(cs_main, cs_wallet);
3017     BOOST_FOREACH(const int64_t& id, setKeyPool)
3018     {
3019         CKeyPool keypool;
3020         if (!walletdb.ReadPool(id, keypool))
3021             throw runtime_error("GetAllReserveKeyHashes() : read failed");
3022         assert(keypool.vchPubKey.IsValid());
3023         CKeyID keyID = keypool.vchPubKey.GetID();
3024         if (!HaveKey(keyID))
3025             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
3026         setAddress.insert(keyID);
3027     }
3028 }
3029
3030 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3031 {
3032     {
3033         LOCK(cs_wallet);
3034         // Only notify UI if this transaction is in this wallet
3035         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3036         if (mi != mapWallet.end())
3037         {
3038             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3039             vMintingWalletUpdated.push_back(hashTx);
3040         }
3041     }
3042 }
3043
3044 void CWallet::GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const {
3045     mapAddresses.clear();
3046
3047     // get birth times for keys with metadata
3048     for (std::map<CBitcoinAddress, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
3049         mapAddresses[it->first] = it->second.nCreateTime ? it->second.nCreateTime : 0;
3050     }
3051
3052     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3053         // iterate over all wallet transactions...
3054         const CWalletTx &wtx = (*it).second;
3055         if (wtx.hashBlock == 0)
3056             continue; // skip unconfirmed transactions
3057
3058         for(std::vector<CTxOut>::const_iterator it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
3059             const CTxOut &out = (*it2);
3060             // iterate over all their outputs
3061             CBitcoinAddress addressRet;
3062             if (ExtractAddress(*this, out.scriptPubKey, addressRet)) {
3063                 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
3064                     mapAddresses[addressRet] = wtx.nTime;
3065             }
3066             else {
3067                 // multisig output affects more than one key
3068                 std::vector<CKeyID> vAffected;
3069                 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
3070
3071                 for(std::vector<CKeyID>::const_iterator it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
3072                     CBitcoinAddress addrAffected(*it3);
3073                     if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
3074                         mapAddresses[addrAffected] = wtx.nTime;
3075                 }
3076                 vAffected.clear();
3077             }
3078         }
3079     }
3080 }
3081
3082 void CWallet::ClearOrphans()
3083 {
3084     list<uint256> orphans;
3085
3086     LOCK(cs_wallet);
3087     for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3088     {
3089         const CWalletTx *wtx = &(*it).second;
3090         if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
3091         {
3092             orphans.push_back(wtx->GetHash());
3093         }
3094     }
3095
3096     for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
3097         EraseFromWallet(*it);
3098 }
3099