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