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