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