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 https://www.opensource.org/licenses/mit-license.php .
8 #include "clientversion.h"
9 #include "consensus/consensus.h"
10 #include "consensus/validation.h"
12 #include "policy/fees.h"
16 #include "utilmoneystr.h"
17 #include "validationinterface.h"
19 #include "pbaas/pbaas.h"
20 #define _COINBASE_MATURITY 100
24 CTxMemPoolEntry::CTxMemPoolEntry():
25 nFee(0), nTxSize(0), nModSize(0), nUsageSize(0), nTime(0), dPriority(0.0),
26 hadNoDependencies(false), spendsCoinbase(false), hasReserve(false)
28 nHeight = MEMPOOL_HEIGHT;
31 CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
32 int64_t _nTime, double _dPriority,
33 unsigned int _nHeight, bool poolHasNoInputsOf,
34 bool _spendsCoinbase, uint32_t _nBranchId, bool hasreserve):
35 tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight),
36 hadNoDependencies(poolHasNoInputsOf), hasReserve(hasreserve),
37 spendsCoinbase(_spendsCoinbase), nBranchId(_nBranchId)
39 nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
40 nModSize = tx.CalculateModifiedSize(nTxSize);
41 nUsageSize = RecursiveDynamicUsage(tx);
42 feeRate = CFeeRate(nFee, nTxSize);
45 CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
51 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
53 CAmount nValueIn = tx.GetValueOut()+nFee;
54 CCurrencyState currencyState;
55 unsigned int lastHeight = currentHeight < 1 ? 0 : currentHeight - 1;
56 if (hasReserve && (currencyState = ConnectedChains.GetCurrencyState(currentHeight - 1)).IsValid())
58 nValueIn += currencyState.ReserveToNative(tx.GetReserveValueOut());
60 double deltaPriority = ((double)(currentHeight-nHeight)*nValueIn)/nModSize;
61 double dResult = dPriority + deltaPriority;
65 CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) :
66 nTransactionsUpdated(0)
68 // Sanity checks off by default for performance, because otherwise
69 // accepting transactions becomes O(N^2) where N is the number
70 // of transactions in the pool
73 minerPolicyEstimator = new CBlockPolicyEstimator(_minRelayFee);
76 CTxMemPool::~CTxMemPool()
78 delete minerPolicyEstimator;
81 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
85 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
87 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
88 while (it != mapNextTx.end() && it->first.hash == hashTx) {
89 coins.Spend(it->first.n); // and remove those outputs from coins
94 unsigned int CTxMemPool::GetTransactionsUpdated() const
97 return nTransactionsUpdated;
100 void CTxMemPool::AddTransactionsUpdated(unsigned int n)
103 nTransactionsUpdated += n;
107 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
109 // Add to memory pool without checking anything.
110 // Used by main.cpp AcceptToMemoryPool(), which DOES do
111 // all the appropriate checks.
114 const CTransaction& tx = mapTx.find(hash)->GetTx();
115 mapRecentlyAddedTx[tx.GetHash()] = &tx;
116 nRecentlyAddedSequence += 1;
117 if (!tx.IsCoinImport()) {
118 for (unsigned int i = 0; i < tx.vin.size(); i++)
119 mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
121 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
122 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
123 mapSproutNullifiers[nf] = &tx;
126 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
127 mapSaplingNullifiers[spendDescription.nullifier] = &tx;
129 nTransactionsUpdated++;
130 totalTxSize += entry.GetTxSize();
131 cachedInnerUsage += entry.DynamicMemoryUsage();
132 minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
137 void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
140 const CTransaction& tx = entry.GetTx();
141 std::vector<CMempoolAddressDeltaKey> inserted;
143 uint256 txhash = tx.GetHash();
144 if (!tx.IsCoinBase())
146 for (unsigned int j = 0; j < tx.vin.size(); j++) {
147 const CTxIn input = tx.vin[j];
148 const CTxOut &prevout = view.GetOutputFor(input);
149 CScript::ScriptType type = prevout.scriptPubKey.GetType();
150 if (type == CScript::UNKNOWN)
153 if (type == CScript::P2CC)
155 std::vector<CTxDestination> dests = prevout.scriptPubKey.GetDestinations();
156 for (auto dest : dests)
158 if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
160 CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 1);
161 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
162 mapAddress.insert(make_pair(key, delta));
163 inserted.push_back(key);
169 CMempoolAddressDeltaKey key(type, prevout.scriptPubKey.AddressHash(), txhash, j, 1);
170 CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
171 mapAddress.insert(make_pair(key, delta));
172 inserted.push_back(key);
177 for (unsigned int j = 0; j < tx.vout.size(); j++) {
178 const CTxOut &out = tx.vout[j];
179 CScript::ScriptType type = out.scriptPubKey.GetType();
180 if (type == CScript::UNKNOWN)
184 if (type == CScript::P2CC)
186 std::vector<CTxDestination> dests = out.scriptPubKey.GetDestinations();
187 for (auto dest : dests)
189 if (dest.which() != COptCCParams::ADDRTYPE_INVALID)
191 CMempoolAddressDeltaKey key(AddressTypeFromDest(dest), GetDestinationID(dest), txhash, j, 0);
192 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
193 inserted.push_back(key);
199 CMempoolAddressDeltaKey key(type, out.scriptPubKey.AddressHash(), txhash, j, 0);
200 mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
201 inserted.push_back(key);
205 mapAddressInserted.insert(make_pair(txhash, inserted));
208 bool CTxMemPool::getAddressIndex(const std::vector<std::pair<uint160, int> > &addresses, std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
211 for (std::vector<std::pair<uint160, int> >::const_iterator it = addresses.begin(); it != addresses.end(); it++) {
212 auto ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
213 while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
214 results.push_back(*ait);
221 bool CTxMemPool::removeAddressIndex(const uint256 txhash)
224 auto it = mapAddressInserted.find(txhash);
226 if (it != mapAddressInserted.end()) {
227 std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
228 for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
229 mapAddress.erase(*mit);
231 mapAddressInserted.erase(it);
237 void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
240 const CTransaction& tx = entry.GetTx();
241 uint256 txhash = tx.GetHash();
242 std::vector<CSpentIndexKey> inserted;
244 for (unsigned int j = 0; j < tx.vin.size(); j++) {
245 const CTxIn input = tx.vin[j];
246 const CTxOut &prevout = view.GetOutputFor(input);
247 CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
248 CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue,
249 prevout.scriptPubKey.GetType(),
250 prevout.scriptPubKey.AddressHash());
251 mapSpent.insert(make_pair(key, value));
252 inserted.push_back(key);
254 mapSpentInserted.insert(make_pair(txhash, inserted));
257 bool CTxMemPool::getSpentIndex(const CSpentIndexKey &key, CSpentIndexValue &value)
260 std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare>::iterator it = mapSpent.find(key);
261 if (it != mapSpent.end()) {
268 bool CTxMemPool::removeSpentIndex(const uint256 txhash)
271 auto it = mapSpentInserted.find(txhash);
273 if (it != mapSpentInserted.end()) {
274 std::vector<CSpentIndexKey> keys = (*it).second;
275 for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
276 mapSpent.erase(*mit);
278 mapSpentInserted.erase(it);
284 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
286 // Remove transaction from memory pool
289 std::deque<uint256> txToRemove;
290 txToRemove.push_back(origTx.GetHash());
291 if (fRecursive && !mapTx.count(origTx.GetHash())) {
292 // If recursively removing but origTx isn't in the mempool
293 // be sure to remove any children that are in the pool. This can
294 // happen during chain re-orgs if origTx isn't re-accepted into
295 // the mempool for any reason.
296 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
297 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
298 if (it == mapNextTx.end())
300 txToRemove.push_back(it->second.ptx->GetHash());
303 while (!txToRemove.empty())
305 uint256 hash = txToRemove.front();
306 txToRemove.pop_front();
307 if (!mapTx.count(hash))
309 const CTransaction& tx = mapTx.find(hash)->GetTx();
311 for (unsigned int i = 0; i < tx.vout.size(); i++) {
312 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
313 if (it == mapNextTx.end())
315 txToRemove.push_back(it->second.ptx->GetHash());
318 mapRecentlyAddedTx.erase(hash);
319 BOOST_FOREACH(const CTxIn& txin, tx.vin)
320 mapNextTx.erase(txin.prevout);
321 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
322 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers) {
323 mapSproutNullifiers.erase(nf);
326 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
327 mapSaplingNullifiers.erase(spendDescription.nullifier);
329 removed.push_back(tx);
330 totalTxSize -= mapTx.find(hash)->GetTxSize();
331 cachedInnerUsage -= mapTx.find(hash)->DynamicMemoryUsage();
333 nTransactionsUpdated++;
334 minerPolicyEstimator->removeTx(hash);
336 removeAddressIndex(hash);
338 removeSpentIndex(hash);
339 ClearPrioritisation(tx.GetHash());
344 extern uint64_t ASSETCHAINS_TIMELOCKGTE;
345 int64_t komodo_block_unlocktime(uint32_t nHeight);
347 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
349 // Remove transactions spending a coinbase which are now immature
350 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
352 if ( ASSETCHAINS_SYMBOL[0] == 0 )
353 COINBASE_MATURITY = _COINBASE_MATURITY;
355 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
357 list<CTransaction> transactionsToRemove;
358 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
359 const CTransaction& tx = it->GetTx();
360 if (!CheckFinalTx(tx, flags)) {
361 transactionsToRemove.push_back(tx);
362 } else if (it->GetSpendsCoinbase()) {
363 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
364 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
365 if (it2 != mapTx.end())
367 const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
368 if (nCheckFrequency != 0) assert(coins);
370 if (!coins || (coins->IsCoinBase() &&
371 (((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY) ||
372 ((signed long)nMemPoolHeight < komodo_block_unlocktime(coins->nHeight) &&
373 coins->IsAvailable(0) && coins->vout[0].nValue >= ASSETCHAINS_TIMELOCKGTE))) {
374 transactionsToRemove.push_back(tx);
380 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
381 list<CTransaction> removed;
382 remove(tx, removed, true);
387 void CTxMemPool::removeWithAnchor(const uint256 &invalidRoot, ShieldedType type)
389 // If a block is disconnected from the tip, and the root changed,
390 // we must invalidate transactions from the mempool which spend
391 // from that root -- almost as though they were spending coinbases
392 // which are no longer valid to spend due to coinbase maturity.
394 list<CTransaction> transactionsToRemove;
396 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
397 const CTransaction& tx = it->GetTx();
400 BOOST_FOREACH(const JSDescription& joinsplit, tx.vJoinSplit) {
401 if (joinsplit.anchor == invalidRoot) {
402 transactionsToRemove.push_back(tx);
408 BOOST_FOREACH(const SpendDescription& spendDescription, tx.vShieldedSpend) {
409 if (spendDescription.anchor == invalidRoot) {
410 transactionsToRemove.push_back(tx);
416 throw runtime_error("Unknown shielded type");
421 BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
422 list<CTransaction> removed;
423 remove(tx, removed, true);
427 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
429 // Remove transactions which depend on inputs of tx, recursively
430 list<CTransaction> result;
432 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
433 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
434 if (it != mapNextTx.end()) {
435 const CTransaction &txConflict = *it->second.ptx;
436 if (txConflict != tx)
438 remove(txConflict, removed, true);
443 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
444 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
445 std::map<uint256, const CTransaction*>::iterator it = mapSproutNullifiers.find(nf);
446 if (it != mapSproutNullifiers.end()) {
447 const CTransaction &txConflict = *it->second;
448 if (txConflict != tx) {
449 remove(txConflict, removed, true);
454 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
455 std::map<uint256, const CTransaction*>::iterator it = mapSaplingNullifiers.find(spendDescription.nullifier);
456 if (it != mapSaplingNullifiers.end()) {
457 const CTransaction &txConflict = *it->second;
458 if (txConflict != tx) {
459 remove(txConflict, removed, true);
465 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
466 extern char ASSETCHAINS_SYMBOL[];
468 void CTxMemPool::removeExpired(unsigned int nBlockHeight)
470 CBlockIndex *tipindex;
471 // Remove expired txs from the mempool
473 list<CTransaction> transactionsToRemove;
474 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
476 const CTransaction& tx = it->GetTx();
477 tipindex = chainActive.LastTip();
478 if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->GetHeight()+1,tipindex->GetMedianTimePast() + 777,0)) < 0)
480 transactionsToRemove.push_back(tx);
483 for (const CTransaction& tx : transactionsToRemove) {
484 list<CTransaction> removed;
485 remove(tx, removed, true);
486 LogPrint("mempool", "Removing expired txid: %s\n", tx.GetHash().ToString());
491 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
493 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
494 std::list<CTransaction>& conflicts, bool fCurrentEstimate)
497 std::vector<CTxMemPoolEntry> entries;
498 BOOST_FOREACH(const CTransaction& tx, vtx)
500 uint256 hash = tx.GetHash();
502 indexed_transaction_set::iterator i = mapTx.find(hash);
503 if (i != mapTx.end())
504 entries.push_back(*i);
506 BOOST_FOREACH(const CTransaction& tx, vtx)
508 std::list<CTransaction> dummy;
509 remove(tx, dummy, false);
510 removeConflicts(tx, conflicts);
511 ClearPrioritisation(tx.GetHash());
513 // After the txs in the new block have been removed from the mempool, update policy estimates
514 minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
518 * Called whenever the tip changes. Removes transactions which don't commit to
519 * the given branch ID from the mempool.
521 void CTxMemPool::removeWithoutBranchId(uint32_t nMemPoolBranchId)
524 std::list<CTransaction> transactionsToRemove;
526 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
527 const CTransaction& tx = it->GetTx();
528 if (it->GetValidatedBranchId() != nMemPoolBranchId) {
529 transactionsToRemove.push_back(tx);
533 for (const CTransaction& tx : transactionsToRemove) {
534 std::list<CTransaction> removed;
535 remove(tx, removed, true);
539 void CTxMemPool::clear()
545 cachedInnerUsage = 0;
546 ++nTransactionsUpdated;
549 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
551 if (nCheckFrequency == 0)
554 if (insecure_rand() >= nCheckFrequency)
557 LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
559 uint64_t checkTotal = 0;
560 uint64_t innerUsage = 0;
562 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
563 const int64_t nSpendHeight = GetSpendHeight(mempoolDuplicate);
566 list<const CTxMemPoolEntry*> waitingOnDependants;
567 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
569 checkTotal += it->GetTxSize();
570 innerUsage += it->DynamicMemoryUsage();
571 const CTransaction& tx = it->GetTx();
572 bool fDependsWait = false;
573 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
574 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
575 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
576 if (it2 != mapTx.end()) {
577 const CTransaction& tx2 = it2->GetTx();
578 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
581 const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
582 assert(coins && coins->IsAvailable(txin.prevout.n));
584 // Check whether its inputs are marked in mapNextTx.
585 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
586 assert(it3 != mapNextTx.end());
587 assert(it3->second.ptx == &tx);
588 assert(it3->second.n == i);
592 boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
594 BOOST_FOREACH(const JSDescription &joinsplit, tx.vJoinSplit) {
595 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
596 assert(!pcoins->GetNullifier(nf, SPROUT));
599 SproutMerkleTree tree;
600 auto it = intermediates.find(joinsplit.anchor);
601 if (it != intermediates.end()) {
604 assert(pcoins->GetSproutAnchorAt(joinsplit.anchor, tree));
607 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
609 tree.append(commitment);
612 intermediates.insert(std::make_pair(tree.root(), tree));
614 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
615 SaplingMerkleTree tree;
617 assert(pcoins->GetSaplingAnchorAt(spendDescription.anchor, tree));
618 assert(!pcoins->GetNullifier(spendDescription.nullifier, SAPLING));
621 waitingOnDependants.push_back(&(*it));
623 CValidationState state;
624 bool fCheckResult = tx.IsCoinBase() ||
625 Consensus::CheckTxInputs(tx, state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
626 assert(fCheckResult);
627 UpdateCoins(tx, mempoolDuplicate, 1000000);
630 unsigned int stepsSinceLastRemove = 0;
631 while (!waitingOnDependants.empty()) {
632 const CTxMemPoolEntry* entry = waitingOnDependants.front();
633 waitingOnDependants.pop_front();
634 CValidationState state;
635 if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
636 waitingOnDependants.push_back(entry);
637 stepsSinceLastRemove++;
638 assert(stepsSinceLastRemove < waitingOnDependants.size());
640 bool fCheckResult = entry->GetTx().IsCoinBase() ||
641 Consensus::CheckTxInputs(entry->GetTx(), state, mempoolDuplicate, nSpendHeight, Params().GetConsensus());
642 assert(fCheckResult);
643 UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
644 stepsSinceLastRemove = 0;
647 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
648 uint256 hash = it->second.ptx->GetHash();
649 indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
650 const CTransaction& tx = it2->GetTx();
651 assert(it2 != mapTx.end());
652 assert(&tx == it->second.ptx);
653 assert(tx.vin.size() > it->second.n);
654 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
657 checkNullifiers(SPROUT);
658 checkNullifiers(SAPLING);
660 assert(totalTxSize == checkTotal);
661 assert(innerUsage == cachedInnerUsage);
664 void CTxMemPool::checkNullifiers(ShieldedType type) const
666 const std::map<uint256, const CTransaction*>* mapToUse;
669 mapToUse = &mapSproutNullifiers;
672 mapToUse = &mapSaplingNullifiers;
675 throw runtime_error("Unknown nullifier type");
677 for (const auto& entry : *mapToUse) {
678 uint256 hash = entry.second->GetHash();
679 CTxMemPool::indexed_transaction_set::const_iterator findTx = mapTx.find(hash);
680 const CTransaction& tx = findTx->GetTx();
681 assert(findTx != mapTx.end());
682 assert(&tx == entry.second);
686 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
691 vtxid.reserve(mapTx.size());
692 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
693 vtxid.push_back(mi->GetTx().GetHash());
696 bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
699 indexed_transaction_set::const_iterator i = mapTx.find(hash);
700 if (i == mapTx.end()) return false;
705 CFeeRate CTxMemPool::estimateFee(int nBlocks) const
708 return minerPolicyEstimator->estimateFee(nBlocks);
710 double CTxMemPool::estimatePriority(int nBlocks) const
713 return minerPolicyEstimator->estimatePriority(nBlocks);
717 CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
721 fileout << 109900; // version required to read: 0.10.99 or later
722 fileout << CLIENT_VERSION; // version that wrote the file
723 minerPolicyEstimator->Write(fileout);
725 catch (const std::exception&) {
726 LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
733 CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
736 int nVersionRequired, nVersionThatWrote;
737 filein >> nVersionRequired >> nVersionThatWrote;
738 if (nVersionRequired > CLIENT_VERSION)
739 return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
742 minerPolicyEstimator->Read(filein);
744 catch (const std::exception&) {
745 LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
751 void CTxMemPool::PrioritiseTransaction(const uint256 &hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
755 std::pair<double, CAmount> &deltas = mapDeltas[hash];
756 deltas.first += dPriorityDelta;
757 deltas.second += nFeeDelta;
759 LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
762 void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
765 std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
766 if (pos == mapDeltas.end())
768 const std::pair<double, CAmount> &deltas = pos->second;
769 dPriorityDelta += deltas.first;
770 nFeeDelta += deltas.second;
773 void CTxMemPool::ClearPrioritisation(const uint256 hash)
776 mapDeltas.erase(hash);
777 mapReserveTransactions.erase(hash);
780 bool CTxMemPool::PrioritiseReserveTransaction(const CReserveTransactionDescriptor &txDesc, const CCurrencyState ¤cyState)
783 uint256 hash = txDesc.ptx->GetHash();
784 auto it = mapReserveTransactions.find(hash);
785 if (txDesc.IsValid())
787 mapReserveTransactions[hash] = txDesc;
788 CAmount feeDelta = currencyState.ReserveToNative(txDesc.ReserveFees() + txDesc.reserveConversionFees) + txDesc.nativeConversionFees;
789 PrioritiseTransaction(hash, hash.GetHex().c_str(), (double)feeDelta * 100.0, feeDelta);
795 bool CTxMemPool::IsKnownReserveTransaction(const uint256 &hash, CReserveTransactionDescriptor &txDesc)
798 auto it = mapReserveTransactions.find(hash);
799 if (it != mapReserveTransactions.end() && it->second.IsValid())
801 // refresh transaction from mempool or delete it if not found (we may not need this at all)
802 indexed_transaction_set::const_iterator i = mapTx.find(hash);
803 if (i == mapTx.end())
805 ClearPrioritisation(hash);
809 it->second.ptx = &(i->GetTx());
818 bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
820 for (unsigned int i = 0; i < tx.vin.size(); i++)
821 if (exists(tx.vin[i].prevout.hash))
826 bool CTxMemPool::nullifierExists(const uint256& nullifier, ShieldedType type) const
830 return mapSproutNullifiers.count(nullifier);
832 return mapSaplingNullifiers.count(nullifier);
834 throw runtime_error("Unknown nullifier type");
838 void CTxMemPool::NotifyRecentlyAdded()
840 uint64_t recentlyAddedSequence;
841 std::vector<CTransaction> txs;
844 recentlyAddedSequence = nRecentlyAddedSequence;
845 for (const auto& kv : mapRecentlyAddedTx) {
846 txs.push_back(*(kv.second));
848 mapRecentlyAddedTx.clear();
851 // A race condition can occur here between these SyncWithWallets calls, and
852 // the ones triggered by block logic (in ConnectTip and DisconnectTip). It
853 // is harmless because calling SyncWithWallets(_, NULL) does not alter the
854 // wallet transaction's block information.
855 for (auto tx : txs) {
857 SyncWithWallets(tx, NULL);
858 } catch (const boost::thread_interrupted&) {
860 } catch (const std::exception& e) {
861 PrintExceptionContinue(&e, "CTxMemPool::NotifyRecentlyAdded()");
863 PrintExceptionContinue(NULL, "CTxMemPool::NotifyRecentlyAdded()");
867 // Update the notified sequence number. We only need this in regtest mode,
868 // and should not lock on cs after calling SyncWithWallets otherwise.
869 if (Params().NetworkIDString() == "regtest") {
871 nNotifiedSequence = recentlyAddedSequence;
875 bool CTxMemPool::IsFullyNotified() {
876 assert(Params().NetworkIDString() == "regtest");
878 return nRecentlyAddedSequence == nNotifiedSequence;
881 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
883 bool CCoinsViewMemPool::GetNullifier(const uint256 &nf, ShieldedType type) const
885 return mempool.nullifierExists(nf, type) || base->GetNullifier(nf, type);
888 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) const {
889 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
890 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
891 // transactions. First checking the underlying cache risks returning a pruned entry instead.
893 if (mempool.lookup(txid, tx)) {
894 coins = CCoins(tx, MEMPOOL_HEIGHT);
897 return (base->GetCoins(txid, coins) && !coins.IsPruned());
900 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) const {
901 return mempool.exists(txid) || base->HaveCoins(txid);
904 size_t CTxMemPool::DynamicMemoryUsage() const {
906 // Estimate the overhead of mapTx to be 6 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
907 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 6 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapDeltas) + cachedInnerUsage;