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