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