Bitcoin Core  26.1.0
P2P Digital Currency
txmempool.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <txmempool.h>
7 
8 #include <chain.h>
9 #include <coins.h>
10 #include <common/system.h>
11 #include <consensus/consensus.h>
12 #include <consensus/tx_verify.h>
13 #include <consensus/validation.h>
14 #include <logging.h>
15 #include <policy/fees.h>
16 #include <policy/policy.h>
17 #include <policy/settings.h>
18 #include <reverse_iterator.h>
19 #include <util/check.h>
20 #include <util/moneystr.h>
21 #include <util/overflow.h>
22 #include <util/result.h>
23 #include <util/time.h>
24 #include <util/trace.h>
25 #include <util/translation.h>
26 #include <validationinterface.h>
27 
28 #include <cmath>
29 #include <numeric>
30 #include <optional>
31 #include <string_view>
32 #include <utility>
33 
34 bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
35 {
37  // If there are relative lock times then the maxInputBlock will be set
38  // If there are no relative lock times, the LockPoints don't depend on the chain
39  if (lp.maxInputBlock) {
40  // Check whether active_chain is an extension of the block at which the LockPoints
41  // calculation was valid. If not LockPoints are no longer valid
42  if (!active_chain.Contains(lp.maxInputBlock)) {
43  return false;
44  }
45  }
46 
47  // LockPoints still valid
48  return true;
49 }
50 
51 void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
52  const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove)
53 {
54  CTxMemPoolEntry::Children stageEntries, descendants;
55  stageEntries = updateIt->GetMemPoolChildrenConst();
56 
57  while (!stageEntries.empty()) {
58  const CTxMemPoolEntry& descendant = *stageEntries.begin();
59  descendants.insert(descendant);
60  stageEntries.erase(descendant);
61  const CTxMemPoolEntry::Children& children = descendant.GetMemPoolChildrenConst();
62  for (const CTxMemPoolEntry& childEntry : children) {
63  cacheMap::iterator cacheIt = cachedDescendants.find(mapTx.iterator_to(childEntry));
64  if (cacheIt != cachedDescendants.end()) {
65  // We've already calculated this one, just add the entries for this set
66  // but don't traverse again.
67  for (txiter cacheEntry : cacheIt->second) {
68  descendants.insert(*cacheEntry);
69  }
70  } else if (!descendants.count(childEntry)) {
71  // Schedule for later processing
72  stageEntries.insert(childEntry);
73  }
74  }
75  }
76  // descendants now contains all in-mempool descendants of updateIt.
77  // Update and add to cached descendant map
78  int32_t modifySize = 0;
79  CAmount modifyFee = 0;
80  int64_t modifyCount = 0;
81  for (const CTxMemPoolEntry& descendant : descendants) {
82  if (!setExclude.count(descendant.GetTx().GetHash())) {
83  modifySize += descendant.GetTxSize();
84  modifyFee += descendant.GetModifiedFee();
85  modifyCount++;
86  cachedDescendants[updateIt].insert(mapTx.iterator_to(descendant));
87  // Update ancestor state for each descendant
88  mapTx.modify(mapTx.iterator_to(descendant), [=](CTxMemPoolEntry& e) {
89  e.UpdateAncestorState(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost());
90  });
91  // Don't directly remove the transaction here -- doing so would
92  // invalidate iterators in cachedDescendants. Mark it for removal
93  // by inserting into descendants_to_remove.
94  if (descendant.GetCountWithAncestors() > uint64_t(m_limits.ancestor_count) || descendant.GetSizeWithAncestors() > m_limits.ancestor_size_vbytes) {
95  descendants_to_remove.insert(descendant.GetTx().GetHash());
96  }
97  }
98  }
99  mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); });
100 }
101 
102 void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate)
103 {
105  // For each entry in vHashesToUpdate, store the set of in-mempool, but not
106  // in-vHashesToUpdate transactions, so that we don't have to recalculate
107  // descendants when we come across a previously seen entry.
108  cacheMap mapMemPoolDescendantsToUpdate;
109 
110  // Use a set for lookups into vHashesToUpdate (these entries are already
111  // accounted for in the state of their ancestors)
112  std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
113 
114  std::set<uint256> descendants_to_remove;
115 
116  // Iterate in reverse, so that whenever we are looking at a transaction
117  // we are sure that all in-mempool descendants have already been processed.
118  // This maximizes the benefit of the descendant cache and guarantees that
119  // CTxMemPoolEntry::m_children will be updated, an assumption made in
120  // UpdateForDescendants.
121  for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) {
122  // calculate children from mapNextTx
123  txiter it = mapTx.find(hash);
124  if (it == mapTx.end()) {
125  continue;
126  }
127  auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
128  // First calculate the children, and update CTxMemPoolEntry::m_children to
129  // include them, and update their CTxMemPoolEntry::m_parents to include this tx.
130  // we cache the in-mempool children to avoid duplicate updates
131  {
133  for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
134  const uint256 &childHash = iter->second->GetHash();
135  txiter childIter = mapTx.find(childHash);
136  assert(childIter != mapTx.end());
137  // We can skip updating entries we've encountered before or that
138  // are in the block (which are already accounted for).
139  if (!visited(childIter) && !setAlreadyIncluded.count(childHash)) {
140  UpdateChild(it, childIter, true);
141  UpdateParent(childIter, it, true);
142  }
143  }
144  } // release epoch guard for UpdateForDescendants
145  UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded, descendants_to_remove);
146  }
147 
148  for (const auto& txid : descendants_to_remove) {
149  // This txid may have been removed already in a prior call to removeRecursive.
150  // Therefore we ensure it is not yet removed already.
151  if (const std::optional<txiter> txiter = GetIter(txid)) {
153  }
154  }
155 }
156 
158  int64_t entry_size,
159  size_t entry_count,
160  CTxMemPoolEntry::Parents& staged_ancestors,
161  const Limits& limits) const
162 {
163  int64_t totalSizeWithAncestors = entry_size;
164  setEntries ancestors;
165 
166  while (!staged_ancestors.empty()) {
167  const CTxMemPoolEntry& stage = staged_ancestors.begin()->get();
168  txiter stageit = mapTx.iterator_to(stage);
169 
170  ancestors.insert(stageit);
171  staged_ancestors.erase(stage);
172  totalSizeWithAncestors += stageit->GetTxSize();
173 
174  if (stageit->GetSizeWithDescendants() + entry_size > limits.descendant_size_vbytes) {
175  return util::Error{Untranslated(strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_size_vbytes))};
176  } else if (stageit->GetCountWithDescendants() + entry_count > static_cast<uint64_t>(limits.descendant_count)) {
177  return util::Error{Untranslated(strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_count))};
178  } else if (totalSizeWithAncestors > limits.ancestor_size_vbytes) {
179  return util::Error{Untranslated(strprintf("exceeds ancestor size limit [limit: %u]", limits.ancestor_size_vbytes))};
180  }
181 
182  const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst();
183  for (const CTxMemPoolEntry& parent : parents) {
184  txiter parent_it = mapTx.iterator_to(parent);
185 
186  // If this is a new ancestor, add it.
187  if (ancestors.count(parent_it) == 0) {
188  staged_ancestors.insert(parent);
189  }
190  if (staged_ancestors.size() + ancestors.size() + entry_count > static_cast<uint64_t>(limits.ancestor_count)) {
191  return util::Error{Untranslated(strprintf("too many unconfirmed ancestors [limit: %u]", limits.ancestor_count))};
192  }
193  }
194  }
195 
196  return ancestors;
197 }
198 
200  const int64_t total_vsize,
201  std::string &errString) const
202 {
203  size_t pack_count = package.size();
204 
205  // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist
206  if (pack_count > static_cast<uint64_t>(m_limits.ancestor_count)) {
207  errString = strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_limits.ancestor_count);
208  return false;
209  } else if (pack_count > static_cast<uint64_t>(m_limits.descendant_count)) {
210  errString = strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_limits.descendant_count);
211  return false;
212  } else if (total_vsize > m_limits.ancestor_size_vbytes) {
213  errString = strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_limits.ancestor_size_vbytes);
214  return false;
215  } else if (total_vsize > m_limits.descendant_size_vbytes) {
216  errString = strprintf("package size %u exceeds descendant size limit [limit: %u]", total_vsize, m_limits.descendant_size_vbytes);
217  return false;
218  }
219 
220  CTxMemPoolEntry::Parents staged_ancestors;
221  for (const auto& tx : package) {
222  for (const auto& input : tx->vin) {
223  std::optional<txiter> piter = GetIter(input.prevout.hash);
224  if (piter) {
225  staged_ancestors.insert(**piter);
226  if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_limits.ancestor_count)) {
227  errString = strprintf("too many unconfirmed parents [limit: %u]", m_limits.ancestor_count);
228  return false;
229  }
230  }
231  }
232  }
233  // When multiple transactions are passed in, the ancestors and descendants of all transactions
234  // considered together must be within limits even if they are not interdependent. This may be
235  // stricter than the limits for each individual transaction.
236  const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(),
237  staged_ancestors, m_limits)};
238  // It's possible to overestimate the ancestor/descendant totals.
239  if (!ancestors.has_value()) errString = "possibly " + util::ErrorString(ancestors).original;
240  return ancestors.has_value();
241 }
242 
244  const CTxMemPoolEntry &entry,
245  const Limits& limits,
246  bool fSearchForParents /* = true */) const
247 {
248  CTxMemPoolEntry::Parents staged_ancestors;
249  const CTransaction &tx = entry.GetTx();
250 
251  if (fSearchForParents) {
252  // Get parents of this transaction that are in the mempool
253  // GetMemPoolParents() is only valid for entries in the mempool, so we
254  // iterate mapTx to find parents.
255  for (unsigned int i = 0; i < tx.vin.size(); i++) {
256  std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
257  if (piter) {
258  staged_ancestors.insert(**piter);
259  if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) {
260  return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", limits.ancestor_count))};
261  }
262  }
263  }
264  } else {
265  // If we're not searching for parents, we require this to already be an
266  // entry in the mempool and use the entry's cached parents.
267  txiter it = mapTx.iterator_to(entry);
268  staged_ancestors = it->GetMemPoolParentsConst();
269  }
270 
271  return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
272  limits);
273 }
274 
276  std::string_view calling_fn_name,
277  const CTxMemPoolEntry &entry,
278  const Limits& limits,
279  bool fSearchForParents /* = true */) const
280 {
281  auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
282  if (!Assume(result)) {
283  LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Error, "%s: CalculateMemPoolAncestors failed unexpectedly, continuing with empty ancestor set (%s)\n",
284  calling_fn_name, util::ErrorString(result).original);
285  }
286  return std::move(result).value_or(CTxMemPool::setEntries{});
287 }
288 
289 void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
290 {
291  const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
292  // add or remove this tx as a child of each parent
293  for (const CTxMemPoolEntry& parent : parents) {
294  UpdateChild(mapTx.iterator_to(parent), it, add);
295  }
296  const int32_t updateCount = (add ? 1 : -1);
297  const int32_t updateSize{updateCount * it->GetTxSize()};
298  const CAmount updateFee = updateCount * it->GetModifiedFee();
299  for (txiter ancestorIt : setAncestors) {
300  mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
301  }
302 }
303 
305 {
306  int64_t updateCount = setAncestors.size();
307  int64_t updateSize = 0;
308  CAmount updateFee = 0;
309  int64_t updateSigOpsCost = 0;
310  for (txiter ancestorIt : setAncestors) {
311  updateSize += ancestorIt->GetTxSize();
312  updateFee += ancestorIt->GetModifiedFee();
313  updateSigOpsCost += ancestorIt->GetSigOpCost();
314  }
315  mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
316 }
317 
319 {
320  const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
321  for (const CTxMemPoolEntry& updateIt : children) {
322  UpdateParent(mapTx.iterator_to(updateIt), it, false);
323  }
324 }
325 
326 void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
327 {
328  // For each entry, walk back all ancestors and decrement size associated with this
329  // transaction
330  if (updateDescendants) {
331  // updateDescendants should be true whenever we're not recursively
332  // removing a tx and all its descendants, eg when a transaction is
333  // confirmed in a block.
334  // Here we only update statistics and not data in CTxMemPool::Parents
335  // and CTxMemPoolEntry::Children (which we need to preserve until we're
336  // finished with all operations that need to traverse the mempool).
337  for (txiter removeIt : entriesToRemove) {
338  setEntries setDescendants;
339  CalculateDescendants(removeIt, setDescendants);
340  setDescendants.erase(removeIt); // don't update state for self
341  int32_t modifySize = -removeIt->GetTxSize();
342  CAmount modifyFee = -removeIt->GetModifiedFee();
343  int modifySigOps = -removeIt->GetSigOpCost();
344  for (txiter dit : setDescendants) {
345  mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); });
346  }
347  }
348  }
349  for (txiter removeIt : entriesToRemove) {
350  const CTxMemPoolEntry &entry = *removeIt;
351  // Since this is a tx that is already in the mempool, we can call CMPA
352  // with fSearchForParents = false. If the mempool is in a consistent
353  // state, then using true or false should both be correct, though false
354  // should be a bit faster.
355  // However, if we happen to be in the middle of processing a reorg, then
356  // the mempool can be in an inconsistent state. In this case, the set
357  // of ancestors reachable via GetMemPoolParents()/GetMemPoolChildren()
358  // will be the same as the set of ancestors whose packages include this
359  // transaction, because when we add a new transaction to the mempool in
360  // addUnchecked(), we assume it has no children, and in the case of a
361  // reorg where that assumption is false, the in-mempool children aren't
362  // linked to the in-block tx's until UpdateTransactionsFromBlock() is
363  // called.
364  // So if we're being called during a reorg, ie before
365  // UpdateTransactionsFromBlock() has been called, then
366  // GetMemPoolParents()/GetMemPoolChildren() will differ from the set of
367  // mempool parents we'd calculate by searching, and it's important that
368  // we use the cached notion of ancestor transactions as the set of
369  // things to update for removal.
370  auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits(), /*fSearchForParents=*/false)};
371  // Note that UpdateAncestorsOf severs the child links that point to
372  // removeIt in the entries for the parents of removeIt.
373  UpdateAncestorsOf(false, removeIt, ancestors);
374  }
375  // After updating all the ancestor sizes, we can now sever the link between each
376  // transaction being removed and any mempool children (ie, update CTxMemPoolEntry::m_parents
377  // for each direct child of a transaction being removed).
378  for (txiter removeIt : entriesToRemove) {
379  UpdateChildrenForRemoval(removeIt);
380  }
381 }
382 
383 void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
384 {
385  nSizeWithDescendants += modifySize;
388  m_count_with_descendants += modifyCount;
390 }
391 
392 void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
393 {
394  nSizeWithAncestors += modifySize;
397  m_count_with_ancestors += modifyCount;
399  nSigOpCostWithAncestors += modifySigOps;
400  assert(int(nSigOpCostWithAncestors) >= 0);
401 }
402 
404  : m_check_ratio{opts.check_ratio},
405  minerPolicyEstimator{opts.estimator},
406  m_max_size_bytes{opts.max_size_bytes},
407  m_expiry{opts.expiry},
408  m_incremental_relay_feerate{opts.incremental_relay_feerate},
409  m_min_relay_feerate{opts.min_relay_feerate},
410  m_dust_relay_feerate{opts.dust_relay_feerate},
411  m_permit_bare_multisig{opts.permit_bare_multisig},
412  m_max_datacarrier_bytes{opts.max_datacarrier_bytes},
413  m_require_standard{opts.require_standard},
414  m_full_rbf{opts.full_rbf},
415  m_limits{opts.limits}
416 {
417 }
418 
419 bool CTxMemPool::isSpent(const COutPoint& outpoint) const
420 {
421  LOCK(cs);
422  return mapNextTx.count(outpoint);
423 }
424 
426 {
427  return nTransactionsUpdated;
428 }
429 
431 {
433 }
434 
435 void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate)
436 {
437  // Add to memory pool without checking anything.
438  // Used by AcceptToMemoryPool(), which DOES do
439  // all the appropriate checks.
440  indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
441 
442  // Update transaction for any feeDelta created by PrioritiseTransaction
443  CAmount delta{0};
444  ApplyDelta(entry.GetTx().GetHash(), delta);
445  // The following call to UpdateModifiedFee assumes no previous fee modifications
446  Assume(entry.GetFee() == entry.GetModifiedFee());
447  if (delta) {
448  mapTx.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
449  }
450 
451  // Update cachedInnerUsage to include contained transaction's usage.
452  // (When we update the entry for in-mempool parents, memory usage will be
453  // further updated.)
454  cachedInnerUsage += entry.DynamicMemoryUsage();
455 
456  const CTransaction& tx = newit->GetTx();
457  std::set<uint256> setParentTransactions;
458  for (unsigned int i = 0; i < tx.vin.size(); i++) {
459  mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
460  setParentTransactions.insert(tx.vin[i].prevout.hash);
461  }
462  // Don't bother worrying about child transactions of this one.
463  // Normal case of a new transaction arriving is that there can't be any
464  // children, because such children would be orphans.
465  // An exception to that is if a transaction enters that used to be in a block.
466  // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
467  // to clean up the mess we're leaving here.
468 
469  // Update ancestors with information about this tx
470  for (const auto& pit : GetIterSet(setParentTransactions)) {
471  UpdateParent(newit, pit, true);
472  }
473  UpdateAncestorsOf(true, newit, setAncestors);
474  UpdateEntryForAncestors(newit, setAncestors);
475 
477  totalTxSize += entry.GetTxSize();
478  m_total_fee += entry.GetFee();
479  if (minerPolicyEstimator) {
480  minerPolicyEstimator->processTransaction(entry, validFeeEstimate);
481  }
482 
483  vTxHashes.emplace_back(tx.GetWitnessHash(), newit);
484  newit->vTxHashesIdx = vTxHashes.size() - 1;
485 
486  TRACE3(mempool, added,
487  entry.GetTx().GetHash().data(),
488  entry.GetTxSize(),
489  entry.GetFee()
490  );
491 }
492 
494 {
495  // We increment mempool sequence value no matter removal reason
496  // even if not directly reported below.
497  uint64_t mempool_sequence = GetAndIncrementSequence();
498 
499  if (reason != MemPoolRemovalReason::BLOCK) {
500  // Notify clients that a transaction has been removed from the mempool
501  // for any reason except being included in a block. Clients interested
502  // in transactions included in blocks can subscribe to the BlockConnected
503  // notification.
504  GetMainSignals().TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
505  }
506  TRACE5(mempool, removed,
507  it->GetTx().GetHash().data(),
508  RemovalReasonToString(reason).c_str(),
509  it->GetTxSize(),
510  it->GetFee(),
511  std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
512  );
513 
514  const uint256 hash = it->GetTx().GetHash();
515  for (const CTxIn& txin : it->GetTx().vin)
516  mapNextTx.erase(txin.prevout);
517 
518  RemoveUnbroadcastTx(hash, true /* add logging because unchecked */ );
519 
520  if (vTxHashes.size() > 1) {
521  vTxHashes[it->vTxHashesIdx] = std::move(vTxHashes.back());
522  vTxHashes[it->vTxHashesIdx].second->vTxHashesIdx = it->vTxHashesIdx;
523  vTxHashes.pop_back();
524  if (vTxHashes.size() * 2 < vTxHashes.capacity())
525  vTxHashes.shrink_to_fit();
526  } else
527  vTxHashes.clear();
528 
529  totalTxSize -= it->GetTxSize();
530  m_total_fee -= it->GetFee();
531  cachedInnerUsage -= it->DynamicMemoryUsage();
532  cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
533  mapTx.erase(it);
536 }
537 
538 // Calculates descendants of entry that are not already in setDescendants, and adds to
539 // setDescendants. Assumes entryit is already a tx in the mempool and CTxMemPoolEntry::m_children
540 // is correct for tx and all descendants.
541 // Also assumes that if an entry is in setDescendants already, then all
542 // in-mempool descendants of it are already in setDescendants as well, so that we
543 // can save time by not iterating over those entries.
544 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
545 {
546  setEntries stage;
547  if (setDescendants.count(entryit) == 0) {
548  stage.insert(entryit);
549  }
550  // Traverse down the children of entry, only adding children that are not
551  // accounted for in setDescendants already (because those children have either
552  // already been walked, or will be walked in this iteration).
553  while (!stage.empty()) {
554  txiter it = *stage.begin();
555  setDescendants.insert(it);
556  stage.erase(it);
557 
558  const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
559  for (const CTxMemPoolEntry& child : children) {
560  txiter childiter = mapTx.iterator_to(child);
561  if (!setDescendants.count(childiter)) {
562  stage.insert(childiter);
563  }
564  }
565  }
566 }
567 
569 {
570  // Remove transaction from memory pool
572  setEntries txToRemove;
573  txiter origit = mapTx.find(origTx.GetHash());
574  if (origit != mapTx.end()) {
575  txToRemove.insert(origit);
576  } else {
577  // When recursively removing but origTx isn't in the mempool
578  // be sure to remove any children that are in the pool. This can
579  // happen during chain re-orgs if origTx isn't re-accepted into
580  // the mempool for any reason.
581  for (unsigned int i = 0; i < origTx.vout.size(); i++) {
582  auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
583  if (it == mapNextTx.end())
584  continue;
585  txiter nextit = mapTx.find(it->second->GetHash());
586  assert(nextit != mapTx.end());
587  txToRemove.insert(nextit);
588  }
589  }
590  setEntries setAllRemoves;
591  for (txiter it : txToRemove) {
592  CalculateDescendants(it, setAllRemoves);
593  }
594 
595  RemoveStaged(setAllRemoves, false, reason);
596 }
597 
598 void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
599 {
600  // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
603 
604  setEntries txToRemove;
605  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
606  if (check_final_and_mature(it)) txToRemove.insert(it);
607  }
608  setEntries setAllRemoves;
609  for (txiter it : txToRemove) {
610  CalculateDescendants(it, setAllRemoves);
611  }
612  RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
613  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
614  assert(TestLockPointValidity(chain, it->GetLockPoints()));
615  }
616 }
617 
619 {
620  // Remove transactions which depend on inputs of tx, recursively
622  for (const CTxIn &txin : tx.vin) {
623  auto it = mapNextTx.find(txin.prevout);
624  if (it != mapNextTx.end()) {
625  const CTransaction &txConflict = *it->second;
626  if (txConflict != tx)
627  {
628  ClearPrioritisation(txConflict.GetHash());
630  }
631  }
632  }
633 }
634 
638 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
639 {
641  std::vector<const CTxMemPoolEntry*> entries;
642  for (const auto& tx : vtx)
643  {
644  uint256 hash = tx->GetHash();
645 
646  indexed_transaction_set::iterator i = mapTx.find(hash);
647  if (i != mapTx.end())
648  entries.push_back(&*i);
649  }
650  // Before the txs in the new block have been removed from the mempool, update policy estimates
651  if (minerPolicyEstimator) {minerPolicyEstimator->processBlock(nBlockHeight, entries);}
652  for (const auto& tx : vtx)
653  {
654  txiter it = mapTx.find(tx->GetHash());
655  if (it != mapTx.end()) {
656  setEntries stage;
657  stage.insert(it);
659  }
660  removeConflicts(*tx);
662  }
663  lastRollingFeeUpdate = GetTime();
664  blockSinceLastRollingFeeBump = true;
665 }
666 
667 void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
668 {
669  if (m_check_ratio == 0) return;
670 
671  if (GetRand(m_check_ratio) >= 1) return;
672 
674  LOCK(cs);
675  LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
676 
677  uint64_t checkTotal = 0;
678  CAmount check_total_fee{0};
679  uint64_t innerUsage = 0;
680  uint64_t prev_ancestor_count{0};
681 
682  CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
683 
684  for (const auto& it : GetSortedDepthAndScore()) {
685  checkTotal += it->GetTxSize();
686  check_total_fee += it->GetFee();
687  innerUsage += it->DynamicMemoryUsage();
688  const CTransaction& tx = it->GetTx();
689  innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
690  CTxMemPoolEntry::Parents setParentCheck;
691  for (const CTxIn &txin : tx.vin) {
692  // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
693  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
694  if (it2 != mapTx.end()) {
695  const CTransaction& tx2 = it2->GetTx();
696  assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
697  setParentCheck.insert(*it2);
698  }
699  // We are iterating through the mempool entries sorted in order by ancestor count.
700  // All parents must have been checked before their children and their coins added to
701  // the mempoolDuplicate coins cache.
702  assert(mempoolDuplicate.HaveCoin(txin.prevout));
703  // Check whether its inputs are marked in mapNextTx.
704  auto it3 = mapNextTx.find(txin.prevout);
705  assert(it3 != mapNextTx.end());
706  assert(it3->first == &txin.prevout);
707  assert(it3->second == &tx);
708  }
709  auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
710  return a.GetTx().GetHash() == b.GetTx().GetHash();
711  };
712  assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
713  assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
714  // Verify ancestor state is correct.
715  auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
716  uint64_t nCountCheck = ancestors.size() + 1;
717  int32_t nSizeCheck = it->GetTxSize();
718  CAmount nFeesCheck = it->GetModifiedFee();
719  int64_t nSigOpCheck = it->GetSigOpCost();
720 
721  for (txiter ancestorIt : ancestors) {
722  nSizeCheck += ancestorIt->GetTxSize();
723  nFeesCheck += ancestorIt->GetModifiedFee();
724  nSigOpCheck += ancestorIt->GetSigOpCost();
725  }
726 
727  assert(it->GetCountWithAncestors() == nCountCheck);
728  assert(it->GetSizeWithAncestors() == nSizeCheck);
729  assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
730  assert(it->GetModFeesWithAncestors() == nFeesCheck);
731  // Sanity check: we are walking in ascending ancestor count order.
732  assert(prev_ancestor_count <= it->GetCountWithAncestors());
733  prev_ancestor_count = it->GetCountWithAncestors();
734 
735  // Check children against mapNextTx
736  CTxMemPoolEntry::Children setChildrenCheck;
737  auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
738  int32_t child_sizes{0};
739  for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
740  txiter childit = mapTx.find(iter->second->GetHash());
741  assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
742  if (setChildrenCheck.insert(*childit).second) {
743  child_sizes += childit->GetTxSize();
744  }
745  }
746  assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
747  assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), it->GetMemPoolChildrenConst().begin(), comp));
748  // Also check to make sure size is greater than sum with immediate children.
749  // just a sanity check, not definitive that this calc is correct...
750  assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
751 
752  TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
753  CAmount txfee = 0;
754  assert(!tx.IsCoinBase());
755  assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
756  for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
757  AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
758  }
759  for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
760  uint256 hash = it->second->GetHash();
761  indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
762  const CTransaction& tx = it2->GetTx();
763  assert(it2 != mapTx.end());
764  assert(&tx == it->second);
765  }
766 
767  assert(totalTxSize == checkTotal);
768  assert(m_total_fee == check_total_fee);
769  assert(innerUsage == cachedInnerUsage);
770 }
771 
772 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid)
773 {
774  /* Return `true` if hasha should be considered sooner than hashb. Namely when:
775  * a is not in the mempool, but b is
776  * both are in the mempool and a has fewer ancestors than b
777  * both are in the mempool and a has a higher score than b
778  */
779  LOCK(cs);
780  indexed_transaction_set::const_iterator j = wtxid ? get_iter_from_wtxid(hashb) : mapTx.find(hashb);
781  if (j == mapTx.end()) return false;
782  indexed_transaction_set::const_iterator i = wtxid ? get_iter_from_wtxid(hasha) : mapTx.find(hasha);
783  if (i == mapTx.end()) return true;
784  uint64_t counta = i->GetCountWithAncestors();
785  uint64_t countb = j->GetCountWithAncestors();
786  if (counta == countb) {
787  return CompareTxMemPoolEntryByScore()(*i, *j);
788  }
789  return counta < countb;
790 }
791 
792 namespace {
793 class DepthAndScoreComparator
794 {
795 public:
796  bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
797  {
798  uint64_t counta = a->GetCountWithAncestors();
799  uint64_t countb = b->GetCountWithAncestors();
800  if (counta == countb) {
801  return CompareTxMemPoolEntryByScore()(*a, *b);
802  }
803  return counta < countb;
804  }
805 };
806 } // namespace
807 
808 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
809 {
810  std::vector<indexed_transaction_set::const_iterator> iters;
812 
813  iters.reserve(mapTx.size());
814 
815  for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
816  iters.push_back(mi);
817  }
818  std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
819  return iters;
820 }
821 
822 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) const
823 {
824  LOCK(cs);
825  auto iters = GetSortedDepthAndScore();
826 
827  vtxid.clear();
828  vtxid.reserve(mapTx.size());
829 
830  for (auto it : iters) {
831  vtxid.push_back(it->GetTx().GetHash());
832  }
833 }
834 
835 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
836  return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
837 }
838 
839 std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
840 {
842 
843  std::vector<CTxMemPoolEntryRef> ret;
844  ret.reserve(mapTx.size());
845  for (const auto& it : GetSortedDepthAndScore()) {
846  ret.emplace_back(*it);
847  }
848  return ret;
849 }
850 
851 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
852 {
853  LOCK(cs);
854  auto iters = GetSortedDepthAndScore();
855 
856  std::vector<TxMempoolInfo> ret;
857  ret.reserve(mapTx.size());
858  for (auto it : iters) {
859  ret.push_back(GetInfo(it));
860  }
861 
862  return ret;
863 }
864 
866 {
867  LOCK(cs);
868  indexed_transaction_set::const_iterator i = mapTx.find(hash);
869  if (i == mapTx.end())
870  return nullptr;
871  return i->GetSharedTx();
872 }
873 
875 {
876  LOCK(cs);
877  indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
878  if (i == mapTx.end())
879  return TxMempoolInfo();
880  return GetInfo(i);
881 }
882 
883 TxMempoolInfo CTxMemPool::info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const
884 {
885  LOCK(cs);
886  indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
887  if (i != mapTx.end() && i->GetSequence() < last_sequence) {
888  return GetInfo(i);
889  } else {
890  return TxMempoolInfo();
891  }
892 }
893 
894 void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
895 {
896  {
897  LOCK(cs);
898  CAmount &delta = mapDeltas[hash];
899  delta = SaturatingAdd(delta, nFeeDelta);
900  txiter it = mapTx.find(hash);
901  if (it != mapTx.end()) {
902  mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
903  // Now update all ancestors' modified fees with descendants
904  auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
905  for (txiter ancestorIt : ancestors) {
906  mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
907  }
908  // Now update all descendants' modified fees with ancestors
909  setEntries setDescendants;
910  CalculateDescendants(it, setDescendants);
911  setDescendants.erase(it);
912  for (txiter descendantIt : setDescendants) {
913  mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
914  }
916  }
917  if (delta == 0) {
918  mapDeltas.erase(hash);
919  LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
920  } else {
921  LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
922  hash.ToString(),
923  it == mapTx.end() ? "not " : "",
924  FormatMoney(nFeeDelta),
925  FormatMoney(delta));
926  }
927  }
928 }
929 
930 void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
931 {
933  std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
934  if (pos == mapDeltas.end())
935  return;
936  const CAmount &delta = pos->second;
937  nFeeDelta += delta;
938 }
939 
941 {
943  mapDeltas.erase(hash);
944 }
945 
946 std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
947 {
949  LOCK(cs);
950  std::vector<delta_info> result;
951  result.reserve(mapDeltas.size());
952  for (const auto& [txid, delta] : mapDeltas) {
953  const auto iter{mapTx.find(txid)};
954  const bool in_mempool{iter != mapTx.end()};
955  std::optional<CAmount> modified_fee;
956  if (in_mempool) modified_fee = iter->GetModifiedFee();
957  result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
958  }
959  return result;
960 }
961 
963 {
964  const auto it = mapNextTx.find(prevout);
965  return it == mapNextTx.end() ? nullptr : it->second;
966 }
967 
968 std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const uint256& txid) const
969 {
970  auto it = mapTx.find(txid);
971  if (it != mapTx.end()) return it;
972  return std::nullopt;
973 }
974 
975 CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<uint256>& hashes) const
976 {
978  for (const auto& h : hashes) {
979  const auto mi = GetIter(h);
980  if (mi) ret.insert(*mi);
981  }
982  return ret;
983 }
984 
985 std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<uint256>& txids) const
986 {
988  std::vector<txiter> ret;
989  ret.reserve(txids.size());
990  for (const auto& txid : txids) {
991  const auto it{GetIter(txid)};
992  if (!it) return {};
993  ret.push_back(*it);
994  }
995  return ret;
996 }
997 
999 {
1000  for (unsigned int i = 0; i < tx.vin.size(); i++)
1001  if (exists(GenTxid::Txid(tx.vin[i].prevout.hash)))
1002  return false;
1003  return true;
1004 }
1005 
1006 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1007 
1008 bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
1009  // Check to see if the inputs are made available by another tx in the package.
1010  // These Coins would not be available in the underlying CoinsView.
1011  if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
1012  coin = it->second;
1013  return true;
1014  }
1015 
1016  // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1017  // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1018  // transactions. First checking the underlying cache risks returning a pruned entry instead.
1019  CTransactionRef ptx = mempool.get(outpoint.hash);
1020  if (ptx) {
1021  if (outpoint.n < ptx->vout.size()) {
1022  coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
1023  m_non_base_coins.emplace(outpoint);
1024  return true;
1025  } else {
1026  return false;
1027  }
1028  }
1029  return base->GetCoin(outpoint, coin);
1030 }
1031 
1033 {
1034  for (unsigned int n = 0; n < tx->vout.size(); ++n) {
1035  m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
1036  m_non_base_coins.emplace(tx->GetHash(), n);
1037  }
1038 }
1040 {
1041  m_temp_added.clear();
1042  m_non_base_coins.clear();
1043 }
1044 
1046  LOCK(cs);
1047  // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1048  return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(vTxHashes) + cachedInnerUsage;
1049 }
1050 
1051 void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) {
1052  LOCK(cs);
1053 
1054  if (m_unbroadcast_txids.erase(txid))
1055  {
1056  LogPrint(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
1057  }
1058 }
1059 
1060 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1061  AssertLockHeld(cs);
1062  UpdateForRemoveFromMempool(stage, updateDescendants);
1063  for (txiter it : stage) {
1064  removeUnchecked(it, reason);
1065  }
1066 }
1067 
1068 int CTxMemPool::Expire(std::chrono::seconds time)
1069 {
1070  AssertLockHeld(cs);
1071  indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1072  setEntries toremove;
1073  while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1074  toremove.insert(mapTx.project<0>(it));
1075  it++;
1076  }
1077  setEntries stage;
1078  for (txiter removeit : toremove) {
1079  CalculateDescendants(removeit, stage);
1080  }
1082  return stage.size();
1083 }
1084 
1085 void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry, bool validFeeEstimate)
1086 {
1087  auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits())};
1088  return addUnchecked(entry, ancestors, validFeeEstimate);
1089 }
1090 
1091 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1092 {
1093  AssertLockHeld(cs);
1095  if (add && entry->GetMemPoolChildren().insert(*child).second) {
1096  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1097  } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
1098  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1099  }
1100 }
1101 
1102 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1103 {
1104  AssertLockHeld(cs);
1106  if (add && entry->GetMemPoolParents().insert(*parent).second) {
1107  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1108  } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
1109  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1110  }
1111 }
1112 
1113 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1114  LOCK(cs);
1115  if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1116  return CFeeRate(llround(rollingMinimumFeeRate));
1117 
1118  int64_t time = GetTime();
1119  if (time > lastRollingFeeUpdate + 10) {
1120  double halflife = ROLLING_FEE_HALFLIFE;
1121  if (DynamicMemoryUsage() < sizelimit / 4)
1122  halflife /= 4;
1123  else if (DynamicMemoryUsage() < sizelimit / 2)
1124  halflife /= 2;
1125 
1126  rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1127  lastRollingFeeUpdate = time;
1128 
1129  if (rollingMinimumFeeRate < (double)m_incremental_relay_feerate.GetFeePerK() / 2) {
1130  rollingMinimumFeeRate = 0;
1131  return CFeeRate(0);
1132  }
1133  }
1134  return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_incremental_relay_feerate);
1135 }
1136 
1138  AssertLockHeld(cs);
1139  if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1140  rollingMinimumFeeRate = rate.GetFeePerK();
1141  blockSinceLastRollingFeeBump = false;
1142  }
1143 }
1144 
1145 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1146  AssertLockHeld(cs);
1147 
1148  unsigned nTxnRemoved = 0;
1149  CFeeRate maxFeeRateRemoved(0);
1150  while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1151  indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1152 
1153  // We set the new mempool min fee to the feerate of the removed set, plus the
1154  // "minimum reasonable fee rate" (ie some value under which we consider txn
1155  // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1156  // equal to txn which were removed with no block in between.
1157  CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1158  removed += m_incremental_relay_feerate;
1159  trackPackageRemoved(removed);
1160  maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1161 
1162  setEntries stage;
1163  CalculateDescendants(mapTx.project<0>(it), stage);
1164  nTxnRemoved += stage.size();
1165 
1166  std::vector<CTransaction> txn;
1167  if (pvNoSpendsRemaining) {
1168  txn.reserve(stage.size());
1169  for (txiter iter : stage)
1170  txn.push_back(iter->GetTx());
1171  }
1173  if (pvNoSpendsRemaining) {
1174  for (const CTransaction& tx : txn) {
1175  for (const CTxIn& txin : tx.vin) {
1176  if (exists(GenTxid::Txid(txin.prevout.hash))) continue;
1177  pvNoSpendsRemaining->push_back(txin.prevout);
1178  }
1179  }
1180  }
1181  }
1182 
1183  if (maxFeeRateRemoved > CFeeRate(0)) {
1184  LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1185  }
1186 }
1187 
1189  // find parent with highest descendant count
1190  std::vector<txiter> candidates;
1191  setEntries counted;
1192  candidates.push_back(entry);
1193  uint64_t maximum = 0;
1194  while (candidates.size()) {
1195  txiter candidate = candidates.back();
1196  candidates.pop_back();
1197  if (!counted.insert(candidate).second) continue;
1198  const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst();
1199  if (parents.size() == 0) {
1200  maximum = std::max(maximum, candidate->GetCountWithDescendants());
1201  } else {
1202  for (const CTxMemPoolEntry& i : parents) {
1203  candidates.push_back(mapTx.iterator_to(i));
1204  }
1205  }
1206  }
1207  return maximum;
1208 }
1209 
1210 void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
1211  LOCK(cs);
1212  auto it = mapTx.find(txid);
1213  ancestors = descendants = 0;
1214  if (it != mapTx.end()) {
1215  ancestors = it->GetCountWithAncestors();
1216  if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
1217  if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
1218  descendants = CalculateDescendantMaximum(it);
1219  }
1220 }
1221 
1223 {
1224  LOCK(cs);
1225  return m_load_tried;
1226 }
1227 
1228 void CTxMemPool::SetLoadTried(bool load_tried)
1229 {
1230  LOCK(cs);
1231  m_load_tried = load_tried;
1232 }
1233 
1234 std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<uint256>& txids) const
1235 {
1236  AssertLockHeld(cs);
1237  std::vector<txiter> clustered_txs{GetIterVec(txids)};
1238  // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not
1239  // necessarily mean the entry has been processed.
1241  for (const auto& it : clustered_txs) {
1242  visited(it);
1243  }
1244  // i = index of where the list of entries to process starts
1245  for (size_t i{0}; i < clustered_txs.size(); ++i) {
1246  // DoS protection: if there are 500 or more entries to process, just quit.
1247  if (clustered_txs.size() > 500) return {};
1248  const txiter& tx_iter = clustered_txs.at(i);
1249  for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
1250  for (const CTxMemPoolEntry& entry : entries) {
1251  const auto entry_it = mapTx.iterator_to(entry);
1252  if (!visited(entry_it)) {
1253  clustered_txs.push_back(entry_it);
1254  }
1255  }
1256  }
1257  }
1258  return clustered_txs;
1259 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
void UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
Definition: txmempool.cpp:383
void queryHashes(std::vector< uint256 > &vtxid) const
Definition: txmempool.cpp:822
Information about a mempool transaction.
Definition: txmempool.h:210
std::vector< txiter > GetIterVec(const std::vector< uint256 > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
Definition: txmempool.cpp:985
std::unordered_set< COutPoint, SaltedOutpointHasher > m_non_base_coins
Set of all coins that have been fetched from mempool or created using PackageAddTransaction (not base...
Definition: txmempool.h:835
int ret
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:168
CAmount nModFeesWithDescendants
... and total fees (all including us)
Definition: mempool_entry.h:94
std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
void UpdateModifiedFee(CAmount fee_diff)
AssertLockHeld(pool.cs)
void processBlock(unsigned int nBlockHeight, std::vector< const CTxMemPoolEntry *> &entries) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Process all the transactions that have been included in a block.
Definition: fees.cpp:636
#define LogPrint(category,...)
Definition: logging.h:246
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:394
assert(!tx.IsCoinBase())
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:13
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:851
int32_t GetTxSize() const
A UTXO entry.
Definition: coins.h:31
bool exists(const GenTxid &gtxid) const
Definition: txmempool.h:678
void UpdateTransactionsFromBlock(const std::vector< uint256 > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
UpdateTransactionsFromBlock is called when adding transactions from a disconnected block back to the ...
Definition: txmempool.cpp:102
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
Options struct containing limit options for a CTxMemPool.
An in-memory indexed chain of blocks.
Definition: chain.h:441
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:544
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:30
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1045
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
GetCoin, returning whether it exists and is not spent.
Definition: txmempool.cpp:1008
reverse_range< T > reverse_iterate(T &x)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:48
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:618
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1060
const uint256 & GetHash() const
Definition: transaction.h:435
Removed for conflict with in-block transaction.
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb, bool wtxid=false)
Definition: txmempool.cpp:772
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:397
const Children & GetMemPoolChildrenConst() const
CTxMemPool(const Options &opts)
Create a new CTxMemPool.
Definition: txmempool.cpp:403
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:305
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:568
void SetLoadTried(bool load_tried)
Set whether or not an initial attempt to load the persisted mempool was made (regardless of whether t...
Definition: txmempool.cpp:1228
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.h:627
setEntries AssumeCalculateMemPoolAncestors(std::string_view calling_fn_name, const CTxMemPoolEntry &entry, const Limits &limits, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Same as CalculateMemPoolAncestors, but always returns a (non-optional) setEntries.
Definition: txmempool.cpp:275
CAmount GetModifiedFee() const
#define WITH_FRESH_EPOCH(epoch)
Definition: epochguard.h:100
bool IsCoinBase() const
Definition: transaction.h:350
util::Result< setEntries > CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, const Limits &limits, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:243
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:419
const std::vector< CTxIn > vin
Definition: transaction.h:305
void removeForReorg(CChain &chain, std::function< bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs
After reorg, filter the entries that would no longer be valid in the next block, and update the entri...
Definition: txmempool.cpp:598
bool removeTx(uint256 hash, bool inBlock) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Remove a transaction from the mempool tracking stats.
Definition: fees.cpp:510
std::vector< txiter > GatherClusters(const std::vector< uint256 > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Collect the entire cluster of connected transactions for each transaction in txids.
Definition: txmempool.cpp:1234
Expired from mempool.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:65
int64_t nSizeWithAncestors
Definition: mempool_entry.h:99
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void addUnchecked(const CTxMemPoolEntry &entry, bool validFeeEstimate=true) EXCLUSIVE_LOCKS_REQUIRED(cs
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.h:474
const int m_check_ratio
Value n means that 1 times in n we check.
Definition: txmempool.h:304
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Update ancestors of hash to add/remove it as a descendant transaction.
Definition: txmempool.cpp:289
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition: random.h:80
void UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set< uint256 > &setExclude, std::set< uint256 > &descendants_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs)
UpdateForDescendants is used by UpdateTransactionsFromBlock to update the descendants for a single tr...
Definition: txmempool.cpp:51
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction&#39;s outputs to a cache.
Definition: coins.cpp:118
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0...
Definition: txmempool.h:45
int64_t nSigOpCostWithAncestors
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Parents
Definition: mempool_entry.h:70
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.cpp:835
int64_t m_count_with_descendants
number of descendant transactions
Definition: mempool_entry.h:91
Abstract view on the open txout dataset.
Definition: coins.h:172
size_t DynamicMemoryUsage() const
int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Expire all transaction (and their dependencies) in the mempool older than time.
Definition: txmempool.cpp:1068
An input of a transaction.
Definition: transaction.h:74
const uint256 & GetWitnessHash() const
Definition: transaction.h:338
int64_t descendant_count
The maximum allowed number of transactions in a package including the entry and its descendants...
Removed for reorganization.
#define LOCK(cs)
Definition: sync.h:258
CCoinsView * base
Definition: coins.h:212
const uint256 & GetHash() const
Definition: transaction.h:337
const CAmount & GetFee() const
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:472
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Before calling removeUnchecked for a given transaction, UpdateForRemoveFromMempool must be called on ...
Definition: txmempool.cpp:493
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:39
uint32_t n
Definition: transaction.h:39
const std::vector< CTxOut > vout
Definition: transaction.h:306
Removed in size limiting.
const Limits m_limits
Definition: txmempool.h:450
bool TestLockPointValidity(CChain &active_chain, const LockPoints &lp)
Test whether the LockPoints height and time are still valid on the current chain. ...
Definition: txmempool.cpp:34
std::vector< delta_info > GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return a vector of all entries in mapDeltas with their corresponding delta_info.
Definition: txmempool.cpp:946
CMainSignals & GetMainSignals()
#define LogPrintLevel(category, level,...)
Definition: logging.h:254
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:330
CAmount nModFeesWithAncestors
std::string ToString() const
Definition: uint256.cpp:55
const CTransaction * GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
Definition: txmempool.cpp:962
int64_t m_count_with_ancestors
Definition: mempool_entry.h:97
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:35
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:430
void processTransaction(const CTxMemPoolEntry &entry, bool validFeeEstimate) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Process a transaction accepted to the mempool.
Definition: fees.cpp:569
void ApplyDelta(const uint256 &hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:930
#define Assume(val)
Assume is the identity function.
Definition: check.h:85
const CFeeRate m_incremental_relay_feerate
Definition: txmempool.h:442
int64_t ancestor_size_vbytes
The maximum allowed size in virtual bytes of an entry and its ancestors within a package.
#define TRACE5(context, event, a, b, c, d, e)
Definition: trace.h:46
bool IsWtxid() const
Definition: transaction.h:434
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1188
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
Definition: memusage.h:51
bool GetLoadTried() const
Definition: txmempool.cpp:1222
TxMempoolInfo info_for_relay(const GenTxid &gtxid, uint64_t last_sequence) const
Returns info for a transaction if its entry_sequence < last_sequence.
Definition: txmempool.cpp:883
std::optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:968
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void cs_main
Definition: txmempool.h:474
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:16
256-bit opaque blob.
Definition: uint256.h:106
T SaturatingAdd(const T i, const T j) noexcept
Definition: overflow.h:33
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:730
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:808
bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs
visited marks a CTxMemPoolEntry as having been traversed during the lifetime of the most recently cre...
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:301
bool HasNoInputsOf(const CTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
Definition: txmempool.cpp:998
#define TRACE3(context, event, a, b, c)
Definition: trace.h:44
constexpr const unsigned char * data() const
Definition: uint256.h:65
void UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
Definition: txmempool.cpp:392
void Reset()
Clear m_temp_added and m_non_base_coins.
Definition: txmempool.cpp:1039
std::string original
Definition: translation.h:19
int64_t nSizeWithDescendants
... and size
Definition: mempool_entry.h:93
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
Definition: txmempool.h:403
Removed for block.
int64_t descendant_size_vbytes
The maximum allowed size in virtual bytes of an entry and its descendants within a package...
const CTransaction & GetTx() const
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Set ancestor state for an entry.
Definition: txmempool.cpp:304
bool m_epoch
Definition: txmempool.h:799
TxMempoolInfo info(const GenTxid &gtxid) const
Definition: txmempool.cpp:874
txiter get_iter_from_wtxid(const uint256 &wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:688
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1091
void ClearPrioritisation(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:940
setEntries GetIterSet(const std::set< uint256 > &hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of hashes into a set of pool iterators to avoid repeated lookups. ...
Definition: txmempool.cpp:975
CBlockPolicyEstimator *const minerPolicyEstimator
Definition: txmempool.h:306
void GetTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants, size_t *ancestorsize=nullptr, CAmount *ancestorfees=nullptr) const
Calculate the ancestor and descendant count for the given transaction.
Definition: txmempool.cpp:1210
std::string GetHex() const
Definition: uint256.cpp:11
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Children
Definition: mempool_entry.h:71
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
#define AssertLockNotHeld(cs)
Definition: sync.h:148
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:425
static int count
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:81
static size_t IncrementalDynamicUsage(const std::set< X, Y > &s)
Definition: memusage.h:106
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
Definition: txmempool.cpp:1032
void TrimToSize(size_t sizelimit, std::vector< COutPoint > *pvNoSpendsRemaining=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
Definition: txmempool.cpp:1145
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:865
util::Result< setEntries > CalculateAncestorsAndCheckLimits(int64_t entry_size, size_t entry_count, CTxMemPoolEntry::Parents &staged_ancestors, const Limits &limits) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Helper function to calculate all in-mempool ancestors of staged_ancestors and apply ancestor and desc...
Definition: txmempool.cpp:157
void RemoveUnbroadcastTx(const uint256 &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:1051
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1137
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:1006
static constexpr MemPoolLimits NoLimits()
Options struct containing options for constructing a CTxMemPool.
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:294
CCoinsView backed by another CCoinsView.
Definition: coins.h:209
int64_t ancestor_count
The maximum allowed number of transactions in a package including the entry and its ancestors...
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:228
Sort by feerate of entry (fee/size) in descending order This is only used for transaction relay...
Definition: txmempool.h:132
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1102
#define LogPrintf(...)
Definition: logging.h:237
const CTxMemPool & mempool
Definition: txmempool.h:837
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:97
COutPoint prevout
Definition: transaction.h:77
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:318
CBlockIndex * maxInputBlock
Definition: mempool_entry.h:35
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
return !it visited * it
Definition: txmempool.h:806
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:638
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:894
A generic txid reference (txid or wtxid).
Definition: transaction.h:425
bool CheckPackageLimits(const Package &package, int64_t total_vsize, std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Calculate all in-mempool ancestors of a set of transactions not already in the mempool and check ance...
Definition: txmempool.cpp:199
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
Definition: feerate.h:65
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
Definition: txmempool.h:829
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:432
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:839
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs)
For each transaction being removed, update ancestors and any direct children.
Definition: txmempool.cpp:326
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:391
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)
LockPoints lp
uint256 hash
Definition: transaction.h:38