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"
9 #include "checkpoints.h"
10 #include "coincontrol.h"
11 #include "consensus/upgrades.h"
12 #include "consensus/validation.h"
13 #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 CZCPaymentAddress CWallet::GenerateNewZKey()
85 AssertLockHeld(cs_wallet); // mapZKeyMetadata
86 auto k = SpendingKey::random();
87 auto addr = k.address();
89 // Check for collision, even though it is unlikely to ever occur
90 if (CCryptoKeyStore::HaveSpendingKey(addr))
91 throw std::runtime_error("CWallet::GenerateNewZKey(): Collision detected");
93 // Create new metadata
94 int64_t nCreationTime = GetTime();
95 mapZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
97 CZCPaymentAddress pubaddr(addr);
99 throw std::runtime_error("CWallet::GenerateNewZKey(): AddZKey failed");
103 // Add spending key to keystore and persist to disk
104 bool CWallet::AddZKey(const libzcash::SpendingKey &key)
106 AssertLockHeld(cs_wallet); // mapZKeyMetadata
107 auto addr = key.address();
109 if (!CCryptoKeyStore::AddSpendingKey(key))
112 // check if we need to remove from viewing keys
113 if (HaveViewingKey(addr))
114 RemoveViewingKey(key.viewing_key());
120 return CWalletDB(strWalletFile).WriteZKey(addr,
122 mapZKeyMetadata[addr]);
127 CPubKey CWallet::GenerateNewKey()
129 AssertLockHeld(cs_wallet); // mapKeyMetadata
130 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
133 secret.MakeNewKey(fCompressed);
135 // Compressed public keys were introduced in version 0.6.0
137 SetMinVersion(FEATURE_COMPRPUBKEY);
139 CPubKey pubkey = secret.GetPubKey();
140 assert(secret.VerifyPubKey(pubkey));
142 // Create new metadata
143 int64_t nCreationTime = GetTime();
144 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
145 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
146 nTimeFirstKey = nCreationTime;
148 if (!AddKeyPubKey(secret, pubkey))
149 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
153 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
155 AssertLockHeld(cs_wallet); // mapKeyMetadata
156 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
159 // check if we need to remove from watch-only
161 script = GetScriptForDestination(pubkey.GetID());
162 if (HaveWatchOnly(script))
163 RemoveWatchOnly(script);
168 return CWalletDB(strWalletFile).WriteKey(pubkey,
170 mapKeyMetadata[pubkey.GetID()]);
175 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
176 const vector<unsigned char> &vchCryptedSecret)
179 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
185 if (pwalletdbEncryption)
186 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
188 mapKeyMetadata[vchPubKey.GetID()]);
190 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
192 mapKeyMetadata[vchPubKey.GetID()]);
198 bool CWallet::AddCryptedSpendingKey(const libzcash::PaymentAddress &address,
199 const libzcash::ReceivingKey &rk,
200 const std::vector<unsigned char> &vchCryptedSecret)
202 if (!CCryptoKeyStore::AddCryptedSpendingKey(address, rk, vchCryptedSecret))
208 if (pwalletdbEncryption) {
209 return pwalletdbEncryption->WriteCryptedZKey(address,
212 mapZKeyMetadata[address]);
214 return CWalletDB(strWalletFile).WriteCryptedZKey(address,
217 mapZKeyMetadata[address]);
223 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
225 AssertLockHeld(cs_wallet); // mapKeyMetadata
226 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
227 nTimeFirstKey = meta.nCreateTime;
229 mapKeyMetadata[pubkey.GetID()] = meta;
233 bool CWallet::LoadZKeyMetadata(const PaymentAddress &addr, const CKeyMetadata &meta)
235 AssertLockHeld(cs_wallet); // mapZKeyMetadata
236 mapZKeyMetadata[addr] = meta;
240 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
242 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
245 bool CWallet::LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret)
247 return CCryptoKeyStore::AddCryptedSpendingKey(addr, rk, vchCryptedSecret);
250 bool CWallet::LoadZKey(const libzcash::SpendingKey &key)
252 return CCryptoKeyStore::AddSpendingKey(key);
255 bool CWallet::AddViewingKey(const libzcash::ViewingKey &vk)
257 if (!CCryptoKeyStore::AddViewingKey(vk)) {
260 nTimeFirstKey = 1; // No birthday information for viewing keys.
264 return CWalletDB(strWalletFile).WriteViewingKey(vk);
267 bool CWallet::RemoveViewingKey(const libzcash::ViewingKey &vk)
269 AssertLockHeld(cs_wallet);
270 if (!CCryptoKeyStore::RemoveViewingKey(vk)) {
274 if (!CWalletDB(strWalletFile).EraseViewingKey(vk)) {
282 bool CWallet::LoadViewingKey(const libzcash::ViewingKey &vk)
284 return CCryptoKeyStore::AddViewingKey(vk);
287 bool CWallet::AddCScript(const CScript& redeemScript)
289 if (!CCryptoKeyStore::AddCScript(redeemScript))
293 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
296 bool CWallet::LoadCScript(const CScript& redeemScript)
298 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
299 * that never can be redeemed. However, old wallets may still contain
300 * these. Do not add them to the wallet and warn. */
301 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
303 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
304 LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
305 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
309 return CCryptoKeyStore::AddCScript(redeemScript);
312 bool CWallet::AddWatchOnly(const CScript &dest)
314 if (!CCryptoKeyStore::AddWatchOnly(dest))
316 nTimeFirstKey = 1; // No birthday information for watch-only keys.
317 NotifyWatchonlyChanged(true);
320 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
323 bool CWallet::RemoveWatchOnly(const CScript &dest)
325 AssertLockHeld(cs_wallet);
326 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
328 if (!HaveWatchOnly())
329 NotifyWatchonlyChanged(false);
331 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
337 bool CWallet::LoadWatchOnly(const CScript &dest)
339 return CCryptoKeyStore::AddWatchOnly(dest);
342 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
345 CKeyingMaterial vMasterKey;
349 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
351 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
353 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
354 continue; // try another master key
355 if (CCryptoKeyStore::Unlock(vMasterKey))
362 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
364 bool fWasLocked = IsLocked();
371 CKeyingMaterial vMasterKey;
372 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
374 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
376 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
378 if (CCryptoKeyStore::Unlock(vMasterKey))
380 int64_t nStartTime = GetTimeMillis();
381 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
382 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
384 nStartTime = GetTimeMillis();
385 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
386 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
388 if (pMasterKey.second.nDeriveIterations < 25000)
389 pMasterKey.second.nDeriveIterations = 25000;
391 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
393 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
395 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
397 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
408 void CWallet::ChainTip(const CBlockIndex *pindex, const CBlock *pblock,
409 ZCIncrementalMerkleTree tree, bool added)
412 IncrementNoteWitnesses(pindex, pblock, tree);
414 DecrementNoteWitnesses(pindex);
418 void CWallet::SetBestChain(const CBlockLocator& loc)
420 CWalletDB walletdb(strWalletFile);
421 SetBestChainINTERNAL(walletdb, loc);
424 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
426 LOCK(cs_wallet); // nWalletVersion
427 if (nWalletVersion >= nVersion)
430 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
431 if (fExplicit && nVersion > nWalletMaxVersion)
432 nVersion = FEATURE_LATEST;
434 nWalletVersion = nVersion;
436 if (nVersion > nWalletMaxVersion)
437 nWalletMaxVersion = nVersion;
441 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
442 if (nWalletVersion > 40000)
443 pwalletdb->WriteMinVersion(nWalletVersion);
451 bool CWallet::SetMaxVersion(int nVersion)
453 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
454 // cannot downgrade below current version
455 if (nWalletVersion > nVersion)
458 nWalletMaxVersion = nVersion;
463 set<uint256> CWallet::GetConflicts(const uint256& txid) const
466 AssertLockHeld(cs_wallet);
468 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
469 if (it == mapWallet.end())
471 const CWalletTx& wtx = it->second;
473 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
475 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
477 if (mapTxSpends.count(txin.prevout) <= 1)
478 continue; // No conflict if zero or one spends
479 range = mapTxSpends.equal_range(txin.prevout);
480 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
481 result.insert(it->second);
484 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
486 for (const JSDescription& jsdesc : wtx.vjoinsplit) {
487 for (const uint256& nullifier : jsdesc.nullifiers) {
488 if (mapTxNullifiers.count(nullifier) <= 1) {
489 continue; // No conflict if zero or one spends
491 range_n = mapTxNullifiers.equal_range(nullifier);
492 for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
493 result.insert(it->second);
500 void CWallet::Flush(bool shutdown)
502 bitdb.Flush(shutdown);
505 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
507 if (!bitdb.Open(GetDataDir()))
509 // try moving the database env out of the way
510 boost::filesystem::path pathDatabase = GetDataDir() / "database";
511 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
513 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
514 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
515 } catch (const boost::filesystem::filesystem_error&) {
516 // failure is ok (well, not really, but it's not worse than what we started with)
520 if (!bitdb.Open(GetDataDir())) {
521 // if it still fails, it probably means we can't even create the database env
522 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
528 if (GetBoolArg("-salvagewallet", false))
530 // Recover readable keypairs:
531 if (!CWalletDB::Recover(bitdb, walletFile, true))
535 if (boost::filesystem::exists(GetDataDir() / walletFile))
537 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
538 if (r == CDBEnv::RECOVER_OK)
540 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
541 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
542 " your balance or transactions are incorrect you should"
543 " restore from a backup."), GetDataDir());
545 if (r == CDBEnv::RECOVER_FAIL)
546 errorString += _("wallet.dat corrupt, salvage failed");
553 void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
555 // We want all the wallet transactions in range to have the same metadata as
556 // the oldest (smallest nOrderPos).
557 // So: find smallest nOrderPos:
559 int nMinOrderPos = std::numeric_limits<int>::max();
560 const CWalletTx* copyFrom = NULL;
561 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
563 const uint256& hash = it->second;
564 int n = mapWallet[hash].nOrderPos;
565 if (n < nMinOrderPos)
568 copyFrom = &mapWallet[hash];
571 // Now copy data from copyFrom to rest:
572 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
574 const uint256& hash = it->second;
575 CWalletTx* copyTo = &mapWallet[hash];
576 if (copyFrom == copyTo) continue;
577 copyTo->mapValue = copyFrom->mapValue;
578 // mapNoteData not copied on purpose
579 // (it is always set correctly for each CWalletTx)
580 copyTo->vOrderForm = copyFrom->vOrderForm;
581 // fTimeReceivedIsTxTime not copied on purpose
582 // nTimeReceived not copied on purpose
583 copyTo->nTimeSmart = copyFrom->nTimeSmart;
584 copyTo->fFromMe = copyFrom->fFromMe;
585 copyTo->strFromAccount = copyFrom->strFromAccount;
586 // nOrderPos not copied on purpose
587 // cached members not copied on purpose
592 * Outpoint is spent if any non-conflicted transaction
595 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
597 const COutPoint outpoint(hash, n);
598 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
599 range = mapTxSpends.equal_range(outpoint);
601 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
603 const uint256& wtxid = it->second;
604 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
605 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
606 return true; // Spent
612 * Note is spent if any non-conflicted transaction
615 bool CWallet::IsSpent(const uint256& nullifier) const
617 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
618 range = mapTxNullifiers.equal_range(nullifier);
620 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
621 const uint256& wtxid = it->second;
622 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
623 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
624 return true; // Spent
630 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
632 mapTxSpends.insert(make_pair(outpoint, wtxid));
634 pair<TxSpends::iterator, TxSpends::iterator> range;
635 range = mapTxSpends.equal_range(outpoint);
636 SyncMetaData<COutPoint>(range);
639 void CWallet::AddToSpends(const uint256& nullifier, const uint256& wtxid)
641 mapTxNullifiers.insert(make_pair(nullifier, wtxid));
643 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
644 range = mapTxNullifiers.equal_range(nullifier);
645 SyncMetaData<uint256>(range);
648 void CWallet::AddToSpends(const uint256& wtxid)
650 assert(mapWallet.count(wtxid));
651 CWalletTx& thisTx = mapWallet[wtxid];
652 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
655 for (const CTxIn& txin : thisTx.vin) {
656 AddToSpends(txin.prevout, wtxid);
658 for (const JSDescription& jsdesc : thisTx.vjoinsplit) {
659 for (const uint256& nullifier : jsdesc.nullifiers) {
660 AddToSpends(nullifier, wtxid);
665 void CWallet::ClearNoteWitnessCache()
668 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
669 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
670 item.second.witnesses.clear();
671 item.second.witnessHeight = -1;
674 nWitnessCacheSize = 0;
677 void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
678 const CBlock* pblockIn,
679 ZCIncrementalMerkleTree& tree)
683 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
684 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
685 CNoteData* nd = &(item.second);
686 // Only increment witnesses that are behind the current height
687 if (nd->witnessHeight < pindex->nHeight) {
688 // Check the validity of the cache
689 // The only time a note witnessed above the current height
690 // would be invalid here is during a reindex when blocks
691 // have been decremented, and we are incrementing the blocks
692 // immediately after.
693 assert(nWitnessCacheSize >= nd->witnesses.size());
694 // Witnesses being incremented should always be either -1
695 // (never incremented or decremented) or one below pindex
696 assert((nd->witnessHeight == -1) ||
697 (nd->witnessHeight == pindex->nHeight - 1));
698 // Copy the witness for the previous block if we have one
699 if (nd->witnesses.size() > 0) {
700 nd->witnesses.push_front(nd->witnesses.front());
702 if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
703 nd->witnesses.pop_back();
708 if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
709 nWitnessCacheSize += 1;
712 const CBlock* pblock {pblockIn};
715 ReadBlockFromDisk(block, pindex);
719 for (const CTransaction& tx : pblock->vtx) {
720 auto hash = tx.GetHash();
721 bool txIsOurs = mapWallet.count(hash);
722 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
723 const JSDescription& jsdesc = tx.vjoinsplit[i];
724 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
725 const uint256& note_commitment = jsdesc.commitments[j];
726 tree.append(note_commitment);
728 // Increment existing witnesses
729 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
730 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
731 CNoteData* nd = &(item.second);
732 if (nd->witnessHeight < pindex->nHeight &&
733 nd->witnesses.size() > 0) {
734 // Check the validity of the cache
735 // See earlier comment about validity.
736 assert(nWitnessCacheSize >= nd->witnesses.size());
737 nd->witnesses.front().append(note_commitment);
742 // If this is our note, witness it
744 JSOutPoint jsoutpt {hash, i, j};
745 if (mapWallet[hash].mapNoteData.count(jsoutpt) &&
746 mapWallet[hash].mapNoteData[jsoutpt].witnessHeight < pindex->nHeight) {
747 CNoteData* nd = &(mapWallet[hash].mapNoteData[jsoutpt]);
748 if (nd->witnesses.size() > 0) {
749 // We think this can happen because we write out the
750 // witness cache state after every block increment or
751 // decrement, but the block index itself is written in
752 // batches. So if the node crashes in between these two
753 // operations, it is possible for IncrementNoteWitnesses
754 // to be called again on previously-cached blocks. This
755 // doesn't affect existing cached notes because of the
756 // CNoteData::witnessHeight checks. See #1378 for details.
757 LogPrintf("Inconsistent witness cache state found for %s\n- Cache size: %d\n- Top (height %d): %s\n- New (height %d): %s\n",
758 jsoutpt.ToString(), nd->witnesses.size(),
760 nd->witnesses.front().root().GetHex(),
762 tree.witness().root().GetHex());
763 nd->witnesses.clear();
765 nd->witnesses.push_front(tree.witness());
766 // Set height to one less than pindex so it gets incremented
767 nd->witnessHeight = pindex->nHeight - 1;
768 // Check the validity of the cache
769 assert(nWitnessCacheSize >= nd->witnesses.size());
776 // Update witness heights
777 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
778 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
779 CNoteData* nd = &(item.second);
780 if (nd->witnessHeight < pindex->nHeight) {
781 nd->witnessHeight = pindex->nHeight;
782 // Check the validity of the cache
783 // See earlier comment about validity.
784 assert(nWitnessCacheSize >= nd->witnesses.size());
789 // For performance reasons, we write out the witness cache in
790 // CWallet::SetBestChain() (which also ensures that overall consistency
791 // of the wallet.dat is maintained).
795 void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
799 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
800 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
801 CNoteData* nd = &(item.second);
802 // Only increment witnesses that are not above the current height
803 if (nd->witnessHeight <= pindex->nHeight) {
804 // Check the validity of the cache
805 // See comment below (this would be invalid if there was a
807 assert(nWitnessCacheSize >= nd->witnesses.size());
808 // Witnesses being decremented should always be either -1
809 // (never incremented or decremented) or equal to pindex
810 assert((nd->witnessHeight == -1) ||
811 (nd->witnessHeight == pindex->nHeight));
812 if (nd->witnesses.size() > 0) {
813 nd->witnesses.pop_front();
815 // pindex is the block being removed, so the new witness cache
816 // height is one below it.
817 nd->witnessHeight = pindex->nHeight - 1;
821 nWitnessCacheSize -= 1;
822 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
823 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
824 CNoteData* nd = &(item.second);
825 // Check the validity of the cache
826 // Technically if there are notes witnessed above the current
827 // height, their cache will now be invalid (relative to the new
828 // value of nWitnessCacheSize). However, this would only occur
829 // during a reindex, and by the time the reindex reaches the tip
830 // of the chain again, the existing witness caches will be valid
832 // We don't set nWitnessCacheSize to zero at the start of the
833 // reindex because the on-disk blocks had already resulted in a
834 // chain that didn't trigger the assertion below.
835 if (nd->witnessHeight < pindex->nHeight) {
836 assert(nWitnessCacheSize >= nd->witnesses.size());
840 // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
841 assert(nWitnessCacheSize > 0);
843 // For performance reasons, we write out the witness cache in
844 // CWallet::SetBestChain() (which also ensures that overall consistency
845 // of the wallet.dat is maintained).
849 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
854 CKeyingMaterial vMasterKey;
856 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
857 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
859 CMasterKey kMasterKey;
861 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
862 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
865 int64_t nStartTime = GetTimeMillis();
866 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
867 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
869 nStartTime = GetTimeMillis();
870 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
871 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
873 if (kMasterKey.nDeriveIterations < 25000)
874 kMasterKey.nDeriveIterations = 25000;
876 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
878 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
880 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
885 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
888 assert(!pwalletdbEncryption);
889 pwalletdbEncryption = new CWalletDB(strWalletFile);
890 if (!pwalletdbEncryption->TxnBegin()) {
891 delete pwalletdbEncryption;
892 pwalletdbEncryption = NULL;
895 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
898 if (!EncryptKeys(vMasterKey))
901 pwalletdbEncryption->TxnAbort();
902 delete pwalletdbEncryption;
904 // We now probably have half of our keys encrypted in memory, and half not...
905 // die and let the user reload the unencrypted wallet.
909 // Encryption was introduced in version 0.4.0
910 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
914 if (!pwalletdbEncryption->TxnCommit()) {
915 delete pwalletdbEncryption;
916 // We now have keys encrypted in memory, but not on disk...
917 // die to avoid confusion and let the user reload the unencrypted wallet.
921 delete pwalletdbEncryption;
922 pwalletdbEncryption = NULL;
926 Unlock(strWalletPassphrase);
930 // Need to completely rewrite the wallet file; if we don't, bdb might keep
931 // bits of the unencrypted private key in slack space in the database file.
932 CDB::Rewrite(strWalletFile);
935 NotifyStatusChanged(this);
940 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
942 AssertLockHeld(cs_wallet); // nOrderPosNext
943 int64_t nRet = nOrderPosNext++;
945 pwalletdb->WriteOrderPosNext(nOrderPosNext);
947 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
952 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
954 AssertLockHeld(cs_wallet); // mapWallet
955 CWalletDB walletdb(strWalletFile);
957 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
960 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
961 // would make this much faster for applications that do this a lot.
962 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
964 CWalletTx* wtx = &((*it).second);
965 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
968 walletdb.ListAccountCreditDebit(strAccount, acentries);
969 BOOST_FOREACH(CAccountingEntry& entry, acentries)
971 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
977 void CWallet::MarkDirty()
981 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
982 item.second.MarkDirty();
987 * Ensure that every note in the wallet (for which we possess a spending key)
988 * has a cached nullifier.
990 bool CWallet::UpdateNullifierNoteMap()
998 ZCNoteDecryption dec;
999 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1000 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
1001 if (!item.second.nullifier) {
1002 if (GetNoteDecryptor(item.second.address, dec)) {
1003 auto i = item.first.js;
1004 auto hSig = wtxItem.second.vjoinsplit[i].h_sig(
1005 *pzcashParams, wtxItem.second.joinSplitPubKey);
1006 item.second.nullifier = GetNoteNullifier(
1007 wtxItem.second.vjoinsplit[i],
1008 item.second.address,
1015 UpdateNullifierNoteMapWithTx(wtxItem.second);
1022 * Update mapNullifiersToNotes with the cached nullifiers in this tx.
1024 void CWallet::UpdateNullifierNoteMapWithTx(const CWalletTx& wtx)
1028 for (const mapNoteData_t::value_type& item : wtx.mapNoteData) {
1029 if (item.second.nullifier) {
1030 mapNullifiersToNotes[*item.second.nullifier] = item.first;
1036 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
1038 uint256 hash = wtxIn.GetHash();
1040 if (fFromLoadWallet)
1042 mapWallet[hash] = wtxIn;
1043 mapWallet[hash].BindWallet(this);
1044 UpdateNullifierNoteMapWithTx(mapWallet[hash]);
1050 // Inserts only if not already there, returns tx inserted or tx found
1051 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
1052 CWalletTx& wtx = (*ret.first).second;
1053 wtx.BindWallet(this);
1054 UpdateNullifierNoteMapWithTx(wtx);
1055 bool fInsertedNew = ret.second;
1058 wtx.nTimeReceived = GetAdjustedTime();
1059 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
1061 wtx.nTimeSmart = wtx.nTimeReceived;
1062 if (!wtxIn.hashBlock.IsNull())
1064 if (mapBlockIndex.count(wtxIn.hashBlock))
1066 int64_t latestNow = wtx.nTimeReceived;
1067 int64_t latestEntry = 0;
1069 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
1070 int64_t latestTolerated = latestNow + 300;
1071 std::list<CAccountingEntry> acentries;
1072 TxItems txOrdered = OrderedTxItems(acentries);
1073 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1075 CWalletTx *const pwtx = (*it).second.first;
1078 CAccountingEntry *const pacentry = (*it).second.second;
1082 nSmartTime = pwtx->nTimeSmart;
1084 nSmartTime = pwtx->nTimeReceived;
1087 nSmartTime = pacentry->nTime;
1088 if (nSmartTime <= latestTolerated)
1090 latestEntry = nSmartTime;
1091 if (nSmartTime > latestNow)
1092 latestNow = nSmartTime;
1098 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
1099 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
1102 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
1103 wtxIn.GetHash().ToString(),
1104 wtxIn.hashBlock.ToString());
1109 bool fUpdated = false;
1113 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
1115 wtx.hashBlock = wtxIn.hashBlock;
1118 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
1120 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
1121 wtx.nIndex = wtxIn.nIndex;
1124 if (UpdatedNoteData(wtxIn, wtx)) {
1127 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1129 wtx.fFromMe = wtxIn.fFromMe;
1135 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1138 if (fInsertedNew || fUpdated)
1139 if (!wtx.WriteToDisk(pwalletdb))
1142 // Break debit/credit balance caches:
1145 // Notify UI of new or updated transaction
1146 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1148 // notify an external script when a wallet transaction comes in or is updated
1149 std::string strCmd = GetArg("-walletnotify", "");
1151 if ( !strCmd.empty())
1153 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1154 boost::thread t(runCommand, strCmd); // thread runs free
1161 bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1163 if (wtxIn.mapNoteData.empty() || wtxIn.mapNoteData == wtx.mapNoteData) {
1166 auto tmp = wtxIn.mapNoteData;
1167 // Ensure we keep any cached witnesses we may already have
1168 for (const std::pair<JSOutPoint, CNoteData> nd : wtx.mapNoteData) {
1169 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1170 tmp.at(nd.first).witnesses.assign(
1171 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1173 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1175 // Now copy over the updated note data
1176 wtx.mapNoteData = tmp;
1181 * Add a transaction to the wallet, or update it.
1182 * pblock is optional, but should be provided if the transaction is known to be in a block.
1183 * If fUpdate is true, existing transactions will be updated.
1185 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1188 AssertLockHeld(cs_wallet);
1189 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1190 if (fExisted && !fUpdate) return false;
1191 auto noteData = FindMyNotes(tx);
1192 if (fExisted || IsMine(tx) || IsFromMe(tx) || noteData.size() > 0)
1194 CWalletTx wtx(this,tx);
1196 if (noteData.size() > 0) {
1197 wtx.SetNoteData(noteData);
1200 // Get merkle branch if transaction was found in a block
1202 wtx.SetMerkleBranch(*pblock);
1204 // Do not flush the wallet here for performance reasons
1205 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1206 CWalletDB walletdb(strWalletFile, "r+", false);
1208 return AddToWallet(wtx, false, &walletdb);
1214 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1216 LOCK2(cs_main, cs_wallet);
1217 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1218 return; // Not one of ours
1220 MarkAffectedTransactionsDirty(tx);
1223 void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1225 // If a transaction changes 'conflicted' state, that changes the balance
1226 // available of the outputs it spends. So force those to be
1227 // recomputed, also:
1228 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1230 if (mapWallet.count(txin.prevout.hash))
1231 mapWallet[txin.prevout.hash].MarkDirty();
1233 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1234 for (const uint256& nullifier : jsdesc.nullifiers) {
1235 if (mapNullifiersToNotes.count(nullifier) &&
1236 mapWallet.count(mapNullifiersToNotes[nullifier].hash)) {
1237 mapWallet[mapNullifiersToNotes[nullifier].hash].MarkDirty();
1243 void CWallet::EraseFromWallet(const uint256 &hash)
1249 if (mapWallet.erase(hash))
1250 CWalletDB(strWalletFile).EraseTx(hash);
1257 * Returns a nullifier if the SpendingKey is available
1258 * Throws std::runtime_error if the decryptor doesn't match this note
1260 boost::optional<uint256> CWallet::GetNoteNullifier(const JSDescription& jsdesc,
1261 const libzcash::PaymentAddress& address,
1262 const ZCNoteDecryption& dec,
1263 const uint256& hSig,
1266 boost::optional<uint256> ret;
1267 auto note_pt = libzcash::NotePlaintext::decrypt(
1269 jsdesc.ciphertexts[n],
1270 jsdesc.ephemeralKey,
1273 auto note = note_pt.note(address);
1274 // SpendingKeys are only available if:
1275 // - We have them (this isn't a viewing key)
1276 // - The wallet is unlocked
1277 libzcash::SpendingKey key;
1278 if (GetSpendingKey(address, key)) {
1279 ret = note.nullifier(key);
1285 * Finds all output notes in the given transaction that have been sent to
1286 * PaymentAddresses in this wallet.
1288 * It should never be necessary to call this method with a CWalletTx, because
1289 * the result of FindMyNotes (for the addresses available at the time) will
1290 * already have been cached in CWalletTx.mapNoteData.
1292 mapNoteData_t CWallet::FindMyNotes(const CTransaction& tx) const
1294 LOCK(cs_SpendingKeyStore);
1295 uint256 hash = tx.GetHash();
1297 mapNoteData_t noteData;
1298 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1299 auto hSig = tx.vjoinsplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1300 for (uint8_t j = 0; j < tx.vjoinsplit[i].ciphertexts.size(); j++) {
1301 for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
1303 auto address = item.first;
1304 JSOutPoint jsoutpt {hash, i, j};
1305 auto nullifier = GetNoteNullifier(
1311 CNoteData nd {address, *nullifier};
1312 noteData.insert(std::make_pair(jsoutpt, nd));
1314 CNoteData nd {address};
1315 noteData.insert(std::make_pair(jsoutpt, nd));
1318 } catch (const note_decryption_failed &err) {
1319 // Couldn't decrypt with this decryptor
1320 } catch (const std::exception &exc) {
1321 // Unexpected failure
1322 LogPrintf("FindMyNotes(): Unexpected error while testing decrypt:\n");
1323 LogPrintf("%s\n", exc.what());
1331 bool CWallet::IsFromMe(const uint256& nullifier) const
1335 if (mapNullifiersToNotes.count(nullifier) &&
1336 mapWallet.count(mapNullifiersToNotes.at(nullifier).hash)) {
1343 void CWallet::GetNoteWitnesses(std::vector<JSOutPoint> notes,
1344 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1345 uint256 &final_anchor)
1349 witnesses.resize(notes.size());
1350 boost::optional<uint256> rt;
1352 for (JSOutPoint note : notes) {
1353 if (mapWallet.count(note.hash) &&
1354 mapWallet[note.hash].mapNoteData.count(note) &&
1355 mapWallet[note.hash].mapNoteData[note].witnesses.size() > 0) {
1356 witnesses[i] = mapWallet[note.hash].mapNoteData[note].witnesses.front();
1358 rt = witnesses[i]->root();
1360 assert(*rt == witnesses[i]->root());
1365 // All returned witnesses have the same anchor
1372 isminetype CWallet::IsMine(const CTxIn &txin) const
1376 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1377 if (mi != mapWallet.end())
1379 const CWalletTx& prev = (*mi).second;
1380 if (txin.prevout.n < prev.vout.size())
1381 return IsMine(prev.vout[txin.prevout.n]);
1387 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1391 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1392 if (mi != mapWallet.end())
1394 const CWalletTx& prev = (*mi).second;
1395 if (txin.prevout.n < prev.vout.size())
1396 if (IsMine(prev.vout[txin.prevout.n]) & filter)
1397 return prev.vout[txin.prevout.n].nValue;
1403 isminetype CWallet::IsMine(const CTxOut& txout) const
1405 return ::IsMine(*this, txout.scriptPubKey);
1408 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1410 if (!MoneyRange(txout.nValue))
1411 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1412 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1415 bool CWallet::IsChange(const CTxOut& txout) const
1417 // TODO: fix handling of 'change' outputs. The assumption is that any
1418 // payment to a script that is ours, but is not in the address book
1419 // is change. That assumption is likely to break when we implement multisignature
1420 // wallets that return change back into a multi-signature-protected address;
1421 // a better way of identifying which outputs are 'the send' and which are
1422 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1423 // which output, if any, was change).
1424 if (::IsMine(*this, txout.scriptPubKey))
1426 CTxDestination address;
1427 if (!ExtractDestination(txout.scriptPubKey, address))
1431 if (!mapAddressBook.count(address))
1437 CAmount CWallet::GetChange(const CTxOut& txout) const
1439 if (!MoneyRange(txout.nValue))
1440 throw std::runtime_error("CWallet::GetChange(): value out of range");
1441 return (IsChange(txout) ? txout.nValue : 0);
1444 bool CWallet::IsMine(const CTransaction& tx) const
1446 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1452 bool CWallet::IsFromMe(const CTransaction& tx) const
1454 if (GetDebit(tx, ISMINE_ALL) > 0) {
1457 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1458 for (const uint256& nullifier : jsdesc.nullifiers) {
1459 if (IsFromMe(nullifier)) {
1467 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1470 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1472 nDebit += GetDebit(txin, filter);
1473 if (!MoneyRange(nDebit))
1474 throw std::runtime_error("CWallet::GetDebit(): value out of range");
1479 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1481 CAmount nCredit = 0;
1482 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1484 nCredit += GetCredit(txout, filter);
1485 if (!MoneyRange(nCredit))
1486 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1491 CAmount CWallet::GetChange(const CTransaction& tx) const
1493 CAmount nChange = 0;
1494 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1496 nChange += GetChange(txout);
1497 if (!MoneyRange(nChange))
1498 throw std::runtime_error("CWallet::GetChange(): value out of range");
1503 void CWalletTx::SetNoteData(mapNoteData_t ¬eData)
1505 mapNoteData.clear();
1506 for (const std::pair<JSOutPoint, CNoteData> nd : noteData) {
1507 if (nd.first.js < vjoinsplit.size() &&
1508 nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1509 // Store the address and nullifier for the Note
1510 mapNoteData[nd.first] = nd.second;
1512 // If FindMyNotes() was used to obtain noteData,
1513 // this should never happen
1514 throw std::logic_error("CWalletTx::SetNoteData(): Invalid note");
1519 int64_t CWalletTx::GetTxTime() const
1521 int64_t n = nTimeSmart;
1522 return n ? n : nTimeReceived;
1525 int CWalletTx::GetRequestCount() const
1527 // Returns -1 if it wasn't being tracked
1530 LOCK(pwallet->cs_wallet);
1534 if (!hashBlock.IsNull())
1536 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1537 if (mi != pwallet->mapRequestCount.end())
1538 nRequests = (*mi).second;
1543 // Did anyone request this transaction?
1544 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1545 if (mi != pwallet->mapRequestCount.end())
1547 nRequests = (*mi).second;
1549 // How about the block it's in?
1550 if (nRequests == 0 && !hashBlock.IsNull())
1552 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1553 if (mi != pwallet->mapRequestCount.end())
1554 nRequests = (*mi).second;
1556 nRequests = 1; // If it's in someone else's block it must have got out
1564 // GetAmounts will determine the transparent debits and credits for a given wallet tx.
1565 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1566 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1569 listReceived.clear();
1571 strSentAccount = strFromAccount;
1573 // Is this tx sent/signed by me?
1574 CAmount nDebit = GetDebit(filter);
1575 bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
1577 // Does this tx spend my notes?
1578 bool isFromMyZaddr = false;
1579 for (const JSDescription& js : vjoinsplit) {
1580 for (const uint256& nullifier : js.nullifiers) {
1581 if (pwallet->IsFromMe(nullifier)) {
1582 isFromMyZaddr = true;
1586 if (isFromMyZaddr) {
1591 // Compute fee if we sent this transaction.
1592 if (isFromMyTaddr) {
1593 CAmount nValueOut = GetValueOut(); // transparent outputs plus all vpub_old
1594 CAmount nValueIn = 0;
1595 for (const JSDescription & js : vjoinsplit) {
1596 nValueIn += js.vpub_new;
1598 nFee = nDebit - nValueOut + nValueIn;
1601 // Create output entry for vpub_old/new, if we sent utxos from this transaction
1602 if (isFromMyTaddr) {
1603 CAmount myVpubOld = 0;
1604 CAmount myVpubNew = 0;
1605 for (const JSDescription& js : vjoinsplit) {
1606 bool fMyJSDesc = false;
1609 for (const uint256& nullifier : js.nullifiers) {
1610 if (pwallet->IsFromMe(nullifier)) {
1616 // Check output side
1618 for (const std::pair<JSOutPoint, CNoteData> nd : this->mapNoteData) {
1619 if (nd.first.js < vjoinsplit.size() && nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1627 myVpubOld += js.vpub_old;
1628 myVpubNew += js.vpub_new;
1631 if (!MoneyRange(js.vpub_old) || !MoneyRange(js.vpub_new) || !MoneyRange(myVpubOld) || !MoneyRange(myVpubNew)) {
1632 throw std::runtime_error("CWalletTx::GetAmounts: value out of range");
1636 // Create an output for the value taken from or added to the transparent value pool by JoinSplits
1637 if (myVpubOld > myVpubNew) {
1638 COutputEntry output = {CNoDestination(), myVpubOld - myVpubNew, (int)vout.size()};
1639 listSent.push_back(output);
1640 } else if (myVpubNew > myVpubOld) {
1641 COutputEntry output = {CNoDestination(), myVpubNew - myVpubOld, (int)vout.size()};
1642 listReceived.push_back(output);
1647 for (unsigned int i = 0; i < vout.size(); ++i)
1649 const CTxOut& txout = vout[i];
1650 isminetype fIsMine = pwallet->IsMine(txout);
1651 // Only need to handle txouts if AT LEAST one of these is true:
1652 // 1) they debit from us (sent)
1653 // 2) the output is to us (received)
1656 // Don't report 'change' txouts
1657 if (pwallet->IsChange(txout))
1660 else if (!(fIsMine & filter))
1663 // In either case, we need to get the destination address
1664 CTxDestination address;
1665 if (!ExtractDestination(txout.scriptPubKey, address))
1667 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1668 this->GetHash().ToString());
1669 address = CNoDestination();
1672 COutputEntry output = {address, txout.nValue, (int)i};
1674 // If we are debited by the transaction, add the output as a "sent" entry
1676 listSent.push_back(output);
1678 // If we are receiving the output, add it as a "received" entry
1679 if (fIsMine & filter)
1680 listReceived.push_back(output);
1685 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1686 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1688 nReceived = nSent = nFee = 0;
1691 string strSentAccount;
1692 list<COutputEntry> listReceived;
1693 list<COutputEntry> listSent;
1694 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1696 if (strAccount == strSentAccount)
1698 BOOST_FOREACH(const COutputEntry& s, listSent)
1703 LOCK(pwallet->cs_wallet);
1704 BOOST_FOREACH(const COutputEntry& r, listReceived)
1706 if (pwallet->mapAddressBook.count(r.destination))
1708 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1709 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1710 nReceived += r.amount;
1712 else if (strAccount.empty())
1714 nReceived += r.amount;
1721 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
1723 return pwalletdb->WriteTx(GetHash(), *this);
1726 void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
1727 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1728 uint256 &final_anchor)
1730 witnesses.resize(commitments.size());
1731 CBlockIndex* pindex = chainActive.Genesis();
1732 ZCIncrementalMerkleTree tree;
1736 ReadBlockFromDisk(block, pindex);
1738 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1740 BOOST_FOREACH(const JSDescription& jsdesc, tx.vjoinsplit)
1742 BOOST_FOREACH(const uint256 ¬e_commitment, jsdesc.commitments)
1744 tree.append(note_commitment);
1746 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1748 wit->append(note_commitment);
1753 BOOST_FOREACH(uint256& commitment, commitments) {
1754 if (note_commitment == commitment) {
1755 witnesses.at(i) = tree.witness();
1763 uint256 current_anchor = tree.root();
1765 // Consistency check: we should be able to find the current tree
1766 // in our CCoins view.
1767 ZCIncrementalMerkleTree dummy_tree;
1768 assert(pcoinsTip->GetAnchorAt(current_anchor, dummy_tree));
1770 pindex = chainActive.Next(pindex);
1773 // TODO: #93; Select a root via some heuristic.
1774 final_anchor = tree.root();
1776 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1778 assert(final_anchor == wit->root());
1784 * Scan the block chain (starting in pindexStart) for transactions
1785 * from or to us. If fUpdate is true, found transactions that already
1786 * exist in the wallet will be updated.
1788 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1791 int64_t nNow = GetTime();
1792 const CChainParams& chainParams = Params();
1794 CBlockIndex* pindex = pindexStart;
1796 LOCK2(cs_main, cs_wallet);
1798 // no need to read and scan block, if block was created before
1799 // our wallet birthday (as adjusted for block time variability)
1800 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1801 pindex = chainActive.Next(pindex);
1803 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1804 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1805 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1808 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1809 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1812 ReadBlockFromDisk(block, pindex);
1813 BOOST_FOREACH(CTransaction& tx, block.vtx)
1815 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1819 ZCIncrementalMerkleTree tree;
1820 // This should never fail: we should always be able to get the tree
1821 // state on the path to the tip of our chain
1822 assert(pcoinsTip->GetAnchorAt(pindex->hashAnchor, tree));
1823 // Increment note witness caches
1824 IncrementNoteWitnesses(pindex, &block, tree);
1826 pindex = chainActive.Next(pindex);
1827 if (GetTime() >= nNow + 60) {
1829 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1832 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1837 void CWallet::ReacceptWalletTransactions()
1839 // If transactions aren't being broadcasted, don't let them into local mempool either
1840 if (!fBroadcastTransactions)
1842 LOCK2(cs_main, cs_wallet);
1843 std::map<int64_t, CWalletTx*> mapSorted;
1845 // Sort pending wallet transactions based on their initial wallet insertion order
1846 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1848 const uint256& wtxid = item.first;
1849 CWalletTx& wtx = item.second;
1850 assert(wtx.GetHash() == wtxid);
1852 int nDepth = wtx.GetDepthInMainChain();
1854 if (!wtx.IsCoinBase() && nDepth < 0) {
1855 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1859 // Try to add wallet transactions to memory pool
1860 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1862 CWalletTx& wtx = *(item.second);
1865 wtx.AcceptToMemoryPool(false);
1869 bool CWalletTx::RelayWalletTransaction()
1871 assert(pwallet->GetBroadcastTransactions());
1874 if (GetDepthInMainChain() == 0) {
1875 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1876 RelayTransaction((CTransaction)*this);
1883 set<uint256> CWalletTx::GetConflicts() const
1885 set<uint256> result;
1886 if (pwallet != NULL)
1888 uint256 myHash = GetHash();
1889 result = pwallet->GetConflicts(myHash);
1890 result.erase(myHash);
1895 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1901 if(filter & ISMINE_SPENDABLE)
1904 debit += nDebitCached;
1907 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1908 fDebitCached = true;
1909 debit += nDebitCached;
1912 if(filter & ISMINE_WATCH_ONLY)
1914 if(fWatchDebitCached)
1915 debit += nWatchDebitCached;
1918 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1919 fWatchDebitCached = true;
1920 debit += nWatchDebitCached;
1926 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1928 // Must wait until coinbase is safely deep enough in the chain before valuing it
1929 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1933 if (filter & ISMINE_SPENDABLE)
1935 // GetBalance can assume transactions in mapWallet won't change
1937 credit += nCreditCached;
1940 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1941 fCreditCached = true;
1942 credit += nCreditCached;
1945 if (filter & ISMINE_WATCH_ONLY)
1947 if (fWatchCreditCached)
1948 credit += nWatchCreditCached;
1951 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1952 fWatchCreditCached = true;
1953 credit += nWatchCreditCached;
1959 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1961 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1963 if (fUseCache && fImmatureCreditCached)
1964 return nImmatureCreditCached;
1965 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1966 fImmatureCreditCached = true;
1967 return nImmatureCreditCached;
1973 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1978 // Must wait until coinbase is safely deep enough in the chain before valuing it
1979 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1982 if (fUseCache && fAvailableCreditCached)
1983 return nAvailableCreditCached;
1985 CAmount nCredit = 0;
1986 uint256 hashTx = GetHash();
1987 for (unsigned int i = 0; i < vout.size(); i++)
1989 if (!pwallet->IsSpent(hashTx, i))
1991 const CTxOut &txout = vout[i];
1992 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1993 if (!MoneyRange(nCredit))
1994 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1998 nAvailableCreditCached = nCredit;
1999 fAvailableCreditCached = true;
2003 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
2005 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2007 if (fUseCache && fImmatureWatchCreditCached)
2008 return nImmatureWatchCreditCached;
2009 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2010 fImmatureWatchCreditCached = true;
2011 return nImmatureWatchCreditCached;
2017 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
2022 // Must wait until coinbase is safely deep enough in the chain before valuing it
2023 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2026 if (fUseCache && fAvailableWatchCreditCached)
2027 return nAvailableWatchCreditCached;
2029 CAmount nCredit = 0;
2030 for (unsigned int i = 0; i < vout.size(); i++)
2032 if (!pwallet->IsSpent(GetHash(), i))
2034 const CTxOut &txout = vout[i];
2035 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2036 if (!MoneyRange(nCredit))
2037 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2041 nAvailableWatchCreditCached = nCredit;
2042 fAvailableWatchCreditCached = true;
2046 CAmount CWalletTx::GetChange() const
2049 return nChangeCached;
2050 nChangeCached = pwallet->GetChange(*this);
2051 fChangeCached = true;
2052 return nChangeCached;
2055 bool CWalletTx::IsTrusted() const
2057 // Quick answer in most cases
2058 if (!CheckFinalTx(*this))
2060 int nDepth = GetDepthInMainChain();
2065 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2068 // Trusted if all inputs are from us and are in the mempool:
2069 BOOST_FOREACH(const CTxIn& txin, vin)
2071 // Transactions not sent by us: not trusted
2072 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2075 const CTxOut& parentOut = parent->vout[txin.prevout.n];
2076 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2082 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
2084 std::vector<uint256> result;
2087 // Sort them in chronological order
2088 multimap<unsigned int, CWalletTx*> mapSorted;
2089 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2091 CWalletTx& wtx = item.second;
2092 // Don't rebroadcast if newer than nTime:
2093 if (wtx.nTimeReceived > nTime)
2095 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2097 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2099 CWalletTx& wtx = *item.second;
2100 if (wtx.RelayWalletTransaction())
2101 result.push_back(wtx.GetHash());
2106 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
2108 // Do this infrequently and randomly to avoid giving away
2109 // that these are our transactions.
2110 if (GetTime() < nNextResend || !fBroadcastTransactions)
2112 bool fFirst = (nNextResend == 0);
2113 nNextResend = GetTime() + GetRand(30 * 60);
2117 // Only do it if there's been a new block since last time
2118 if (nBestBlockTime < nLastResend)
2120 nLastResend = GetTime();
2122 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2124 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
2125 if (!relayed.empty())
2126 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2129 /** @} */ // end of mapWallet
2134 /** @defgroup Actions
2140 CAmount CWallet::GetBalance() const
2144 LOCK2(cs_main, cs_wallet);
2145 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2147 const CWalletTx* pcoin = &(*it).second;
2148 if (pcoin->IsTrusted())
2149 nTotal += pcoin->GetAvailableCredit();
2156 CAmount CWallet::GetUnconfirmedBalance() const
2160 LOCK2(cs_main, cs_wallet);
2161 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2163 const CWalletTx* pcoin = &(*it).second;
2164 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2165 nTotal += pcoin->GetAvailableCredit();
2171 CAmount CWallet::GetImmatureBalance() const
2175 LOCK2(cs_main, cs_wallet);
2176 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2178 const CWalletTx* pcoin = &(*it).second;
2179 nTotal += pcoin->GetImmatureCredit();
2185 CAmount CWallet::GetWatchOnlyBalance() const
2189 LOCK2(cs_main, cs_wallet);
2190 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2192 const CWalletTx* pcoin = &(*it).second;
2193 if (pcoin->IsTrusted())
2194 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2201 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2205 LOCK2(cs_main, cs_wallet);
2206 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2208 const CWalletTx* pcoin = &(*it).second;
2209 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2210 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2216 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2220 LOCK2(cs_main, cs_wallet);
2221 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2223 const CWalletTx* pcoin = &(*it).second;
2224 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2231 * populate vCoins with vector of available COutputs.
2233 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const
2238 LOCK2(cs_main, cs_wallet);
2239 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2241 const uint256& wtxid = it->first;
2242 const CWalletTx* pcoin = &(*it).second;
2244 if (!CheckFinalTx(*pcoin))
2247 if (fOnlyConfirmed && !pcoin->IsTrusted())
2250 if (pcoin->IsCoinBase() && !fIncludeCoinBase)
2253 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2256 int nDepth = pcoin->GetDepthInMainChain();
2260 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2261 isminetype mine = IsMine(pcoin->vout[i]);
2262 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2263 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
2264 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
2265 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
2271 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2272 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2274 vector<char> vfIncluded;
2276 vfBest.assign(vValue.size(), true);
2277 nBest = nTotalLower;
2279 seed_insecure_rand();
2281 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2283 vfIncluded.assign(vValue.size(), false);
2285 bool fReachedTarget = false;
2286 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2288 for (unsigned int i = 0; i < vValue.size(); i++)
2290 //The solver here uses a randomized algorithm,
2291 //the randomness serves no real security purpose but is just
2292 //needed to prevent degenerate behavior and it is important
2293 //that the rng is fast. We do not use a constant random sequence,
2294 //because there may be some privacy improvement by making
2295 //the selection random.
2296 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
2298 nTotal += vValue[i].first;
2299 vfIncluded[i] = true;
2300 if (nTotal >= nTargetValue)
2302 fReachedTarget = true;
2306 vfBest = vfIncluded;
2308 nTotal -= vValue[i].first;
2309 vfIncluded[i] = false;
2317 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2318 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
2320 setCoinsRet.clear();
2323 // List of values less than target
2324 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2325 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2326 coinLowestLarger.second.first = NULL;
2327 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2328 CAmount nTotalLower = 0;
2330 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2332 BOOST_FOREACH(const COutput &output, vCoins)
2334 if (!output.fSpendable)
2337 const CWalletTx *pcoin = output.tx;
2339 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2343 CAmount n = pcoin->vout[i].nValue;
2345 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2347 if (n == nTargetValue)
2349 setCoinsRet.insert(coin.second);
2350 nValueRet += coin.first;
2353 else if (n < nTargetValue + CENT)
2355 vValue.push_back(coin);
2358 else if (n < coinLowestLarger.first)
2360 coinLowestLarger = coin;
2364 if (nTotalLower == nTargetValue)
2366 for (unsigned int i = 0; i < vValue.size(); ++i)
2368 setCoinsRet.insert(vValue[i].second);
2369 nValueRet += vValue[i].first;
2374 if (nTotalLower < nTargetValue)
2376 if (coinLowestLarger.second.first == NULL)
2378 setCoinsRet.insert(coinLowestLarger.second);
2379 nValueRet += coinLowestLarger.first;
2383 // Solve subset sum by stochastic approximation
2384 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
2385 vector<char> vfBest;
2388 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
2389 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
2390 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
2392 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2393 // or the next bigger coin is closer), return the bigger coin
2394 if (coinLowestLarger.second.first &&
2395 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
2397 setCoinsRet.insert(coinLowestLarger.second);
2398 nValueRet += coinLowestLarger.first;
2401 for (unsigned int i = 0; i < vValue.size(); i++)
2404 setCoinsRet.insert(vValue[i].second);
2405 nValueRet += vValue[i].first;
2408 LogPrint("selectcoins", "SelectCoins() best subset: ");
2409 for (unsigned int i = 0; i < vValue.size(); i++)
2411 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2412 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
2418 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
2420 // Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
2421 vector<COutput> vCoinsNoCoinbase, vCoinsWithCoinbase;
2422 AvailableCoins(vCoinsNoCoinbase, true, coinControl, false, false);
2423 AvailableCoins(vCoinsWithCoinbase, true, coinControl, false, true);
2424 fOnlyCoinbaseCoinsRet = vCoinsNoCoinbase.size() == 0 && vCoinsWithCoinbase.size() > 0;
2426 // If coinbase utxos can only be sent to zaddrs, exclude any coinbase utxos from coin selection.
2427 bool fProtectCoinbase = Params().GetConsensus().fCoinbaseMustBeProtected;
2428 vector<COutput> vCoins = (fProtectCoinbase) ? vCoinsNoCoinbase : vCoinsWithCoinbase;
2430 // Output parameter fNeedCoinbaseCoinsRet is set to true if coinbase utxos need to be spent to meet target amount
2431 if (fProtectCoinbase && vCoinsWithCoinbase.size() > vCoinsNoCoinbase.size()) {
2433 for (const COutput& out : vCoinsNoCoinbase) {
2434 if (!out.fSpendable) {
2437 value += out.tx->vout[out.i].nValue;
2439 if (value <= nTargetValue) {
2440 CAmount valueWithCoinbase = 0;
2441 for (const COutput& out : vCoinsWithCoinbase) {
2442 if (!out.fSpendable) {
2445 valueWithCoinbase += out.tx->vout[out.i].nValue;
2447 fNeedCoinbaseCoinsRet = (valueWithCoinbase >= nTargetValue);
2451 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2452 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2454 BOOST_FOREACH(const COutput& out, vCoins)
2456 if (!out.fSpendable)
2458 nValueRet += out.tx->vout[out.i].nValue;
2459 setCoinsRet.insert(make_pair(out.tx, out.i));
2461 return (nValueRet >= nTargetValue);
2464 // calculate value from preset inputs and store them
2465 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2466 CAmount nValueFromPresetInputs = 0;
2468 std::vector<COutPoint> vPresetInputs;
2470 coinControl->ListSelected(vPresetInputs);
2471 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2473 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2474 if (it != mapWallet.end())
2476 const CWalletTx* pcoin = &it->second;
2477 // Clearly invalid input, fail
2478 if (pcoin->vout.size() <= outpoint.n)
2480 nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
2481 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2483 return false; // TODO: Allow non-wallet inputs
2486 // remove preset inputs from vCoins
2487 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2489 if (setPresetCoins.count(make_pair(it->tx, it->i)))
2490 it = vCoins.erase(it);
2495 bool res = nTargetValue <= nValueFromPresetInputs ||
2496 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2497 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2498 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
2500 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2501 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2503 // add preset inputs to the total value selected
2504 nValueRet += nValueFromPresetInputs;
2509 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason)
2511 vector<CRecipient> vecSend;
2513 // Turn the txout set into a CRecipient vector
2514 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2516 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2517 vecSend.push_back(recipient);
2520 CCoinControl coinControl;
2521 coinControl.fAllowOtherInputs = true;
2522 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2523 coinControl.Select(txin.prevout);
2525 CReserveKey reservekey(this);
2528 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
2531 if (nChangePosRet != -1)
2532 tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
2534 // Add new txins (keeping original txin scriptSig/order)
2535 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
2538 BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
2540 if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
2547 tx.vin.push_back(txin);
2553 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2554 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2557 unsigned int nSubtractFeeFromAmount = 0;
2558 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2560 if (nValue < 0 || recipient.nAmount < 0)
2562 strFailReason = _("Transaction amounts must be positive");
2565 nValue += recipient.nAmount;
2567 if (recipient.fSubtractFeeFromAmount)
2568 nSubtractFeeFromAmount++;
2570 if (vecSend.empty() || nValue < 0)
2572 strFailReason = _("Transaction amounts must be positive");
2576 wtxNew.fTimeReceivedIsTxTime = true;
2577 wtxNew.BindWallet(this);
2578 int nextBlockHeight = chainActive.Height() + 1;
2579 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(
2580 Params().GetConsensus(), nextBlockHeight);
2582 // Activates after Overwinter network upgrade
2583 // Set nExpiryHeight to expiryDelta (default 20) blocks past current block height
2584 if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
2585 if (nextBlockHeight + expiryDelta >= TX_EXPIRY_HEIGHT_THRESHOLD){
2586 strFailReason = _("nExpiryHeight must be less than TX_EXPIRY_HEIGHT_THRESHOLD.");
2589 txNew.nExpiryHeight = nextBlockHeight + expiryDelta;
2593 // Discourage fee sniping.
2595 // However because of a off-by-one-error in previous versions we need to
2596 // neuter it by setting nLockTime to at least one less than nBestHeight.
2597 // Secondly currently propagation of transactions created for block heights
2598 // corresponding to blocks that were just mined may be iffy - transactions
2599 // aren't re-accepted into the mempool - we additionally neuter the code by
2600 // going ten blocks back. Doesn't yet do anything for sniping, but does act
2601 // to shake out wallet bugs like not showing nLockTime'd transactions at
2603 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
2605 // Secondly occasionally randomly pick a nLockTime even further back, so
2606 // that transactions that are delayed after signing for whatever reason,
2607 // e.g. high-latency mix networks and some CoinJoin implementations, have
2609 if (GetRandInt(10) == 0)
2610 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2612 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2613 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2616 LOCK2(cs_main, cs_wallet);
2623 wtxNew.fFromMe = true;
2627 CAmount nTotalValue = nValue;
2628 if (nSubtractFeeFromAmount == 0)
2629 nTotalValue += nFeeRet;
2630 double dPriority = 0;
2631 // vouts to the payees
2632 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2634 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2636 if (recipient.fSubtractFeeFromAmount)
2638 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2640 if (fFirst) // first receiver pays the remainder not divisible by output count
2643 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2647 if (txout.IsDust(::minRelayTxFee))
2649 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2651 if (txout.nValue < 0)
2652 strFailReason = _("The transaction amount is too small to pay the fee");
2654 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2657 strFailReason = _("Transaction amount too small");
2660 txNew.vout.push_back(txout);
2663 // Choose coins to use
2664 set<pair<const CWalletTx*,unsigned int> > setCoins;
2665 CAmount nValueIn = 0;
2666 bool fOnlyCoinbaseCoins = false;
2667 bool fNeedCoinbaseCoins = false;
2668 if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl))
2670 if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) {
2671 strFailReason = _("Coinbase funds can only be sent to a zaddr");
2672 } else if (fNeedCoinbaseCoins) {
2673 strFailReason = _("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr");
2675 strFailReason = _("Insufficient funds");
2679 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2681 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2682 //The coin age after the next block (depth+1) is used instead of the current,
2683 //reflecting an assumption the user would accept a bit more delay for
2684 //a chance at a free transaction.
2685 //But mempool inputs might still be in the mempool, so their age stays 0
2686 int age = pcoin.first->GetDepthInMainChain();
2689 dPriority += (double)nCredit * age;
2692 CAmount nChange = nValueIn - nValue;
2693 if (nSubtractFeeFromAmount == 0)
2698 // Fill a vout to ourself
2699 // TODO: pass in scriptChange instead of reservekey so
2700 // change transaction isn't always pay-to-bitcoin-address
2701 CScript scriptChange;
2703 // coin control: send change to custom address
2704 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2705 scriptChange = GetScriptForDestination(coinControl->destChange);
2707 // no coin control: send change to newly generated address
2710 // Note: We use a new key here to keep it from being obvious which side is the change.
2711 // The drawback is that by not reusing a previous key, the change may be lost if a
2712 // backup is restored, if the backup doesn't have the new private key for the change.
2713 // If we reused the old key, it would be possible to add code to look for and
2714 // rediscover unknown transactions that were written with keys of ours to recover
2715 // post-backup change.
2717 // Reserve a new key pair from key pool
2720 ret = reservekey.GetReservedKey(vchPubKey);
2721 assert(ret); // should never fail, as we just unlocked
2723 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2726 CTxOut newTxOut(nChange, scriptChange);
2728 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2729 // This would be against the purpose of the all-inclusive feature.
2730 // So instead we raise the change and deduct from the recipient.
2731 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2733 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2734 newTxOut.nValue += nDust; // raise change until no more dust
2735 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2737 if (vecSend[i].fSubtractFeeFromAmount)
2739 txNew.vout[i].nValue -= nDust;
2740 if (txNew.vout[i].IsDust(::minRelayTxFee))
2742 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2750 // Never create dust outputs; if we would, just
2751 // add the dust to the fee.
2752 if (newTxOut.IsDust(::minRelayTxFee))
2755 reservekey.ReturnKey();
2759 // Insert change txn at random position:
2760 nChangePosRet = GetRandInt(txNew.vout.size()+1);
2761 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
2762 txNew.vout.insert(position, newTxOut);
2766 reservekey.ReturnKey();
2770 // Note how the sequence number is set to max()-1 so that the
2771 // nLockTime set above actually works.
2772 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2773 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2774 std::numeric_limits<unsigned int>::max()-1));
2776 // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
2777 size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
2780 if (NetworkUpgradeActive(chainActive.Height() + 1, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
2785 size_t n = txNew.vin.size();
2787 strFailReason = _(strprintf("Too many transparent inputs %zu > limit %zu", n, limit).c_str());
2792 // Grab the current consensus branch ID
2793 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
2797 CTransaction txNewConst(txNew);
2798 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2801 const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
2802 SignatureData sigdata;
2804 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata, consensusBranchId);
2806 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata, consensusBranchId);
2810 strFailReason = _("Signing transaction failed");
2813 UpdateTransaction(txNew, nIn, sigdata);
2819 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2821 // Remove scriptSigs if we used dummy signatures for fee calculation
2823 BOOST_FOREACH (CTxIn& vin, txNew.vin)
2824 vin.scriptSig = CScript();
2827 // Embed the constructed transaction data in wtxNew.
2828 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
2831 if (nBytes >= MAX_TX_SIZE)
2833 strFailReason = _("Transaction too large");
2837 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
2839 // Can we complete this as a free transaction?
2840 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2842 // Not enough fee: enough priority?
2843 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
2844 // Not enough mempool history to estimate: use hard-coded AllowFree.
2845 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
2848 // Small enough, and priority high enough, to send for free
2849 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
2853 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
2855 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2856 // because we must be at the maximum allowed fee.
2857 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2859 strFailReason = _("Transaction too large for fee policy");
2863 if (nFeeRet >= nFeeNeeded)
2864 break; // Done, enough fee included.
2866 // Include more fee and try again.
2867 nFeeRet = nFeeNeeded;
2877 * Call after CreateTransaction unless you want to abort
2879 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2882 LOCK2(cs_main, cs_wallet);
2883 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
2885 // This is only to keep the database open to defeat the auto-flush for the
2886 // duration of this scope. This is the only place where this optimization
2887 // maybe makes sense; please don't do it anywhere else.
2888 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
2890 // Take key pair from key pool so it won't be used again
2891 reservekey.KeepKey();
2893 // Add tx to wallet, because if it has change it's also ours,
2894 // otherwise just for transaction history.
2895 AddToWallet(wtxNew, false, pwalletdb);
2897 // Notify that old coins are spent
2898 set<CWalletTx*> setCoins;
2899 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2901 CWalletTx &coin = mapWallet[txin.prevout.hash];
2902 coin.BindWallet(this);
2903 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2910 // Track how many getdata requests our transaction gets
2911 mapRequestCount[wtxNew.GetHash()] = 0;
2913 if (fBroadcastTransactions)
2916 if (!wtxNew.AcceptToMemoryPool(false))
2918 // This must not fail. The transaction has already been signed and recorded.
2919 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
2922 wtxNew.RelayWalletTransaction();
2928 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2930 // payTxFee is user-set "I want to pay this much"
2931 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2932 // user selected total at least (default=true)
2933 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
2934 nFeeNeeded = payTxFee.GetFeePerK();
2935 // User didn't set: use -txconfirmtarget to estimate...
2936 if (nFeeNeeded == 0)
2937 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
2938 // ... unless we don't have enough mempool data, in which case fall
2939 // back to a hard-coded fee
2940 if (nFeeNeeded == 0)
2941 nFeeNeeded = minTxFee.GetFee(nTxBytes);
2942 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
2943 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
2944 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
2945 // But always obey the maximum
2946 if (nFeeNeeded > maxTxFee)
2947 nFeeNeeded = maxTxFee;
2954 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2958 fFirstRunRet = false;
2959 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2960 if (nLoadWalletRet == DB_NEED_REWRITE)
2962 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2966 // Note: can't top-up keypool here, because wallet is locked.
2967 // User will be prompted to unlock wallet the next operation
2968 // that requires a new key.
2972 if (nLoadWalletRet != DB_LOAD_OK)
2973 return nLoadWalletRet;
2974 fFirstRunRet = !vchDefaultKey.IsValid();
2976 uiInterface.LoadWallet(this);
2982 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2986 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2987 if (nZapWalletTxRet == DB_NEED_REWRITE)
2989 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2993 // Note: can't top-up keypool here, because wallet is locked.
2994 // User will be prompted to unlock wallet the next operation
2995 // that requires a new key.
2999 if (nZapWalletTxRet != DB_LOAD_OK)
3000 return nZapWalletTxRet;
3006 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
3008 bool fUpdated = false;
3010 LOCK(cs_wallet); // mapAddressBook
3011 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3012 fUpdated = mi != mapAddressBook.end();
3013 mapAddressBook[address].name = strName;
3014 if (!strPurpose.empty()) /* update purpose only if requested */
3015 mapAddressBook[address].purpose = strPurpose;
3017 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3018 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3021 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3023 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
3026 bool CWallet::DelAddressBook(const CTxDestination& address)
3029 LOCK(cs_wallet); // mapAddressBook
3033 // Delete destdata tuples associated with address
3034 std::string strAddress = CBitcoinAddress(address).ToString();
3035 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3037 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3040 mapAddressBook.erase(address);
3043 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3047 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
3048 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
3051 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3055 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3058 vchDefaultKey = vchPubKey;
3063 * Mark old keypool keys as used,
3064 * and generate all new keys
3066 bool CWallet::NewKeyPool()
3070 CWalletDB walletdb(strWalletFile);
3071 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3072 walletdb.ErasePool(nIndex);
3078 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
3079 for (int i = 0; i < nKeys; i++)
3081 int64_t nIndex = i+1;
3082 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
3083 setKeyPool.insert(nIndex);
3085 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
3090 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3098 CWalletDB walletdb(strWalletFile);
3101 unsigned int nTargetSize;
3103 nTargetSize = kpSize;
3105 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
3107 while (setKeyPool.size() < (nTargetSize + 1))
3110 if (!setKeyPool.empty())
3111 nEnd = *(--setKeyPool.end()) + 1;
3112 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
3113 throw runtime_error("TopUpKeyPool(): writing generated key failed");
3114 setKeyPool.insert(nEnd);
3115 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
3121 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
3124 keypool.vchPubKey = CPubKey();
3131 // Get the oldest key
3132 if(setKeyPool.empty())
3135 CWalletDB walletdb(strWalletFile);
3137 nIndex = *(setKeyPool.begin());
3138 setKeyPool.erase(setKeyPool.begin());
3139 if (!walletdb.ReadPool(nIndex, keypool))
3140 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
3141 if (!HaveKey(keypool.vchPubKey.GetID()))
3142 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
3143 assert(keypool.vchPubKey.IsValid());
3144 LogPrintf("keypool reserve %d\n", nIndex);
3148 void CWallet::KeepKey(int64_t nIndex)
3150 // Remove from key pool
3153 CWalletDB walletdb(strWalletFile);
3154 walletdb.ErasePool(nIndex);
3156 LogPrintf("keypool keep %d\n", nIndex);
3159 void CWallet::ReturnKey(int64_t nIndex)
3161 // Return to key pool
3164 setKeyPool.insert(nIndex);
3166 LogPrintf("keypool return %d\n", nIndex);
3169 bool CWallet::GetKeyFromPool(CPubKey& result)
3175 ReserveKeyFromKeyPool(nIndex, keypool);
3178 if (IsLocked()) return false;
3179 result = GenerateNewKey();
3183 result = keypool.vchPubKey;
3188 int64_t CWallet::GetOldestKeyPoolTime()
3192 ReserveKeyFromKeyPool(nIndex, keypool);
3196 return keypool.nTime;
3199 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3201 map<CTxDestination, CAmount> balances;
3205 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3207 CWalletTx *pcoin = &walletEntry.second;
3209 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
3212 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3215 int nDepth = pcoin->GetDepthInMainChain();
3216 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3219 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3221 CTxDestination addr;
3222 if (!IsMine(pcoin->vout[i]))
3224 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3227 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
3229 if (!balances.count(addr))
3231 balances[addr] += n;
3239 set< set<CTxDestination> > CWallet::GetAddressGroupings()
3241 AssertLockHeld(cs_wallet); // mapWallet
3242 set< set<CTxDestination> > groupings;
3243 set<CTxDestination> grouping;
3245 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3247 CWalletTx *pcoin = &walletEntry.second;
3249 if (pcoin->vin.size() > 0)
3251 bool any_mine = false;
3252 // group all input addresses with each other
3253 BOOST_FOREACH(CTxIn txin, pcoin->vin)
3255 CTxDestination address;
3256 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3258 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
3260 grouping.insert(address);
3264 // group change with input addresses
3267 BOOST_FOREACH(CTxOut txout, pcoin->vout)
3268 if (IsChange(txout))
3270 CTxDestination txoutAddr;
3271 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3273 grouping.insert(txoutAddr);
3276 if (grouping.size() > 0)
3278 groupings.insert(grouping);
3283 // group lone addrs by themselves
3284 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3285 if (IsMine(pcoin->vout[i]))
3287 CTxDestination address;
3288 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
3290 grouping.insert(address);
3291 groupings.insert(grouping);
3296 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3297 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3298 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
3300 // make a set of all the groups hit by this new group
3301 set< set<CTxDestination>* > hits;
3302 map< CTxDestination, set<CTxDestination>* >::iterator it;
3303 BOOST_FOREACH(CTxDestination address, grouping)
3304 if ((it = setmap.find(address)) != setmap.end())
3305 hits.insert((*it).second);
3307 // merge all hit groups into a new single group and delete old groups
3308 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
3309 BOOST_FOREACH(set<CTxDestination>* hit, hits)
3311 merged->insert(hit->begin(), hit->end());
3312 uniqueGroupings.erase(hit);
3315 uniqueGroupings.insert(merged);
3318 BOOST_FOREACH(CTxDestination element, *merged)
3319 setmap[element] = merged;
3322 set< set<CTxDestination> > ret;
3323 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3325 ret.insert(*uniqueGrouping);
3326 delete uniqueGrouping;
3332 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3335 set<CTxDestination> result;
3336 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3338 const CTxDestination& address = item.first;
3339 const string& strName = item.second.name;
3340 if (strName == strAccount)
3341 result.insert(address);
3346 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
3351 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3353 vchPubKey = keypool.vchPubKey;
3358 assert(vchPubKey.IsValid());
3363 void CReserveKey::KeepKey()
3366 pwallet->KeepKey(nIndex);
3368 vchPubKey = CPubKey();
3371 void CReserveKey::ReturnKey()
3374 pwallet->ReturnKey(nIndex);
3376 vchPubKey = CPubKey();
3379 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3383 CWalletDB walletdb(strWalletFile);
3385 LOCK2(cs_main, cs_wallet);
3386 BOOST_FOREACH(const int64_t& id, setKeyPool)
3389 if (!walletdb.ReadPool(id, keypool))
3390 throw runtime_error("GetAllReserveKeyHashes(): read failed");
3391 assert(keypool.vchPubKey.IsValid());
3392 CKeyID keyID = keypool.vchPubKey.GetID();
3393 if (!HaveKey(keyID))
3394 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
3395 setAddress.insert(keyID);
3399 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3403 // Only notify UI if this transaction is in this wallet
3404 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3405 if (mi != mapWallet.end())
3406 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3410 void CWallet::LockCoin(COutPoint& output)
3412 AssertLockHeld(cs_wallet); // setLockedCoins
3413 setLockedCoins.insert(output);
3416 void CWallet::UnlockCoin(COutPoint& output)
3418 AssertLockHeld(cs_wallet); // setLockedCoins
3419 setLockedCoins.erase(output);
3422 void CWallet::UnlockAllCoins()
3424 AssertLockHeld(cs_wallet); // setLockedCoins
3425 setLockedCoins.clear();
3428 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3430 AssertLockHeld(cs_wallet); // setLockedCoins
3431 COutPoint outpt(hash, n);
3433 return (setLockedCoins.count(outpt) > 0);
3436 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3438 AssertLockHeld(cs_wallet); // setLockedCoins
3439 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3440 it != setLockedCoins.end(); it++) {
3441 COutPoint outpt = (*it);
3442 vOutpts.push_back(outpt);
3446 /** @} */ // end of Actions
3448 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3450 const CKeyStore &keystore;
3451 std::vector<CKeyID> &vKeys;
3454 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3456 void Process(const CScript &script) {
3458 std::vector<CTxDestination> vDest;
3460 if (ExtractDestinations(script, type, vDest, nRequired)) {
3461 BOOST_FOREACH(const CTxDestination &dest, vDest)
3462 boost::apply_visitor(*this, dest);
3466 void operator()(const CKeyID &keyId) {
3467 if (keystore.HaveKey(keyId))
3468 vKeys.push_back(keyId);
3471 void operator()(const CScriptID &scriptId) {
3473 if (keystore.GetCScript(scriptId, script))
3477 void operator()(const CNoDestination &none) {}
3480 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
3481 AssertLockHeld(cs_wallet); // mapKeyMetadata
3482 mapKeyBirth.clear();
3484 // get birth times for keys with metadata
3485 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3486 if (it->second.nCreateTime)
3487 mapKeyBirth[it->first] = it->second.nCreateTime;
3489 // map in which we'll infer heights of other keys
3490 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
3491 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3492 std::set<CKeyID> setKeys;
3494 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3495 if (mapKeyBirth.count(keyid) == 0)
3496 mapKeyFirstBlock[keyid] = pindexMax;
3500 // if there are no such keys, we're done
3501 if (mapKeyFirstBlock.empty())
3504 // find first block that affects those keys, if there are any left
3505 std::vector<CKeyID> vAffected;
3506 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3507 // iterate over all wallet transactions...
3508 const CWalletTx &wtx = (*it).second;
3509 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3510 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3511 // ... which are already in a block
3512 int nHeight = blit->second->nHeight;
3513 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
3514 // iterate over all their outputs
3515 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3516 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3517 // ... and all their affected keys
3518 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3519 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3520 rit->second = blit->second;
3527 // Extract block timestamps for those keys
3528 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3529 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
3532 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3534 if (boost::get<CNoDestination>(&dest))
3537 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3540 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3543 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3545 if (!mapAddressBook[dest].destdata.erase(key))
3549 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3552 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3554 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3558 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3560 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3561 if(i != mapAddressBook.end())
3563 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3564 if(j != i->second.destdata.end())
3574 CKeyPool::CKeyPool()
3579 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3582 vchPubKey = vchPubKeyIn;
3585 CWalletKey::CWalletKey(int64_t nExpires)
3587 nTimeCreated = (nExpires ? GetTime() : 0);
3588 nTimeExpires = nExpires;
3591 int CMerkleTx::SetMerkleBranch(const CBlock& block)
3593 AssertLockHeld(cs_main);
3596 // Update the tx's hashBlock
3597 hashBlock = block.GetHash();
3599 // Locate the transaction
3600 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
3601 if (block.vtx[nIndex] == *(CTransaction*)this)
3603 if (nIndex == (int)block.vtx.size())
3605 vMerkleBranch.clear();
3607 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
3611 // Fill in merkle branch
3612 vMerkleBranch = block.GetMerkleBranch(nIndex);
3614 // Is the tx in a block that's in the main chain
3615 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3616 if (mi == mapBlockIndex.end())
3618 const CBlockIndex* pindex = (*mi).second;
3619 if (!pindex || !chainActive.Contains(pindex))
3622 return chainActive.Height() - pindex->nHeight + 1;
3625 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
3627 if (hashBlock.IsNull() || nIndex == -1)
3629 AssertLockHeld(cs_main);
3631 // Find the block it claims to be in
3632 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3633 if (mi == mapBlockIndex.end())
3635 CBlockIndex* pindex = (*mi).second;
3636 if (!pindex || !chainActive.Contains(pindex))
3639 // Make sure the merkle branch connects to this block
3640 if (!fMerkleVerified)
3642 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
3644 fMerkleVerified = true;
3648 return chainActive.Height() - pindex->nHeight + 1;
3651 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3653 AssertLockHeld(cs_main);
3654 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
3655 if (nResult == 0 && !mempool.exists(GetHash()))
3656 return -1; // Not in chain, not in mempool
3661 int CMerkleTx::GetBlocksToMaturity() const
3665 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3669 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
3671 CValidationState state;
3672 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
3676 * Find notes in the wallet filtered by payment address, min depth and ability to spend.
3677 * These notes are decrypted and added to the output parameter vector, outEntries.
3679 void CWallet::GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries, std::string address, int minDepth, bool ignoreSpent, bool ignoreUnspendable)
3681 std::set<PaymentAddress> filterAddresses;
3683 if (address.length() > 0) {
3684 filterAddresses.insert(CZCPaymentAddress(address).Get());
3687 GetFilteredNotes(outEntries, filterAddresses, minDepth, ignoreSpent, ignoreUnspendable);
3691 * Find notes in the wallet filtered by payment addresses, min depth and ability to spend.
3692 * These notes are decrypted and added to the output parameter vector, outEntries.
3694 void CWallet::GetFilteredNotes(
3695 std::vector<CNotePlaintextEntry>& outEntries,
3696 std::set<PaymentAddress>& filterAddresses,
3699 bool ignoreUnspendable)
3701 LOCK2(cs_main, cs_wallet);
3703 for (auto & p : mapWallet) {
3704 CWalletTx wtx = p.second;
3706 // Filter the transactions before checking for notes
3707 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth) {
3711 if (wtx.mapNoteData.size() == 0) {
3715 for (auto & pair : wtx.mapNoteData) {
3716 JSOutPoint jsop = pair.first;
3717 CNoteData nd = pair.second;
3718 PaymentAddress pa = nd.address;
3720 // skip notes which belong to a different payment address in the wallet
3721 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
3725 // skip note which has been spent
3726 if (ignoreSpent && nd.nullifier && IsSpent(*nd.nullifier)) {
3730 // skip notes which cannot be spent
3731 if (ignoreUnspendable && !HaveSpendingKey(pa)) {
3735 int i = jsop.js; // Index into CTransaction.vjoinsplit
3736 int j = jsop.n; // Index into JSDescription.ciphertexts
3738 // Get cached decryptor
3739 ZCNoteDecryption decryptor;
3740 if (!GetNoteDecryptor(pa, decryptor)) {
3741 // Note decryptors are created when the wallet is loaded, so it should always exist
3742 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", CZCPaymentAddress(pa).ToString()));
3745 // determine amount of funds in the note
3746 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3748 NotePlaintext plaintext = NotePlaintext::decrypt(
3750 wtx.vjoinsplit[i].ciphertexts[j],
3751 wtx.vjoinsplit[i].ephemeralKey,
3755 outEntries.push_back(CNotePlaintextEntry{jsop, pa, plaintext});
3757 } catch (const note_decryption_failed &err) {
3758 // Couldn't decrypt with this spending key
3759 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", CZCPaymentAddress(pa).ToString()));
3760 } catch (const std::exception &exc) {
3761 // Unexpected failure
3762 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", CZCPaymentAddress(pa).ToString(), exc.what()));
3769 /* Find unspent notes filtered by payment address, min depth and max depth */
3770 void CWallet::GetUnspentFilteredNotes(
3771 std::vector<CUnspentNotePlaintextEntry>& outEntries,
3772 std::set<PaymentAddress>& filterAddresses,
3775 bool requireSpendingKey)
3777 LOCK2(cs_main, cs_wallet);
3779 for (auto & p : mapWallet) {
3780 CWalletTx wtx = p.second;
3782 // Filter the transactions before checking for notes
3783 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth || wtx.GetDepthInMainChain() > maxDepth) {
3787 if (wtx.mapNoteData.size() == 0) {
3791 for (auto & pair : wtx.mapNoteData) {
3792 JSOutPoint jsop = pair.first;
3793 CNoteData nd = pair.second;
3794 PaymentAddress pa = nd.address;
3796 // skip notes which belong to a different payment address in the wallet
3797 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
3801 // skip note which has been spent
3802 if (nd.nullifier && IsSpent(*nd.nullifier)) {
3806 // skip notes where the spending key is not available
3807 if (requireSpendingKey && !HaveSpendingKey(pa)) {
3811 int i = jsop.js; // Index into CTransaction.vjoinsplit
3812 int j = jsop.n; // Index into JSDescription.ciphertexts
3814 // Get cached decryptor
3815 ZCNoteDecryption decryptor;
3816 if (!GetNoteDecryptor(pa, decryptor)) {
3817 // Note decryptors are created when the wallet is loaded, so it should always exist
3818 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", CZCPaymentAddress(pa).ToString()));
3821 // determine amount of funds in the note
3822 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3824 NotePlaintext plaintext = NotePlaintext::decrypt(
3826 wtx.vjoinsplit[i].ciphertexts[j],
3827 wtx.vjoinsplit[i].ephemeralKey,
3831 outEntries.push_back(CUnspentNotePlaintextEntry{jsop, pa, plaintext, wtx.GetDepthInMainChain()});
3833 } catch (const note_decryption_failed &err) {
3834 // Couldn't decrypt with this spending key
3835 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", CZCPaymentAddress(pa).ToString()));
3836 } catch (const std::exception &exc) {
3837 // Unexpected failure
3838 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", CZCPaymentAddress(pa).ToString(), exc.what()));