]> Git Repo - VerusCoin.git/blob - src/wallet/wallet.cpp
Auto merge of #3098 - str4d:2343-overwinter-disable-mempooltxinputlimit, r=str4d
[VerusCoin.git] / src / wallet / wallet.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "wallet/wallet.h"
7
8 #include "base58.h"
9 #include "checkpoints.h"
10 #include "coincontrol.h"
11 #include "consensus/upgrades.h"
12 #include "consensus/validation.h"
13 #include "consensus/consensus.h"
14 #include "init.h"
15 #include "main.h"
16 #include "net.h"
17 #include "script/script.h"
18 #include "script/sign.h"
19 #include "timedata.h"
20 #include "utilmoneystr.h"
21 #include "zcash/Note.hpp"
22 #include "crypter.h"
23
24 #include <assert.h>
25
26 #include <boost/algorithm/string/replace.hpp>
27 #include <boost/filesystem.hpp>
28 #include <boost/thread.hpp>
29
30 using namespace std;
31 using namespace libzcash;
32
33 /**
34  * Settings
35  */
36 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
37 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
38 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
39 bool bSpendZeroConfChange = true;
40 bool fSendFreeTransactions = false;
41 bool fPayAtLeastCustomFee = true;
42
43 /**
44  * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
45  * Override with -mintxfee
46  */
47 CFeeRate CWallet::minTxFee = CFeeRate(1000);
48
49 /** @defgroup mapWallet
50  *
51  * @{
52  */
53
54 struct CompareValueOnly
55 {
56     bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
57                     const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
58     {
59         return t1.first < t2.first;
60     }
61 };
62
63 std::string JSOutPoint::ToString() const
64 {
65     return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
66 }
67
68 std::string COutput::ToString() const
69 {
70     return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
71 }
72
73 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
74 {
75     LOCK(cs_wallet);
76     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
77     if (it == mapWallet.end())
78         return NULL;
79     return &(it->second);
80 }
81
82 // Generate a new spending key and return its public payment address
83 CZCPaymentAddress CWallet::GenerateNewZKey()
84 {
85     AssertLockHeld(cs_wallet); // mapZKeyMetadata
86     auto k = SpendingKey::random();
87     auto addr = k.address();
88
89     // Check for collision, even though it is unlikely to ever occur
90     if (CCryptoKeyStore::HaveSpendingKey(addr))
91         throw std::runtime_error("CWallet::GenerateNewZKey(): Collision detected");
92
93     // Create new metadata
94     int64_t nCreationTime = GetTime();
95     mapZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
96
97     CZCPaymentAddress pubaddr(addr);
98     if (!AddZKey(k))
99         throw std::runtime_error("CWallet::GenerateNewZKey(): AddZKey failed");
100     return pubaddr;
101 }
102
103 // Add spending key to keystore and persist to disk
104 bool CWallet::AddZKey(const libzcash::SpendingKey &key)
105 {
106     AssertLockHeld(cs_wallet); // mapZKeyMetadata
107     auto addr = key.address();
108
109     if (!CCryptoKeyStore::AddSpendingKey(key))
110         return false;
111
112     // check if we need to remove from viewing keys
113     if (HaveViewingKey(addr))
114         RemoveViewingKey(key.viewing_key());
115
116     if (!fFileBacked)
117         return true;
118
119     if (!IsCrypted()) {
120         return CWalletDB(strWalletFile).WriteZKey(addr,
121                                                   key,
122                                                   mapZKeyMetadata[addr]);
123     }
124     return true;
125 }
126
127 CPubKey CWallet::GenerateNewKey()
128 {
129     AssertLockHeld(cs_wallet); // mapKeyMetadata
130     bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
131
132     CKey secret;
133     secret.MakeNewKey(fCompressed);
134
135     // Compressed public keys were introduced in version 0.6.0
136     if (fCompressed)
137         SetMinVersion(FEATURE_COMPRPUBKEY);
138
139     CPubKey pubkey = secret.GetPubKey();
140     assert(secret.VerifyPubKey(pubkey));
141
142     // Create new metadata
143     int64_t nCreationTime = GetTime();
144     mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
145     if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
146         nTimeFirstKey = nCreationTime;
147
148     if (!AddKeyPubKey(secret, pubkey))
149         throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
150     return pubkey;
151 }
152
153 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
154 {
155     AssertLockHeld(cs_wallet); // mapKeyMetadata
156     if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
157         return false;
158
159     // check if we need to remove from watch-only
160     CScript script;
161     script = GetScriptForDestination(pubkey.GetID());
162     if (HaveWatchOnly(script))
163         RemoveWatchOnly(script);
164
165     if (!fFileBacked)
166         return true;
167     if (!IsCrypted()) {
168         return CWalletDB(strWalletFile).WriteKey(pubkey,
169                                                  secret.GetPrivKey(),
170                                                  mapKeyMetadata[pubkey.GetID()]);
171     }
172     return true;
173 }
174
175 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
176                             const vector<unsigned char> &vchCryptedSecret)
177 {
178     
179     if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
180         return false;
181     if (!fFileBacked)
182         return true;
183     {
184         LOCK(cs_wallet);
185         if (pwalletdbEncryption)
186             return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
187                                                         vchCryptedSecret,
188                                                         mapKeyMetadata[vchPubKey.GetID()]);
189         else
190             return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
191                                                             vchCryptedSecret,
192                                                             mapKeyMetadata[vchPubKey.GetID()]);
193     }
194     return false;
195 }
196
197
198 bool CWallet::AddCryptedSpendingKey(const libzcash::PaymentAddress &address,
199                                     const libzcash::ReceivingKey &rk,
200                                     const std::vector<unsigned char> &vchCryptedSecret)
201 {
202     if (!CCryptoKeyStore::AddCryptedSpendingKey(address, rk, vchCryptedSecret))
203         return false;
204     if (!fFileBacked)
205         return true;
206     {
207         LOCK(cs_wallet);
208         if (pwalletdbEncryption) {
209             return pwalletdbEncryption->WriteCryptedZKey(address,
210                                                          rk,
211                                                          vchCryptedSecret,
212                                                          mapZKeyMetadata[address]);
213         } else {
214             return CWalletDB(strWalletFile).WriteCryptedZKey(address,
215                                                              rk,
216                                                              vchCryptedSecret,
217                                                              mapZKeyMetadata[address]);
218         }
219     }
220     return false;
221 }
222
223 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
224 {
225     AssertLockHeld(cs_wallet); // mapKeyMetadata
226     if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
227         nTimeFirstKey = meta.nCreateTime;
228
229     mapKeyMetadata[pubkey.GetID()] = meta;
230     return true;
231 }
232
233 bool CWallet::LoadZKeyMetadata(const PaymentAddress &addr, const CKeyMetadata &meta)
234 {
235     AssertLockHeld(cs_wallet); // mapZKeyMetadata
236     mapZKeyMetadata[addr] = meta;
237     return true;
238 }
239
240 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
241 {
242     return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
243 }
244
245 bool CWallet::LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret)
246 {
247     return CCryptoKeyStore::AddCryptedSpendingKey(addr, rk, vchCryptedSecret);
248 }
249
250 bool CWallet::LoadZKey(const libzcash::SpendingKey &key)
251 {
252     return CCryptoKeyStore::AddSpendingKey(key);
253 }
254
255 bool CWallet::AddViewingKey(const libzcash::ViewingKey &vk)
256 {
257     if (!CCryptoKeyStore::AddViewingKey(vk)) {
258         return false;
259     }
260     nTimeFirstKey = 1; // No birthday information for viewing keys.
261     if (!fFileBacked) {
262         return true;
263     }
264     return CWalletDB(strWalletFile).WriteViewingKey(vk);
265 }
266
267 bool CWallet::RemoveViewingKey(const libzcash::ViewingKey &vk)
268 {
269     AssertLockHeld(cs_wallet);
270     if (!CCryptoKeyStore::RemoveViewingKey(vk)) {
271         return false;
272     }
273     if (fFileBacked) {
274         if (!CWalletDB(strWalletFile).EraseViewingKey(vk)) {
275             return false;
276         }
277     }
278
279     return true;
280 }
281
282 bool CWallet::LoadViewingKey(const libzcash::ViewingKey &vk)
283 {
284     return CCryptoKeyStore::AddViewingKey(vk);
285 }
286
287 bool CWallet::AddCScript(const CScript& redeemScript)
288 {
289     if (!CCryptoKeyStore::AddCScript(redeemScript))
290         return false;
291     if (!fFileBacked)
292         return true;
293     return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
294 }
295
296 bool CWallet::LoadCScript(const CScript& redeemScript)
297 {
298     /* A sanity check was added in pull #3843 to avoid adding redeemScripts
299      * that never can be redeemed. However, old wallets may still contain
300      * these. Do not add them to the wallet and warn. */
301     if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
302     {
303         std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
304         LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
305             __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
306         return true;
307     }
308
309     return CCryptoKeyStore::AddCScript(redeemScript);
310 }
311
312 bool CWallet::AddWatchOnly(const CScript &dest)
313 {
314     if (!CCryptoKeyStore::AddWatchOnly(dest))
315         return false;
316     nTimeFirstKey = 1; // No birthday information for watch-only keys.
317     NotifyWatchonlyChanged(true);
318     if (!fFileBacked)
319         return true;
320     return CWalletDB(strWalletFile).WriteWatchOnly(dest);
321 }
322
323 bool CWallet::RemoveWatchOnly(const CScript &dest)
324 {
325     AssertLockHeld(cs_wallet);
326     if (!CCryptoKeyStore::RemoveWatchOnly(dest))
327         return false;
328     if (!HaveWatchOnly())
329         NotifyWatchonlyChanged(false);
330     if (fFileBacked)
331         if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
332             return false;
333
334     return true;
335 }
336
337 bool CWallet::LoadWatchOnly(const CScript &dest)
338 {
339     return CCryptoKeyStore::AddWatchOnly(dest);
340 }
341
342 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
343 {
344     CCrypter crypter;
345     CKeyingMaterial vMasterKey;
346
347     {
348         LOCK(cs_wallet);
349         BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
350         {
351             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
352                 return false;
353             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
354                 continue; // try another master key
355             if (CCryptoKeyStore::Unlock(vMasterKey))
356                 return true;
357         }
358     }
359     return false;
360 }
361
362 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
363 {
364     bool fWasLocked = IsLocked();
365
366     {
367         LOCK(cs_wallet);
368         Lock();
369
370         CCrypter crypter;
371         CKeyingMaterial vMasterKey;
372         BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
373         {
374             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
375                 return false;
376             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
377                 return false;
378             if (CCryptoKeyStore::Unlock(vMasterKey))
379             {
380                 int64_t nStartTime = GetTimeMillis();
381                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
382                 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
383
384                 nStartTime = GetTimeMillis();
385                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
386                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
387
388                 if (pMasterKey.second.nDeriveIterations < 25000)
389                     pMasterKey.second.nDeriveIterations = 25000;
390
391                 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
392
393                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
394                     return false;
395                 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
396                     return false;
397                 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
398                 if (fWasLocked)
399                     Lock();
400                 return true;
401             }
402         }
403     }
404
405     return false;
406 }
407
408 void CWallet::ChainTip(const CBlockIndex *pindex, const CBlock *pblock,
409                        ZCIncrementalMerkleTree tree, bool added)
410 {
411     if (added) {
412         IncrementNoteWitnesses(pindex, pblock, tree);
413     } else {
414         DecrementNoteWitnesses(pindex);
415     }
416 }
417
418 void CWallet::SetBestChain(const CBlockLocator& loc)
419 {
420     CWalletDB walletdb(strWalletFile);
421     SetBestChainINTERNAL(walletdb, loc);
422 }
423
424 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
425 {
426     LOCK(cs_wallet); // nWalletVersion
427     if (nWalletVersion >= nVersion)
428         return true;
429
430     // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
431     if (fExplicit && nVersion > nWalletMaxVersion)
432             nVersion = FEATURE_LATEST;
433
434     nWalletVersion = nVersion;
435
436     if (nVersion > nWalletMaxVersion)
437         nWalletMaxVersion = nVersion;
438
439     if (fFileBacked)
440     {
441         CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
442         if (nWalletVersion > 40000)
443             pwalletdb->WriteMinVersion(nWalletVersion);
444         if (!pwalletdbIn)
445             delete pwalletdb;
446     }
447
448     return true;
449 }
450
451 bool CWallet::SetMaxVersion(int nVersion)
452 {
453     LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
454     // cannot downgrade below current version
455     if (nWalletVersion > nVersion)
456         return false;
457
458     nWalletMaxVersion = nVersion;
459
460     return true;
461 }
462
463 set<uint256> CWallet::GetConflicts(const uint256& txid) const
464 {
465     set<uint256> result;
466     AssertLockHeld(cs_wallet);
467
468     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
469     if (it == mapWallet.end())
470         return result;
471     const CWalletTx& wtx = it->second;
472
473     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
474
475     BOOST_FOREACH(const CTxIn& txin, wtx.vin)
476     {
477         if (mapTxSpends.count(txin.prevout) <= 1)
478             continue;  // No conflict if zero or one spends
479         range = mapTxSpends.equal_range(txin.prevout);
480         for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
481             result.insert(it->second);
482     }
483
484     std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
485
486     for (const JSDescription& jsdesc : wtx.vjoinsplit) {
487         for (const uint256& nullifier : jsdesc.nullifiers) {
488             if (mapTxNullifiers.count(nullifier) <= 1) {
489                 continue;  // No conflict if zero or one spends
490             }
491             range_n = mapTxNullifiers.equal_range(nullifier);
492             for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
493                 result.insert(it->second);
494             }
495         }
496     }
497     return result;
498 }
499
500 void CWallet::Flush(bool shutdown)
501 {
502     bitdb.Flush(shutdown);
503 }
504
505 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
506 {
507     if (!bitdb.Open(GetDataDir()))
508     {
509         // try moving the database env out of the way
510         boost::filesystem::path pathDatabase = GetDataDir() / "database";
511         boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
512         try {
513             boost::filesystem::rename(pathDatabase, pathDatabaseBak);
514             LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
515         } catch (const boost::filesystem::filesystem_error&) {
516             // failure is ok (well, not really, but it's not worse than what we started with)
517         }
518         
519         // try again
520         if (!bitdb.Open(GetDataDir())) {
521             // if it still fails, it probably means we can't even create the database env
522             string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
523             errorString += msg;
524             return true;
525         }
526     }
527     
528     if (GetBoolArg("-salvagewallet", false))
529     {
530         // Recover readable keypairs:
531         if (!CWalletDB::Recover(bitdb, walletFile, true))
532             return false;
533     }
534     
535     if (boost::filesystem::exists(GetDataDir() / walletFile))
536     {
537         CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
538         if (r == CDBEnv::RECOVER_OK)
539         {
540             warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
541                                      " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
542                                      " your balance or transactions are incorrect you should"
543                                      " restore from a backup."), GetDataDir());
544         }
545         if (r == CDBEnv::RECOVER_FAIL)
546             errorString += _("wallet.dat corrupt, salvage failed");
547     }
548     
549     return true;
550 }
551
552 template <class T>
553 void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
554 {
555     // We want all the wallet transactions in range to have the same metadata as
556     // the oldest (smallest nOrderPos).
557     // So: find smallest nOrderPos:
558
559     int nMinOrderPos = std::numeric_limits<int>::max();
560     const CWalletTx* copyFrom = NULL;
561     for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
562     {
563         const uint256& hash = it->second;
564         int n = mapWallet[hash].nOrderPos;
565         if (n < nMinOrderPos)
566         {
567             nMinOrderPos = n;
568             copyFrom = &mapWallet[hash];
569         }
570     }
571     // Now copy data from copyFrom to rest:
572     for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
573     {
574         const uint256& hash = it->second;
575         CWalletTx* copyTo = &mapWallet[hash];
576         if (copyFrom == copyTo) continue;
577         copyTo->mapValue = copyFrom->mapValue;
578         // mapNoteData not copied on purpose
579         // (it is always set correctly for each CWalletTx)
580         copyTo->vOrderForm = copyFrom->vOrderForm;
581         // fTimeReceivedIsTxTime not copied on purpose
582         // nTimeReceived not copied on purpose
583         copyTo->nTimeSmart = copyFrom->nTimeSmart;
584         copyTo->fFromMe = copyFrom->fFromMe;
585         copyTo->strFromAccount = copyFrom->strFromAccount;
586         // nOrderPos not copied on purpose
587         // cached members not copied on purpose
588     }
589 }
590
591 /**
592  * Outpoint is spent if any non-conflicted transaction
593  * spends it:
594  */
595 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
596 {
597     const COutPoint outpoint(hash, n);
598     pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
599     range = mapTxSpends.equal_range(outpoint);
600
601     for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
602     {
603         const uint256& wtxid = it->second;
604         std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
605         if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
606             return true; // Spent
607     }
608     return false;
609 }
610
611 /**
612  * Note is spent if any non-conflicted transaction
613  * spends it:
614  */
615 bool CWallet::IsSpent(const uint256& nullifier) const
616 {
617     pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
618     range = mapTxNullifiers.equal_range(nullifier);
619
620     for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
621         const uint256& wtxid = it->second;
622         std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
623         if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
624             return true; // Spent
625         }
626     }
627     return false;
628 }
629
630 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
631 {
632     mapTxSpends.insert(make_pair(outpoint, wtxid));
633
634     pair<TxSpends::iterator, TxSpends::iterator> range;
635     range = mapTxSpends.equal_range(outpoint);
636     SyncMetaData<COutPoint>(range);
637 }
638
639 void CWallet::AddToSpends(const uint256& nullifier, const uint256& wtxid)
640 {
641     mapTxNullifiers.insert(make_pair(nullifier, wtxid));
642
643     pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
644     range = mapTxNullifiers.equal_range(nullifier);
645     SyncMetaData<uint256>(range);
646 }
647
648 void CWallet::AddToSpends(const uint256& wtxid)
649 {
650     assert(mapWallet.count(wtxid));
651     CWalletTx& thisTx = mapWallet[wtxid];
652     if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
653         return;
654
655     for (const CTxIn& txin : thisTx.vin) {
656         AddToSpends(txin.prevout, wtxid);
657     }
658     for (const JSDescription& jsdesc : thisTx.vjoinsplit) {
659         for (const uint256& nullifier : jsdesc.nullifiers) {
660             AddToSpends(nullifier, wtxid);
661         }
662     }
663 }
664
665 void CWallet::ClearNoteWitnessCache()
666 {
667     LOCK(cs_wallet);
668     for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
669         for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
670             item.second.witnesses.clear();
671             item.second.witnessHeight = -1;
672         }
673     }
674     nWitnessCacheSize = 0;
675 }
676
677 void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
678                                      const CBlock* pblockIn,
679                                      ZCIncrementalMerkleTree& tree)
680 {
681     {
682         LOCK(cs_wallet);
683         for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
684             for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
685                 CNoteData* nd = &(item.second);
686                 // Only increment witnesses that are behind the current height
687                 if (nd->witnessHeight < pindex->nHeight) {
688                     // Check the validity of the cache
689                     // The only time a note witnessed above the current height
690                     // would be invalid here is during a reindex when blocks
691                     // have been decremented, and we are incrementing the blocks
692                     // immediately after.
693                     assert(nWitnessCacheSize >= nd->witnesses.size());
694                     // Witnesses being incremented should always be either -1
695                     // (never incremented or decremented) or one below pindex
696                     assert((nd->witnessHeight == -1) ||
697                            (nd->witnessHeight == pindex->nHeight - 1));
698                     // Copy the witness for the previous block if we have one
699                     if (nd->witnesses.size() > 0) {
700                         nd->witnesses.push_front(nd->witnesses.front());
701                     }
702                     if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
703                         nd->witnesses.pop_back();
704                     }
705                 }
706             }
707         }
708         if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
709             nWitnessCacheSize += 1;
710         }
711
712         const CBlock* pblock {pblockIn};
713         CBlock block;
714         if (!pblock) {
715             ReadBlockFromDisk(block, pindex);
716             pblock = &block;
717         }
718
719         for (const CTransaction& tx : pblock->vtx) {
720             auto hash = tx.GetHash();
721             bool txIsOurs = mapWallet.count(hash);
722             for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
723                 const JSDescription& jsdesc = tx.vjoinsplit[i];
724                 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
725                     const uint256& note_commitment = jsdesc.commitments[j];
726                     tree.append(note_commitment);
727
728                     // Increment existing witnesses
729                     for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
730                         for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
731                             CNoteData* nd = &(item.second);
732                             if (nd->witnessHeight < pindex->nHeight &&
733                                     nd->witnesses.size() > 0) {
734                                 // Check the validity of the cache
735                                 // See earlier comment about validity.
736                                 assert(nWitnessCacheSize >= nd->witnesses.size());
737                                 nd->witnesses.front().append(note_commitment);
738                             }
739                         }
740                     }
741
742                     // If this is our note, witness it
743                     if (txIsOurs) {
744                         JSOutPoint jsoutpt {hash, i, j};
745                         if (mapWallet[hash].mapNoteData.count(jsoutpt) &&
746                                 mapWallet[hash].mapNoteData[jsoutpt].witnessHeight < pindex->nHeight) {
747                             CNoteData* nd = &(mapWallet[hash].mapNoteData[jsoutpt]);
748                             if (nd->witnesses.size() > 0) {
749                                 // We think this can happen because we write out the
750                                 // witness cache state after every block increment or
751                                 // decrement, but the block index itself is written in
752                                 // batches. So if the node crashes in between these two
753                                 // operations, it is possible for IncrementNoteWitnesses
754                                 // to be called again on previously-cached blocks. This
755                                 // doesn't affect existing cached notes because of the
756                                 // CNoteData::witnessHeight checks. See #1378 for details.
757                                 LogPrintf("Inconsistent witness cache state found for %s\n- Cache size: %d\n- Top (height %d): %s\n- New (height %d): %s\n",
758                                           jsoutpt.ToString(), nd->witnesses.size(),
759                                           nd->witnessHeight,
760                                           nd->witnesses.front().root().GetHex(),
761                                           pindex->nHeight,
762                                           tree.witness().root().GetHex());
763                                 nd->witnesses.clear();
764                             }
765                             nd->witnesses.push_front(tree.witness());
766                             // Set height to one less than pindex so it gets incremented
767                             nd->witnessHeight = pindex->nHeight - 1;
768                             // Check the validity of the cache
769                             assert(nWitnessCacheSize >= nd->witnesses.size());
770                         }
771                     }
772                 }
773             }
774         }
775
776         // Update witness heights
777         for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
778             for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
779                 CNoteData* nd = &(item.second);
780                 if (nd->witnessHeight < pindex->nHeight) {
781                     nd->witnessHeight = pindex->nHeight;
782                     // Check the validity of the cache
783                     // See earlier comment about validity.
784                     assert(nWitnessCacheSize >= nd->witnesses.size());
785                 }
786             }
787         }
788
789         // For performance reasons, we write out the witness cache in
790         // CWallet::SetBestChain() (which also ensures that overall consistency
791         // of the wallet.dat is maintained).
792     }
793 }
794
795 void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
796 {
797     {
798         LOCK(cs_wallet);
799         for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
800             for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
801                 CNoteData* nd = &(item.second);
802                 // Only increment witnesses that are not above the current height
803                 if (nd->witnessHeight <= pindex->nHeight) {
804                     // Check the validity of the cache
805                     // See comment below (this would be invalid if there was a
806                     // prior decrement).
807                     assert(nWitnessCacheSize >= nd->witnesses.size());
808                     // Witnesses being decremented should always be either -1
809                     // (never incremented or decremented) or equal to pindex
810                     assert((nd->witnessHeight == -1) ||
811                            (nd->witnessHeight == pindex->nHeight));
812                     if (nd->witnesses.size() > 0) {
813                         nd->witnesses.pop_front();
814                     }
815                     // pindex is the block being removed, so the new witness cache
816                     // height is one below it.
817                     nd->witnessHeight = pindex->nHeight - 1;
818                 }
819             }
820         }
821         nWitnessCacheSize -= 1;
822         for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
823             for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
824                 CNoteData* nd = &(item.second);
825                 // Check the validity of the cache
826                 // Technically if there are notes witnessed above the current
827                 // height, their cache will now be invalid (relative to the new
828                 // value of nWitnessCacheSize). However, this would only occur
829                 // during a reindex, and by the time the reindex reaches the tip
830                 // of the chain again, the existing witness caches will be valid
831                 // again.
832                 // We don't set nWitnessCacheSize to zero at the start of the
833                 // reindex because the on-disk blocks had already resulted in a
834                 // chain that didn't trigger the assertion below.
835                 if (nd->witnessHeight < pindex->nHeight) {
836                     assert(nWitnessCacheSize >= nd->witnesses.size());
837                 }
838             }
839         }
840         // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
841         assert(nWitnessCacheSize > 0);
842
843         // For performance reasons, we write out the witness cache in
844         // CWallet::SetBestChain() (which also ensures that overall consistency
845         // of the wallet.dat is maintained).
846     }
847 }
848
849 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
850 {
851     if (IsCrypted())
852         return false;
853
854     CKeyingMaterial vMasterKey;
855
856     vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
857     GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
858
859     CMasterKey kMasterKey;
860
861     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
862     GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
863
864     CCrypter crypter;
865     int64_t nStartTime = GetTimeMillis();
866     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
867     kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
868
869     nStartTime = GetTimeMillis();
870     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
871     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
872
873     if (kMasterKey.nDeriveIterations < 25000)
874         kMasterKey.nDeriveIterations = 25000;
875
876     LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
877
878     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
879         return false;
880     if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
881         return false;
882
883     {
884         LOCK(cs_wallet);
885         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
886         if (fFileBacked)
887         {
888             assert(!pwalletdbEncryption);
889             pwalletdbEncryption = new CWalletDB(strWalletFile);
890             if (!pwalletdbEncryption->TxnBegin()) {
891                 delete pwalletdbEncryption;
892                 pwalletdbEncryption = NULL;
893                 return false;
894             }
895             pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
896         }
897
898         if (!EncryptKeys(vMasterKey))
899         {
900             if (fFileBacked) {
901                 pwalletdbEncryption->TxnAbort();
902                 delete pwalletdbEncryption;
903             }
904             // We now probably have half of our keys encrypted in memory, and half not...
905             // die and let the user reload the unencrypted wallet.
906             assert(false);
907         }
908
909         // Encryption was introduced in version 0.4.0
910         SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
911
912         if (fFileBacked)
913         {
914             if (!pwalletdbEncryption->TxnCommit()) {
915                 delete pwalletdbEncryption;
916                 // We now have keys encrypted in memory, but not on disk...
917                 // die to avoid confusion and let the user reload the unencrypted wallet.
918                 assert(false);
919             }
920
921             delete pwalletdbEncryption;
922             pwalletdbEncryption = NULL;
923         }
924
925         Lock();
926         Unlock(strWalletPassphrase);
927         NewKeyPool();
928         Lock();
929
930         // Need to completely rewrite the wallet file; if we don't, bdb might keep
931         // bits of the unencrypted private key in slack space in the database file.
932         CDB::Rewrite(strWalletFile);
933
934     }
935     NotifyStatusChanged(this);
936
937     return true;
938 }
939
940 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
941 {
942     AssertLockHeld(cs_wallet); // nOrderPosNext
943     int64_t nRet = nOrderPosNext++;
944     if (pwalletdb) {
945         pwalletdb->WriteOrderPosNext(nOrderPosNext);
946     } else {
947         CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
948     }
949     return nRet;
950 }
951
952 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
953 {
954     AssertLockHeld(cs_wallet); // mapWallet
955     CWalletDB walletdb(strWalletFile);
956
957     // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
958     TxItems txOrdered;
959
960     // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
961     // would make this much faster for applications that do this a lot.
962     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
963     {
964         CWalletTx* wtx = &((*it).second);
965         txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
966     }
967     acentries.clear();
968     walletdb.ListAccountCreditDebit(strAccount, acentries);
969     BOOST_FOREACH(CAccountingEntry& entry, acentries)
970     {
971         txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
972     }
973
974     return txOrdered;
975 }
976
977 void CWallet::MarkDirty()
978 {
979     {
980         LOCK(cs_wallet);
981         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
982             item.second.MarkDirty();
983     }
984 }
985
986 /**
987  * Ensure that every note in the wallet (for which we possess a spending key)
988  * has a cached nullifier.
989  */
990 bool CWallet::UpdateNullifierNoteMap()
991 {
992     {
993         LOCK(cs_wallet);
994
995         if (IsLocked())
996             return false;
997
998         ZCNoteDecryption dec;
999         for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1000             for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
1001                 if (!item.second.nullifier) {
1002                     if (GetNoteDecryptor(item.second.address, dec)) {
1003                         auto i = item.first.js;
1004                         auto hSig = wtxItem.second.vjoinsplit[i].h_sig(
1005                             *pzcashParams, wtxItem.second.joinSplitPubKey);
1006                         item.second.nullifier = GetNoteNullifier(
1007                             wtxItem.second.vjoinsplit[i],
1008                             item.second.address,
1009                             dec,
1010                             hSig,
1011                             item.first.n);
1012                     }
1013                 }
1014             }
1015             UpdateNullifierNoteMapWithTx(wtxItem.second);
1016         }
1017     }
1018     return true;
1019 }
1020
1021 /**
1022  * Update mapNullifiersToNotes with the cached nullifiers in this tx.
1023  */
1024 void CWallet::UpdateNullifierNoteMapWithTx(const CWalletTx& wtx)
1025 {
1026     {
1027         LOCK(cs_wallet);
1028         for (const mapNoteData_t::value_type& item : wtx.mapNoteData) {
1029             if (item.second.nullifier) {
1030                 mapNullifiersToNotes[*item.second.nullifier] = item.first;
1031             }
1032         }
1033     }
1034 }
1035
1036 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
1037 {
1038     uint256 hash = wtxIn.GetHash();
1039
1040     if (fFromLoadWallet)
1041     {
1042         mapWallet[hash] = wtxIn;
1043         mapWallet[hash].BindWallet(this);
1044         UpdateNullifierNoteMapWithTx(mapWallet[hash]);
1045         AddToSpends(hash);
1046     }
1047     else
1048     {
1049         LOCK(cs_wallet);
1050         // Inserts only if not already there, returns tx inserted or tx found
1051         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
1052         CWalletTx& wtx = (*ret.first).second;
1053         wtx.BindWallet(this);
1054         UpdateNullifierNoteMapWithTx(wtx);
1055         bool fInsertedNew = ret.second;
1056         if (fInsertedNew)
1057         {
1058             wtx.nTimeReceived = GetAdjustedTime();
1059             wtx.nOrderPos = IncOrderPosNext(pwalletdb);
1060
1061             wtx.nTimeSmart = wtx.nTimeReceived;
1062             if (!wtxIn.hashBlock.IsNull())
1063             {
1064                 if (mapBlockIndex.count(wtxIn.hashBlock))
1065                 {
1066                     int64_t latestNow = wtx.nTimeReceived;
1067                     int64_t latestEntry = 0;
1068                     {
1069                         // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
1070                         int64_t latestTolerated = latestNow + 300;
1071                         std::list<CAccountingEntry> acentries;
1072                         TxItems txOrdered = OrderedTxItems(acentries);
1073                         for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1074                         {
1075                             CWalletTx *const pwtx = (*it).second.first;
1076                             if (pwtx == &wtx)
1077                                 continue;
1078                             CAccountingEntry *const pacentry = (*it).second.second;
1079                             int64_t nSmartTime;
1080                             if (pwtx)
1081                             {
1082                                 nSmartTime = pwtx->nTimeSmart;
1083                                 if (!nSmartTime)
1084                                     nSmartTime = pwtx->nTimeReceived;
1085                             }
1086                             else
1087                                 nSmartTime = pacentry->nTime;
1088                             if (nSmartTime <= latestTolerated)
1089                             {
1090                                 latestEntry = nSmartTime;
1091                                 if (nSmartTime > latestNow)
1092                                     latestNow = nSmartTime;
1093                                 break;
1094                             }
1095                         }
1096                     }
1097
1098                     int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
1099                     wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
1100                 }
1101                 else
1102                     LogPrintf("AddToWallet(): found %s in block %s not in index\n",
1103                              wtxIn.GetHash().ToString(),
1104                              wtxIn.hashBlock.ToString());
1105             }
1106             AddToSpends(hash);
1107         }
1108
1109         bool fUpdated = false;
1110         if (!fInsertedNew)
1111         {
1112             // Merge
1113             if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
1114             {
1115                 wtx.hashBlock = wtxIn.hashBlock;
1116                 fUpdated = true;
1117             }
1118             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
1119             {
1120                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
1121                 wtx.nIndex = wtxIn.nIndex;
1122                 fUpdated = true;
1123             }
1124             if (UpdatedNoteData(wtxIn, wtx)) {
1125                 fUpdated = true;
1126             }
1127             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1128             {
1129                 wtx.fFromMe = wtxIn.fFromMe;
1130                 fUpdated = true;
1131             }
1132         }
1133
1134         //// debug print
1135         LogPrintf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1136
1137         // Write to disk
1138         if (fInsertedNew || fUpdated)
1139             if (!wtx.WriteToDisk(pwalletdb))
1140                 return false;
1141
1142         // Break debit/credit balance caches:
1143         wtx.MarkDirty();
1144
1145         // Notify UI of new or updated transaction
1146         NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1147
1148         // notify an external script when a wallet transaction comes in or is updated
1149         std::string strCmd = GetArg("-walletnotify", "");
1150
1151         if ( !strCmd.empty())
1152         {
1153             boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1154             boost::thread t(runCommand, strCmd); // thread runs free
1155         }
1156
1157     }
1158     return true;
1159 }
1160
1161 bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1162 {
1163     if (wtxIn.mapNoteData.empty() || wtxIn.mapNoteData == wtx.mapNoteData) {
1164         return false;
1165     }
1166     auto tmp = wtxIn.mapNoteData;
1167     // Ensure we keep any cached witnesses we may already have
1168     for (const std::pair<JSOutPoint, CNoteData> nd : wtx.mapNoteData) {
1169         if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1170             tmp.at(nd.first).witnesses.assign(
1171                 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1172         }
1173         tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1174     }
1175     // Now copy over the updated note data
1176     wtx.mapNoteData = tmp;
1177     return true;
1178 }
1179
1180 /**
1181  * Add a transaction to the wallet, or update it.
1182  * pblock is optional, but should be provided if the transaction is known to be in a block.
1183  * If fUpdate is true, existing transactions will be updated.
1184  */
1185 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1186 {
1187     {
1188         AssertLockHeld(cs_wallet);
1189         bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1190         if (fExisted && !fUpdate) return false;
1191         auto noteData = FindMyNotes(tx);
1192         if (fExisted || IsMine(tx) || IsFromMe(tx) || noteData.size() > 0)
1193         {
1194             CWalletTx wtx(this,tx);
1195
1196             if (noteData.size() > 0) {
1197                 wtx.SetNoteData(noteData);
1198             }
1199
1200             // Get merkle branch if transaction was found in a block
1201             if (pblock)
1202                 wtx.SetMerkleBranch(*pblock);
1203
1204             // Do not flush the wallet here for performance reasons
1205             // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1206             CWalletDB walletdb(strWalletFile, "r+", false);
1207
1208             return AddToWallet(wtx, false, &walletdb);
1209         }
1210     }
1211     return false;
1212 }
1213
1214 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1215 {
1216     LOCK2(cs_main, cs_wallet);
1217     if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1218         return; // Not one of ours
1219
1220     MarkAffectedTransactionsDirty(tx);
1221 }
1222
1223 void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1224 {
1225     // If a transaction changes 'conflicted' state, that changes the balance
1226     // available of the outputs it spends. So force those to be
1227     // recomputed, also:
1228     BOOST_FOREACH(const CTxIn& txin, tx.vin)
1229     {
1230         if (mapWallet.count(txin.prevout.hash))
1231             mapWallet[txin.prevout.hash].MarkDirty();
1232     }
1233     for (const JSDescription& jsdesc : tx.vjoinsplit) {
1234         for (const uint256& nullifier : jsdesc.nullifiers) {
1235             if (mapNullifiersToNotes.count(nullifier) &&
1236                     mapWallet.count(mapNullifiersToNotes[nullifier].hash)) {
1237                 mapWallet[mapNullifiersToNotes[nullifier].hash].MarkDirty();
1238             }
1239         }
1240     }
1241 }
1242
1243 void CWallet::EraseFromWallet(const uint256 &hash)
1244 {
1245     if (!fFileBacked)
1246         return;
1247     {
1248         LOCK(cs_wallet);
1249         if (mapWallet.erase(hash))
1250             CWalletDB(strWalletFile).EraseTx(hash);
1251     }
1252     return;
1253 }
1254
1255
1256 /**
1257  * Returns a nullifier if the SpendingKey is available
1258  * Throws std::runtime_error if the decryptor doesn't match this note
1259  */
1260 boost::optional<uint256> CWallet::GetNoteNullifier(const JSDescription& jsdesc,
1261                                                    const libzcash::PaymentAddress& address,
1262                                                    const ZCNoteDecryption& dec,
1263                                                    const uint256& hSig,
1264                                                    uint8_t n) const
1265 {
1266     boost::optional<uint256> ret;
1267     auto note_pt = libzcash::NotePlaintext::decrypt(
1268         dec,
1269         jsdesc.ciphertexts[n],
1270         jsdesc.ephemeralKey,
1271         hSig,
1272         (unsigned char) n);
1273     auto note = note_pt.note(address);
1274     // SpendingKeys are only available if:
1275     // - We have them (this isn't a viewing key)
1276     // - The wallet is unlocked
1277     libzcash::SpendingKey key;
1278     if (GetSpendingKey(address, key)) {
1279         ret = note.nullifier(key);
1280     }
1281     return ret;
1282 }
1283
1284 /**
1285  * Finds all output notes in the given transaction that have been sent to
1286  * PaymentAddresses in this wallet.
1287  *
1288  * It should never be necessary to call this method with a CWalletTx, because
1289  * the result of FindMyNotes (for the addresses available at the time) will
1290  * already have been cached in CWalletTx.mapNoteData.
1291  */
1292 mapNoteData_t CWallet::FindMyNotes(const CTransaction& tx) const
1293 {
1294     LOCK(cs_SpendingKeyStore);
1295     uint256 hash = tx.GetHash();
1296
1297     mapNoteData_t noteData;
1298     for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1299         auto hSig = tx.vjoinsplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1300         for (uint8_t j = 0; j < tx.vjoinsplit[i].ciphertexts.size(); j++) {
1301             for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
1302                 try {
1303                     auto address = item.first;
1304                     JSOutPoint jsoutpt {hash, i, j};
1305                     auto nullifier = GetNoteNullifier(
1306                         tx.vjoinsplit[i],
1307                         address,
1308                         item.second,
1309                         hSig, j);
1310                     if (nullifier) {
1311                         CNoteData nd {address, *nullifier};
1312                         noteData.insert(std::make_pair(jsoutpt, nd));
1313                     } else {
1314                         CNoteData nd {address};
1315                         noteData.insert(std::make_pair(jsoutpt, nd));
1316                     }
1317                     break;
1318                 } catch (const note_decryption_failed &err) {
1319                     // Couldn't decrypt with this decryptor
1320                 } catch (const std::exception &exc) {
1321                     // Unexpected failure
1322                     LogPrintf("FindMyNotes(): Unexpected error while testing decrypt:\n");
1323                     LogPrintf("%s\n", exc.what());
1324                 }
1325             }
1326         }
1327     }
1328     return noteData;
1329 }
1330
1331 bool CWallet::IsFromMe(const uint256& nullifier) const
1332 {
1333     {
1334         LOCK(cs_wallet);
1335         if (mapNullifiersToNotes.count(nullifier) &&
1336                 mapWallet.count(mapNullifiersToNotes.at(nullifier).hash)) {
1337             return true;
1338         }
1339     }
1340     return false;
1341 }
1342
1343 void CWallet::GetNoteWitnesses(std::vector<JSOutPoint> notes,
1344                                std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1345                                uint256 &final_anchor)
1346 {
1347     {
1348         LOCK(cs_wallet);
1349         witnesses.resize(notes.size());
1350         boost::optional<uint256> rt;
1351         int i = 0;
1352         for (JSOutPoint note : notes) {
1353             if (mapWallet.count(note.hash) &&
1354                     mapWallet[note.hash].mapNoteData.count(note) &&
1355                     mapWallet[note.hash].mapNoteData[note].witnesses.size() > 0) {
1356                 witnesses[i] = mapWallet[note.hash].mapNoteData[note].witnesses.front();
1357                 if (!rt) {
1358                     rt = witnesses[i]->root();
1359                 } else {
1360                     assert(*rt == witnesses[i]->root());
1361                 }
1362             }
1363             i++;
1364         }
1365         // All returned witnesses have the same anchor
1366         if (rt) {
1367             final_anchor = *rt;
1368         }
1369     }
1370 }
1371
1372 isminetype CWallet::IsMine(const CTxIn &txin) const
1373 {
1374     {
1375         LOCK(cs_wallet);
1376         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1377         if (mi != mapWallet.end())
1378         {
1379             const CWalletTx& prev = (*mi).second;
1380             if (txin.prevout.n < prev.vout.size())
1381                 return IsMine(prev.vout[txin.prevout.n]);
1382         }
1383     }
1384     return ISMINE_NO;
1385 }
1386
1387 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1388 {
1389     {
1390         LOCK(cs_wallet);
1391         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1392         if (mi != mapWallet.end())
1393         {
1394             const CWalletTx& prev = (*mi).second;
1395             if (txin.prevout.n < prev.vout.size())
1396                 if (IsMine(prev.vout[txin.prevout.n]) & filter)
1397                     return prev.vout[txin.prevout.n].nValue;
1398         }
1399     }
1400     return 0;
1401 }
1402
1403 isminetype CWallet::IsMine(const CTxOut& txout) const
1404 {
1405     return ::IsMine(*this, txout.scriptPubKey);
1406 }
1407
1408 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1409 {
1410     if (!MoneyRange(txout.nValue))
1411         throw std::runtime_error("CWallet::GetCredit(): value out of range");
1412     return ((IsMine(txout) & filter) ? txout.nValue : 0);
1413 }
1414
1415 bool CWallet::IsChange(const CTxOut& txout) const
1416 {
1417     // TODO: fix handling of 'change' outputs. The assumption is that any
1418     // payment to a script that is ours, but is not in the address book
1419     // is change. That assumption is likely to break when we implement multisignature
1420     // wallets that return change back into a multi-signature-protected address;
1421     // a better way of identifying which outputs are 'the send' and which are
1422     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1423     // which output, if any, was change).
1424     if (::IsMine(*this, txout.scriptPubKey))
1425     {
1426         CTxDestination address;
1427         if (!ExtractDestination(txout.scriptPubKey, address))
1428             return true;
1429
1430         LOCK(cs_wallet);
1431         if (!mapAddressBook.count(address))
1432             return true;
1433     }
1434     return false;
1435 }
1436
1437 CAmount CWallet::GetChange(const CTxOut& txout) const
1438 {
1439     if (!MoneyRange(txout.nValue))
1440         throw std::runtime_error("CWallet::GetChange(): value out of range");
1441     return (IsChange(txout) ? txout.nValue : 0);
1442 }
1443
1444 bool CWallet::IsMine(const CTransaction& tx) const
1445 {
1446     BOOST_FOREACH(const CTxOut& txout, tx.vout)
1447         if (IsMine(txout))
1448             return true;
1449     return false;
1450 }
1451
1452 bool CWallet::IsFromMe(const CTransaction& tx) const
1453 {
1454     if (GetDebit(tx, ISMINE_ALL) > 0) {
1455         return true;
1456     }
1457     for (const JSDescription& jsdesc : tx.vjoinsplit) {
1458         for (const uint256& nullifier : jsdesc.nullifiers) {
1459             if (IsFromMe(nullifier)) {
1460                 return true;
1461             }
1462         }
1463     }
1464     return false;
1465 }
1466
1467 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1468 {
1469     CAmount nDebit = 0;
1470     BOOST_FOREACH(const CTxIn& txin, tx.vin)
1471     {
1472         nDebit += GetDebit(txin, filter);
1473         if (!MoneyRange(nDebit))
1474             throw std::runtime_error("CWallet::GetDebit(): value out of range");
1475     }
1476     return nDebit;
1477 }
1478
1479 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1480 {
1481     CAmount nCredit = 0;
1482     BOOST_FOREACH(const CTxOut& txout, tx.vout)
1483     {
1484         nCredit += GetCredit(txout, filter);
1485         if (!MoneyRange(nCredit))
1486             throw std::runtime_error("CWallet::GetCredit(): value out of range");
1487     }
1488     return nCredit;
1489 }
1490
1491 CAmount CWallet::GetChange(const CTransaction& tx) const
1492 {
1493     CAmount nChange = 0;
1494     BOOST_FOREACH(const CTxOut& txout, tx.vout)
1495     {
1496         nChange += GetChange(txout);
1497         if (!MoneyRange(nChange))
1498             throw std::runtime_error("CWallet::GetChange(): value out of range");
1499     }
1500     return nChange;
1501 }
1502
1503 void CWalletTx::SetNoteData(mapNoteData_t &noteData)
1504 {
1505     mapNoteData.clear();
1506     for (const std::pair<JSOutPoint, CNoteData> nd : noteData) {
1507         if (nd.first.js < vjoinsplit.size() &&
1508                 nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1509             // Store the address and nullifier for the Note
1510             mapNoteData[nd.first] = nd.second;
1511         } else {
1512             // If FindMyNotes() was used to obtain noteData,
1513             // this should never happen
1514             throw std::logic_error("CWalletTx::SetNoteData(): Invalid note");
1515         }
1516     }
1517 }
1518
1519 int64_t CWalletTx::GetTxTime() const
1520 {
1521     int64_t n = nTimeSmart;
1522     return n ? n : nTimeReceived;
1523 }
1524
1525 int CWalletTx::GetRequestCount() const
1526 {
1527     // Returns -1 if it wasn't being tracked
1528     int nRequests = -1;
1529     {
1530         LOCK(pwallet->cs_wallet);
1531         if (IsCoinBase())
1532         {
1533             // Generated block
1534             if (!hashBlock.IsNull())
1535             {
1536                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1537                 if (mi != pwallet->mapRequestCount.end())
1538                     nRequests = (*mi).second;
1539             }
1540         }
1541         else
1542         {
1543             // Did anyone request this transaction?
1544             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1545             if (mi != pwallet->mapRequestCount.end())
1546             {
1547                 nRequests = (*mi).second;
1548
1549                 // How about the block it's in?
1550                 if (nRequests == 0 && !hashBlock.IsNull())
1551                 {
1552                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1553                     if (mi != pwallet->mapRequestCount.end())
1554                         nRequests = (*mi).second;
1555                     else
1556                         nRequests = 1; // If it's in someone else's block it must have got out
1557                 }
1558             }
1559         }
1560     }
1561     return nRequests;
1562 }
1563
1564 // GetAmounts will determine the transparent debits and credits for a given wallet tx.
1565 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1566                            list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1567 {
1568     nFee = 0;
1569     listReceived.clear();
1570     listSent.clear();
1571     strSentAccount = strFromAccount;
1572
1573     // Is this tx sent/signed by me?
1574     CAmount nDebit = GetDebit(filter);
1575     bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
1576
1577     // Does this tx spend my notes?
1578     bool isFromMyZaddr = false;
1579     for (const JSDescription& js : vjoinsplit) {
1580         for (const uint256& nullifier : js.nullifiers) {
1581             if (pwallet->IsFromMe(nullifier)) {
1582                 isFromMyZaddr = true;
1583                 break;
1584             }
1585         }
1586         if (isFromMyZaddr) {
1587             break;
1588         }
1589     }
1590
1591     // Compute fee if we sent this transaction.
1592     if (isFromMyTaddr) {
1593         CAmount nValueOut = GetValueOut();  // transparent outputs plus all vpub_old
1594         CAmount nValueIn = 0;
1595         for (const JSDescription & js : vjoinsplit) {
1596             nValueIn += js.vpub_new;
1597         }
1598         nFee = nDebit - nValueOut + nValueIn;
1599     }
1600
1601     // Create output entry for vpub_old/new, if we sent utxos from this transaction
1602     if (isFromMyTaddr) {
1603         CAmount myVpubOld = 0;
1604         CAmount myVpubNew = 0;
1605         for (const JSDescription& js : vjoinsplit) {
1606             bool fMyJSDesc = false;
1607
1608             // Check input side
1609             for (const uint256& nullifier : js.nullifiers) {
1610                 if (pwallet->IsFromMe(nullifier)) {
1611                     fMyJSDesc = true;
1612                     break;
1613                 }
1614             }
1615
1616             // Check output side
1617             if (!fMyJSDesc) {
1618                 for (const std::pair<JSOutPoint, CNoteData> nd : this->mapNoteData) {
1619                     if (nd.first.js < vjoinsplit.size() && nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1620                         fMyJSDesc = true;
1621                         break;
1622                     }
1623                 }
1624             }
1625
1626             if (fMyJSDesc) {
1627                 myVpubOld += js.vpub_old;
1628                 myVpubNew += js.vpub_new;
1629             }
1630
1631             if (!MoneyRange(js.vpub_old) || !MoneyRange(js.vpub_new) || !MoneyRange(myVpubOld) || !MoneyRange(myVpubNew)) {
1632                  throw std::runtime_error("CWalletTx::GetAmounts: value out of range");
1633             }
1634         }
1635
1636         // Create an output for the value taken from or added to the transparent value pool by JoinSplits
1637         if (myVpubOld > myVpubNew) {
1638             COutputEntry output = {CNoDestination(), myVpubOld - myVpubNew, (int)vout.size()};
1639             listSent.push_back(output);
1640         } else if (myVpubNew > myVpubOld) {
1641             COutputEntry output = {CNoDestination(), myVpubNew - myVpubOld, (int)vout.size()};
1642             listReceived.push_back(output);
1643         }
1644     }
1645
1646     // Sent/received.
1647     for (unsigned int i = 0; i < vout.size(); ++i)
1648     {
1649         const CTxOut& txout = vout[i];
1650         isminetype fIsMine = pwallet->IsMine(txout);
1651         // Only need to handle txouts if AT LEAST one of these is true:
1652         //   1) they debit from us (sent)
1653         //   2) the output is to us (received)
1654         if (nDebit > 0)
1655         {
1656             // Don't report 'change' txouts
1657             if (pwallet->IsChange(txout))
1658                 continue;
1659         }
1660         else if (!(fIsMine & filter))
1661             continue;
1662
1663         // In either case, we need to get the destination address
1664         CTxDestination address;
1665         if (!ExtractDestination(txout.scriptPubKey, address))
1666         {
1667             LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1668                      this->GetHash().ToString());
1669             address = CNoDestination();
1670         }
1671
1672         COutputEntry output = {address, txout.nValue, (int)i};
1673
1674         // If we are debited by the transaction, add the output as a "sent" entry
1675         if (nDebit > 0)
1676             listSent.push_back(output);
1677
1678         // If we are receiving the output, add it as a "received" entry
1679         if (fIsMine & filter)
1680             listReceived.push_back(output);
1681     }
1682
1683 }
1684
1685 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1686                                   CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1687 {
1688     nReceived = nSent = nFee = 0;
1689
1690     CAmount allFee;
1691     string strSentAccount;
1692     list<COutputEntry> listReceived;
1693     list<COutputEntry> listSent;
1694     GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1695
1696     if (strAccount == strSentAccount)
1697     {
1698         BOOST_FOREACH(const COutputEntry& s, listSent)
1699             nSent += s.amount;
1700         nFee = allFee;
1701     }
1702     {
1703         LOCK(pwallet->cs_wallet);
1704         BOOST_FOREACH(const COutputEntry& r, listReceived)
1705         {
1706             if (pwallet->mapAddressBook.count(r.destination))
1707             {
1708                 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1709                 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1710                     nReceived += r.amount;
1711             }
1712             else if (strAccount.empty())
1713             {
1714                 nReceived += r.amount;
1715             }
1716         }
1717     }
1718 }
1719
1720
1721 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
1722 {
1723     return pwalletdb->WriteTx(GetHash(), *this);
1724 }
1725
1726 void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
1727                                     std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1728                                     uint256 &final_anchor)
1729 {
1730     witnesses.resize(commitments.size());
1731     CBlockIndex* pindex = chainActive.Genesis();
1732     ZCIncrementalMerkleTree tree;
1733
1734     while (pindex) {
1735         CBlock block;
1736         ReadBlockFromDisk(block, pindex);
1737
1738         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1739         {
1740             BOOST_FOREACH(const JSDescription& jsdesc, tx.vjoinsplit)
1741             {
1742                 BOOST_FOREACH(const uint256 &note_commitment, jsdesc.commitments)
1743                 {
1744                     tree.append(note_commitment);
1745
1746                     BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1747                         if (wit) {
1748                             wit->append(note_commitment);
1749                         }
1750                     }
1751
1752                     size_t i = 0;
1753                     BOOST_FOREACH(uint256& commitment, commitments) {
1754                         if (note_commitment == commitment) {
1755                             witnesses.at(i) = tree.witness();
1756                         }
1757                         i++;
1758                     }
1759                 }
1760             }
1761         }
1762
1763         uint256 current_anchor = tree.root();
1764
1765         // Consistency check: we should be able to find the current tree
1766         // in our CCoins view.
1767         ZCIncrementalMerkleTree dummy_tree;
1768         assert(pcoinsTip->GetAnchorAt(current_anchor, dummy_tree));
1769
1770         pindex = chainActive.Next(pindex);
1771     }
1772
1773     // TODO: #93; Select a root via some heuristic.
1774     final_anchor = tree.root();
1775
1776     BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1777         if (wit) {
1778             assert(final_anchor == wit->root());
1779         }
1780     }
1781 }
1782
1783 /**
1784  * Scan the block chain (starting in pindexStart) for transactions
1785  * from or to us. If fUpdate is true, found transactions that already
1786  * exist in the wallet will be updated.
1787  */
1788 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1789 {
1790     int ret = 0;
1791     int64_t nNow = GetTime();
1792     const CChainParams& chainParams = Params();
1793
1794     CBlockIndex* pindex = pindexStart;
1795     {
1796         LOCK2(cs_main, cs_wallet);
1797
1798         // no need to read and scan block, if block was created before
1799         // our wallet birthday (as adjusted for block time variability)
1800         while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1801             pindex = chainActive.Next(pindex);
1802
1803         ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1804         double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1805         double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1806         while (pindex)
1807         {
1808             if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1809                 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1810
1811             CBlock block;
1812             ReadBlockFromDisk(block, pindex);
1813             BOOST_FOREACH(CTransaction& tx, block.vtx)
1814             {
1815                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1816                     ret++;
1817             }
1818
1819             ZCIncrementalMerkleTree tree;
1820             // This should never fail: we should always be able to get the tree
1821             // state on the path to the tip of our chain
1822             assert(pcoinsTip->GetAnchorAt(pindex->hashAnchor, tree));
1823             // Increment note witness caches
1824             IncrementNoteWitnesses(pindex, &block, tree);
1825
1826             pindex = chainActive.Next(pindex);
1827             if (GetTime() >= nNow + 60) {
1828                 nNow = GetTime();
1829                 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1830             }
1831         }
1832         ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1833     }
1834     return ret;
1835 }
1836
1837 void CWallet::ReacceptWalletTransactions()
1838 {
1839     // If transactions aren't being broadcasted, don't let them into local mempool either
1840     if (!fBroadcastTransactions)
1841         return;
1842     LOCK2(cs_main, cs_wallet);
1843     std::map<int64_t, CWalletTx*> mapSorted;
1844
1845     // Sort pending wallet transactions based on their initial wallet insertion order
1846     BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1847     {
1848         const uint256& wtxid = item.first;
1849         CWalletTx& wtx = item.second;
1850         assert(wtx.GetHash() == wtxid);
1851
1852         int nDepth = wtx.GetDepthInMainChain();
1853
1854         if (!wtx.IsCoinBase() && nDepth < 0) {
1855             mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1856         }
1857     }
1858
1859     // Try to add wallet transactions to memory pool
1860     BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1861     {
1862         CWalletTx& wtx = *(item.second);
1863
1864         LOCK(mempool.cs);
1865         wtx.AcceptToMemoryPool(false);
1866     }
1867 }
1868
1869 bool CWalletTx::RelayWalletTransaction()
1870 {
1871     assert(pwallet->GetBroadcastTransactions());
1872     if (!IsCoinBase())
1873     {
1874         if (GetDepthInMainChain() == 0) {
1875             LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1876             RelayTransaction((CTransaction)*this);
1877             return true;
1878         }
1879     }
1880     return false;
1881 }
1882
1883 set<uint256> CWalletTx::GetConflicts() const
1884 {
1885     set<uint256> result;
1886     if (pwallet != NULL)
1887     {
1888         uint256 myHash = GetHash();
1889         result = pwallet->GetConflicts(myHash);
1890         result.erase(myHash);
1891     }
1892     return result;
1893 }
1894
1895 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1896 {
1897     if (vin.empty())
1898         return 0;
1899
1900     CAmount debit = 0;
1901     if(filter & ISMINE_SPENDABLE)
1902     {
1903         if (fDebitCached)
1904             debit += nDebitCached;
1905         else
1906         {
1907             nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1908             fDebitCached = true;
1909             debit += nDebitCached;
1910         }
1911     }
1912     if(filter & ISMINE_WATCH_ONLY)
1913     {
1914         if(fWatchDebitCached)
1915             debit += nWatchDebitCached;
1916         else
1917         {
1918             nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1919             fWatchDebitCached = true;
1920             debit += nWatchDebitCached;
1921         }
1922     }
1923     return debit;
1924 }
1925
1926 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1927 {
1928     // Must wait until coinbase is safely deep enough in the chain before valuing it
1929     if (IsCoinBase() && GetBlocksToMaturity() > 0)
1930         return 0;
1931
1932     int64_t credit = 0;
1933     if (filter & ISMINE_SPENDABLE)
1934     {
1935         // GetBalance can assume transactions in mapWallet won't change
1936         if (fCreditCached)
1937             credit += nCreditCached;
1938         else
1939         {
1940             nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1941             fCreditCached = true;
1942             credit += nCreditCached;
1943         }
1944     }
1945     if (filter & ISMINE_WATCH_ONLY)
1946     {
1947         if (fWatchCreditCached)
1948             credit += nWatchCreditCached;
1949         else
1950         {
1951             nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1952             fWatchCreditCached = true;
1953             credit += nWatchCreditCached;
1954         }
1955     }
1956     return credit;
1957 }
1958
1959 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1960 {
1961     if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1962     {
1963         if (fUseCache && fImmatureCreditCached)
1964             return nImmatureCreditCached;
1965         nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1966         fImmatureCreditCached = true;
1967         return nImmatureCreditCached;
1968     }
1969
1970     return 0;
1971 }
1972
1973 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1974 {
1975     if (pwallet == 0)
1976         return 0;
1977
1978     // Must wait until coinbase is safely deep enough in the chain before valuing it
1979     if (IsCoinBase() && GetBlocksToMaturity() > 0)
1980         return 0;
1981
1982     if (fUseCache && fAvailableCreditCached)
1983         return nAvailableCreditCached;
1984
1985     CAmount nCredit = 0;
1986     uint256 hashTx = GetHash();
1987     for (unsigned int i = 0; i < vout.size(); i++)
1988     {
1989         if (!pwallet->IsSpent(hashTx, i))
1990         {
1991             const CTxOut &txout = vout[i];
1992             nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1993             if (!MoneyRange(nCredit))
1994                 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1995         }
1996     }
1997
1998     nAvailableCreditCached = nCredit;
1999     fAvailableCreditCached = true;
2000     return nCredit;
2001 }
2002
2003 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
2004 {
2005     if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2006     {
2007         if (fUseCache && fImmatureWatchCreditCached)
2008             return nImmatureWatchCreditCached;
2009         nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2010         fImmatureWatchCreditCached = true;
2011         return nImmatureWatchCreditCached;
2012     }
2013
2014     return 0;
2015 }
2016
2017 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
2018 {
2019     if (pwallet == 0)
2020         return 0;
2021
2022     // Must wait until coinbase is safely deep enough in the chain before valuing it
2023     if (IsCoinBase() && GetBlocksToMaturity() > 0)
2024         return 0;
2025
2026     if (fUseCache && fAvailableWatchCreditCached)
2027         return nAvailableWatchCreditCached;
2028
2029     CAmount nCredit = 0;
2030     for (unsigned int i = 0; i < vout.size(); i++)
2031     {
2032         if (!pwallet->IsSpent(GetHash(), i))
2033         {
2034             const CTxOut &txout = vout[i];
2035             nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2036             if (!MoneyRange(nCredit))
2037                 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2038         }
2039     }
2040
2041     nAvailableWatchCreditCached = nCredit;
2042     fAvailableWatchCreditCached = true;
2043     return nCredit;
2044 }
2045
2046 CAmount CWalletTx::GetChange() const
2047 {
2048     if (fChangeCached)
2049         return nChangeCached;
2050     nChangeCached = pwallet->GetChange(*this);
2051     fChangeCached = true;
2052     return nChangeCached;
2053 }
2054
2055 bool CWalletTx::IsTrusted() const
2056 {
2057     // Quick answer in most cases
2058     if (!CheckFinalTx(*this))
2059         return false;
2060     int nDepth = GetDepthInMainChain();
2061     if (nDepth >= 1)
2062         return true;
2063     if (nDepth < 0)
2064         return false;
2065     if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2066         return false;
2067
2068     // Trusted if all inputs are from us and are in the mempool:
2069     BOOST_FOREACH(const CTxIn& txin, vin)
2070     {
2071         // Transactions not sent by us: not trusted
2072         const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2073         if (parent == NULL)
2074             return false;
2075         const CTxOut& parentOut = parent->vout[txin.prevout.n];
2076         if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2077             return false;
2078     }
2079     return true;
2080 }
2081
2082 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
2083 {
2084     std::vector<uint256> result;
2085
2086     LOCK(cs_wallet);
2087     // Sort them in chronological order
2088     multimap<unsigned int, CWalletTx*> mapSorted;
2089     BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2090     {
2091         CWalletTx& wtx = item.second;
2092         // Don't rebroadcast if newer than nTime:
2093         if (wtx.nTimeReceived > nTime)
2094             continue;
2095         mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2096     }
2097     BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2098     {
2099         CWalletTx& wtx = *item.second;
2100         if (wtx.RelayWalletTransaction())
2101             result.push_back(wtx.GetHash());
2102     }
2103     return result;
2104 }
2105
2106 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
2107 {
2108     // Do this infrequently and randomly to avoid giving away
2109     // that these are our transactions.
2110     if (GetTime() < nNextResend || !fBroadcastTransactions)
2111         return;
2112     bool fFirst = (nNextResend == 0);
2113     nNextResend = GetTime() + GetRand(30 * 60);
2114     if (fFirst)
2115         return;
2116
2117     // Only do it if there's been a new block since last time
2118     if (nBestBlockTime < nLastResend)
2119         return;
2120     nLastResend = GetTime();
2121
2122     // Rebroadcast unconfirmed txes older than 5 minutes before the last
2123     // block was found:
2124     std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
2125     if (!relayed.empty())
2126         LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2127 }
2128
2129 /** @} */ // end of mapWallet
2130
2131
2132
2133
2134 /** @defgroup Actions
2135  *
2136  * @{
2137  */
2138
2139
2140 CAmount CWallet::GetBalance() const
2141 {
2142     CAmount nTotal = 0;
2143     {
2144         LOCK2(cs_main, cs_wallet);
2145         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2146         {
2147             const CWalletTx* pcoin = &(*it).second;
2148             if (pcoin->IsTrusted())
2149                 nTotal += pcoin->GetAvailableCredit();
2150         }
2151     }
2152
2153     return nTotal;
2154 }
2155
2156 CAmount CWallet::GetUnconfirmedBalance() const
2157 {
2158     CAmount nTotal = 0;
2159     {
2160         LOCK2(cs_main, cs_wallet);
2161         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2162         {
2163             const CWalletTx* pcoin = &(*it).second;
2164             if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2165                 nTotal += pcoin->GetAvailableCredit();
2166         }
2167     }
2168     return nTotal;
2169 }
2170
2171 CAmount CWallet::GetImmatureBalance() const
2172 {
2173     CAmount nTotal = 0;
2174     {
2175         LOCK2(cs_main, cs_wallet);
2176         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2177         {
2178             const CWalletTx* pcoin = &(*it).second;
2179             nTotal += pcoin->GetImmatureCredit();
2180         }
2181     }
2182     return nTotal;
2183 }
2184
2185 CAmount CWallet::GetWatchOnlyBalance() const
2186 {
2187     CAmount nTotal = 0;
2188     {
2189         LOCK2(cs_main, cs_wallet);
2190         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2191         {
2192             const CWalletTx* pcoin = &(*it).second;
2193             if (pcoin->IsTrusted())
2194                 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2195         }
2196     }
2197
2198     return nTotal;
2199 }
2200
2201 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2202 {
2203     CAmount nTotal = 0;
2204     {
2205         LOCK2(cs_main, cs_wallet);
2206         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2207         {
2208             const CWalletTx* pcoin = &(*it).second;
2209             if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2210                 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2211         }
2212     }
2213     return nTotal;
2214 }
2215
2216 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2217 {
2218     CAmount nTotal = 0;
2219     {
2220         LOCK2(cs_main, cs_wallet);
2221         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2222         {
2223             const CWalletTx* pcoin = &(*it).second;
2224             nTotal += pcoin->GetImmatureWatchOnlyCredit();
2225         }
2226     }
2227     return nTotal;
2228 }
2229
2230 /**
2231  * populate vCoins with vector of available COutputs.
2232  */
2233 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const
2234 {
2235     vCoins.clear();
2236
2237     {
2238         LOCK2(cs_main, cs_wallet);
2239         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2240         {
2241             const uint256& wtxid = it->first;
2242             const CWalletTx* pcoin = &(*it).second;
2243
2244             if (!CheckFinalTx(*pcoin))
2245                 continue;
2246
2247             if (fOnlyConfirmed && !pcoin->IsTrusted())
2248                 continue;
2249
2250             if (pcoin->IsCoinBase() && !fIncludeCoinBase)
2251                 continue;
2252
2253             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2254                 continue;
2255
2256             int nDepth = pcoin->GetDepthInMainChain();
2257             if (nDepth < 0)
2258                 continue;
2259
2260             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2261                 isminetype mine = IsMine(pcoin->vout[i]);
2262                 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2263                     !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
2264                     (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
2265                         vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
2266             }
2267         }
2268     }
2269 }
2270
2271 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2272                                   vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2273 {
2274     vector<char> vfIncluded;
2275
2276     vfBest.assign(vValue.size(), true);
2277     nBest = nTotalLower;
2278
2279     seed_insecure_rand();
2280
2281     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2282     {
2283         vfIncluded.assign(vValue.size(), false);
2284         CAmount nTotal = 0;
2285         bool fReachedTarget = false;
2286         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2287         {
2288             for (unsigned int i = 0; i < vValue.size(); i++)
2289             {
2290                 //The solver here uses a randomized algorithm,
2291                 //the randomness serves no real security purpose but is just
2292                 //needed to prevent degenerate behavior and it is important
2293                 //that the rng is fast. We do not use a constant random sequence,
2294                 //because there may be some privacy improvement by making
2295                 //the selection random.
2296                 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
2297                 {
2298                     nTotal += vValue[i].first;
2299                     vfIncluded[i] = true;
2300                     if (nTotal >= nTargetValue)
2301                     {
2302                         fReachedTarget = true;
2303                         if (nTotal < nBest)
2304                         {
2305                             nBest = nTotal;
2306                             vfBest = vfIncluded;
2307                         }
2308                         nTotal -= vValue[i].first;
2309                         vfIncluded[i] = false;
2310                     }
2311                 }
2312             }
2313         }
2314     }
2315 }
2316
2317 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2318                                  set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
2319 {
2320     setCoinsRet.clear();
2321     nValueRet = 0;
2322
2323     // List of values less than target
2324     pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2325     coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2326     coinLowestLarger.second.first = NULL;
2327     vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2328     CAmount nTotalLower = 0;
2329
2330     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2331
2332     BOOST_FOREACH(const COutput &output, vCoins)
2333     {
2334         if (!output.fSpendable)
2335             continue;
2336
2337         const CWalletTx *pcoin = output.tx;
2338
2339         if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2340             continue;
2341
2342         int i = output.i;
2343         CAmount n = pcoin->vout[i].nValue;
2344
2345         pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2346
2347         if (n == nTargetValue)
2348         {
2349             setCoinsRet.insert(coin.second);
2350             nValueRet += coin.first;
2351             return true;
2352         }
2353         else if (n < nTargetValue + CENT)
2354         {
2355             vValue.push_back(coin);
2356             nTotalLower += n;
2357         }
2358         else if (n < coinLowestLarger.first)
2359         {
2360             coinLowestLarger = coin;
2361         }
2362     }
2363
2364     if (nTotalLower == nTargetValue)
2365     {
2366         for (unsigned int i = 0; i < vValue.size(); ++i)
2367         {
2368             setCoinsRet.insert(vValue[i].second);
2369             nValueRet += vValue[i].first;
2370         }
2371         return true;
2372     }
2373
2374     if (nTotalLower < nTargetValue)
2375     {
2376         if (coinLowestLarger.second.first == NULL)
2377             return false;
2378         setCoinsRet.insert(coinLowestLarger.second);
2379         nValueRet += coinLowestLarger.first;
2380         return true;
2381     }
2382
2383     // Solve subset sum by stochastic approximation
2384     sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
2385     vector<char> vfBest;
2386     CAmount nBest;
2387
2388     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
2389     if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
2390         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
2391
2392     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2393     //                                   or the next bigger coin is closer), return the bigger coin
2394     if (coinLowestLarger.second.first &&
2395         ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
2396     {
2397         setCoinsRet.insert(coinLowestLarger.second);
2398         nValueRet += coinLowestLarger.first;
2399     }
2400     else {
2401         for (unsigned int i = 0; i < vValue.size(); i++)
2402             if (vfBest[i])
2403             {
2404                 setCoinsRet.insert(vValue[i].second);
2405                 nValueRet += vValue[i].first;
2406             }
2407
2408         LogPrint("selectcoins", "SelectCoins() best subset: ");
2409         for (unsigned int i = 0; i < vValue.size(); i++)
2410             if (vfBest[i])
2411                 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2412         LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
2413     }
2414
2415     return true;
2416 }
2417
2418 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet,  bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
2419 {
2420     // Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
2421     vector<COutput> vCoinsNoCoinbase, vCoinsWithCoinbase;
2422     AvailableCoins(vCoinsNoCoinbase, true, coinControl, false, false);
2423     AvailableCoins(vCoinsWithCoinbase, true, coinControl, false, true);
2424     fOnlyCoinbaseCoinsRet = vCoinsNoCoinbase.size() == 0 && vCoinsWithCoinbase.size() > 0;
2425
2426     // If coinbase utxos can only be sent to zaddrs, exclude any coinbase utxos from coin selection.
2427     bool fProtectCoinbase = Params().GetConsensus().fCoinbaseMustBeProtected;
2428     vector<COutput> vCoins = (fProtectCoinbase) ? vCoinsNoCoinbase : vCoinsWithCoinbase;
2429
2430     // Output parameter fNeedCoinbaseCoinsRet is set to true if coinbase utxos need to be spent to meet target amount
2431     if (fProtectCoinbase && vCoinsWithCoinbase.size() > vCoinsNoCoinbase.size()) {
2432         CAmount value = 0;
2433         for (const COutput& out : vCoinsNoCoinbase) {
2434             if (!out.fSpendable) {
2435                 continue;
2436             }
2437             value += out.tx->vout[out.i].nValue;
2438         }
2439         if (value <= nTargetValue) {
2440             CAmount valueWithCoinbase = 0;
2441             for (const COutput& out : vCoinsWithCoinbase) {
2442                 if (!out.fSpendable) {
2443                     continue;
2444                 }
2445                 valueWithCoinbase += out.tx->vout[out.i].nValue;
2446             }
2447             fNeedCoinbaseCoinsRet = (valueWithCoinbase >= nTargetValue);
2448         }
2449     }
2450
2451     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2452     if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2453     {
2454         BOOST_FOREACH(const COutput& out, vCoins)
2455         {
2456             if (!out.fSpendable)
2457                  continue;
2458             nValueRet += out.tx->vout[out.i].nValue;
2459             setCoinsRet.insert(make_pair(out.tx, out.i));
2460         }
2461         return (nValueRet >= nTargetValue);
2462     }
2463
2464     // calculate value from preset inputs and store them
2465     set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2466     CAmount nValueFromPresetInputs = 0;
2467
2468     std::vector<COutPoint> vPresetInputs;
2469     if (coinControl)
2470         coinControl->ListSelected(vPresetInputs);
2471     BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2472     {
2473         map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2474         if (it != mapWallet.end())
2475         {
2476             const CWalletTx* pcoin = &it->second;
2477             // Clearly invalid input, fail
2478             if (pcoin->vout.size() <= outpoint.n)
2479                 return false;
2480             nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
2481             setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2482         } else
2483             return false; // TODO: Allow non-wallet inputs
2484     }
2485
2486     // remove preset inputs from vCoins
2487     for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2488     {
2489         if (setPresetCoins.count(make_pair(it->tx, it->i)))
2490             it = vCoins.erase(it);
2491         else
2492             ++it;
2493     }
2494
2495     bool res = nTargetValue <= nValueFromPresetInputs ||
2496         SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2497         SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2498         (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
2499
2500     // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2501     setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2502
2503     // add preset inputs to the total value selected
2504     nValueRet += nValueFromPresetInputs;
2505
2506     return res;
2507 }
2508
2509 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason)
2510 {
2511     vector<CRecipient> vecSend;
2512
2513     // Turn the txout set into a CRecipient vector
2514     BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2515     {
2516         CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2517         vecSend.push_back(recipient);
2518     }
2519
2520     CCoinControl coinControl;
2521     coinControl.fAllowOtherInputs = true;
2522     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2523         coinControl.Select(txin.prevout);
2524
2525     CReserveKey reservekey(this);
2526     CWalletTx wtx;
2527     
2528     if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
2529         return false;
2530
2531     if (nChangePosRet != -1)
2532         tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
2533
2534     // Add new txins (keeping original txin scriptSig/order)
2535     BOOST_FOREACH(const CTxIn& txin, wtx.vin)
2536     {
2537         bool found = false;
2538         BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
2539         {
2540             if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
2541             {
2542                 found = true;
2543                 break;
2544             }
2545         }
2546         if (!found)
2547             tx.vin.push_back(txin);
2548     }
2549
2550     return true;
2551 }
2552
2553 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2554                                 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2555 {
2556     CAmount nValue = 0;
2557     unsigned int nSubtractFeeFromAmount = 0;
2558     BOOST_FOREACH (const CRecipient& recipient, vecSend)
2559     {
2560         if (nValue < 0 || recipient.nAmount < 0)
2561         {
2562             strFailReason = _("Transaction amounts must be positive");
2563             return false;
2564         }
2565         nValue += recipient.nAmount;
2566
2567         if (recipient.fSubtractFeeFromAmount)
2568             nSubtractFeeFromAmount++;
2569     }
2570     if (vecSend.empty() || nValue < 0)
2571     {
2572         strFailReason = _("Transaction amounts must be positive");
2573         return false;
2574     }
2575
2576     wtxNew.fTimeReceivedIsTxTime = true;
2577     wtxNew.BindWallet(this);
2578     int nextBlockHeight = chainActive.Height() + 1;
2579     CMutableTransaction txNew = CreateNewContextualCMutableTransaction(
2580         Params().GetConsensus(), nextBlockHeight);
2581
2582     // Activates after Overwinter network upgrade
2583     // Set nExpiryHeight to expiryDelta (default 20) blocks past current block height
2584     if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
2585         if (nextBlockHeight + expiryDelta >= TX_EXPIRY_HEIGHT_THRESHOLD){
2586             strFailReason = _("nExpiryHeight must be less than TX_EXPIRY_HEIGHT_THRESHOLD.");
2587             return false;
2588         } else {
2589             txNew.nExpiryHeight = nextBlockHeight + expiryDelta;
2590         }
2591     }
2592     
2593     // Discourage fee sniping.
2594     //
2595     // However because of a off-by-one-error in previous versions we need to
2596     // neuter it by setting nLockTime to at least one less than nBestHeight.
2597     // Secondly currently propagation of transactions created for block heights
2598     // corresponding to blocks that were just mined may be iffy - transactions
2599     // aren't re-accepted into the mempool - we additionally neuter the code by
2600     // going ten blocks back. Doesn't yet do anything for sniping, but does act
2601     // to shake out wallet bugs like not showing nLockTime'd transactions at
2602     // all.
2603     txNew.nLockTime = std::max(0, chainActive.Height() - 10);
2604
2605     // Secondly occasionally randomly pick a nLockTime even further back, so
2606     // that transactions that are delayed after signing for whatever reason,
2607     // e.g. high-latency mix networks and some CoinJoin implementations, have
2608     // better privacy.
2609     if (GetRandInt(10) == 0)
2610         txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2611
2612     assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2613     assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2614
2615     {
2616         LOCK2(cs_main, cs_wallet);
2617         {
2618             nFeeRet = 0;
2619             while (true)
2620             {
2621                 txNew.vin.clear();
2622                 txNew.vout.clear();
2623                 wtxNew.fFromMe = true;
2624                 nChangePosRet = -1;
2625                 bool fFirst = true;
2626
2627                 CAmount nTotalValue = nValue;
2628                 if (nSubtractFeeFromAmount == 0)
2629                     nTotalValue += nFeeRet;
2630                 double dPriority = 0;
2631                 // vouts to the payees
2632                 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2633                 {
2634                     CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2635
2636                     if (recipient.fSubtractFeeFromAmount)
2637                     {
2638                         txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2639
2640                         if (fFirst) // first receiver pays the remainder not divisible by output count
2641                         {
2642                             fFirst = false;
2643                             txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2644                         }
2645                     }
2646
2647                     if (txout.IsDust(::minRelayTxFee))
2648                     {
2649                         if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2650                         {
2651                             if (txout.nValue < 0)
2652                                 strFailReason = _("The transaction amount is too small to pay the fee");
2653                             else
2654                                 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2655                         }
2656                         else
2657                             strFailReason = _("Transaction amount too small");
2658                         return false;
2659                     }
2660                     txNew.vout.push_back(txout);
2661                 }
2662
2663                 // Choose coins to use
2664                 set<pair<const CWalletTx*,unsigned int> > setCoins;
2665                 CAmount nValueIn = 0;
2666                 bool fOnlyCoinbaseCoins = false;
2667                 bool fNeedCoinbaseCoins = false;
2668                 if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl))
2669                 {
2670                     if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) {
2671                         strFailReason = _("Coinbase funds can only be sent to a zaddr");
2672                     } else if (fNeedCoinbaseCoins) {
2673                         strFailReason = _("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr");
2674                     } else {
2675                         strFailReason = _("Insufficient funds");
2676                     }
2677                     return false;
2678                 }
2679                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2680                 {
2681                     CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2682                     //The coin age after the next block (depth+1) is used instead of the current,
2683                     //reflecting an assumption the user would accept a bit more delay for
2684                     //a chance at a free transaction.
2685                     //But mempool inputs might still be in the mempool, so their age stays 0
2686                     int age = pcoin.first->GetDepthInMainChain();
2687                     if (age != 0)
2688                         age += 1;
2689                     dPriority += (double)nCredit * age;
2690                 }
2691
2692                 CAmount nChange = nValueIn - nValue;
2693                 if (nSubtractFeeFromAmount == 0)
2694                     nChange -= nFeeRet;
2695
2696                 if (nChange > 0)
2697                 {
2698                     // Fill a vout to ourself
2699                     // TODO: pass in scriptChange instead of reservekey so
2700                     // change transaction isn't always pay-to-bitcoin-address
2701                     CScript scriptChange;
2702
2703                     // coin control: send change to custom address
2704                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2705                         scriptChange = GetScriptForDestination(coinControl->destChange);
2706
2707                     // no coin control: send change to newly generated address
2708                     else
2709                     {
2710                         // Note: We use a new key here to keep it from being obvious which side is the change.
2711                         //  The drawback is that by not reusing a previous key, the change may be lost if a
2712                         //  backup is restored, if the backup doesn't have the new private key for the change.
2713                         //  If we reused the old key, it would be possible to add code to look for and
2714                         //  rediscover unknown transactions that were written with keys of ours to recover
2715                         //  post-backup change.
2716
2717                         // Reserve a new key pair from key pool
2718                         CPubKey vchPubKey;
2719                         bool ret;
2720                         ret = reservekey.GetReservedKey(vchPubKey);
2721                         assert(ret); // should never fail, as we just unlocked
2722
2723                         scriptChange = GetScriptForDestination(vchPubKey.GetID());
2724                     }
2725
2726                     CTxOut newTxOut(nChange, scriptChange);
2727
2728                     // We do not move dust-change to fees, because the sender would end up paying more than requested.
2729                     // This would be against the purpose of the all-inclusive feature.
2730                     // So instead we raise the change and deduct from the recipient.
2731                     if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2732                     {
2733                         CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2734                         newTxOut.nValue += nDust; // raise change until no more dust
2735                         for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2736                         {
2737                             if (vecSend[i].fSubtractFeeFromAmount)
2738                             {
2739                                 txNew.vout[i].nValue -= nDust;
2740                                 if (txNew.vout[i].IsDust(::minRelayTxFee))
2741                                 {
2742                                     strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2743                                     return false;
2744                                 }
2745                                 break;
2746                             }
2747                         }
2748                     }
2749
2750                     // Never create dust outputs; if we would, just
2751                     // add the dust to the fee.
2752                     if (newTxOut.IsDust(::minRelayTxFee))
2753                     {
2754                         nFeeRet += nChange;
2755                         reservekey.ReturnKey();
2756                     }
2757                     else
2758                     {
2759                         // Insert change txn at random position:
2760                         nChangePosRet = GetRandInt(txNew.vout.size()+1);
2761                         vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
2762                         txNew.vout.insert(position, newTxOut);
2763                     }
2764                 }
2765                 else
2766                     reservekey.ReturnKey();
2767
2768                 // Fill vin
2769                 //
2770                 // Note how the sequence number is set to max()-1 so that the
2771                 // nLockTime set above actually works.
2772                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2773                     txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2774                                               std::numeric_limits<unsigned int>::max()-1));
2775
2776                 // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
2777                 size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
2778                 {
2779                     LOCK(cs_main);
2780                     if (NetworkUpgradeActive(chainActive.Height() + 1, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
2781                         limit = 0;
2782                     }
2783                 }
2784                 if (limit > 0) {
2785                     size_t n = txNew.vin.size();
2786                     if (n > limit) {
2787                         strFailReason = _(strprintf("Too many transparent inputs %zu > limit %zu", n, limit).c_str());
2788                         return false;
2789                     }
2790                 }
2791
2792                 // Grab the current consensus branch ID
2793                 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
2794
2795                 // Sign
2796                 int nIn = 0;
2797                 CTransaction txNewConst(txNew);
2798                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2799                 {
2800                     bool signSuccess;
2801                     const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
2802                     SignatureData sigdata;
2803                     if (sign)
2804                         signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata, consensusBranchId);
2805                     else
2806                         signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata, consensusBranchId);
2807
2808                     if (!signSuccess)
2809                     {
2810                         strFailReason = _("Signing transaction failed");
2811                         return false;
2812                     } else {
2813                         UpdateTransaction(txNew, nIn, sigdata);
2814                     }
2815
2816                     nIn++;
2817                 }
2818
2819                 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2820
2821                 // Remove scriptSigs if we used dummy signatures for fee calculation
2822                 if (!sign) {
2823                     BOOST_FOREACH (CTxIn& vin, txNew.vin)
2824                         vin.scriptSig = CScript();
2825                 }
2826
2827                 // Embed the constructed transaction data in wtxNew.
2828                 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
2829
2830                 // Limit size
2831                 if (nBytes >= MAX_TX_SIZE)
2832                 {
2833                     strFailReason = _("Transaction too large");
2834                     return false;
2835                 }
2836
2837                 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
2838
2839                 // Can we complete this as a free transaction?
2840                 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2841                 {
2842                     // Not enough fee: enough priority?
2843                     double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
2844                     // Not enough mempool history to estimate: use hard-coded AllowFree.
2845                     if (dPriorityNeeded <= 0 && AllowFree(dPriority))
2846                         break;
2847
2848                     // Small enough, and priority high enough, to send for free
2849                     if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
2850                         break;
2851                 }
2852
2853                 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
2854
2855                 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2856                 // because we must be at the maximum allowed fee.
2857                 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2858                 {
2859                     strFailReason = _("Transaction too large for fee policy");
2860                     return false;
2861                 }
2862
2863                 if (nFeeRet >= nFeeNeeded)
2864                     break; // Done, enough fee included.
2865
2866                 // Include more fee and try again.
2867                 nFeeRet = nFeeNeeded;
2868                 continue;
2869             }
2870         }
2871     }
2872
2873     return true;
2874 }
2875
2876 /**
2877  * Call after CreateTransaction unless you want to abort
2878  */
2879 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2880 {
2881     {
2882         LOCK2(cs_main, cs_wallet);
2883         LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
2884         {
2885             // This is only to keep the database open to defeat the auto-flush for the
2886             // duration of this scope.  This is the only place where this optimization
2887             // maybe makes sense; please don't do it anywhere else.
2888             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
2889
2890             // Take key pair from key pool so it won't be used again
2891             reservekey.KeepKey();
2892
2893             // Add tx to wallet, because if it has change it's also ours,
2894             // otherwise just for transaction history.
2895             AddToWallet(wtxNew, false, pwalletdb);
2896
2897             // Notify that old coins are spent
2898             set<CWalletTx*> setCoins;
2899             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2900             {
2901                 CWalletTx &coin = mapWallet[txin.prevout.hash];
2902                 coin.BindWallet(this);
2903                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2904             }
2905
2906             if (fFileBacked)
2907                 delete pwalletdb;
2908         }
2909
2910         // Track how many getdata requests our transaction gets
2911         mapRequestCount[wtxNew.GetHash()] = 0;
2912
2913         if (fBroadcastTransactions)
2914         {
2915             // Broadcast
2916             if (!wtxNew.AcceptToMemoryPool(false))
2917             {
2918                 // This must not fail. The transaction has already been signed and recorded.
2919                 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
2920                 return false;
2921             }
2922             wtxNew.RelayWalletTransaction();
2923         }
2924     }
2925     return true;
2926 }
2927
2928 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2929 {
2930     // payTxFee is user-set "I want to pay this much"
2931     CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2932     // user selected total at least (default=true)
2933     if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
2934         nFeeNeeded = payTxFee.GetFeePerK();
2935     // User didn't set: use -txconfirmtarget to estimate...
2936     if (nFeeNeeded == 0)
2937         nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
2938     // ... unless we don't have enough mempool data, in which case fall
2939     // back to a hard-coded fee
2940     if (nFeeNeeded == 0)
2941         nFeeNeeded = minTxFee.GetFee(nTxBytes);
2942     // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
2943     if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
2944         nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
2945     // But always obey the maximum
2946     if (nFeeNeeded > maxTxFee)
2947         nFeeNeeded = maxTxFee;
2948     return nFeeNeeded;
2949 }
2950
2951
2952
2953
2954 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2955 {
2956     if (!fFileBacked)
2957         return DB_LOAD_OK;
2958     fFirstRunRet = false;
2959     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2960     if (nLoadWalletRet == DB_NEED_REWRITE)
2961     {
2962         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2963         {
2964             LOCK(cs_wallet);
2965             setKeyPool.clear();
2966             // Note: can't top-up keypool here, because wallet is locked.
2967             // User will be prompted to unlock wallet the next operation
2968             // that requires a new key.
2969         }
2970     }
2971
2972     if (nLoadWalletRet != DB_LOAD_OK)
2973         return nLoadWalletRet;
2974     fFirstRunRet = !vchDefaultKey.IsValid();
2975
2976     uiInterface.LoadWallet(this);
2977
2978     return DB_LOAD_OK;
2979 }
2980
2981
2982 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2983 {
2984     if (!fFileBacked)
2985         return DB_LOAD_OK;
2986     DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2987     if (nZapWalletTxRet == DB_NEED_REWRITE)
2988     {
2989         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2990         {
2991             LOCK(cs_wallet);
2992             setKeyPool.clear();
2993             // Note: can't top-up keypool here, because wallet is locked.
2994             // User will be prompted to unlock wallet the next operation
2995             // that requires a new key.
2996         }
2997     }
2998
2999     if (nZapWalletTxRet != DB_LOAD_OK)
3000         return nZapWalletTxRet;
3001
3002     return DB_LOAD_OK;
3003 }
3004
3005
3006 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
3007 {
3008     bool fUpdated = false;
3009     {
3010         LOCK(cs_wallet); // mapAddressBook
3011         std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3012         fUpdated = mi != mapAddressBook.end();
3013         mapAddressBook[address].name = strName;
3014         if (!strPurpose.empty()) /* update purpose only if requested */
3015             mapAddressBook[address].purpose = strPurpose;
3016     }
3017     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3018                              strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3019     if (!fFileBacked)
3020         return false;
3021     if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3022         return false;
3023     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
3024 }
3025
3026 bool CWallet::DelAddressBook(const CTxDestination& address)
3027 {
3028     {
3029         LOCK(cs_wallet); // mapAddressBook
3030
3031         if(fFileBacked)
3032         {
3033             // Delete destdata tuples associated with address
3034             std::string strAddress = CBitcoinAddress(address).ToString();
3035             BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3036             {
3037                 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3038             }
3039         }
3040         mapAddressBook.erase(address);
3041     }
3042
3043     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3044
3045     if (!fFileBacked)
3046         return false;
3047     CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
3048     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
3049 }
3050
3051 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3052 {
3053     if (fFileBacked)
3054     {
3055         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3056             return false;
3057     }
3058     vchDefaultKey = vchPubKey;
3059     return true;
3060 }
3061
3062 /**
3063  * Mark old keypool keys as used,
3064  * and generate all new keys 
3065  */
3066 bool CWallet::NewKeyPool()
3067 {
3068     {
3069         LOCK(cs_wallet);
3070         CWalletDB walletdb(strWalletFile);
3071         BOOST_FOREACH(int64_t nIndex, setKeyPool)
3072             walletdb.ErasePool(nIndex);
3073         setKeyPool.clear();
3074
3075         if (IsLocked())
3076             return false;
3077
3078         int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
3079         for (int i = 0; i < nKeys; i++)
3080         {
3081             int64_t nIndex = i+1;
3082             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
3083             setKeyPool.insert(nIndex);
3084         }
3085         LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
3086     }
3087     return true;
3088 }
3089
3090 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3091 {
3092     {
3093         LOCK(cs_wallet);
3094
3095         if (IsLocked())
3096             return false;
3097
3098         CWalletDB walletdb(strWalletFile);
3099
3100         // Top up key pool
3101         unsigned int nTargetSize;
3102         if (kpSize > 0)
3103             nTargetSize = kpSize;
3104         else
3105             nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
3106
3107         while (setKeyPool.size() < (nTargetSize + 1))
3108         {
3109             int64_t nEnd = 1;
3110             if (!setKeyPool.empty())
3111                 nEnd = *(--setKeyPool.end()) + 1;
3112             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
3113                 throw runtime_error("TopUpKeyPool(): writing generated key failed");
3114             setKeyPool.insert(nEnd);
3115             LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
3116         }
3117     }
3118     return true;
3119 }
3120
3121 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
3122 {
3123     nIndex = -1;
3124     keypool.vchPubKey = CPubKey();
3125     {
3126         LOCK(cs_wallet);
3127
3128         if (!IsLocked())
3129             TopUpKeyPool();
3130
3131         // Get the oldest key
3132         if(setKeyPool.empty())
3133             return;
3134
3135         CWalletDB walletdb(strWalletFile);
3136
3137         nIndex = *(setKeyPool.begin());
3138         setKeyPool.erase(setKeyPool.begin());
3139         if (!walletdb.ReadPool(nIndex, keypool))
3140             throw runtime_error("ReserveKeyFromKeyPool(): read failed");
3141         if (!HaveKey(keypool.vchPubKey.GetID()))
3142             throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
3143         assert(keypool.vchPubKey.IsValid());
3144         LogPrintf("keypool reserve %d\n", nIndex);
3145     }
3146 }
3147
3148 void CWallet::KeepKey(int64_t nIndex)
3149 {
3150     // Remove from key pool
3151     if (fFileBacked)
3152     {
3153         CWalletDB walletdb(strWalletFile);
3154         walletdb.ErasePool(nIndex);
3155     }
3156     LogPrintf("keypool keep %d\n", nIndex);
3157 }
3158
3159 void CWallet::ReturnKey(int64_t nIndex)
3160 {
3161     // Return to key pool
3162     {
3163         LOCK(cs_wallet);
3164         setKeyPool.insert(nIndex);
3165     }
3166     LogPrintf("keypool return %d\n", nIndex);
3167 }
3168
3169 bool CWallet::GetKeyFromPool(CPubKey& result)
3170 {
3171     int64_t nIndex = 0;
3172     CKeyPool keypool;
3173     {
3174         LOCK(cs_wallet);
3175         ReserveKeyFromKeyPool(nIndex, keypool);
3176         if (nIndex == -1)
3177         {
3178             if (IsLocked()) return false;
3179             result = GenerateNewKey();
3180             return true;
3181         }
3182         KeepKey(nIndex);
3183         result = keypool.vchPubKey;
3184     }
3185     return true;
3186 }
3187
3188 int64_t CWallet::GetOldestKeyPoolTime()
3189 {
3190     int64_t nIndex = 0;
3191     CKeyPool keypool;
3192     ReserveKeyFromKeyPool(nIndex, keypool);
3193     if (nIndex == -1)
3194         return GetTime();
3195     ReturnKey(nIndex);
3196     return keypool.nTime;
3197 }
3198
3199 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3200 {
3201     map<CTxDestination, CAmount> balances;
3202
3203     {
3204         LOCK(cs_wallet);
3205         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3206         {
3207             CWalletTx *pcoin = &walletEntry.second;
3208
3209             if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
3210                 continue;
3211
3212             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3213                 continue;
3214
3215             int nDepth = pcoin->GetDepthInMainChain();
3216             if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3217                 continue;
3218
3219             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3220             {
3221                 CTxDestination addr;
3222                 if (!IsMine(pcoin->vout[i]))
3223                     continue;
3224                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3225                     continue;
3226
3227                 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
3228
3229                 if (!balances.count(addr))
3230                     balances[addr] = 0;
3231                 balances[addr] += n;
3232             }
3233         }
3234     }
3235
3236     return balances;
3237 }
3238
3239 set< set<CTxDestination> > CWallet::GetAddressGroupings()
3240 {
3241     AssertLockHeld(cs_wallet); // mapWallet
3242     set< set<CTxDestination> > groupings;
3243     set<CTxDestination> grouping;
3244
3245     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3246     {
3247         CWalletTx *pcoin = &walletEntry.second;
3248
3249         if (pcoin->vin.size() > 0)
3250         {
3251             bool any_mine = false;
3252             // group all input addresses with each other
3253             BOOST_FOREACH(CTxIn txin, pcoin->vin)
3254             {
3255                 CTxDestination address;
3256                 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3257                     continue;
3258                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
3259                     continue;
3260                 grouping.insert(address);
3261                 any_mine = true;
3262             }
3263
3264             // group change with input addresses
3265             if (any_mine)
3266             {
3267                BOOST_FOREACH(CTxOut txout, pcoin->vout)
3268                    if (IsChange(txout))
3269                    {
3270                        CTxDestination txoutAddr;
3271                        if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3272                            continue;
3273                        grouping.insert(txoutAddr);
3274                    }
3275             }
3276             if (grouping.size() > 0)
3277             {
3278                 groupings.insert(grouping);
3279                 grouping.clear();
3280             }
3281         }
3282
3283         // group lone addrs by themselves
3284         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3285             if (IsMine(pcoin->vout[i]))
3286             {
3287                 CTxDestination address;
3288                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
3289                     continue;
3290                 grouping.insert(address);
3291                 groupings.insert(grouping);
3292                 grouping.clear();
3293             }
3294     }
3295
3296     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3297     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
3298     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
3299     {
3300         // make a set of all the groups hit by this new group
3301         set< set<CTxDestination>* > hits;
3302         map< CTxDestination, set<CTxDestination>* >::iterator it;
3303         BOOST_FOREACH(CTxDestination address, grouping)
3304             if ((it = setmap.find(address)) != setmap.end())
3305                 hits.insert((*it).second);
3306
3307         // merge all hit groups into a new single group and delete old groups
3308         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
3309         BOOST_FOREACH(set<CTxDestination>* hit, hits)
3310         {
3311             merged->insert(hit->begin(), hit->end());
3312             uniqueGroupings.erase(hit);
3313             delete hit;
3314         }
3315         uniqueGroupings.insert(merged);
3316
3317         // update setmap
3318         BOOST_FOREACH(CTxDestination element, *merged)
3319             setmap[element] = merged;
3320     }
3321
3322     set< set<CTxDestination> > ret;
3323     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3324     {
3325         ret.insert(*uniqueGrouping);
3326         delete uniqueGrouping;
3327     }
3328
3329     return ret;
3330 }
3331
3332 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3333 {
3334     LOCK(cs_wallet);
3335     set<CTxDestination> result;
3336     BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3337     {
3338         const CTxDestination& address = item.first;
3339         const string& strName = item.second.name;
3340         if (strName == strAccount)
3341             result.insert(address);
3342     }
3343     return result;
3344 }
3345
3346 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
3347 {
3348     if (nIndex == -1)
3349     {
3350         CKeyPool keypool;
3351         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3352         if (nIndex != -1)
3353             vchPubKey = keypool.vchPubKey;
3354         else {
3355             return false;
3356         }
3357     }
3358     assert(vchPubKey.IsValid());
3359     pubkey = vchPubKey;
3360     return true;
3361 }
3362
3363 void CReserveKey::KeepKey()
3364 {
3365     if (nIndex != -1)
3366         pwallet->KeepKey(nIndex);
3367     nIndex = -1;
3368     vchPubKey = CPubKey();
3369 }
3370
3371 void CReserveKey::ReturnKey()
3372 {
3373     if (nIndex != -1)
3374         pwallet->ReturnKey(nIndex);
3375     nIndex = -1;
3376     vchPubKey = CPubKey();
3377 }
3378
3379 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3380 {
3381     setAddress.clear();
3382
3383     CWalletDB walletdb(strWalletFile);
3384
3385     LOCK2(cs_main, cs_wallet);
3386     BOOST_FOREACH(const int64_t& id, setKeyPool)
3387     {
3388         CKeyPool keypool;
3389         if (!walletdb.ReadPool(id, keypool))
3390             throw runtime_error("GetAllReserveKeyHashes(): read failed");
3391         assert(keypool.vchPubKey.IsValid());
3392         CKeyID keyID = keypool.vchPubKey.GetID();
3393         if (!HaveKey(keyID))
3394             throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
3395         setAddress.insert(keyID);
3396     }
3397 }
3398
3399 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3400 {
3401     {
3402         LOCK(cs_wallet);
3403         // Only notify UI if this transaction is in this wallet
3404         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3405         if (mi != mapWallet.end())
3406             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3407     }
3408 }
3409
3410 void CWallet::LockCoin(COutPoint& output)
3411 {
3412     AssertLockHeld(cs_wallet); // setLockedCoins
3413     setLockedCoins.insert(output);
3414 }
3415
3416 void CWallet::UnlockCoin(COutPoint& output)
3417 {
3418     AssertLockHeld(cs_wallet); // setLockedCoins
3419     setLockedCoins.erase(output);
3420 }
3421
3422 void CWallet::UnlockAllCoins()
3423 {
3424     AssertLockHeld(cs_wallet); // setLockedCoins
3425     setLockedCoins.clear();
3426 }
3427
3428 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3429 {
3430     AssertLockHeld(cs_wallet); // setLockedCoins
3431     COutPoint outpt(hash, n);
3432
3433     return (setLockedCoins.count(outpt) > 0);
3434 }
3435
3436 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3437 {
3438     AssertLockHeld(cs_wallet); // setLockedCoins
3439     for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3440          it != setLockedCoins.end(); it++) {
3441         COutPoint outpt = (*it);
3442         vOutpts.push_back(outpt);
3443     }
3444 }
3445
3446 /** @} */ // end of Actions
3447
3448 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3449 private:
3450     const CKeyStore &keystore;
3451     std::vector<CKeyID> &vKeys;
3452
3453 public:
3454     CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3455
3456     void Process(const CScript &script) {
3457         txnouttype type;
3458         std::vector<CTxDestination> vDest;
3459         int nRequired;
3460         if (ExtractDestinations(script, type, vDest, nRequired)) {
3461             BOOST_FOREACH(const CTxDestination &dest, vDest)
3462                 boost::apply_visitor(*this, dest);
3463         }
3464     }
3465
3466     void operator()(const CKeyID &keyId) {
3467         if (keystore.HaveKey(keyId))
3468             vKeys.push_back(keyId);
3469     }
3470
3471     void operator()(const CScriptID &scriptId) {
3472         CScript script;
3473         if (keystore.GetCScript(scriptId, script))
3474             Process(script);
3475     }
3476
3477     void operator()(const CNoDestination &none) {}
3478 };
3479
3480 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
3481     AssertLockHeld(cs_wallet); // mapKeyMetadata
3482     mapKeyBirth.clear();
3483
3484     // get birth times for keys with metadata
3485     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3486         if (it->second.nCreateTime)
3487             mapKeyBirth[it->first] = it->second.nCreateTime;
3488
3489     // map in which we'll infer heights of other keys
3490     CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
3491     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3492     std::set<CKeyID> setKeys;
3493     GetKeys(setKeys);
3494     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3495         if (mapKeyBirth.count(keyid) == 0)
3496             mapKeyFirstBlock[keyid] = pindexMax;
3497     }
3498     setKeys.clear();
3499
3500     // if there are no such keys, we're done
3501     if (mapKeyFirstBlock.empty())
3502         return;
3503
3504     // find first block that affects those keys, if there are any left
3505     std::vector<CKeyID> vAffected;
3506     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3507         // iterate over all wallet transactions...
3508         const CWalletTx &wtx = (*it).second;
3509         BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3510         if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3511             // ... which are already in a block
3512             int nHeight = blit->second->nHeight;
3513             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
3514                 // iterate over all their outputs
3515                 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3516                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3517                     // ... and all their affected keys
3518                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3519                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3520                         rit->second = blit->second;
3521                 }
3522                 vAffected.clear();
3523             }
3524         }
3525     }
3526
3527     // Extract block timestamps for those keys
3528     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3529         mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
3530 }
3531
3532 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3533 {
3534     if (boost::get<CNoDestination>(&dest))
3535         return false;
3536
3537     mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3538     if (!fFileBacked)
3539         return true;
3540     return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3541 }
3542
3543 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3544 {
3545     if (!mapAddressBook[dest].destdata.erase(key))
3546         return false;
3547     if (!fFileBacked)
3548         return true;
3549     return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3550 }
3551
3552 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3553 {
3554     mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3555     return true;
3556 }
3557
3558 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3559 {
3560     std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3561     if(i != mapAddressBook.end())
3562     {
3563         CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3564         if(j != i->second.destdata.end())
3565         {
3566             if(value)
3567                 *value = j->second;
3568             return true;
3569         }
3570     }
3571     return false;
3572 }
3573
3574 CKeyPool::CKeyPool()
3575 {
3576     nTime = GetTime();
3577 }
3578
3579 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3580 {
3581     nTime = GetTime();
3582     vchPubKey = vchPubKeyIn;
3583 }
3584
3585 CWalletKey::CWalletKey(int64_t nExpires)
3586 {
3587     nTimeCreated = (nExpires ? GetTime() : 0);
3588     nTimeExpires = nExpires;
3589 }
3590
3591 int CMerkleTx::SetMerkleBranch(const CBlock& block)
3592 {
3593     AssertLockHeld(cs_main);
3594     CBlock blockTmp;
3595
3596     // Update the tx's hashBlock
3597     hashBlock = block.GetHash();
3598
3599     // Locate the transaction
3600     for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
3601         if (block.vtx[nIndex] == *(CTransaction*)this)
3602             break;
3603     if (nIndex == (int)block.vtx.size())
3604     {
3605         vMerkleBranch.clear();
3606         nIndex = -1;
3607         LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
3608         return 0;
3609     }
3610
3611     // Fill in merkle branch
3612     vMerkleBranch = block.GetMerkleBranch(nIndex);
3613
3614     // Is the tx in a block that's in the main chain
3615     BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3616     if (mi == mapBlockIndex.end())
3617         return 0;
3618     const CBlockIndex* pindex = (*mi).second;
3619     if (!pindex || !chainActive.Contains(pindex))
3620         return 0;
3621
3622     return chainActive.Height() - pindex->nHeight + 1;
3623 }
3624
3625 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
3626 {
3627     if (hashBlock.IsNull() || nIndex == -1)
3628         return 0;
3629     AssertLockHeld(cs_main);
3630
3631     // Find the block it claims to be in
3632     BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3633     if (mi == mapBlockIndex.end())
3634         return 0;
3635     CBlockIndex* pindex = (*mi).second;
3636     if (!pindex || !chainActive.Contains(pindex))
3637         return 0;
3638
3639     // Make sure the merkle branch connects to this block
3640     if (!fMerkleVerified)
3641     {
3642         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
3643             return 0;
3644         fMerkleVerified = true;
3645     }
3646
3647     pindexRet = pindex;
3648     return chainActive.Height() - pindex->nHeight + 1;
3649 }
3650
3651 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3652 {
3653     AssertLockHeld(cs_main);
3654     int nResult = GetDepthInMainChainINTERNAL(pindexRet);
3655     if (nResult == 0 && !mempool.exists(GetHash()))
3656         return -1; // Not in chain, not in mempool
3657
3658     return nResult;
3659 }
3660
3661 int CMerkleTx::GetBlocksToMaturity() const
3662 {
3663     if (!IsCoinBase())
3664         return 0;
3665     return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3666 }
3667
3668
3669 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
3670 {
3671     CValidationState state;
3672     return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
3673 }
3674
3675 /**
3676  * Find notes in the wallet filtered by payment address, min depth and ability to spend.
3677  * These notes are decrypted and added to the output parameter vector, outEntries.
3678  */
3679 void CWallet::GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries, std::string address, int minDepth, bool ignoreSpent, bool ignoreUnspendable)
3680 {
3681     std::set<PaymentAddress> filterAddresses;
3682
3683     if (address.length() > 0) {
3684         filterAddresses.insert(CZCPaymentAddress(address).Get());
3685     }
3686
3687     GetFilteredNotes(outEntries, filterAddresses, minDepth, ignoreSpent, ignoreUnspendable);
3688 }
3689
3690 /**
3691  * Find notes in the wallet filtered by payment addresses, min depth and ability to spend.
3692  * These notes are decrypted and added to the output parameter vector, outEntries.
3693  */
3694 void CWallet::GetFilteredNotes(
3695     std::vector<CNotePlaintextEntry>& outEntries,
3696     std::set<PaymentAddress>& filterAddresses,
3697     int minDepth,
3698     bool ignoreSpent,
3699     bool ignoreUnspendable)
3700 {
3701     LOCK2(cs_main, cs_wallet);
3702
3703     for (auto & p : mapWallet) {
3704         CWalletTx wtx = p.second;
3705
3706         // Filter the transactions before checking for notes
3707         if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth) {
3708             continue;
3709         }
3710
3711         if (wtx.mapNoteData.size() == 0) {
3712             continue;
3713         }
3714
3715         for (auto & pair : wtx.mapNoteData) {
3716             JSOutPoint jsop = pair.first;
3717             CNoteData nd = pair.second;
3718             PaymentAddress pa = nd.address;
3719
3720             // skip notes which belong to a different payment address in the wallet
3721             if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
3722                 continue;
3723             }
3724
3725             // skip note which has been spent
3726             if (ignoreSpent && nd.nullifier && IsSpent(*nd.nullifier)) {
3727                 continue;
3728             }
3729
3730             // skip notes which cannot be spent
3731             if (ignoreUnspendable && !HaveSpendingKey(pa)) {
3732                 continue;
3733             }
3734
3735             int i = jsop.js; // Index into CTransaction.vjoinsplit
3736             int j = jsop.n; // Index into JSDescription.ciphertexts
3737
3738             // Get cached decryptor
3739             ZCNoteDecryption decryptor;
3740             if (!GetNoteDecryptor(pa, decryptor)) {
3741                 // Note decryptors are created when the wallet is loaded, so it should always exist
3742                 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", CZCPaymentAddress(pa).ToString()));
3743             }
3744
3745             // determine amount of funds in the note
3746             auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3747             try {
3748                 NotePlaintext plaintext = NotePlaintext::decrypt(
3749                         decryptor,
3750                         wtx.vjoinsplit[i].ciphertexts[j],
3751                         wtx.vjoinsplit[i].ephemeralKey,
3752                         hSig,
3753                         (unsigned char) j);
3754
3755                 outEntries.push_back(CNotePlaintextEntry{jsop, pa, plaintext});
3756
3757             } catch (const note_decryption_failed &err) {
3758                 // Couldn't decrypt with this spending key
3759                 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", CZCPaymentAddress(pa).ToString()));
3760             } catch (const std::exception &exc) {
3761                 // Unexpected failure
3762                 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", CZCPaymentAddress(pa).ToString(), exc.what()));
3763             }
3764         }
3765     }
3766 }
3767
3768
3769 /* Find unspent notes filtered by payment address, min depth and max depth */
3770 void CWallet::GetUnspentFilteredNotes(
3771     std::vector<CUnspentNotePlaintextEntry>& outEntries,
3772     std::set<PaymentAddress>& filterAddresses,
3773     int minDepth,
3774     int maxDepth,
3775     bool requireSpendingKey)
3776 {
3777     LOCK2(cs_main, cs_wallet);
3778
3779     for (auto & p : mapWallet) {
3780         CWalletTx wtx = p.second;
3781
3782         // Filter the transactions before checking for notes
3783         if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth || wtx.GetDepthInMainChain() > maxDepth) {
3784             continue;
3785         }
3786
3787         if (wtx.mapNoteData.size() == 0) {
3788             continue;
3789         }
3790
3791         for (auto & pair : wtx.mapNoteData) {
3792             JSOutPoint jsop = pair.first;
3793             CNoteData nd = pair.second;
3794             PaymentAddress pa = nd.address;
3795
3796             // skip notes which belong to a different payment address in the wallet
3797             if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
3798                 continue;
3799             }
3800
3801             // skip note which has been spent
3802             if (nd.nullifier && IsSpent(*nd.nullifier)) {
3803                 continue;
3804             }
3805
3806             // skip notes where the spending key is not available
3807             if (requireSpendingKey && !HaveSpendingKey(pa)) {
3808                 continue;
3809             }
3810
3811             int i = jsop.js; // Index into CTransaction.vjoinsplit
3812             int j = jsop.n; // Index into JSDescription.ciphertexts
3813
3814             // Get cached decryptor
3815             ZCNoteDecryption decryptor;
3816             if (!GetNoteDecryptor(pa, decryptor)) {
3817                 // Note decryptors are created when the wallet is loaded, so it should always exist
3818                 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", CZCPaymentAddress(pa).ToString()));
3819             }
3820
3821             // determine amount of funds in the note
3822             auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3823             try {
3824                 NotePlaintext plaintext = NotePlaintext::decrypt(
3825                         decryptor,
3826                         wtx.vjoinsplit[i].ciphertexts[j],
3827                         wtx.vjoinsplit[i].ephemeralKey,
3828                         hSig,
3829                         (unsigned char) j);
3830
3831                 outEntries.push_back(CUnspentNotePlaintextEntry{jsop, pa, plaintext, wtx.GetDepthInMainChain()});
3832
3833             } catch (const note_decryption_failed &err) {
3834                 // Couldn't decrypt with this spending key
3835                 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", CZCPaymentAddress(pa).ToString()));
3836             } catch (const std::exception &exc) {
3837                 // Unexpected failure
3838                 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", CZCPaymentAddress(pa).ToString(), exc.what()));
3839             }
3840         }
3841     }
3842 }
3843
This page took 0.254966 seconds and 4 git commands to generate.