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