Bitcoin Core  27.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/policy.h>
16 #include <policy/settings.h>
17 #include <random.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(Txid::FromUint256(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) const
201 {
202  size_t pack_count = package.size();
203 
204  // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist
205  if (pack_count > static_cast<uint64_t>(m_limits.ancestor_count)) {
206  return util::Error{Untranslated(strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_limits.ancestor_count))};
207  } else if (pack_count > static_cast<uint64_t>(m_limits.descendant_count)) {
208  return util::Error{Untranslated(strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_limits.descendant_count))};
209  } else if (total_vsize > m_limits.ancestor_size_vbytes) {
210  return util::Error{Untranslated(strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_limits.ancestor_size_vbytes))};
211  } else if (total_vsize > m_limits.descendant_size_vbytes) {
212  return util::Error{Untranslated(strprintf("package size %u exceeds descendant size limit [limit: %u]", total_vsize, m_limits.descendant_size_vbytes))};
213  }
214 
215  CTxMemPoolEntry::Parents staged_ancestors;
216  for (const auto& tx : package) {
217  for (const auto& input : tx->vin) {
218  std::optional<txiter> piter = GetIter(input.prevout.hash);
219  if (piter) {
220  staged_ancestors.insert(**piter);
221  if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_limits.ancestor_count)) {
222  return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", m_limits.ancestor_count))};
223  }
224  }
225  }
226  }
227  // When multiple transactions are passed in, the ancestors and descendants of all transactions
228  // considered together must be within limits even if they are not interdependent. This may be
229  // stricter than the limits for each individual transaction.
230  const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(),
231  staged_ancestors, m_limits)};
232  // It's possible to overestimate the ancestor/descendant totals.
233  if (!ancestors.has_value()) return util::Error{Untranslated("possibly " + util::ErrorString(ancestors).original)};
234  return {};
235 }
236 
238  const CTxMemPoolEntry &entry,
239  const Limits& limits,
240  bool fSearchForParents /* = true */) const
241 {
242  CTxMemPoolEntry::Parents staged_ancestors;
243  const CTransaction &tx = entry.GetTx();
244 
245  if (fSearchForParents) {
246  // Get parents of this transaction that are in the mempool
247  // GetMemPoolParents() is only valid for entries in the mempool, so we
248  // iterate mapTx to find parents.
249  for (unsigned int i = 0; i < tx.vin.size(); i++) {
250  std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
251  if (piter) {
252  staged_ancestors.insert(**piter);
253  if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) {
254  return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", limits.ancestor_count))};
255  }
256  }
257  }
258  } else {
259  // If we're not searching for parents, we require this to already be an
260  // entry in the mempool and use the entry's cached parents.
261  txiter it = mapTx.iterator_to(entry);
262  staged_ancestors = it->GetMemPoolParentsConst();
263  }
264 
265  return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
266  limits);
267 }
268 
270  std::string_view calling_fn_name,
271  const CTxMemPoolEntry &entry,
272  const Limits& limits,
273  bool fSearchForParents /* = true */) const
274 {
275  auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
276  if (!Assume(result)) {
277  LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Error, "%s: CalculateMemPoolAncestors failed unexpectedly, continuing with empty ancestor set (%s)\n",
278  calling_fn_name, util::ErrorString(result).original);
279  }
280  return std::move(result).value_or(CTxMemPool::setEntries{});
281 }
282 
283 void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
284 {
285  const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
286  // add or remove this tx as a child of each parent
287  for (const CTxMemPoolEntry& parent : parents) {
288  UpdateChild(mapTx.iterator_to(parent), it, add);
289  }
290  const int32_t updateCount = (add ? 1 : -1);
291  const int32_t updateSize{updateCount * it->GetTxSize()};
292  const CAmount updateFee = updateCount * it->GetModifiedFee();
293  for (txiter ancestorIt : setAncestors) {
294  mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
295  }
296 }
297 
299 {
300  int64_t updateCount = setAncestors.size();
301  int64_t updateSize = 0;
302  CAmount updateFee = 0;
303  int64_t updateSigOpsCost = 0;
304  for (txiter ancestorIt : setAncestors) {
305  updateSize += ancestorIt->GetTxSize();
306  updateFee += ancestorIt->GetModifiedFee();
307  updateSigOpsCost += ancestorIt->GetSigOpCost();
308  }
309  mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
310 }
311 
313 {
314  const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
315  for (const CTxMemPoolEntry& updateIt : children) {
316  UpdateParent(mapTx.iterator_to(updateIt), it, false);
317  }
318 }
319 
320 void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
321 {
322  // For each entry, walk back all ancestors and decrement size associated with this
323  // transaction
324  if (updateDescendants) {
325  // updateDescendants should be true whenever we're not recursively
326  // removing a tx and all its descendants, eg when a transaction is
327  // confirmed in a block.
328  // Here we only update statistics and not data in CTxMemPool::Parents
329  // and CTxMemPoolEntry::Children (which we need to preserve until we're
330  // finished with all operations that need to traverse the mempool).
331  for (txiter removeIt : entriesToRemove) {
332  setEntries setDescendants;
333  CalculateDescendants(removeIt, setDescendants);
334  setDescendants.erase(removeIt); // don't update state for self
335  int32_t modifySize = -removeIt->GetTxSize();
336  CAmount modifyFee = -removeIt->GetModifiedFee();
337  int modifySigOps = -removeIt->GetSigOpCost();
338  for (txiter dit : setDescendants) {
339  mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); });
340  }
341  }
342  }
343  for (txiter removeIt : entriesToRemove) {
344  const CTxMemPoolEntry &entry = *removeIt;
345  // Since this is a tx that is already in the mempool, we can call CMPA
346  // with fSearchForParents = false. If the mempool is in a consistent
347  // state, then using true or false should both be correct, though false
348  // should be a bit faster.
349  // However, if we happen to be in the middle of processing a reorg, then
350  // the mempool can be in an inconsistent state. In this case, the set
351  // of ancestors reachable via GetMemPoolParents()/GetMemPoolChildren()
352  // will be the same as the set of ancestors whose packages include this
353  // transaction, because when we add a new transaction to the mempool in
354  // addUnchecked(), we assume it has no children, and in the case of a
355  // reorg where that assumption is false, the in-mempool children aren't
356  // linked to the in-block tx's until UpdateTransactionsFromBlock() is
357  // called.
358  // So if we're being called during a reorg, ie before
359  // UpdateTransactionsFromBlock() has been called, then
360  // GetMemPoolParents()/GetMemPoolChildren() will differ from the set of
361  // mempool parents we'd calculate by searching, and it's important that
362  // we use the cached notion of ancestor transactions as the set of
363  // things to update for removal.
364  auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits(), /*fSearchForParents=*/false)};
365  // Note that UpdateAncestorsOf severs the child links that point to
366  // removeIt in the entries for the parents of removeIt.
367  UpdateAncestorsOf(false, removeIt, ancestors);
368  }
369  // After updating all the ancestor sizes, we can now sever the link between each
370  // transaction being removed and any mempool children (ie, update CTxMemPoolEntry::m_parents
371  // for each direct child of a transaction being removed).
372  for (txiter removeIt : entriesToRemove) {
373  UpdateChildrenForRemoval(removeIt);
374  }
375 }
376 
377 void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
378 {
379  nSizeWithDescendants += modifySize;
382  m_count_with_descendants += modifyCount;
384 }
385 
386 void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
387 {
388  nSizeWithAncestors += modifySize;
391  m_count_with_ancestors += modifyCount;
393  nSigOpCostWithAncestors += modifySigOps;
394  assert(int(nSigOpCostWithAncestors) >= 0);
395 }
396 
398  : m_check_ratio{opts.check_ratio},
399  m_max_size_bytes{opts.max_size_bytes},
400  m_expiry{opts.expiry},
401  m_incremental_relay_feerate{opts.incremental_relay_feerate},
402  m_min_relay_feerate{opts.min_relay_feerate},
403  m_dust_relay_feerate{opts.dust_relay_feerate},
404  m_permit_bare_multisig{opts.permit_bare_multisig},
405  m_max_datacarrier_bytes{opts.max_datacarrier_bytes},
406  m_require_standard{opts.require_standard},
407  m_full_rbf{opts.full_rbf},
408  m_persist_v1_dat{opts.persist_v1_dat},
409  m_limits{opts.limits}
410 {
411 }
412 
413 bool CTxMemPool::isSpent(const COutPoint& outpoint) const
414 {
415  LOCK(cs);
416  return mapNextTx.count(outpoint);
417 }
418 
420 {
421  return nTransactionsUpdated;
422 }
423 
425 {
427 }
428 
429 void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry, setEntries &setAncestors)
430 {
431  // Add to memory pool without checking anything.
432  // Used by AcceptToMemoryPool(), which DOES do
433  // all the appropriate checks.
434  indexed_transaction_set::iterator newit = mapTx.emplace(CTxMemPoolEntry::ExplicitCopy, entry).first;
435 
436  // Update transaction for any feeDelta created by PrioritiseTransaction
437  CAmount delta{0};
438  ApplyDelta(entry.GetTx().GetHash(), delta);
439  // The following call to UpdateModifiedFee assumes no previous fee modifications
440  Assume(entry.GetFee() == entry.GetModifiedFee());
441  if (delta) {
442  mapTx.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
443  }
444 
445  // Update cachedInnerUsage to include contained transaction's usage.
446  // (When we update the entry for in-mempool parents, memory usage will be
447  // further updated.)
448  cachedInnerUsage += entry.DynamicMemoryUsage();
449 
450  const CTransaction& tx = newit->GetTx();
451  std::set<Txid> setParentTransactions;
452  for (unsigned int i = 0; i < tx.vin.size(); i++) {
453  mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
454  setParentTransactions.insert(tx.vin[i].prevout.hash);
455  }
456  // Don't bother worrying about child transactions of this one.
457  // Normal case of a new transaction arriving is that there can't be any
458  // children, because such children would be orphans.
459  // An exception to that is if a transaction enters that used to be in a block.
460  // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
461  // to clean up the mess we're leaving here.
462 
463  // Update ancestors with information about this tx
464  for (const auto& pit : GetIterSet(setParentTransactions)) {
465  UpdateParent(newit, pit, true);
466  }
467  UpdateAncestorsOf(true, newit, setAncestors);
468  UpdateEntryForAncestors(newit, setAncestors);
469 
471  totalTxSize += entry.GetTxSize();
472  m_total_fee += entry.GetFee();
473 
474  txns_randomized.emplace_back(newit->GetSharedTx());
475  newit->idx_randomized = txns_randomized.size() - 1;
476 
477  TRACE3(mempool, added,
478  entry.GetTx().GetHash().data(),
479  entry.GetTxSize(),
480  entry.GetFee()
481  );
482 }
483 
485 {
486  // We increment mempool sequence value no matter removal reason
487  // even if not directly reported below.
488  uint64_t mempool_sequence = GetAndIncrementSequence();
489 
490  if (reason != MemPoolRemovalReason::BLOCK) {
491  // Notify clients that a transaction has been removed from the mempool
492  // for any reason except being included in a block. Clients interested
493  // in transactions included in blocks can subscribe to the BlockConnected
494  // notification.
495  GetMainSignals().TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
496  }
497  TRACE5(mempool, removed,
498  it->GetTx().GetHash().data(),
499  RemovalReasonToString(reason).c_str(),
500  it->GetTxSize(),
501  it->GetFee(),
502  std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
503  );
504 
505  for (const CTxIn& txin : it->GetTx().vin)
506  mapNextTx.erase(txin.prevout);
507 
508  RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
509 
510  if (txns_randomized.size() > 1) {
511  // Update idx_randomized of the to-be-moved entry.
512  Assert(GetEntry(txns_randomized.back()->GetHash()))->idx_randomized = it->idx_randomized;
513  // Remove entry from txns_randomized by replacing it with the back and deleting the back.
514  txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
515  txns_randomized.pop_back();
516  if (txns_randomized.size() * 2 < txns_randomized.capacity())
517  txns_randomized.shrink_to_fit();
518  } else
519  txns_randomized.clear();
520 
521  totalTxSize -= it->GetTxSize();
522  m_total_fee -= it->GetFee();
523  cachedInnerUsage -= it->DynamicMemoryUsage();
524  cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
525  mapTx.erase(it);
527 }
528 
529 // Calculates descendants of entry that are not already in setDescendants, and adds to
530 // setDescendants. Assumes entryit is already a tx in the mempool and CTxMemPoolEntry::m_children
531 // is correct for tx and all descendants.
532 // Also assumes that if an entry is in setDescendants already, then all
533 // in-mempool descendants of it are already in setDescendants as well, so that we
534 // can save time by not iterating over those entries.
535 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
536 {
537  setEntries stage;
538  if (setDescendants.count(entryit) == 0) {
539  stage.insert(entryit);
540  }
541  // Traverse down the children of entry, only adding children that are not
542  // accounted for in setDescendants already (because those children have either
543  // already been walked, or will be walked in this iteration).
544  while (!stage.empty()) {
545  txiter it = *stage.begin();
546  setDescendants.insert(it);
547  stage.erase(it);
548 
549  const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
550  for (const CTxMemPoolEntry& child : children) {
551  txiter childiter = mapTx.iterator_to(child);
552  if (!setDescendants.count(childiter)) {
553  stage.insert(childiter);
554  }
555  }
556  }
557 }
558 
560 {
561  // Remove transaction from memory pool
563  setEntries txToRemove;
564  txiter origit = mapTx.find(origTx.GetHash());
565  if (origit != mapTx.end()) {
566  txToRemove.insert(origit);
567  } else {
568  // When recursively removing but origTx isn't in the mempool
569  // be sure to remove any children that are in the pool. This can
570  // happen during chain re-orgs if origTx isn't re-accepted into
571  // the mempool for any reason.
572  for (unsigned int i = 0; i < origTx.vout.size(); i++) {
573  auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
574  if (it == mapNextTx.end())
575  continue;
576  txiter nextit = mapTx.find(it->second->GetHash());
577  assert(nextit != mapTx.end());
578  txToRemove.insert(nextit);
579  }
580  }
581  setEntries setAllRemoves;
582  for (txiter it : txToRemove) {
583  CalculateDescendants(it, setAllRemoves);
584  }
585 
586  RemoveStaged(setAllRemoves, false, reason);
587 }
588 
589 void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
590 {
591  // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
594 
595  setEntries txToRemove;
596  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
597  if (check_final_and_mature(it)) txToRemove.insert(it);
598  }
599  setEntries setAllRemoves;
600  for (txiter it : txToRemove) {
601  CalculateDescendants(it, setAllRemoves);
602  }
603  RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
604  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
605  assert(TestLockPointValidity(chain, it->GetLockPoints()));
606  }
607 }
608 
610 {
611  // Remove transactions which depend on inputs of tx, recursively
613  for (const CTxIn &txin : tx.vin) {
614  auto it = mapNextTx.find(txin.prevout);
615  if (it != mapNextTx.end()) {
616  const CTransaction &txConflict = *it->second;
617  if (txConflict != tx)
618  {
619  ClearPrioritisation(txConflict.GetHash());
621  }
622  }
623  }
624 }
625 
629 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
630 {
632  std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
633  txs_removed_for_block.reserve(vtx.size());
634  for (const auto& tx : vtx)
635  {
636  txiter it = mapTx.find(tx->GetHash());
637  if (it != mapTx.end()) {
638  setEntries stage;
639  stage.insert(it);
640  txs_removed_for_block.emplace_back(*it);
642  }
643  removeConflicts(*tx);
645  }
646  GetMainSignals().MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
647  lastRollingFeeUpdate = GetTime();
648  blockSinceLastRollingFeeBump = true;
649 }
650 
651 void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
652 {
653  if (m_check_ratio == 0) return;
654 
655  if (GetRand(m_check_ratio) >= 1) return;
656 
658  LOCK(cs);
659  LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
660 
661  uint64_t checkTotal = 0;
662  CAmount check_total_fee{0};
663  uint64_t innerUsage = 0;
664  uint64_t prev_ancestor_count{0};
665 
666  CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
667 
668  for (const auto& it : GetSortedDepthAndScore()) {
669  checkTotal += it->GetTxSize();
670  check_total_fee += it->GetFee();
671  innerUsage += it->DynamicMemoryUsage();
672  const CTransaction& tx = it->GetTx();
673  innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
674  CTxMemPoolEntry::Parents setParentCheck;
675  for (const CTxIn &txin : tx.vin) {
676  // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
677  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
678  if (it2 != mapTx.end()) {
679  const CTransaction& tx2 = it2->GetTx();
680  assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
681  setParentCheck.insert(*it2);
682  }
683  // We are iterating through the mempool entries sorted in order by ancestor count.
684  // All parents must have been checked before their children and their coins added to
685  // the mempoolDuplicate coins cache.
686  assert(mempoolDuplicate.HaveCoin(txin.prevout));
687  // Check whether its inputs are marked in mapNextTx.
688  auto it3 = mapNextTx.find(txin.prevout);
689  assert(it3 != mapNextTx.end());
690  assert(it3->first == &txin.prevout);
691  assert(it3->second == &tx);
692  }
693  auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
694  return a.GetTx().GetHash() == b.GetTx().GetHash();
695  };
696  assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
697  assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
698  // Verify ancestor state is correct.
699  auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
700  uint64_t nCountCheck = ancestors.size() + 1;
701  int32_t nSizeCheck = it->GetTxSize();
702  CAmount nFeesCheck = it->GetModifiedFee();
703  int64_t nSigOpCheck = it->GetSigOpCost();
704 
705  for (txiter ancestorIt : ancestors) {
706  nSizeCheck += ancestorIt->GetTxSize();
707  nFeesCheck += ancestorIt->GetModifiedFee();
708  nSigOpCheck += ancestorIt->GetSigOpCost();
709  }
710 
711  assert(it->GetCountWithAncestors() == nCountCheck);
712  assert(it->GetSizeWithAncestors() == nSizeCheck);
713  assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
714  assert(it->GetModFeesWithAncestors() == nFeesCheck);
715  // Sanity check: we are walking in ascending ancestor count order.
716  assert(prev_ancestor_count <= it->GetCountWithAncestors());
717  prev_ancestor_count = it->GetCountWithAncestors();
718 
719  // Check children against mapNextTx
720  CTxMemPoolEntry::Children setChildrenCheck;
721  auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
722  int32_t child_sizes{0};
723  for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
724  txiter childit = mapTx.find(iter->second->GetHash());
725  assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
726  if (setChildrenCheck.insert(*childit).second) {
727  child_sizes += childit->GetTxSize();
728  }
729  }
730  assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
731  assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), it->GetMemPoolChildrenConst().begin(), comp));
732  // Also check to make sure size is greater than sum with immediate children.
733  // just a sanity check, not definitive that this calc is correct...
734  assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
735 
736  TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
737  CAmount txfee = 0;
738  assert(!tx.IsCoinBase());
739  assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
740  for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
741  AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
742  }
743  for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
744  uint256 hash = it->second->GetHash();
745  indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
746  const CTransaction& tx = it2->GetTx();
747  assert(it2 != mapTx.end());
748  assert(&tx == it->second);
749  }
750 
751  assert(totalTxSize == checkTotal);
752  assert(m_total_fee == check_total_fee);
753  assert(innerUsage == cachedInnerUsage);
754 }
755 
756 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid)
757 {
758  /* Return `true` if hasha should be considered sooner than hashb. Namely when:
759  * a is not in the mempool, but b is
760  * both are in the mempool and a has fewer ancestors than b
761  * both are in the mempool and a has a higher score than b
762  */
763  LOCK(cs);
764  indexed_transaction_set::const_iterator j = wtxid ? get_iter_from_wtxid(hashb) : mapTx.find(hashb);
765  if (j == mapTx.end()) return false;
766  indexed_transaction_set::const_iterator i = wtxid ? get_iter_from_wtxid(hasha) : mapTx.find(hasha);
767  if (i == mapTx.end()) return true;
768  uint64_t counta = i->GetCountWithAncestors();
769  uint64_t countb = j->GetCountWithAncestors();
770  if (counta == countb) {
771  return CompareTxMemPoolEntryByScore()(*i, *j);
772  }
773  return counta < countb;
774 }
775 
776 namespace {
777 class DepthAndScoreComparator
778 {
779 public:
780  bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
781  {
782  uint64_t counta = a->GetCountWithAncestors();
783  uint64_t countb = b->GetCountWithAncestors();
784  if (counta == countb) {
785  return CompareTxMemPoolEntryByScore()(*a, *b);
786  }
787  return counta < countb;
788  }
789 };
790 } // namespace
791 
792 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
793 {
794  std::vector<indexed_transaction_set::const_iterator> iters;
796 
797  iters.reserve(mapTx.size());
798 
799  for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
800  iters.push_back(mi);
801  }
802  std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
803  return iters;
804 }
805 
806 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
807  return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
808 }
809 
810 std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
811 {
813 
814  std::vector<CTxMemPoolEntryRef> ret;
815  ret.reserve(mapTx.size());
816  for (const auto& it : GetSortedDepthAndScore()) {
817  ret.emplace_back(*it);
818  }
819  return ret;
820 }
821 
822 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
823 {
824  LOCK(cs);
825  auto iters = GetSortedDepthAndScore();
826 
827  std::vector<TxMempoolInfo> ret;
828  ret.reserve(mapTx.size());
829  for (auto it : iters) {
830  ret.push_back(GetInfo(it));
831  }
832 
833  return ret;
834 }
835 
836 const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
837 {
839  const auto i = mapTx.find(txid);
840  return i == mapTx.end() ? nullptr : &(*i);
841 }
842 
844 {
845  LOCK(cs);
846  indexed_transaction_set::const_iterator i = mapTx.find(hash);
847  if (i == mapTx.end())
848  return nullptr;
849  return i->GetSharedTx();
850 }
851 
853 {
854  LOCK(cs);
855  indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
856  if (i == mapTx.end())
857  return TxMempoolInfo();
858  return GetInfo(i);
859 }
860 
861 TxMempoolInfo CTxMemPool::info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const
862 {
863  LOCK(cs);
864  indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
865  if (i != mapTx.end() && i->GetSequence() < last_sequence) {
866  return GetInfo(i);
867  } else {
868  return TxMempoolInfo();
869  }
870 }
871 
872 void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
873 {
874  {
875  LOCK(cs);
876  CAmount &delta = mapDeltas[hash];
877  delta = SaturatingAdd(delta, nFeeDelta);
878  txiter it = mapTx.find(hash);
879  if (it != mapTx.end()) {
880  mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
881  // Now update all ancestors' modified fees with descendants
882  auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
883  for (txiter ancestorIt : ancestors) {
884  mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
885  }
886  // Now update all descendants' modified fees with ancestors
887  setEntries setDescendants;
888  CalculateDescendants(it, setDescendants);
889  setDescendants.erase(it);
890  for (txiter descendantIt : setDescendants) {
891  mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
892  }
894  }
895  if (delta == 0) {
896  mapDeltas.erase(hash);
897  LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
898  } else {
899  LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
900  hash.ToString(),
901  it == mapTx.end() ? "not " : "",
902  FormatMoney(nFeeDelta),
903  FormatMoney(delta));
904  }
905  }
906 }
907 
908 void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
909 {
911  std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
912  if (pos == mapDeltas.end())
913  return;
914  const CAmount &delta = pos->second;
915  nFeeDelta += delta;
916 }
917 
919 {
921  mapDeltas.erase(hash);
922 }
923 
924 std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
925 {
927  LOCK(cs);
928  std::vector<delta_info> result;
929  result.reserve(mapDeltas.size());
930  for (const auto& [txid, delta] : mapDeltas) {
931  const auto iter{mapTx.find(txid)};
932  const bool in_mempool{iter != mapTx.end()};
933  std::optional<CAmount> modified_fee;
934  if (in_mempool) modified_fee = iter->GetModifiedFee();
935  result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
936  }
937  return result;
938 }
939 
941 {
942  const auto it = mapNextTx.find(prevout);
943  return it == mapNextTx.end() ? nullptr : it->second;
944 }
945 
946 std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const uint256& txid) const
947 {
948  auto it = mapTx.find(txid);
949  if (it != mapTx.end()) return it;
950  return std::nullopt;
951 }
952 
953 CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
954 {
956  for (const auto& h : hashes) {
957  const auto mi = GetIter(h);
958  if (mi) ret.insert(*mi);
959  }
960  return ret;
961 }
962 
963 std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<uint256>& txids) const
964 {
966  std::vector<txiter> ret;
967  ret.reserve(txids.size());
968  for (const auto& txid : txids) {
969  const auto it{GetIter(txid)};
970  if (!it) return {};
971  ret.push_back(*it);
972  }
973  return ret;
974 }
975 
977 {
978  for (unsigned int i = 0; i < tx.vin.size(); i++)
979  if (exists(GenTxid::Txid(tx.vin[i].prevout.hash)))
980  return false;
981  return true;
982 }
983 
984 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
985 
986 bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
987  // Check to see if the inputs are made available by another tx in the package.
988  // These Coins would not be available in the underlying CoinsView.
989  if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
990  coin = it->second;
991  return true;
992  }
993 
994  // If an entry in the mempool exists, always return that one, as it's guaranteed to never
995  // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
996  // transactions. First checking the underlying cache risks returning a pruned entry instead.
997  CTransactionRef ptx = mempool.get(outpoint.hash);
998  if (ptx) {
999  if (outpoint.n < ptx->vout.size()) {
1000  coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
1001  m_non_base_coins.emplace(outpoint);
1002  return true;
1003  } else {
1004  return false;
1005  }
1006  }
1007  return base->GetCoin(outpoint, coin);
1008 }
1009 
1011 {
1012  for (unsigned int n = 0; n < tx->vout.size(); ++n) {
1013  m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
1014  m_non_base_coins.emplace(tx->GetHash(), n);
1015  }
1016 }
1018 {
1019  m_temp_added.clear();
1020  m_non_base_coins.clear();
1021 }
1022 
1024  LOCK(cs);
1025  // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1026  return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
1027 }
1028 
1029 void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) {
1030  LOCK(cs);
1031 
1032  if (m_unbroadcast_txids.erase(txid))
1033  {
1034  LogPrint(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
1035  }
1036 }
1037 
1038 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1039  AssertLockHeld(cs);
1040  UpdateForRemoveFromMempool(stage, updateDescendants);
1041  for (txiter it : stage) {
1042  removeUnchecked(it, reason);
1043  }
1044 }
1045 
1046 int CTxMemPool::Expire(std::chrono::seconds time)
1047 {
1048  AssertLockHeld(cs);
1049  indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1050  setEntries toremove;
1051  while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1052  toremove.insert(mapTx.project<0>(it));
1053  it++;
1054  }
1055  setEntries stage;
1056  for (txiter removeit : toremove) {
1057  CalculateDescendants(removeit, stage);
1058  }
1060  return stage.size();
1061 }
1062 
1063 void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry)
1064 {
1065  auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits())};
1066  return addUnchecked(entry, ancestors);
1067 }
1068 
1069 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1070 {
1071  AssertLockHeld(cs);
1073  if (add && entry->GetMemPoolChildren().insert(*child).second) {
1074  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1075  } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
1076  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1077  }
1078 }
1079 
1080 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1081 {
1082  AssertLockHeld(cs);
1084  if (add && entry->GetMemPoolParents().insert(*parent).second) {
1085  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1086  } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
1087  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1088  }
1089 }
1090 
1091 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1092  LOCK(cs);
1093  if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1094  return CFeeRate(llround(rollingMinimumFeeRate));
1095 
1096  int64_t time = GetTime();
1097  if (time > lastRollingFeeUpdate + 10) {
1098  double halflife = ROLLING_FEE_HALFLIFE;
1099  if (DynamicMemoryUsage() < sizelimit / 4)
1100  halflife /= 4;
1101  else if (DynamicMemoryUsage() < sizelimit / 2)
1102  halflife /= 2;
1103 
1104  rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1105  lastRollingFeeUpdate = time;
1106 
1107  if (rollingMinimumFeeRate < (double)m_incremental_relay_feerate.GetFeePerK() / 2) {
1108  rollingMinimumFeeRate = 0;
1109  return CFeeRate(0);
1110  }
1111  }
1112  return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_incremental_relay_feerate);
1113 }
1114 
1116  AssertLockHeld(cs);
1117  if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1118  rollingMinimumFeeRate = rate.GetFeePerK();
1119  blockSinceLastRollingFeeBump = false;
1120  }
1121 }
1122 
1123 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1124  AssertLockHeld(cs);
1125 
1126  unsigned nTxnRemoved = 0;
1127  CFeeRate maxFeeRateRemoved(0);
1128  while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1129  indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1130 
1131  // We set the new mempool min fee to the feerate of the removed set, plus the
1132  // "minimum reasonable fee rate" (ie some value under which we consider txn
1133  // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1134  // equal to txn which were removed with no block in between.
1135  CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1136  removed += m_incremental_relay_feerate;
1137  trackPackageRemoved(removed);
1138  maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1139 
1140  setEntries stage;
1141  CalculateDescendants(mapTx.project<0>(it), stage);
1142  nTxnRemoved += stage.size();
1143 
1144  std::vector<CTransaction> txn;
1145  if (pvNoSpendsRemaining) {
1146  txn.reserve(stage.size());
1147  for (txiter iter : stage)
1148  txn.push_back(iter->GetTx());
1149  }
1151  if (pvNoSpendsRemaining) {
1152  for (const CTransaction& tx : txn) {
1153  for (const CTxIn& txin : tx.vin) {
1154  if (exists(GenTxid::Txid(txin.prevout.hash))) continue;
1155  pvNoSpendsRemaining->push_back(txin.prevout);
1156  }
1157  }
1158  }
1159  }
1160 
1161  if (maxFeeRateRemoved > CFeeRate(0)) {
1162  LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1163  }
1164 }
1165 
1167  // find parent with highest descendant count
1168  std::vector<txiter> candidates;
1169  setEntries counted;
1170  candidates.push_back(entry);
1171  uint64_t maximum = 0;
1172  while (candidates.size()) {
1173  txiter candidate = candidates.back();
1174  candidates.pop_back();
1175  if (!counted.insert(candidate).second) continue;
1176  const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst();
1177  if (parents.size() == 0) {
1178  maximum = std::max(maximum, candidate->GetCountWithDescendants());
1179  } else {
1180  for (const CTxMemPoolEntry& i : parents) {
1181  candidates.push_back(mapTx.iterator_to(i));
1182  }
1183  }
1184  }
1185  return maximum;
1186 }
1187 
1188 void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
1189  LOCK(cs);
1190  auto it = mapTx.find(txid);
1191  ancestors = descendants = 0;
1192  if (it != mapTx.end()) {
1193  ancestors = it->GetCountWithAncestors();
1194  if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
1195  if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
1196  descendants = CalculateDescendantMaximum(it);
1197  }
1198 }
1199 
1201 {
1202  LOCK(cs);
1203  return m_load_tried;
1204 }
1205 
1206 void CTxMemPool::SetLoadTried(bool load_tried)
1207 {
1208  LOCK(cs);
1209  m_load_tried = load_tried;
1210 }
1211 
1212 std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<uint256>& txids) const
1213 {
1214  AssertLockHeld(cs);
1215  std::vector<txiter> clustered_txs{GetIterVec(txids)};
1216  // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not
1217  // necessarily mean the entry has been processed.
1219  for (const auto& it : clustered_txs) {
1220  visited(it);
1221  }
1222  // i = index of where the list of entries to process starts
1223  for (size_t i{0}; i < clustered_txs.size(); ++i) {
1224  // DoS protection: if there are 500 or more entries to process, just quit.
1225  if (clustered_txs.size() > 500) return {};
1226  const txiter& tx_iter = clustered_txs.at(i);
1227  for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
1228  for (const CTxMemPoolEntry& entry : entries) {
1229  const auto entry_it = mapTx.iterator_to(entry);
1230  if (!visited(entry_it)) {
1231  clustered_txs.push_back(entry_it);
1232  }
1233  }
1234  }
1235  }
1236  return clustered_txs;
1237 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
void UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
Definition: txmempool.cpp:377
Information about a mempool transaction.
Definition: txmempool.h:208
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:963
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:833
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:99
std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
void UpdateModifiedFee(CAmount fee_diff)
AssertLockHeld(pool.cs)
#define LogPrint(category,...)
Definition: logging.h:264
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:391
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:12
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:822
int32_t GetTxSize() const
A UTXO entry.
Definition: coins.h:31
bool exists(const GenTxid &gtxid) const
Definition: txmempool.h:674
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:446
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:535
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:1023
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
GetCoin, returning whether it exists and is not spent.
Definition: txmempool.cpp:986
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:50
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:609
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1038
Removed for conflict with in-block transaction.
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb, bool wtxid=false)
Definition: txmempool.cpp:756
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:394
const Children & GetMemPoolChildrenConst() const
CTxMemPool(const Options &opts)
Create a new CTxMemPool.
Definition: txmempool.cpp:397
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:303
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:559
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:1206
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.h:623
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:269
CAmount GetModifiedFee() const
#define WITH_FRESH_EPOCH(epoch)
Definition: epochguard.h:100
bool IsCoinBase() const
Definition: transaction.h:356
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:237
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:413
static constexpr ExplicitCopyTag ExplicitCopy
const std::vector< CTxIn > vin
Definition: transaction.h:306
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:589
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:1212
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
const int m_check_ratio
Value n means that 1 times in n we check.
Definition: txmempool.h:302
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:283
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:81
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:117
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:806
int64_t m_count_with_descendants
number of descendant transactions
Definition: mempool_entry.h:96
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:1046
An input of a transaction.
Definition: transaction.h:66
void MempoolTransactionsRemovedForBlock(const std::vector< RemovedMempoolTransactionInfo > &, unsigned int nBlockHeight)
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:257
CCoinsView * base
Definition: coins.h:212
const CAmount & GetFee() const
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:477
Txid hash
Definition: transaction.h:31
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:484
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:39
uint32_t n
Definition: transaction.h:32
const std::vector< CTxOut > vout
Definition: transaction.h:307
Removed in size limiting.
const Limits m_limits
Definition: txmempool.h:448
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:924
CMainSignals & GetMainSignals()
#define LogPrintLevel(category, level,...)
Definition: logging.h:252
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:327
CAmount nModFeesWithAncestors
std::string ToString() const
Definition: uint256.cpp:55
constexpr const std::byte * data() const
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:940
int64_t m_count_with_ancestors
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:424
void ApplyDelta(const uint256 &hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:908
#define Assume(val)
Assume is the identity function.
Definition: check.h:89
const CFeeRate m_incremental_relay_feerate
Definition: txmempool.h:439
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:37
bool IsWtxid() const
Definition: transaction.h:436
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1166
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:1200
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:861
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void addUnchecked(const CTxMemPoolEntry &entry) 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:472
std::optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:946
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void cs_main
Definition: txmempool.h:472
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
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:836
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:728
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:792
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:299
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:976
#define TRACE3(context, event, a, b, c)
Definition: trace.h:35
void UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
Definition: txmempool.cpp:386
void Reset()
Clear m_temp_added and m_non_base_coins.
Definition: txmempool.cpp:1017
int64_t nSizeWithDescendants
... and size
Definition: mempool_entry.h:98
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
Definition: txmempool.h:400
Removed for block.
static transaction_identifier FromUint256(const uint256 &id)
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:298
bool m_epoch
Definition: txmempool.h:797
TxMempoolInfo info(const GenTxid &gtxid) const
Definition: txmempool.cpp:852
txiter get_iter_from_wtxid(const uint256 &wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:686
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1069
void ClearPrioritisation(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:918
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:1188
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:147
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:419
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:1010
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:1123
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:843
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:1029
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1115
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:984
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:295
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:1080
#define LogPrintf(...)
Definition: logging.h:245
const CTxMemPool & mempool
Definition: txmempool.h:835
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:97
COutPoint prevout
Definition: transaction.h:69
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:312
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:804
util::Result< void > CheckPackageLimits(const Package &package, int64_t total_vsize) 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
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:629
setEntries GetIterSet(const std::set< Txid > &hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of hashes into a set of pool iterators to avoid repeated lookups. ...
Definition: txmempool.cpp:953
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:872
A generic txid reference (txid or wtxid).
Definition: transaction.h:427
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:827
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:434
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:810
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:320
const uint256 & GetHash() const LIFETIMEBOUND
Definition: transaction.h:437
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:388
#define Assert(val)
Identity function.
Definition: check.h:77
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
LockPoints lp