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