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