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