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