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.
6 #include "wallet/wallet.h"
8 #include "checkpoints.h"
9 #include "coincontrol.h"
10 #include "consensus/upgrades.h"
11 #include "consensus/validation.h"
12 #include "consensus/consensus.h"
17 #include "script/script.h"
18 #include "script/sign.h"
20 #include "utilmoneystr.h"
21 #include "zcash/Note.hpp"
26 #include <boost/algorithm/string/replace.hpp>
27 #include <boost/filesystem.hpp>
28 #include <boost/thread.hpp>
31 using namespace libzcash;
36 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
37 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
38 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
39 bool bSpendZeroConfChange = true;
40 bool fSendFreeTransactions = false;
41 bool fPayAtLeastCustomFee = true;
44 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
45 * Override with -mintxfee
47 CFeeRate CWallet::minTxFee = CFeeRate(1000);
49 /** @defgroup mapWallet
54 struct CompareValueOnly
56 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
57 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
59 return t1.first < t2.first;
63 std::string JSOutPoint::ToString() const
65 return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
68 std::string COutput::ToString() const
70 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
73 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
76 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
77 if (it == mapWallet.end())
82 // Generate a new spending key and return its public payment address
83 libzcash::PaymentAddress CWallet::GenerateNewZKey()
85 AssertLockHeld(cs_wallet); // mapZKeyMetadata
86 // TODO: Add Sapling support
87 auto k = SproutSpendingKey::random();
88 auto addr = k.address();
90 // Check for collision, even though it is unlikely to ever occur
91 if (CCryptoKeyStore::HaveSpendingKey(addr))
92 throw std::runtime_error("CWallet::GenerateNewZKey(): Collision detected");
94 // Create new metadata
95 int64_t nCreationTime = GetTime();
96 mapZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
99 throw std::runtime_error("CWallet::GenerateNewZKey(): AddZKey failed");
103 // Add spending key to keystore and persist to disk
104 // TODO: Add Sapling support
105 bool CWallet::AddZKey(const libzcash::SproutSpendingKey &key)
107 AssertLockHeld(cs_wallet); // mapZKeyMetadata
108 auto addr = key.address();
110 if (!CCryptoKeyStore::AddSpendingKey(key))
113 // check if we need to remove from viewing keys
114 if (HaveViewingKey(addr))
115 RemoveViewingKey(key.viewing_key());
121 return CWalletDB(strWalletFile).WriteZKey(addr,
123 mapZKeyMetadata[addr]);
128 CPubKey CWallet::GenerateNewKey()
130 AssertLockHeld(cs_wallet); // mapKeyMetadata
131 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
134 secret.MakeNewKey(fCompressed);
136 // Compressed public keys were introduced in version 0.6.0
138 SetMinVersion(FEATURE_COMPRPUBKEY);
140 CPubKey pubkey = secret.GetPubKey();
141 assert(secret.VerifyPubKey(pubkey));
143 // Create new metadata
144 int64_t nCreationTime = GetTime();
145 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
146 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
147 nTimeFirstKey = nCreationTime;
149 if (!AddKeyPubKey(secret, pubkey))
150 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
154 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
156 AssertLockHeld(cs_wallet); // mapKeyMetadata
157 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
160 // check if we need to remove from watch-only
162 script = GetScriptForDestination(pubkey.GetID());
163 if (HaveWatchOnly(script))
164 RemoveWatchOnly(script);
169 return CWalletDB(strWalletFile).WriteKey(pubkey,
171 mapKeyMetadata[pubkey.GetID()]);
176 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
177 const vector<unsigned char> &vchCryptedSecret)
180 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
186 if (pwalletdbEncryption)
187 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
189 mapKeyMetadata[vchPubKey.GetID()]);
191 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
193 mapKeyMetadata[vchPubKey.GetID()]);
199 bool CWallet::AddCryptedSpendingKey(const libzcash::SproutPaymentAddress &address,
200 const libzcash::ReceivingKey &rk,
201 const std::vector<unsigned char> &vchCryptedSecret)
203 if (!CCryptoKeyStore::AddCryptedSpendingKey(address, rk, vchCryptedSecret))
209 if (pwalletdbEncryption) {
210 return pwalletdbEncryption->WriteCryptedZKey(address,
213 mapZKeyMetadata[address]);
215 return CWalletDB(strWalletFile).WriteCryptedZKey(address,
218 mapZKeyMetadata[address]);
224 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
226 AssertLockHeld(cs_wallet); // mapKeyMetadata
227 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
228 nTimeFirstKey = meta.nCreateTime;
230 mapKeyMetadata[pubkey.GetID()] = meta;
234 bool CWallet::LoadZKeyMetadata(const SproutPaymentAddress &addr, const CKeyMetadata &meta)
236 AssertLockHeld(cs_wallet); // mapZKeyMetadata
237 mapZKeyMetadata[addr] = meta;
241 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
243 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
246 bool CWallet::LoadCryptedZKey(const libzcash::SproutPaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret)
248 return CCryptoKeyStore::AddCryptedSpendingKey(addr, rk, vchCryptedSecret);
251 bool CWallet::LoadZKey(const libzcash::SproutSpendingKey &key)
253 return CCryptoKeyStore::AddSpendingKey(key);
256 bool CWallet::AddViewingKey(const libzcash::SproutViewingKey &vk)
258 if (!CCryptoKeyStore::AddViewingKey(vk)) {
261 nTimeFirstKey = 1; // No birthday information for viewing keys.
265 return CWalletDB(strWalletFile).WriteViewingKey(vk);
268 bool CWallet::RemoveViewingKey(const libzcash::SproutViewingKey &vk)
270 AssertLockHeld(cs_wallet);
271 if (!CCryptoKeyStore::RemoveViewingKey(vk)) {
275 if (!CWalletDB(strWalletFile).EraseViewingKey(vk)) {
283 bool CWallet::LoadViewingKey(const libzcash::SproutViewingKey &vk)
285 return CCryptoKeyStore::AddViewingKey(vk);
288 bool CWallet::AddCScript(const CScript& redeemScript)
290 if (!CCryptoKeyStore::AddCScript(redeemScript))
294 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
297 bool CWallet::LoadCScript(const CScript& redeemScript)
299 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
300 * that never can be redeemed. However, old wallets may still contain
301 * these. Do not add them to the wallet and warn. */
302 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
304 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
305 LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
306 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
310 return CCryptoKeyStore::AddCScript(redeemScript);
313 bool CWallet::AddWatchOnly(const CScript &dest)
315 if (!CCryptoKeyStore::AddWatchOnly(dest))
317 nTimeFirstKey = 1; // No birthday information for watch-only keys.
318 NotifyWatchonlyChanged(true);
321 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
324 bool CWallet::RemoveWatchOnly(const CScript &dest)
326 AssertLockHeld(cs_wallet);
327 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
329 if (!HaveWatchOnly())
330 NotifyWatchonlyChanged(false);
332 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
338 bool CWallet::LoadWatchOnly(const CScript &dest)
340 return CCryptoKeyStore::AddWatchOnly(dest);
343 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
346 CKeyingMaterial vMasterKey;
350 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
352 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
354 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
355 continue; // try another master key
356 if (CCryptoKeyStore::Unlock(vMasterKey))
363 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
365 bool fWasLocked = IsLocked();
372 CKeyingMaterial vMasterKey;
373 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
375 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
377 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
379 if (CCryptoKeyStore::Unlock(vMasterKey))
381 int64_t nStartTime = GetTimeMillis();
382 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
383 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
385 nStartTime = GetTimeMillis();
386 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
387 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
389 if (pMasterKey.second.nDeriveIterations < 25000)
390 pMasterKey.second.nDeriveIterations = 25000;
392 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
394 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
396 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
398 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
409 void CWallet::ChainTip(const CBlockIndex *pindex, const CBlock *pblock,
410 ZCIncrementalMerkleTree tree, bool added)
413 IncrementNoteWitnesses(pindex, pblock, tree);
415 DecrementNoteWitnesses(pindex);
419 void CWallet::SetBestChain(const CBlockLocator& loc)
421 CWalletDB walletdb(strWalletFile);
422 SetBestChainINTERNAL(walletdb, loc);
425 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
427 LOCK(cs_wallet); // nWalletVersion
428 if (nWalletVersion >= nVersion)
431 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
432 if (fExplicit && nVersion > nWalletMaxVersion)
433 nVersion = FEATURE_LATEST;
435 nWalletVersion = nVersion;
437 if (nVersion > nWalletMaxVersion)
438 nWalletMaxVersion = nVersion;
442 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
443 if (nWalletVersion > 40000)
444 pwalletdb->WriteMinVersion(nWalletVersion);
452 bool CWallet::SetMaxVersion(int nVersion)
454 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
455 // cannot downgrade below current version
456 if (nWalletVersion > nVersion)
459 nWalletMaxVersion = nVersion;
464 set<uint256> CWallet::GetConflicts(const uint256& txid) const
467 AssertLockHeld(cs_wallet);
469 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
470 if (it == mapWallet.end())
472 const CWalletTx& wtx = it->second;
474 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
476 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
478 if (mapTxSpends.count(txin.prevout) <= 1)
479 continue; // No conflict if zero or one spends
480 range = mapTxSpends.equal_range(txin.prevout);
481 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
482 result.insert(it->second);
485 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
487 for (const JSDescription& jsdesc : wtx.vjoinsplit) {
488 for (const uint256& nullifier : jsdesc.nullifiers) {
489 if (mapTxNullifiers.count(nullifier) <= 1) {
490 continue; // No conflict if zero or one spends
492 range_n = mapTxNullifiers.equal_range(nullifier);
493 for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
494 result.insert(it->second);
501 void CWallet::Flush(bool shutdown)
503 bitdb.Flush(shutdown);
506 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
508 if (!bitdb.Open(GetDataDir()))
510 // try moving the database env out of the way
511 boost::filesystem::path pathDatabase = GetDataDir() / "database";
512 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
514 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
515 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
516 } catch (const boost::filesystem::filesystem_error&) {
517 // failure is ok (well, not really, but it's not worse than what we started with)
521 if (!bitdb.Open(GetDataDir())) {
522 // if it still fails, it probably means we can't even create the database env
523 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
529 if (GetBoolArg("-salvagewallet", false))
531 // Recover readable keypairs:
532 if (!CWalletDB::Recover(bitdb, walletFile, true))
536 if (boost::filesystem::exists(GetDataDir() / walletFile))
538 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
539 if (r == CDBEnv::RECOVER_OK)
541 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
542 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
543 " your balance or transactions are incorrect you should"
544 " restore from a backup."), GetDataDir());
546 if (r == CDBEnv::RECOVER_FAIL)
547 errorString += _("wallet.dat corrupt, salvage failed");
554 void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
556 // We want all the wallet transactions in range to have the same metadata as
557 // the oldest (smallest nOrderPos).
558 // So: find smallest nOrderPos:
560 int nMinOrderPos = std::numeric_limits<int>::max();
561 const CWalletTx* copyFrom = NULL;
562 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
564 const uint256& hash = it->second;
565 int n = mapWallet[hash].nOrderPos;
566 if (n < nMinOrderPos)
569 copyFrom = &mapWallet[hash];
572 // Now copy data from copyFrom to rest:
573 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
575 const uint256& hash = it->second;
576 CWalletTx* copyTo = &mapWallet[hash];
577 if (copyFrom == copyTo) continue;
578 copyTo->mapValue = copyFrom->mapValue;
579 // mapNoteData not copied on purpose
580 // (it is always set correctly for each CWalletTx)
581 copyTo->vOrderForm = copyFrom->vOrderForm;
582 // fTimeReceivedIsTxTime not copied on purpose
583 // nTimeReceived not copied on purpose
584 copyTo->nTimeSmart = copyFrom->nTimeSmart;
585 copyTo->fFromMe = copyFrom->fFromMe;
586 copyTo->strFromAccount = copyFrom->strFromAccount;
587 // nOrderPos not copied on purpose
588 // cached members not copied on purpose
593 * Outpoint is spent if any non-conflicted transaction
596 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
598 const COutPoint outpoint(hash, n);
599 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
600 range = mapTxSpends.equal_range(outpoint);
602 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
604 const uint256& wtxid = it->second;
605 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
606 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
607 return true; // Spent
613 * Note is spent if any non-conflicted transaction
616 bool CWallet::IsSpent(const uint256& nullifier) const
618 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
619 range = mapTxNullifiers.equal_range(nullifier);
621 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
622 const uint256& wtxid = it->second;
623 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
624 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
625 return true; // Spent
631 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
633 mapTxSpends.insert(make_pair(outpoint, wtxid));
635 pair<TxSpends::iterator, TxSpends::iterator> range;
636 range = mapTxSpends.equal_range(outpoint);
637 SyncMetaData<COutPoint>(range);
640 void CWallet::AddToSpends(const uint256& nullifier, const uint256& wtxid)
642 mapTxNullifiers.insert(make_pair(nullifier, wtxid));
644 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
645 range = mapTxNullifiers.equal_range(nullifier);
646 SyncMetaData<uint256>(range);
649 void CWallet::AddToSpends(const uint256& wtxid)
651 assert(mapWallet.count(wtxid));
652 CWalletTx& thisTx = mapWallet[wtxid];
653 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
656 for (const CTxIn& txin : thisTx.vin) {
657 AddToSpends(txin.prevout, wtxid);
659 for (const JSDescription& jsdesc : thisTx.vjoinsplit) {
660 for (const uint256& nullifier : jsdesc.nullifiers) {
661 AddToSpends(nullifier, wtxid);
666 void CWallet::ClearNoteWitnessCache()
669 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
670 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
671 item.second.witnesses.clear();
672 item.second.witnessHeight = -1;
675 nWitnessCacheSize = 0;
678 void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
679 const CBlock* pblockIn,
680 ZCIncrementalMerkleTree& tree)
684 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
685 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
686 CNoteData* nd = &(item.second);
687 // Only increment witnesses that are behind the current height
688 if (nd->witnessHeight < pindex->nHeight) {
689 // Check the validity of the cache
690 // The only time a note witnessed above the current height
691 // would be invalid here is during a reindex when blocks
692 // have been decremented, and we are incrementing the blocks
693 // immediately after.
694 assert(nWitnessCacheSize >= nd->witnesses.size());
695 // Witnesses being incremented should always be either -1
696 // (never incremented or decremented) or one below pindex
697 assert((nd->witnessHeight == -1) ||
698 (nd->witnessHeight == pindex->nHeight - 1));
699 // Copy the witness for the previous block if we have one
700 if (nd->witnesses.size() > 0) {
701 nd->witnesses.push_front(nd->witnesses.front());
703 if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
704 nd->witnesses.pop_back();
709 if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
710 nWitnessCacheSize += 1;
713 const CBlock* pblock {pblockIn};
716 ReadBlockFromDisk(block, pindex);
720 for (const CTransaction& tx : pblock->vtx) {
721 auto hash = tx.GetHash();
722 bool txIsOurs = mapWallet.count(hash);
723 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
724 const JSDescription& jsdesc = tx.vjoinsplit[i];
725 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
726 const uint256& note_commitment = jsdesc.commitments[j];
727 tree.append(note_commitment);
729 // Increment existing witnesses
730 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
731 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
732 CNoteData* nd = &(item.second);
733 if (nd->witnessHeight < pindex->nHeight &&
734 nd->witnesses.size() > 0) {
735 // Check the validity of the cache
736 // See earlier comment about validity.
737 assert(nWitnessCacheSize >= nd->witnesses.size());
738 nd->witnesses.front().append(note_commitment);
743 // If this is our note, witness it
745 JSOutPoint jsoutpt {hash, i, j};
746 if (mapWallet[hash].mapNoteData.count(jsoutpt) &&
747 mapWallet[hash].mapNoteData[jsoutpt].witnessHeight < pindex->nHeight) {
748 CNoteData* nd = &(mapWallet[hash].mapNoteData[jsoutpt]);
749 if (nd->witnesses.size() > 0) {
750 // We think this can happen because we write out the
751 // witness cache state after every block increment or
752 // decrement, but the block index itself is written in
753 // batches. So if the node crashes in between these two
754 // operations, it is possible for IncrementNoteWitnesses
755 // to be called again on previously-cached blocks. This
756 // doesn't affect existing cached notes because of the
757 // CNoteData::witnessHeight checks. See #1378 for details.
758 LogPrintf("Inconsistent witness cache state found for %s\n- Cache size: %d\n- Top (height %d): %s\n- New (height %d): %s\n",
759 jsoutpt.ToString(), nd->witnesses.size(),
761 nd->witnesses.front().root().GetHex(),
763 tree.witness().root().GetHex());
764 nd->witnesses.clear();
766 nd->witnesses.push_front(tree.witness());
767 // Set height to one less than pindex so it gets incremented
768 nd->witnessHeight = pindex->nHeight - 1;
769 // Check the validity of the cache
770 assert(nWitnessCacheSize >= nd->witnesses.size());
777 // Update witness heights
778 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
779 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
780 CNoteData* nd = &(item.second);
781 if (nd->witnessHeight < pindex->nHeight) {
782 nd->witnessHeight = pindex->nHeight;
783 // Check the validity of the cache
784 // See earlier comment about validity.
785 assert(nWitnessCacheSize >= nd->witnesses.size());
790 // For performance reasons, we write out the witness cache in
791 // CWallet::SetBestChain() (which also ensures that overall consistency
792 // of the wallet.dat is maintained).
796 void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
800 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
801 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
802 CNoteData* nd = &(item.second);
803 // Only increment witnesses that are not above the current height
804 if (nd->witnessHeight <= pindex->nHeight) {
805 // Check the validity of the cache
806 // See comment below (this would be invalid if there was a
808 assert(nWitnessCacheSize >= nd->witnesses.size());
809 // Witnesses being decremented should always be either -1
810 // (never incremented or decremented) or equal to pindex
811 assert((nd->witnessHeight == -1) ||
812 (nd->witnessHeight == pindex->nHeight));
813 if (nd->witnesses.size() > 0) {
814 nd->witnesses.pop_front();
816 // pindex is the block being removed, so the new witness cache
817 // height is one below it.
818 nd->witnessHeight = pindex->nHeight - 1;
822 nWitnessCacheSize -= 1;
823 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
824 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
825 CNoteData* nd = &(item.second);
826 // Check the validity of the cache
827 // Technically if there are notes witnessed above the current
828 // height, their cache will now be invalid (relative to the new
829 // value of nWitnessCacheSize). However, this would only occur
830 // during a reindex, and by the time the reindex reaches the tip
831 // of the chain again, the existing witness caches will be valid
833 // We don't set nWitnessCacheSize to zero at the start of the
834 // reindex because the on-disk blocks had already resulted in a
835 // chain that didn't trigger the assertion below.
836 if (nd->witnessHeight < pindex->nHeight) {
837 assert(nWitnessCacheSize >= nd->witnesses.size());
841 // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
842 assert(nWitnessCacheSize > 0);
844 // For performance reasons, we write out the witness cache in
845 // CWallet::SetBestChain() (which also ensures that overall consistency
846 // of the wallet.dat is maintained).
850 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
855 CKeyingMaterial vMasterKey;
857 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
858 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
860 CMasterKey kMasterKey;
862 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
863 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
866 int64_t nStartTime = GetTimeMillis();
867 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
868 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
870 nStartTime = GetTimeMillis();
871 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
872 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
874 if (kMasterKey.nDeriveIterations < 25000)
875 kMasterKey.nDeriveIterations = 25000;
877 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
879 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
881 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
886 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
889 assert(!pwalletdbEncryption);
890 pwalletdbEncryption = new CWalletDB(strWalletFile);
891 if (!pwalletdbEncryption->TxnBegin()) {
892 delete pwalletdbEncryption;
893 pwalletdbEncryption = NULL;
896 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
899 if (!EncryptKeys(vMasterKey))
902 pwalletdbEncryption->TxnAbort();
903 delete pwalletdbEncryption;
905 // We now probably have half of our keys encrypted in memory, and half not...
906 // die and let the user reload the unencrypted wallet.
910 // Encryption was introduced in version 0.4.0
911 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
915 if (!pwalletdbEncryption->TxnCommit()) {
916 delete pwalletdbEncryption;
917 // We now have keys encrypted in memory, but not on disk...
918 // die to avoid confusion and let the user reload the unencrypted wallet.
922 delete pwalletdbEncryption;
923 pwalletdbEncryption = NULL;
927 Unlock(strWalletPassphrase);
931 // Need to completely rewrite the wallet file; if we don't, bdb might keep
932 // bits of the unencrypted private key in slack space in the database file.
933 CDB::Rewrite(strWalletFile);
936 NotifyStatusChanged(this);
941 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
943 AssertLockHeld(cs_wallet); // nOrderPosNext
944 int64_t nRet = nOrderPosNext++;
946 pwalletdb->WriteOrderPosNext(nOrderPosNext);
948 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
953 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
955 AssertLockHeld(cs_wallet); // mapWallet
956 CWalletDB walletdb(strWalletFile);
958 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
961 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
962 // would make this much faster for applications that do this a lot.
963 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
965 CWalletTx* wtx = &((*it).second);
966 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
969 walletdb.ListAccountCreditDebit(strAccount, acentries);
970 BOOST_FOREACH(CAccountingEntry& entry, acentries)
972 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
978 void CWallet::MarkDirty()
982 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
983 item.second.MarkDirty();
988 * Ensure that every note in the wallet (for which we possess a spending key)
989 * has a cached nullifier.
991 bool CWallet::UpdateNullifierNoteMap()
999 ZCNoteDecryption dec;
1000 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1001 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
1002 if (!item.second.nullifier) {
1003 if (GetNoteDecryptor(item.second.address, dec)) {
1004 auto i = item.first.js;
1005 auto hSig = wtxItem.second.vjoinsplit[i].h_sig(
1006 *pzcashParams, wtxItem.second.joinSplitPubKey);
1007 item.second.nullifier = GetNoteNullifier(
1008 wtxItem.second.vjoinsplit[i],
1009 item.second.address,
1016 UpdateNullifierNoteMapWithTx(wtxItem.second);
1023 * Update mapNullifiersToNotes with the cached nullifiers in this tx.
1025 void CWallet::UpdateNullifierNoteMapWithTx(const CWalletTx& wtx)
1029 for (const mapNoteData_t::value_type& item : wtx.mapNoteData) {
1030 if (item.second.nullifier) {
1031 mapNullifiersToNotes[*item.second.nullifier] = item.first;
1037 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
1039 uint256 hash = wtxIn.GetHash();
1041 if (fFromLoadWallet)
1043 mapWallet[hash] = wtxIn;
1044 mapWallet[hash].BindWallet(this);
1045 UpdateNullifierNoteMapWithTx(mapWallet[hash]);
1051 // Inserts only if not already there, returns tx inserted or tx found
1052 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
1053 CWalletTx& wtx = (*ret.first).second;
1054 wtx.BindWallet(this);
1055 UpdateNullifierNoteMapWithTx(wtx);
1056 bool fInsertedNew = ret.second;
1059 wtx.nTimeReceived = GetAdjustedTime();
1060 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
1062 wtx.nTimeSmart = wtx.nTimeReceived;
1063 if (!wtxIn.hashBlock.IsNull())
1065 if (mapBlockIndex.count(wtxIn.hashBlock))
1067 int64_t latestNow = wtx.nTimeReceived;
1068 int64_t latestEntry = 0;
1070 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
1071 int64_t latestTolerated = latestNow + 300;
1072 std::list<CAccountingEntry> acentries;
1073 TxItems txOrdered = OrderedTxItems(acentries);
1074 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1076 CWalletTx *const pwtx = (*it).second.first;
1079 CAccountingEntry *const pacentry = (*it).second.second;
1083 nSmartTime = pwtx->nTimeSmart;
1085 nSmartTime = pwtx->nTimeReceived;
1088 nSmartTime = pacentry->nTime;
1089 if (nSmartTime <= latestTolerated)
1091 latestEntry = nSmartTime;
1092 if (nSmartTime > latestNow)
1093 latestNow = nSmartTime;
1099 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
1100 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
1103 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
1104 wtxIn.GetHash().ToString(),
1105 wtxIn.hashBlock.ToString());
1110 bool fUpdated = false;
1114 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
1116 wtx.hashBlock = wtxIn.hashBlock;
1119 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
1121 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
1122 wtx.nIndex = wtxIn.nIndex;
1125 if (UpdatedNoteData(wtxIn, wtx)) {
1128 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1130 wtx.fFromMe = wtxIn.fFromMe;
1136 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1139 if (fInsertedNew || fUpdated)
1140 if (!wtx.WriteToDisk(pwalletdb))
1143 // Break debit/credit balance caches:
1146 // Notify UI of new or updated transaction
1147 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1149 // notify an external script when a wallet transaction comes in or is updated
1150 std::string strCmd = GetArg("-walletnotify", "");
1152 if ( !strCmd.empty())
1154 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1155 boost::thread t(runCommand, strCmd); // thread runs free
1162 bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1164 if (wtxIn.mapNoteData.empty() || wtxIn.mapNoteData == wtx.mapNoteData) {
1167 auto tmp = wtxIn.mapNoteData;
1168 // Ensure we keep any cached witnesses we may already have
1169 for (const std::pair<JSOutPoint, CNoteData> nd : wtx.mapNoteData) {
1170 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1171 tmp.at(nd.first).witnesses.assign(
1172 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1174 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1176 // Now copy over the updated note data
1177 wtx.mapNoteData = tmp;
1182 * Add a transaction to the wallet, or update it.
1183 * pblock is optional, but should be provided if the transaction is known to be in a block.
1184 * If fUpdate is true, existing transactions will be updated.
1186 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1189 AssertLockHeld(cs_wallet);
1190 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1191 if (fExisted && !fUpdate) return false;
1192 auto noteData = FindMyNotes(tx);
1193 if (fExisted || IsMine(tx) || IsFromMe(tx) || noteData.size() > 0)
1195 CWalletTx wtx(this,tx);
1197 if (noteData.size() > 0) {
1198 wtx.SetNoteData(noteData);
1201 // Get merkle branch if transaction was found in a block
1203 wtx.SetMerkleBranch(*pblock);
1205 // Do not flush the wallet here for performance reasons
1206 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1207 CWalletDB walletdb(strWalletFile, "r+", false);
1209 return AddToWallet(wtx, false, &walletdb);
1215 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1217 LOCK2(cs_main, cs_wallet);
1218 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1219 return; // Not one of ours
1221 MarkAffectedTransactionsDirty(tx);
1224 void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1226 // If a transaction changes 'conflicted' state, that changes the balance
1227 // available of the outputs it spends. So force those to be
1228 // recomputed, also:
1229 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1231 if (mapWallet.count(txin.prevout.hash))
1232 mapWallet[txin.prevout.hash].MarkDirty();
1234 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1235 for (const uint256& nullifier : jsdesc.nullifiers) {
1236 if (mapNullifiersToNotes.count(nullifier) &&
1237 mapWallet.count(mapNullifiersToNotes[nullifier].hash)) {
1238 mapWallet[mapNullifiersToNotes[nullifier].hash].MarkDirty();
1244 void CWallet::EraseFromWallet(const uint256 &hash)
1250 if (mapWallet.erase(hash))
1251 CWalletDB(strWalletFile).EraseTx(hash);
1258 * Returns a nullifier if the SpendingKey is available
1259 * Throws std::runtime_error if the decryptor doesn't match this note
1261 boost::optional<uint256> CWallet::GetNoteNullifier(const JSDescription& jsdesc,
1262 const libzcash::SproutPaymentAddress& address,
1263 const ZCNoteDecryption& dec,
1264 const uint256& hSig,
1267 boost::optional<uint256> ret;
1268 auto note_pt = libzcash::SproutNotePlaintext::decrypt(
1270 jsdesc.ciphertexts[n],
1271 jsdesc.ephemeralKey,
1274 auto note = note_pt.note(address);
1275 // SpendingKeys are only available if:
1276 // - We have them (this isn't a viewing key)
1277 // - The wallet is unlocked
1278 libzcash::SproutSpendingKey key;
1279 if (GetSpendingKey(address, key)) {
1280 ret = note.nullifier(key);
1286 * Finds all output notes in the given transaction that have been sent to
1287 * PaymentAddresses in this wallet.
1289 * It should never be necessary to call this method with a CWalletTx, because
1290 * the result of FindMyNotes (for the addresses available at the time) will
1291 * already have been cached in CWalletTx.mapNoteData.
1293 mapNoteData_t CWallet::FindMyNotes(const CTransaction& tx) const
1295 LOCK(cs_SpendingKeyStore);
1296 uint256 hash = tx.GetHash();
1298 mapNoteData_t noteData;
1299 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1300 auto hSig = tx.vjoinsplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1301 for (uint8_t j = 0; j < tx.vjoinsplit[i].ciphertexts.size(); j++) {
1302 for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
1304 auto address = item.first;
1305 JSOutPoint jsoutpt {hash, i, j};
1306 auto nullifier = GetNoteNullifier(
1312 CNoteData nd {address, *nullifier};
1313 noteData.insert(std::make_pair(jsoutpt, nd));
1315 CNoteData nd {address};
1316 noteData.insert(std::make_pair(jsoutpt, nd));
1319 } catch (const note_decryption_failed &err) {
1320 // Couldn't decrypt with this decryptor
1321 } catch (const std::exception &exc) {
1322 // Unexpected failure
1323 LogPrintf("FindMyNotes(): Unexpected error while testing decrypt:\n");
1324 LogPrintf("%s\n", exc.what());
1332 bool CWallet::IsFromMe(const uint256& nullifier) const
1336 if (mapNullifiersToNotes.count(nullifier) &&
1337 mapWallet.count(mapNullifiersToNotes.at(nullifier).hash)) {
1344 void CWallet::GetNoteWitnesses(std::vector<JSOutPoint> notes,
1345 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1346 uint256 &final_anchor)
1350 witnesses.resize(notes.size());
1351 boost::optional<uint256> rt;
1353 for (JSOutPoint note : notes) {
1354 if (mapWallet.count(note.hash) &&
1355 mapWallet[note.hash].mapNoteData.count(note) &&
1356 mapWallet[note.hash].mapNoteData[note].witnesses.size() > 0) {
1357 witnesses[i] = mapWallet[note.hash].mapNoteData[note].witnesses.front();
1359 rt = witnesses[i]->root();
1361 assert(*rt == witnesses[i]->root());
1366 // All returned witnesses have the same anchor
1373 isminetype CWallet::IsMine(const CTxIn &txin) const
1377 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1378 if (mi != mapWallet.end())
1380 const CWalletTx& prev = (*mi).second;
1381 if (txin.prevout.n < prev.vout.size())
1382 return IsMine(prev.vout[txin.prevout.n]);
1388 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1392 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1393 if (mi != mapWallet.end())
1395 const CWalletTx& prev = (*mi).second;
1396 if (txin.prevout.n < prev.vout.size())
1397 if (IsMine(prev.vout[txin.prevout.n]) & filter)
1398 return prev.vout[txin.prevout.n].nValue;
1404 isminetype CWallet::IsMine(const CTxOut& txout) const
1406 return ::IsMine(*this, txout.scriptPubKey);
1409 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1411 if (!MoneyRange(txout.nValue))
1412 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1413 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1416 bool CWallet::IsChange(const CTxOut& txout) const
1418 // TODO: fix handling of 'change' outputs. The assumption is that any
1419 // payment to a script that is ours, but is not in the address book
1420 // is change. That assumption is likely to break when we implement multisignature
1421 // wallets that return change back into a multi-signature-protected address;
1422 // a better way of identifying which outputs are 'the send' and which are
1423 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1424 // which output, if any, was change).
1425 if (::IsMine(*this, txout.scriptPubKey))
1427 CTxDestination address;
1428 if (!ExtractDestination(txout.scriptPubKey, address))
1432 if (!mapAddressBook.count(address))
1438 CAmount CWallet::GetChange(const CTxOut& txout) const
1440 if (!MoneyRange(txout.nValue))
1441 throw std::runtime_error("CWallet::GetChange(): value out of range");
1442 return (IsChange(txout) ? txout.nValue : 0);
1445 bool CWallet::IsMine(const CTransaction& tx) const
1447 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1453 bool CWallet::IsFromMe(const CTransaction& tx) const
1455 if (GetDebit(tx, ISMINE_ALL) > 0) {
1458 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1459 for (const uint256& nullifier : jsdesc.nullifiers) {
1460 if (IsFromMe(nullifier)) {
1468 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1471 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1473 nDebit += GetDebit(txin, filter);
1474 if (!MoneyRange(nDebit))
1475 throw std::runtime_error("CWallet::GetDebit(): value out of range");
1480 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1482 CAmount nCredit = 0;
1483 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1485 nCredit += GetCredit(txout, filter);
1486 if (!MoneyRange(nCredit))
1487 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1492 CAmount CWallet::GetChange(const CTransaction& tx) const
1494 CAmount nChange = 0;
1495 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1497 nChange += GetChange(txout);
1498 if (!MoneyRange(nChange))
1499 throw std::runtime_error("CWallet::GetChange(): value out of range");
1504 void CWalletTx::SetNoteData(mapNoteData_t ¬eData)
1506 mapNoteData.clear();
1507 for (const std::pair<JSOutPoint, CNoteData> nd : noteData) {
1508 if (nd.first.js < vjoinsplit.size() &&
1509 nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1510 // Store the address and nullifier for the Note
1511 mapNoteData[nd.first] = nd.second;
1513 // If FindMyNotes() was used to obtain noteData,
1514 // this should never happen
1515 throw std::logic_error("CWalletTx::SetNoteData(): Invalid note");
1520 int64_t CWalletTx::GetTxTime() const
1522 int64_t n = nTimeSmart;
1523 return n ? n : nTimeReceived;
1526 int CWalletTx::GetRequestCount() const
1528 // Returns -1 if it wasn't being tracked
1531 LOCK(pwallet->cs_wallet);
1535 if (!hashBlock.IsNull())
1537 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1538 if (mi != pwallet->mapRequestCount.end())
1539 nRequests = (*mi).second;
1544 // Did anyone request this transaction?
1545 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1546 if (mi != pwallet->mapRequestCount.end())
1548 nRequests = (*mi).second;
1550 // How about the block it's in?
1551 if (nRequests == 0 && !hashBlock.IsNull())
1553 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1554 if (mi != pwallet->mapRequestCount.end())
1555 nRequests = (*mi).second;
1557 nRequests = 1; // If it's in someone else's block it must have got out
1565 // GetAmounts will determine the transparent debits and credits for a given wallet tx.
1566 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1567 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1570 listReceived.clear();
1572 strSentAccount = strFromAccount;
1574 // Is this tx sent/signed by me?
1575 CAmount nDebit = GetDebit(filter);
1576 bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
1578 // Does this tx spend my notes?
1579 bool isFromMyZaddr = false;
1580 for (const JSDescription& js : vjoinsplit) {
1581 for (const uint256& nullifier : js.nullifiers) {
1582 if (pwallet->IsFromMe(nullifier)) {
1583 isFromMyZaddr = true;
1587 if (isFromMyZaddr) {
1592 // Compute fee if we sent this transaction.
1593 if (isFromMyTaddr) {
1594 CAmount nValueOut = GetValueOut(); // transparent outputs plus all vpub_old
1595 CAmount nValueIn = 0;
1596 nValueIn += GetShieldedValueIn();
1597 nFee = nDebit - nValueOut + nValueIn;
1600 // Create output entry for vpub_old/new, if we sent utxos from this transaction
1601 if (isFromMyTaddr) {
1602 CAmount myVpubOld = 0;
1603 CAmount myVpubNew = 0;
1604 for (const JSDescription& js : vjoinsplit) {
1605 bool fMyJSDesc = false;
1608 for (const uint256& nullifier : js.nullifiers) {
1609 if (pwallet->IsFromMe(nullifier)) {
1615 // Check output side
1617 for (const std::pair<JSOutPoint, CNoteData> nd : this->mapNoteData) {
1618 if (nd.first.js < vjoinsplit.size() && nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1626 myVpubOld += js.vpub_old;
1627 myVpubNew += js.vpub_new;
1630 if (!MoneyRange(js.vpub_old) || !MoneyRange(js.vpub_new) || !MoneyRange(myVpubOld) || !MoneyRange(myVpubNew)) {
1631 throw std::runtime_error("CWalletTx::GetAmounts: value out of range");
1635 // Create an output for the value taken from or added to the transparent value pool by JoinSplits
1636 if (myVpubOld > myVpubNew) {
1637 COutputEntry output = {CNoDestination(), myVpubOld - myVpubNew, (int)vout.size()};
1638 listSent.push_back(output);
1639 } else if (myVpubNew > myVpubOld) {
1640 COutputEntry output = {CNoDestination(), myVpubNew - myVpubOld, (int)vout.size()};
1641 listReceived.push_back(output);
1646 for (unsigned int i = 0; i < vout.size(); ++i)
1648 const CTxOut& txout = vout[i];
1649 isminetype fIsMine = pwallet->IsMine(txout);
1650 // Only need to handle txouts if AT LEAST one of these is true:
1651 // 1) they debit from us (sent)
1652 // 2) the output is to us (received)
1655 // Don't report 'change' txouts
1656 if (pwallet->IsChange(txout))
1659 else if (!(fIsMine & filter))
1662 // In either case, we need to get the destination address
1663 CTxDestination address;
1664 if (!ExtractDestination(txout.scriptPubKey, address))
1666 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1667 this->GetHash().ToString());
1668 address = CNoDestination();
1671 COutputEntry output = {address, txout.nValue, (int)i};
1673 // If we are debited by the transaction, add the output as a "sent" entry
1675 listSent.push_back(output);
1677 // If we are receiving the output, add it as a "received" entry
1678 if (fIsMine & filter)
1679 listReceived.push_back(output);
1684 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1685 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1687 nReceived = nSent = nFee = 0;
1690 string strSentAccount;
1691 list<COutputEntry> listReceived;
1692 list<COutputEntry> listSent;
1693 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1695 if (strAccount == strSentAccount)
1697 BOOST_FOREACH(const COutputEntry& s, listSent)
1702 LOCK(pwallet->cs_wallet);
1703 BOOST_FOREACH(const COutputEntry& r, listReceived)
1705 if (pwallet->mapAddressBook.count(r.destination))
1707 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1708 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1709 nReceived += r.amount;
1711 else if (strAccount.empty())
1713 nReceived += r.amount;
1720 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
1722 return pwalletdb->WriteTx(GetHash(), *this);
1725 void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
1726 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1727 uint256 &final_anchor)
1729 witnesses.resize(commitments.size());
1730 CBlockIndex* pindex = chainActive.Genesis();
1731 ZCIncrementalMerkleTree tree;
1735 ReadBlockFromDisk(block, pindex);
1737 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1739 BOOST_FOREACH(const JSDescription& jsdesc, tx.vjoinsplit)
1741 BOOST_FOREACH(const uint256 ¬e_commitment, jsdesc.commitments)
1743 tree.append(note_commitment);
1745 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1747 wit->append(note_commitment);
1752 BOOST_FOREACH(uint256& commitment, commitments) {
1753 if (note_commitment == commitment) {
1754 witnesses.at(i) = tree.witness();
1762 uint256 current_anchor = tree.root();
1764 // Consistency check: we should be able to find the current tree
1765 // in our CCoins view.
1766 ZCIncrementalMerkleTree dummy_tree;
1767 assert(pcoinsTip->GetSproutAnchorAt(current_anchor, dummy_tree));
1769 pindex = chainActive.Next(pindex);
1772 // TODO: #93; Select a root via some heuristic.
1773 final_anchor = tree.root();
1775 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1777 assert(final_anchor == wit->root());
1783 * Scan the block chain (starting in pindexStart) for transactions
1784 * from or to us. If fUpdate is true, found transactions that already
1785 * exist in the wallet will be updated.
1787 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1790 int64_t nNow = GetTime();
1791 const CChainParams& chainParams = Params();
1793 CBlockIndex* pindex = pindexStart;
1795 LOCK2(cs_main, cs_wallet);
1797 // no need to read and scan block, if block was created before
1798 // our wallet birthday (as adjusted for block time variability)
1799 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1800 pindex = chainActive.Next(pindex);
1802 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1803 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1804 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1807 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1808 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1811 ReadBlockFromDisk(block, pindex);
1812 BOOST_FOREACH(CTransaction& tx, block.vtx)
1814 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1818 ZCIncrementalMerkleTree tree;
1819 // This should never fail: we should always be able to get the tree
1820 // state on the path to the tip of our chain
1821 assert(pcoinsTip->GetSproutAnchorAt(pindex->hashSproutAnchor, tree));
1822 // Increment note witness caches
1823 IncrementNoteWitnesses(pindex, &block, tree);
1825 pindex = chainActive.Next(pindex);
1826 if (GetTime() >= nNow + 60) {
1828 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1831 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1836 void CWallet::ReacceptWalletTransactions()
1838 // If transactions aren't being broadcasted, don't let them into local mempool either
1839 if (!fBroadcastTransactions)
1841 LOCK2(cs_main, cs_wallet);
1842 std::map<int64_t, CWalletTx*> mapSorted;
1844 // Sort pending wallet transactions based on their initial wallet insertion order
1845 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1847 const uint256& wtxid = item.first;
1848 CWalletTx& wtx = item.second;
1849 assert(wtx.GetHash() == wtxid);
1851 int nDepth = wtx.GetDepthInMainChain();
1853 if (!wtx.IsCoinBase() && nDepth < 0) {
1854 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1858 // Try to add wallet transactions to memory pool
1859 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1861 CWalletTx& wtx = *(item.second);
1864 wtx.AcceptToMemoryPool(false);
1868 bool CWalletTx::RelayWalletTransaction()
1870 assert(pwallet->GetBroadcastTransactions());
1873 if (GetDepthInMainChain() == 0) {
1874 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1875 RelayTransaction((CTransaction)*this);
1882 set<uint256> CWalletTx::GetConflicts() const
1884 set<uint256> result;
1885 if (pwallet != NULL)
1887 uint256 myHash = GetHash();
1888 result = pwallet->GetConflicts(myHash);
1889 result.erase(myHash);
1894 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1900 if(filter & ISMINE_SPENDABLE)
1903 debit += nDebitCached;
1906 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1907 fDebitCached = true;
1908 debit += nDebitCached;
1911 if(filter & ISMINE_WATCH_ONLY)
1913 if(fWatchDebitCached)
1914 debit += nWatchDebitCached;
1917 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1918 fWatchDebitCached = true;
1919 debit += nWatchDebitCached;
1925 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1927 // Must wait until coinbase is safely deep enough in the chain before valuing it
1928 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1932 if (filter & ISMINE_SPENDABLE)
1934 // GetBalance can assume transactions in mapWallet won't change
1936 credit += nCreditCached;
1939 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1940 fCreditCached = true;
1941 credit += nCreditCached;
1944 if (filter & ISMINE_WATCH_ONLY)
1946 if (fWatchCreditCached)
1947 credit += nWatchCreditCached;
1950 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1951 fWatchCreditCached = true;
1952 credit += nWatchCreditCached;
1958 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1960 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1962 if (fUseCache && fImmatureCreditCached)
1963 return nImmatureCreditCached;
1964 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1965 fImmatureCreditCached = true;
1966 return nImmatureCreditCached;
1972 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1977 // Must wait until coinbase is safely deep enough in the chain before valuing it
1978 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1981 if (fUseCache && fAvailableCreditCached)
1982 return nAvailableCreditCached;
1984 CAmount nCredit = 0;
1985 uint256 hashTx = GetHash();
1986 for (unsigned int i = 0; i < vout.size(); i++)
1988 if (!pwallet->IsSpent(hashTx, i))
1990 const CTxOut &txout = vout[i];
1991 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1992 if (!MoneyRange(nCredit))
1993 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1997 nAvailableCreditCached = nCredit;
1998 fAvailableCreditCached = true;
2002 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
2004 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2006 if (fUseCache && fImmatureWatchCreditCached)
2007 return nImmatureWatchCreditCached;
2008 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2009 fImmatureWatchCreditCached = true;
2010 return nImmatureWatchCreditCached;
2016 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
2021 // Must wait until coinbase is safely deep enough in the chain before valuing it
2022 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2025 if (fUseCache && fAvailableWatchCreditCached)
2026 return nAvailableWatchCreditCached;
2028 CAmount nCredit = 0;
2029 for (unsigned int i = 0; i < vout.size(); i++)
2031 if (!pwallet->IsSpent(GetHash(), i))
2033 const CTxOut &txout = vout[i];
2034 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2035 if (!MoneyRange(nCredit))
2036 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2040 nAvailableWatchCreditCached = nCredit;
2041 fAvailableWatchCreditCached = true;
2045 CAmount CWalletTx::GetChange() const
2048 return nChangeCached;
2049 nChangeCached = pwallet->GetChange(*this);
2050 fChangeCached = true;
2051 return nChangeCached;
2054 bool CWalletTx::IsTrusted() const
2056 // Quick answer in most cases
2057 if (!CheckFinalTx(*this))
2059 int nDepth = GetDepthInMainChain();
2064 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2067 // Trusted if all inputs are from us and are in the mempool:
2068 BOOST_FOREACH(const CTxIn& txin, vin)
2070 // Transactions not sent by us: not trusted
2071 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2074 const CTxOut& parentOut = parent->vout[txin.prevout.n];
2075 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2081 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
2083 std::vector<uint256> result;
2086 // Sort them in chronological order
2087 multimap<unsigned int, CWalletTx*> mapSorted;
2088 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2090 CWalletTx& wtx = item.second;
2091 // Don't rebroadcast if newer than nTime:
2092 if (wtx.nTimeReceived > nTime)
2094 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2096 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2098 CWalletTx& wtx = *item.second;
2099 if (wtx.RelayWalletTransaction())
2100 result.push_back(wtx.GetHash());
2105 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
2107 // Do this infrequently and randomly to avoid giving away
2108 // that these are our transactions.
2109 if (GetTime() < nNextResend || !fBroadcastTransactions)
2111 bool fFirst = (nNextResend == 0);
2112 nNextResend = GetTime() + GetRand(30 * 60);
2116 // Only do it if there's been a new block since last time
2117 if (nBestBlockTime < nLastResend)
2119 nLastResend = GetTime();
2121 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2123 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
2124 if (!relayed.empty())
2125 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2128 /** @} */ // end of mapWallet
2133 /** @defgroup Actions
2139 CAmount CWallet::GetBalance() const
2143 LOCK2(cs_main, cs_wallet);
2144 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2146 const CWalletTx* pcoin = &(*it).second;
2147 if (pcoin->IsTrusted())
2148 nTotal += pcoin->GetAvailableCredit();
2155 CAmount CWallet::GetUnconfirmedBalance() const
2159 LOCK2(cs_main, cs_wallet);
2160 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2162 const CWalletTx* pcoin = &(*it).second;
2163 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2164 nTotal += pcoin->GetAvailableCredit();
2170 CAmount CWallet::GetImmatureBalance() const
2174 LOCK2(cs_main, cs_wallet);
2175 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2177 const CWalletTx* pcoin = &(*it).second;
2178 nTotal += pcoin->GetImmatureCredit();
2184 CAmount CWallet::GetWatchOnlyBalance() const
2188 LOCK2(cs_main, cs_wallet);
2189 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2191 const CWalletTx* pcoin = &(*it).second;
2192 if (pcoin->IsTrusted())
2193 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2200 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2204 LOCK2(cs_main, cs_wallet);
2205 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2207 const CWalletTx* pcoin = &(*it).second;
2208 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2209 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2215 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2219 LOCK2(cs_main, cs_wallet);
2220 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2222 const CWalletTx* pcoin = &(*it).second;
2223 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2230 * populate vCoins with vector of available COutputs.
2232 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const
2237 LOCK2(cs_main, cs_wallet);
2238 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2240 const uint256& wtxid = it->first;
2241 const CWalletTx* pcoin = &(*it).second;
2243 if (!CheckFinalTx(*pcoin))
2246 if (fOnlyConfirmed && !pcoin->IsTrusted())
2249 if (pcoin->IsCoinBase() && !fIncludeCoinBase)
2252 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2255 int nDepth = pcoin->GetDepthInMainChain();
2259 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2260 isminetype mine = IsMine(pcoin->vout[i]);
2261 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2262 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
2263 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
2264 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
2270 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2271 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2273 vector<char> vfIncluded;
2275 vfBest.assign(vValue.size(), true);
2276 nBest = nTotalLower;
2278 seed_insecure_rand();
2280 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2282 vfIncluded.assign(vValue.size(), false);
2284 bool fReachedTarget = false;
2285 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2287 for (unsigned int i = 0; i < vValue.size(); i++)
2289 //The solver here uses a randomized algorithm,
2290 //the randomness serves no real security purpose but is just
2291 //needed to prevent degenerate behavior and it is important
2292 //that the rng is fast. We do not use a constant random sequence,
2293 //because there may be some privacy improvement by making
2294 //the selection random.
2295 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
2297 nTotal += vValue[i].first;
2298 vfIncluded[i] = true;
2299 if (nTotal >= nTargetValue)
2301 fReachedTarget = true;
2305 vfBest = vfIncluded;
2307 nTotal -= vValue[i].first;
2308 vfIncluded[i] = false;
2316 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2317 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
2319 setCoinsRet.clear();
2322 // List of values less than target
2323 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2324 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2325 coinLowestLarger.second.first = NULL;
2326 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2327 CAmount nTotalLower = 0;
2329 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2331 BOOST_FOREACH(const COutput &output, vCoins)
2333 if (!output.fSpendable)
2336 const CWalletTx *pcoin = output.tx;
2338 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2342 CAmount n = pcoin->vout[i].nValue;
2344 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2346 if (n == nTargetValue)
2348 setCoinsRet.insert(coin.second);
2349 nValueRet += coin.first;
2352 else if (n < nTargetValue + CENT)
2354 vValue.push_back(coin);
2357 else if (n < coinLowestLarger.first)
2359 coinLowestLarger = coin;
2363 if (nTotalLower == nTargetValue)
2365 for (unsigned int i = 0; i < vValue.size(); ++i)
2367 setCoinsRet.insert(vValue[i].second);
2368 nValueRet += vValue[i].first;
2373 if (nTotalLower < nTargetValue)
2375 if (coinLowestLarger.second.first == NULL)
2377 setCoinsRet.insert(coinLowestLarger.second);
2378 nValueRet += coinLowestLarger.first;
2382 // Solve subset sum by stochastic approximation
2383 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
2384 vector<char> vfBest;
2387 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
2388 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
2389 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
2391 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2392 // or the next bigger coin is closer), return the bigger coin
2393 if (coinLowestLarger.second.first &&
2394 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
2396 setCoinsRet.insert(coinLowestLarger.second);
2397 nValueRet += coinLowestLarger.first;
2400 for (unsigned int i = 0; i < vValue.size(); i++)
2403 setCoinsRet.insert(vValue[i].second);
2404 nValueRet += vValue[i].first;
2407 LogPrint("selectcoins", "SelectCoins() best subset: ");
2408 for (unsigned int i = 0; i < vValue.size(); i++)
2410 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2411 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
2417 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
2419 // Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
2420 vector<COutput> vCoinsNoCoinbase, vCoinsWithCoinbase;
2421 AvailableCoins(vCoinsNoCoinbase, true, coinControl, false, false);
2422 AvailableCoins(vCoinsWithCoinbase, true, coinControl, false, true);
2423 fOnlyCoinbaseCoinsRet = vCoinsNoCoinbase.size() == 0 && vCoinsWithCoinbase.size() > 0;
2425 // If coinbase utxos can only be sent to zaddrs, exclude any coinbase utxos from coin selection.
2426 bool fProtectCoinbase = Params().GetConsensus().fCoinbaseMustBeProtected;
2427 vector<COutput> vCoins = (fProtectCoinbase) ? vCoinsNoCoinbase : vCoinsWithCoinbase;
2429 // Output parameter fNeedCoinbaseCoinsRet is set to true if coinbase utxos need to be spent to meet target amount
2430 if (fProtectCoinbase && vCoinsWithCoinbase.size() > vCoinsNoCoinbase.size()) {
2432 for (const COutput& out : vCoinsNoCoinbase) {
2433 if (!out.fSpendable) {
2436 value += out.tx->vout[out.i].nValue;
2438 if (value <= nTargetValue) {
2439 CAmount valueWithCoinbase = 0;
2440 for (const COutput& out : vCoinsWithCoinbase) {
2441 if (!out.fSpendable) {
2444 valueWithCoinbase += out.tx->vout[out.i].nValue;
2446 fNeedCoinbaseCoinsRet = (valueWithCoinbase >= nTargetValue);
2450 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2451 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2453 BOOST_FOREACH(const COutput& out, vCoins)
2455 if (!out.fSpendable)
2457 nValueRet += out.tx->vout[out.i].nValue;
2458 setCoinsRet.insert(make_pair(out.tx, out.i));
2460 return (nValueRet >= nTargetValue);
2463 // calculate value from preset inputs and store them
2464 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2465 CAmount nValueFromPresetInputs = 0;
2467 std::vector<COutPoint> vPresetInputs;
2469 coinControl->ListSelected(vPresetInputs);
2470 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2472 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2473 if (it != mapWallet.end())
2475 const CWalletTx* pcoin = &it->second;
2476 // Clearly invalid input, fail
2477 if (pcoin->vout.size() <= outpoint.n)
2479 nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
2480 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2482 return false; // TODO: Allow non-wallet inputs
2485 // remove preset inputs from vCoins
2486 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2488 if (setPresetCoins.count(make_pair(it->tx, it->i)))
2489 it = vCoins.erase(it);
2494 bool res = nTargetValue <= nValueFromPresetInputs ||
2495 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2496 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2497 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
2499 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2500 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2502 // add preset inputs to the total value selected
2503 nValueRet += nValueFromPresetInputs;
2508 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason)
2510 vector<CRecipient> vecSend;
2512 // Turn the txout set into a CRecipient vector
2513 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2515 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2516 vecSend.push_back(recipient);
2519 CCoinControl coinControl;
2520 coinControl.fAllowOtherInputs = true;
2521 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2522 coinControl.Select(txin.prevout);
2524 CReserveKey reservekey(this);
2527 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
2530 if (nChangePosRet != -1)
2531 tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
2533 // Add new txins (keeping original txin scriptSig/order)
2534 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
2537 BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
2539 if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
2546 tx.vin.push_back(txin);
2552 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2553 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2556 unsigned int nSubtractFeeFromAmount = 0;
2557 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2559 if (nValue < 0 || recipient.nAmount < 0)
2561 strFailReason = _("Transaction amounts must be positive");
2564 nValue += recipient.nAmount;
2566 if (recipient.fSubtractFeeFromAmount)
2567 nSubtractFeeFromAmount++;
2569 if (vecSend.empty() || nValue < 0)
2571 strFailReason = _("Transaction amounts must be positive");
2575 wtxNew.fTimeReceivedIsTxTime = true;
2576 wtxNew.BindWallet(this);
2577 int nextBlockHeight = chainActive.Height() + 1;
2578 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(
2579 Params().GetConsensus(), nextBlockHeight);
2581 // Activates after Overwinter network upgrade
2582 if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
2583 if (txNew.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD){
2584 strFailReason = _("nExpiryHeight must be less than TX_EXPIRY_HEIGHT_THRESHOLD.");
2589 unsigned int max_tx_size = MAX_TX_SIZE_AFTER_SAPLING;
2590 if (!NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2591 max_tx_size = MAX_TX_SIZE_BEFORE_SAPLING;
2594 // Discourage fee sniping.
2596 // However because of a off-by-one-error in previous versions we need to
2597 // neuter it by setting nLockTime to at least one less than nBestHeight.
2598 // Secondly currently propagation of transactions created for block heights
2599 // corresponding to blocks that were just mined may be iffy - transactions
2600 // aren't re-accepted into the mempool - we additionally neuter the code by
2601 // going ten blocks back. Doesn't yet do anything for sniping, but does act
2602 // to shake out wallet bugs like not showing nLockTime'd transactions at
2604 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
2606 // Secondly occasionally randomly pick a nLockTime even further back, so
2607 // that transactions that are delayed after signing for whatever reason,
2608 // e.g. high-latency mix networks and some CoinJoin implementations, have
2610 if (GetRandInt(10) == 0)
2611 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2613 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2614 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2617 LOCK2(cs_main, cs_wallet);
2624 wtxNew.fFromMe = true;
2628 CAmount nTotalValue = nValue;
2629 if (nSubtractFeeFromAmount == 0)
2630 nTotalValue += nFeeRet;
2631 double dPriority = 0;
2632 // vouts to the payees
2633 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2635 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2637 if (recipient.fSubtractFeeFromAmount)
2639 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2641 if (fFirst) // first receiver pays the remainder not divisible by output count
2644 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2648 if (txout.IsDust(::minRelayTxFee))
2650 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2652 if (txout.nValue < 0)
2653 strFailReason = _("The transaction amount is too small to pay the fee");
2655 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2658 strFailReason = _("Transaction amount too small");
2661 txNew.vout.push_back(txout);
2664 // Choose coins to use
2665 set<pair<const CWalletTx*,unsigned int> > setCoins;
2666 CAmount nValueIn = 0;
2667 bool fOnlyCoinbaseCoins = false;
2668 bool fNeedCoinbaseCoins = false;
2669 if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl))
2671 if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) {
2672 strFailReason = _("Coinbase funds can only be sent to a zaddr");
2673 } else if (fNeedCoinbaseCoins) {
2674 strFailReason = _("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr");
2676 strFailReason = _("Insufficient funds");
2680 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2682 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2683 //The coin age after the next block (depth+1) is used instead of the current,
2684 //reflecting an assumption the user would accept a bit more delay for
2685 //a chance at a free transaction.
2686 //But mempool inputs might still be in the mempool, so their age stays 0
2687 int age = pcoin.first->GetDepthInMainChain();
2690 dPriority += (double)nCredit * age;
2693 CAmount nChange = nValueIn - nValue;
2694 if (nSubtractFeeFromAmount == 0)
2699 // Fill a vout to ourself
2700 // TODO: pass in scriptChange instead of reservekey so
2701 // change transaction isn't always pay-to-bitcoin-address
2702 CScript scriptChange;
2704 // coin control: send change to custom address
2705 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2706 scriptChange = GetScriptForDestination(coinControl->destChange);
2708 // no coin control: send change to newly generated address
2711 // Note: We use a new key here to keep it from being obvious which side is the change.
2712 // The drawback is that by not reusing a previous key, the change may be lost if a
2713 // backup is restored, if the backup doesn't have the new private key for the change.
2714 // If we reused the old key, it would be possible to add code to look for and
2715 // rediscover unknown transactions that were written with keys of ours to recover
2716 // post-backup change.
2718 // Reserve a new key pair from key pool
2721 ret = reservekey.GetReservedKey(vchPubKey);
2722 assert(ret); // should never fail, as we just unlocked
2724 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2727 CTxOut newTxOut(nChange, scriptChange);
2729 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2730 // This would be against the purpose of the all-inclusive feature.
2731 // So instead we raise the change and deduct from the recipient.
2732 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2734 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2735 newTxOut.nValue += nDust; // raise change until no more dust
2736 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2738 if (vecSend[i].fSubtractFeeFromAmount)
2740 txNew.vout[i].nValue -= nDust;
2741 if (txNew.vout[i].IsDust(::minRelayTxFee))
2743 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2751 // Never create dust outputs; if we would, just
2752 // add the dust to the fee.
2753 if (newTxOut.IsDust(::minRelayTxFee))
2756 reservekey.ReturnKey();
2760 // Insert change txn at random position:
2761 nChangePosRet = GetRandInt(txNew.vout.size()+1);
2762 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
2763 txNew.vout.insert(position, newTxOut);
2767 reservekey.ReturnKey();
2771 // Note how the sequence number is set to max()-1 so that the
2772 // nLockTime set above actually works.
2773 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2774 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2775 std::numeric_limits<unsigned int>::max()-1));
2777 // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
2778 size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
2781 if (NetworkUpgradeActive(chainActive.Height() + 1, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
2786 size_t n = txNew.vin.size();
2788 strFailReason = _(strprintf("Too many transparent inputs %zu > limit %zu", n, limit).c_str());
2793 // Grab the current consensus branch ID
2794 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
2798 CTransaction txNewConst(txNew);
2799 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2802 const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
2803 SignatureData sigdata;
2805 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata, consensusBranchId);
2807 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata, consensusBranchId);
2811 strFailReason = _("Signing transaction failed");
2814 UpdateTransaction(txNew, nIn, sigdata);
2820 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2822 // Remove scriptSigs if we used dummy signatures for fee calculation
2824 BOOST_FOREACH (CTxIn& vin, txNew.vin)
2825 vin.scriptSig = CScript();
2828 // Embed the constructed transaction data in wtxNew.
2829 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
2832 if (nBytes >= max_tx_size)
2834 strFailReason = _("Transaction too large");
2838 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
2840 // Can we complete this as a free transaction?
2841 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2843 // Not enough fee: enough priority?
2844 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
2845 // Not enough mempool history to estimate: use hard-coded AllowFree.
2846 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
2849 // Small enough, and priority high enough, to send for free
2850 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
2854 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
2856 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2857 // because we must be at the maximum allowed fee.
2858 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2860 strFailReason = _("Transaction too large for fee policy");
2864 if (nFeeRet >= nFeeNeeded)
2865 break; // Done, enough fee included.
2867 // Include more fee and try again.
2868 nFeeRet = nFeeNeeded;
2878 * Call after CreateTransaction unless you want to abort
2880 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2883 LOCK2(cs_main, cs_wallet);
2884 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
2886 // This is only to keep the database open to defeat the auto-flush for the
2887 // duration of this scope. This is the only place where this optimization
2888 // maybe makes sense; please don't do it anywhere else.
2889 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
2891 // Take key pair from key pool so it won't be used again
2892 reservekey.KeepKey();
2894 // Add tx to wallet, because if it has change it's also ours,
2895 // otherwise just for transaction history.
2896 AddToWallet(wtxNew, false, pwalletdb);
2898 // Notify that old coins are spent
2899 set<CWalletTx*> setCoins;
2900 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2902 CWalletTx &coin = mapWallet[txin.prevout.hash];
2903 coin.BindWallet(this);
2904 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2911 // Track how many getdata requests our transaction gets
2912 mapRequestCount[wtxNew.GetHash()] = 0;
2914 if (fBroadcastTransactions)
2917 if (!wtxNew.AcceptToMemoryPool(false))
2919 // This must not fail. The transaction has already been signed and recorded.
2920 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
2923 wtxNew.RelayWalletTransaction();
2929 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2931 // payTxFee is user-set "I want to pay this much"
2932 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2933 // user selected total at least (default=true)
2934 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
2935 nFeeNeeded = payTxFee.GetFeePerK();
2936 // User didn't set: use -txconfirmtarget to estimate...
2937 if (nFeeNeeded == 0)
2938 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
2939 // ... unless we don't have enough mempool data, in which case fall
2940 // back to a hard-coded fee
2941 if (nFeeNeeded == 0)
2942 nFeeNeeded = minTxFee.GetFee(nTxBytes);
2943 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
2944 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
2945 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
2946 // But always obey the maximum
2947 if (nFeeNeeded > maxTxFee)
2948 nFeeNeeded = maxTxFee;
2955 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2959 fFirstRunRet = false;
2960 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2961 if (nLoadWalletRet == DB_NEED_REWRITE)
2963 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2967 // Note: can't top-up keypool here, because wallet is locked.
2968 // User will be prompted to unlock wallet the next operation
2969 // that requires a new key.
2973 if (nLoadWalletRet != DB_LOAD_OK)
2974 return nLoadWalletRet;
2975 fFirstRunRet = !vchDefaultKey.IsValid();
2977 uiInterface.LoadWallet(this);
2983 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2987 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2988 if (nZapWalletTxRet == DB_NEED_REWRITE)
2990 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2994 // Note: can't top-up keypool here, because wallet is locked.
2995 // User will be prompted to unlock wallet the next operation
2996 // that requires a new key.
3000 if (nZapWalletTxRet != DB_LOAD_OK)
3001 return nZapWalletTxRet;
3007 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
3009 bool fUpdated = false;
3011 LOCK(cs_wallet); // mapAddressBook
3012 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3013 fUpdated = mi != mapAddressBook.end();
3014 mapAddressBook[address].name = strName;
3015 if (!strPurpose.empty()) /* update purpose only if requested */
3016 mapAddressBook[address].purpose = strPurpose;
3018 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3019 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3022 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(EncodeDestination(address), strPurpose))
3024 return CWalletDB(strWalletFile).WriteName(EncodeDestination(address), strName);
3027 bool CWallet::DelAddressBook(const CTxDestination& address)
3030 LOCK(cs_wallet); // mapAddressBook
3034 // Delete destdata tuples associated with address
3035 std::string strAddress = EncodeDestination(address);
3036 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3038 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3041 mapAddressBook.erase(address);
3044 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3048 CWalletDB(strWalletFile).ErasePurpose(EncodeDestination(address));
3049 return CWalletDB(strWalletFile).EraseName(EncodeDestination(address));
3052 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3056 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3059 vchDefaultKey = vchPubKey;
3064 * Mark old keypool keys as used,
3065 * and generate all new keys
3067 bool CWallet::NewKeyPool()
3071 CWalletDB walletdb(strWalletFile);
3072 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3073 walletdb.ErasePool(nIndex);
3079 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
3080 for (int i = 0; i < nKeys; i++)
3082 int64_t nIndex = i+1;
3083 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
3084 setKeyPool.insert(nIndex);
3086 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
3091 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3099 CWalletDB walletdb(strWalletFile);
3102 unsigned int nTargetSize;
3104 nTargetSize = kpSize;
3106 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
3108 while (setKeyPool.size() < (nTargetSize + 1))
3111 if (!setKeyPool.empty())
3112 nEnd = *(--setKeyPool.end()) + 1;
3113 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
3114 throw runtime_error("TopUpKeyPool(): writing generated key failed");
3115 setKeyPool.insert(nEnd);
3116 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
3122 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
3125 keypool.vchPubKey = CPubKey();
3132 // Get the oldest key
3133 if(setKeyPool.empty())
3136 CWalletDB walletdb(strWalletFile);
3138 nIndex = *(setKeyPool.begin());
3139 setKeyPool.erase(setKeyPool.begin());
3140 if (!walletdb.ReadPool(nIndex, keypool))
3141 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
3142 if (!HaveKey(keypool.vchPubKey.GetID()))
3143 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
3144 assert(keypool.vchPubKey.IsValid());
3145 LogPrintf("keypool reserve %d\n", nIndex);
3149 void CWallet::KeepKey(int64_t nIndex)
3151 // Remove from key pool
3154 CWalletDB walletdb(strWalletFile);
3155 walletdb.ErasePool(nIndex);
3157 LogPrintf("keypool keep %d\n", nIndex);
3160 void CWallet::ReturnKey(int64_t nIndex)
3162 // Return to key pool
3165 setKeyPool.insert(nIndex);
3167 LogPrintf("keypool return %d\n", nIndex);
3170 bool CWallet::GetKeyFromPool(CPubKey& result)
3176 ReserveKeyFromKeyPool(nIndex, keypool);
3179 if (IsLocked()) return false;
3180 result = GenerateNewKey();
3184 result = keypool.vchPubKey;
3189 int64_t CWallet::GetOldestKeyPoolTime()
3193 ReserveKeyFromKeyPool(nIndex, keypool);
3197 return keypool.nTime;
3200 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3202 map<CTxDestination, CAmount> balances;
3206 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3208 CWalletTx *pcoin = &walletEntry.second;
3210 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
3213 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3216 int nDepth = pcoin->GetDepthInMainChain();
3217 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3220 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3222 CTxDestination addr;
3223 if (!IsMine(pcoin->vout[i]))
3225 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3228 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
3230 if (!balances.count(addr))
3232 balances[addr] += n;
3240 set< set<CTxDestination> > CWallet::GetAddressGroupings()
3242 AssertLockHeld(cs_wallet); // mapWallet
3243 set< set<CTxDestination> > groupings;
3244 set<CTxDestination> grouping;
3246 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3248 CWalletTx *pcoin = &walletEntry.second;
3250 if (pcoin->vin.size() > 0)
3252 bool any_mine = false;
3253 // group all input addresses with each other
3254 BOOST_FOREACH(CTxIn txin, pcoin->vin)
3256 CTxDestination address;
3257 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3259 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
3261 grouping.insert(address);
3265 // group change with input addresses
3268 BOOST_FOREACH(CTxOut txout, pcoin->vout)
3269 if (IsChange(txout))
3271 CTxDestination txoutAddr;
3272 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3274 grouping.insert(txoutAddr);
3277 if (grouping.size() > 0)
3279 groupings.insert(grouping);
3284 // group lone addrs by themselves
3285 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3286 if (IsMine(pcoin->vout[i]))
3288 CTxDestination address;
3289 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
3291 grouping.insert(address);
3292 groupings.insert(grouping);
3297 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3298 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3299 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
3301 // make a set of all the groups hit by this new group
3302 set< set<CTxDestination>* > hits;
3303 map< CTxDestination, set<CTxDestination>* >::iterator it;
3304 BOOST_FOREACH(CTxDestination address, grouping)
3305 if ((it = setmap.find(address)) != setmap.end())
3306 hits.insert((*it).second);
3308 // merge all hit groups into a new single group and delete old groups
3309 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
3310 BOOST_FOREACH(set<CTxDestination>* hit, hits)
3312 merged->insert(hit->begin(), hit->end());
3313 uniqueGroupings.erase(hit);
3316 uniqueGroupings.insert(merged);
3319 BOOST_FOREACH(CTxDestination element, *merged)
3320 setmap[element] = merged;
3323 set< set<CTxDestination> > ret;
3324 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3326 ret.insert(*uniqueGrouping);
3327 delete uniqueGrouping;
3333 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3336 set<CTxDestination> result;
3337 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3339 const CTxDestination& address = item.first;
3340 const string& strName = item.second.name;
3341 if (strName == strAccount)
3342 result.insert(address);
3347 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
3352 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3354 vchPubKey = keypool.vchPubKey;
3359 assert(vchPubKey.IsValid());
3364 void CReserveKey::KeepKey()
3367 pwallet->KeepKey(nIndex);
3369 vchPubKey = CPubKey();
3372 void CReserveKey::ReturnKey()
3375 pwallet->ReturnKey(nIndex);
3377 vchPubKey = CPubKey();
3380 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3384 CWalletDB walletdb(strWalletFile);
3386 LOCK2(cs_main, cs_wallet);
3387 BOOST_FOREACH(const int64_t& id, setKeyPool)
3390 if (!walletdb.ReadPool(id, keypool))
3391 throw runtime_error("GetAllReserveKeyHashes(): read failed");
3392 assert(keypool.vchPubKey.IsValid());
3393 CKeyID keyID = keypool.vchPubKey.GetID();
3394 if (!HaveKey(keyID))
3395 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
3396 setAddress.insert(keyID);
3400 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3404 // Only notify UI if this transaction is in this wallet
3405 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3406 if (mi != mapWallet.end())
3407 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3411 void CWallet::LockCoin(COutPoint& output)
3413 AssertLockHeld(cs_wallet); // setLockedCoins
3414 setLockedCoins.insert(output);
3417 void CWallet::UnlockCoin(COutPoint& output)
3419 AssertLockHeld(cs_wallet); // setLockedCoins
3420 setLockedCoins.erase(output);
3423 void CWallet::UnlockAllCoins()
3425 AssertLockHeld(cs_wallet); // setLockedCoins
3426 setLockedCoins.clear();
3429 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3431 AssertLockHeld(cs_wallet); // setLockedCoins
3432 COutPoint outpt(hash, n);
3434 return (setLockedCoins.count(outpt) > 0);
3437 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3439 AssertLockHeld(cs_wallet); // setLockedCoins
3440 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3441 it != setLockedCoins.end(); it++) {
3442 COutPoint outpt = (*it);
3443 vOutpts.push_back(outpt);
3448 // Note Locking Operations
3450 void CWallet::LockNote(const JSOutPoint& output)
3452 AssertLockHeld(cs_wallet); // setLockedNotes
3453 setLockedNotes.insert(output);
3456 void CWallet::UnlockNote(const JSOutPoint& output)
3458 AssertLockHeld(cs_wallet); // setLockedNotes
3459 setLockedNotes.erase(output);
3462 void CWallet::UnlockAllNotes()
3464 AssertLockHeld(cs_wallet); // setLockedNotes
3465 setLockedNotes.clear();
3468 bool CWallet::IsLockedNote(const JSOutPoint& outpt) const
3470 AssertLockHeld(cs_wallet); // setLockedNotes
3472 return (setLockedNotes.count(outpt) > 0);
3475 std::vector<JSOutPoint> CWallet::ListLockedNotes()
3477 AssertLockHeld(cs_wallet); // setLockedNotes
3478 std::vector<JSOutPoint> vOutpts(setLockedNotes.begin(), setLockedNotes.end());
3482 /** @} */ // end of Actions
3484 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3486 const CKeyStore &keystore;
3487 std::vector<CKeyID> &vKeys;
3490 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3492 void Process(const CScript &script) {
3494 std::vector<CTxDestination> vDest;
3496 if (ExtractDestinations(script, type, vDest, nRequired)) {
3497 BOOST_FOREACH(const CTxDestination &dest, vDest)
3498 boost::apply_visitor(*this, dest);
3502 void operator()(const CKeyID &keyId) {
3503 if (keystore.HaveKey(keyId))
3504 vKeys.push_back(keyId);
3507 void operator()(const CScriptID &scriptId) {
3509 if (keystore.GetCScript(scriptId, script))
3513 void operator()(const CNoDestination &none) {}
3516 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
3517 AssertLockHeld(cs_wallet); // mapKeyMetadata
3518 mapKeyBirth.clear();
3520 // get birth times for keys with metadata
3521 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3522 if (it->second.nCreateTime)
3523 mapKeyBirth[it->first] = it->second.nCreateTime;
3525 // map in which we'll infer heights of other keys
3526 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
3527 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3528 std::set<CKeyID> setKeys;
3530 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3531 if (mapKeyBirth.count(keyid) == 0)
3532 mapKeyFirstBlock[keyid] = pindexMax;
3536 // if there are no such keys, we're done
3537 if (mapKeyFirstBlock.empty())
3540 // find first block that affects those keys, if there are any left
3541 std::vector<CKeyID> vAffected;
3542 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3543 // iterate over all wallet transactions...
3544 const CWalletTx &wtx = (*it).second;
3545 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3546 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3547 // ... which are already in a block
3548 int nHeight = blit->second->nHeight;
3549 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
3550 // iterate over all their outputs
3551 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3552 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3553 // ... and all their affected keys
3554 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3555 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3556 rit->second = blit->second;
3563 // Extract block timestamps for those keys
3564 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3565 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
3568 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3570 if (boost::get<CNoDestination>(&dest))
3573 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3576 return CWalletDB(strWalletFile).WriteDestData(EncodeDestination(dest), key, value);
3579 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3581 if (!mapAddressBook[dest].destdata.erase(key))
3585 return CWalletDB(strWalletFile).EraseDestData(EncodeDestination(dest), key);
3588 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3590 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3594 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3596 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3597 if(i != mapAddressBook.end())
3599 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3600 if(j != i->second.destdata.end())
3610 CKeyPool::CKeyPool()
3615 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3618 vchPubKey = vchPubKeyIn;
3621 CWalletKey::CWalletKey(int64_t nExpires)
3623 nTimeCreated = (nExpires ? GetTime() : 0);
3624 nTimeExpires = nExpires;
3627 int CMerkleTx::SetMerkleBranch(const CBlock& block)
3629 AssertLockHeld(cs_main);
3632 // Update the tx's hashBlock
3633 hashBlock = block.GetHash();
3635 // Locate the transaction
3636 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
3637 if (block.vtx[nIndex] == *(CTransaction*)this)
3639 if (nIndex == (int)block.vtx.size())
3641 vMerkleBranch.clear();
3643 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
3647 // Fill in merkle branch
3648 vMerkleBranch = block.GetMerkleBranch(nIndex);
3650 // Is the tx in a block that's in the main chain
3651 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3652 if (mi == mapBlockIndex.end())
3654 const CBlockIndex* pindex = (*mi).second;
3655 if (!pindex || !chainActive.Contains(pindex))
3658 return chainActive.Height() - pindex->nHeight + 1;
3661 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
3663 if (hashBlock.IsNull() || nIndex == -1)
3665 AssertLockHeld(cs_main);
3667 // Find the block it claims to be in
3668 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3669 if (mi == mapBlockIndex.end())
3671 CBlockIndex* pindex = (*mi).second;
3672 if (!pindex || !chainActive.Contains(pindex))
3675 // Make sure the merkle branch connects to this block
3676 if (!fMerkleVerified)
3678 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
3680 fMerkleVerified = true;
3684 return chainActive.Height() - pindex->nHeight + 1;
3687 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3689 AssertLockHeld(cs_main);
3690 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
3691 if (nResult == 0 && !mempool.exists(GetHash()))
3692 return -1; // Not in chain, not in mempool
3697 int CMerkleTx::GetBlocksToMaturity() const
3701 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3705 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
3707 CValidationState state;
3708 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
3712 * Find notes in the wallet filtered by payment address, min depth and ability to spend.
3713 * These notes are decrypted and added to the output parameter vector, outEntries.
3715 void CWallet::GetFilteredNotes(std::vector<CSproutNotePlaintextEntry> & outEntries, std::string address, int minDepth, bool ignoreSpent, bool ignoreUnspendable)
3717 std::set<PaymentAddress> filterAddresses;
3719 if (address.length() > 0) {
3720 filterAddresses.insert(DecodePaymentAddress(address));
3723 GetFilteredNotes(outEntries, filterAddresses, minDepth, ignoreSpent, ignoreUnspendable);
3727 * Find notes in the wallet filtered by payment addresses, min depth and ability to spend.
3728 * These notes are decrypted and added to the output parameter vector, outEntries.
3730 void CWallet::GetFilteredNotes(
3731 std::vector<CSproutNotePlaintextEntry>& outEntries,
3732 std::set<PaymentAddress>& filterAddresses,
3735 bool ignoreUnspendable)
3737 LOCK2(cs_main, cs_wallet);
3739 for (auto & p : mapWallet) {
3740 CWalletTx wtx = p.second;
3742 // Filter the transactions before checking for notes
3743 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth) {
3747 if (wtx.mapNoteData.size() == 0) {
3751 for (auto & pair : wtx.mapNoteData) {
3752 JSOutPoint jsop = pair.first;
3753 CNoteData nd = pair.second;
3754 SproutPaymentAddress pa = nd.address;
3756 // skip notes which belong to a different payment address in the wallet
3757 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
3761 // skip note which has been spent
3762 if (ignoreSpent && nd.nullifier && IsSpent(*nd.nullifier)) {
3766 // skip notes which cannot be spent
3767 if (ignoreUnspendable && !HaveSpendingKey(pa)) {
3771 // skip locked notes
3772 if (IsLockedNote(jsop)) {
3776 int i = jsop.js; // Index into CTransaction.vjoinsplit
3777 int j = jsop.n; // Index into JSDescription.ciphertexts
3779 // Get cached decryptor
3780 ZCNoteDecryption decryptor;
3781 if (!GetNoteDecryptor(pa, decryptor)) {
3782 // Note decryptors are created when the wallet is loaded, so it should always exist
3783 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", EncodePaymentAddress(pa)));
3786 // determine amount of funds in the note
3787 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3789 SproutNotePlaintext plaintext = SproutNotePlaintext::decrypt(
3791 wtx.vjoinsplit[i].ciphertexts[j],
3792 wtx.vjoinsplit[i].ephemeralKey,
3796 outEntries.push_back(CSproutNotePlaintextEntry{jsop, pa, plaintext});
3798 } catch (const note_decryption_failed &err) {
3799 // Couldn't decrypt with this spending key
3800 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", EncodePaymentAddress(pa)));
3801 } catch (const std::exception &exc) {
3802 // Unexpected failure
3803 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", EncodePaymentAddress(pa), exc.what()));
3810 /* Find unspent notes filtered by payment address, min depth and max depth */
3811 void CWallet::GetUnspentFilteredNotes(
3812 std::vector<CUnspentSproutNotePlaintextEntry>& outEntries,
3813 std::set<PaymentAddress>& filterAddresses,
3816 bool requireSpendingKey)
3818 LOCK2(cs_main, cs_wallet);
3820 for (auto & p : mapWallet) {
3821 CWalletTx wtx = p.second;
3823 // Filter the transactions before checking for notes
3824 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth || wtx.GetDepthInMainChain() > maxDepth) {
3828 if (wtx.mapNoteData.size() == 0) {
3832 for (auto & pair : wtx.mapNoteData) {
3833 JSOutPoint jsop = pair.first;
3834 CNoteData nd = pair.second;
3835 SproutPaymentAddress pa = nd.address;
3837 // skip notes which belong to a different payment address in the wallet
3838 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
3842 // skip note which has been spent
3843 if (nd.nullifier && IsSpent(*nd.nullifier)) {
3847 // skip notes where the spending key is not available
3848 if (requireSpendingKey && !HaveSpendingKey(pa)) {
3852 int i = jsop.js; // Index into CTransaction.vjoinsplit
3853 int j = jsop.n; // Index into JSDescription.ciphertexts
3855 // Get cached decryptor
3856 ZCNoteDecryption decryptor;
3857 if (!GetNoteDecryptor(pa, decryptor)) {
3858 // Note decryptors are created when the wallet is loaded, so it should always exist
3859 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", EncodePaymentAddress(pa)));
3862 // determine amount of funds in the note
3863 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3865 SproutNotePlaintext plaintext = SproutNotePlaintext::decrypt(
3867 wtx.vjoinsplit[i].ciphertexts[j],
3868 wtx.vjoinsplit[i].ephemeralKey,
3872 outEntries.push_back(CUnspentSproutNotePlaintextEntry{jsop, pa, plaintext, wtx.GetDepthInMainChain()});
3874 } catch (const note_decryption_failed &err) {
3875 // Couldn't decrypt with this spending key
3876 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", EncodePaymentAddress(pa)));
3877 } catch (const std::exception &exc) {
3878 // Unexpected failure
3879 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", EncodePaymentAddress(pa), exc.what()));