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