Bitcoin ABC  0.24.11
P2P Digital Currency
txmempool.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 <chainparams.h> // for GetConsensus.
10 #include <clientversion.h>
11 #include <config.h>
12 #include <consensus/consensus.h>
13 #include <consensus/tx_verify.h>
14 #include <consensus/validation.h>
15 #include <policy/fees.h>
16 #include <policy/policy.h>
17 #include <policy/settings.h>
18 #include <reverse_iterator.h>
19 #include <util/moneystr.h>
20 #include <util/system.h>
21 #include <util/time.h>
22 #include <validation.h>
23 #include <validationinterface.h>
24 #include <version.h>
25 
26 #include <algorithm>
27 
29  int64_t _nTime, unsigned int _entryHeight,
30  bool _spendsCoinbase, int64_t _sigOpsCount,
31  LockPoints lp)
32  : tx(_tx), nFee(_nFee), nTxSize(tx->GetTotalSize()),
33  nUsageSize(RecursiveDynamicUsage(tx)), nTime(_nTime),
34  entryHeight(_entryHeight), spendsCoinbase(_spendsCoinbase),
35  sigOpCount(_sigOpsCount), lockPoints(lp), m_epoch(0) {
40 
42 
47 }
48 
51 }
52 
54  // note this is distinct from the sum of descendants' individual virtual
55  // sizes, and may be smaller.
58 }
59 
61  // note this is distinct from the sum of ancestors' individual virtual
62  // sizes, and may be smaller.
65 }
66 
68  nModFeesWithDescendants += newFeeDelta - feeDelta;
69  nModFeesWithAncestors += newFeeDelta - feeDelta;
70  feeDelta = newFeeDelta;
71 }
72 
74  lockPoints = lp;
75 }
76 
77 // Update the given tx for any in-mempool descendants.
78 // Assumes that CTxMemPool::m_children is correct for the given tx and all
79 // descendants.
81  cacheMap &cachedDescendants,
82  const std::set<TxId> &setExclude) {
83  CTxMemPoolEntry::Children stageEntries, descendants;
84  stageEntries = updateIt->GetMemPoolChildrenConst();
85 
86  while (!stageEntries.empty()) {
87  const CTxMemPoolEntry &descendant = *stageEntries.begin();
88  descendants.insert(descendant);
89  stageEntries.erase(descendant);
90  const CTxMemPoolEntry::Children &children =
91  descendant.GetMemPoolChildrenConst();
92  for (const CTxMemPoolEntry &childEntry : children) {
93  cacheMap::iterator cacheIt =
94  cachedDescendants.find(mapTx.iterator_to(childEntry));
95  if (cacheIt != cachedDescendants.end()) {
96  // We've already calculated this one, just add the entries for
97  // this set but don't traverse again.
98  for (txiter cacheEntry : cacheIt->second) {
99  descendants.insert(*cacheEntry);
100  }
101  } else if (!descendants.count(childEntry)) {
102  // Schedule for later processing
103  stageEntries.insert(childEntry);
104  }
105  }
106  }
107  // descendants now contains all in-mempool descendants of updateIt.
108  // Update and add to cached descendant map
109  int64_t modifySize = 0;
110  int64_t modifyCount = 0;
111  Amount modifyFee = Amount::zero();
112  int64_t modifySigOpCount = 0;
113  for (const CTxMemPoolEntry &descendant : descendants) {
114  if (!setExclude.count(descendant.GetTx().GetId())) {
115  modifySize += descendant.GetTxSize();
116  modifyFee += descendant.GetModifiedFee();
117  modifyCount++;
118  modifySigOpCount += descendant.GetSigOpCount();
119  cachedDescendants[updateIt].insert(mapTx.iterator_to(descendant));
120  // Update ancestor state for each descendant
121  mapTx.modify(mapTx.iterator_to(descendant),
122  update_ancestor_state(updateIt->GetTxSize(),
123  updateIt->GetModifiedFee(), 1,
124  updateIt->GetSigOpCount()));
125  }
126  }
127  mapTx.modify(updateIt,
128  update_descendant_state(modifySize, modifyFee, modifyCount,
129  modifySigOpCount));
130 }
131 
132 // txidsToUpdate is the set of transaction hashes from a disconnected block
133 // which has been re-added to the mempool. For each entry, look for descendants
134 // that are outside txidsToUpdate, and add fee/size information for such
135 // descendants to the parent. For each such descendant, also update the ancestor
136 // state to include the parent.
138  const std::vector<TxId> &txidsToUpdate) {
140  // For each entry in txidsToUpdate, store the set of in-mempool, but not
141  // in-txidsToUpdate transactions, so that we don't have to recalculate
142  // descendants when we come across a previously seen entry.
143  cacheMap mapMemPoolDescendantsToUpdate;
144 
145  // Use a set for lookups into txidsToUpdate (these entries are already
146  // accounted for in the state of their ancestors)
147  std::set<TxId> setAlreadyIncluded(txidsToUpdate.begin(),
148  txidsToUpdate.end());
149 
150  // Iterate in reverse, so that whenever we are looking at a transaction
151  // we are sure that all in-mempool descendants have already been processed.
152  // This maximizes the benefit of the descendant cache and guarantees that
153  // CTxMemPool::m_children will be updated, an assumption made in
154  // UpdateForDescendants.
155  for (const TxId &txid : reverse_iterate(txidsToUpdate)) {
156  // calculate children from mapNextTx
157  txiter it = mapTx.find(txid);
158  if (it == mapTx.end()) {
159  continue;
160  }
161 
162  auto iter = mapNextTx.lower_bound(COutPoint(txid, 0));
163  // First calculate the children, and update CTxMemPool::m_children to
164  // include them, and update their CTxMemPoolEntry::m_parents to include
165  // this tx. we cache the in-mempool children to avoid duplicate updates
166  {
167  const auto epoch = GetFreshEpoch();
168  for (; iter != mapNextTx.end() && iter->first->GetTxId() == txid;
169  ++iter) {
170  const TxId &childTxId = iter->second->GetId();
171  txiter childIter = mapTx.find(childTxId);
172  assert(childIter != mapTx.end());
173  // We can skip updating entries we've encountered before or that
174  // are in the block (which are already accounted for).
175  if (!visited(childIter) &&
176  !setAlreadyIncluded.count(childTxId)) {
177  UpdateChild(it, childIter, true);
178  UpdateParent(childIter, it, true);
179  }
180  }
181  } // release epoch guard for UpdateForDescendants
182  UpdateForDescendants(it, mapMemPoolDescendantsToUpdate,
183  setAlreadyIncluded);
184  }
185 }
186 
188  const CTxMemPoolEntry &entry, setEntries &setAncestors,
189  uint64_t limitAncestorCount, uint64_t limitAncestorSize,
190  uint64_t limitDescendantCount, uint64_t limitDescendantSize,
191  std::string &errString, bool fSearchForParents /* = true */) const {
192  CTxMemPoolEntry::Parents staged_ancestors;
193  const CTransaction &tx = entry.GetTx();
194 
195  if (fSearchForParents) {
196  // Get parents of this transaction that are in the mempool
197  // GetMemPoolParents() is only valid for entries in the mempool, so we
198  // iterate mapTx to find parents.
199  for (const CTxIn &in : tx.vin) {
200  std::optional<txiter> piter = GetIter(in.prevout.GetTxId());
201  if (!piter) {
202  continue;
203  }
204  staged_ancestors.insert(**piter);
205  if (staged_ancestors.size() + 1 > limitAncestorCount) {
206  errString =
207  strprintf("too many unconfirmed parents [limit: %u]",
208  limitAncestorCount);
209  return false;
210  }
211  }
212  } else {
213  // If we're not searching for parents, we require this to be an entry in
214  // the mempool already.
215  txiter it = mapTx.iterator_to(entry);
216  staged_ancestors = it->GetMemPoolParentsConst();
217  }
218 
219  size_t totalSizeWithAncestors = entry.GetTxSize();
220 
221  while (!staged_ancestors.empty()) {
222  const CTxMemPoolEntry &stage = staged_ancestors.begin()->get();
223  txiter stageit = mapTx.iterator_to(stage);
224 
225  setAncestors.insert(stageit);
226  staged_ancestors.erase(stage);
227  totalSizeWithAncestors += stageit->GetTxSize();
228 
229  if (stageit->GetSizeWithDescendants() + entry.GetTxSize() >
230  limitDescendantSize) {
231  errString = strprintf(
232  "exceeds descendant size limit for tx %s [limit: %u]",
233  stageit->GetTx().GetId().ToString(), limitDescendantSize);
234  return false;
235  }
236 
237  if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {
238  errString = strprintf("too many descendants for tx %s [limit: %u]",
239  stageit->GetTx().GetId().ToString(),
240  limitDescendantCount);
241  return false;
242  }
243 
244  if (totalSizeWithAncestors > limitAncestorSize) {
245  errString = strprintf("exceeds ancestor size limit [limit: %u]",
246  limitAncestorSize);
247  return false;
248  }
249 
250  const CTxMemPoolEntry::Parents &parents =
251  stageit->GetMemPoolParentsConst();
252  for (const CTxMemPoolEntry &parent : parents) {
253  txiter parent_it = mapTx.iterator_to(parent);
254 
255  // If this is a new ancestor, add it.
256  if (setAncestors.count(parent_it) == 0) {
257  staged_ancestors.insert(parent);
258  }
259  if (staged_ancestors.size() + setAncestors.size() + 1 >
260  limitAncestorCount) {
261  errString =
262  strprintf("too many unconfirmed ancestors [limit: %u]",
263  limitAncestorCount);
264  return false;
265  }
266  }
267  }
268 
269  return true;
270 }
271 
273  setEntries &setAncestors) {
274  CTxMemPoolEntry::Parents parents = it->GetMemPoolParents();
275  // add or remove this tx as a child of each parent
276  for (const CTxMemPoolEntry &parent : parents) {
277  UpdateChild(mapTx.iterator_to(parent), it, add);
278  }
279  const int64_t updateCount = (add ? 1 : -1);
280  const int64_t updateSize = updateCount * it->GetTxSize();
281  const int64_t updateSigOpCount = updateCount * it->GetSigOpCount();
282  const Amount updateFee = updateCount * it->GetModifiedFee();
283  for (txiter ancestorIt : setAncestors) {
284  mapTx.modify(ancestorIt,
285  update_descendant_state(updateSize, updateFee, updateCount,
286  updateSigOpCount));
287  }
288 }
289 
291  const setEntries &setAncestors) {
292  int64_t updateCount = setAncestors.size();
293  int64_t updateSize = 0;
294  int64_t updateSigOpsCount = 0;
295  Amount updateFee = Amount::zero();
296 
297  for (txiter ancestorIt : setAncestors) {
298  updateSize += ancestorIt->GetTxSize();
299  updateFee += ancestorIt->GetModifiedFee();
300  updateSigOpsCount += ancestorIt->GetSigOpCount();
301  }
302  mapTx.modify(it, update_ancestor_state(updateSize, updateFee, updateCount,
303  updateSigOpsCount));
304 }
305 
307  const CTxMemPoolEntry::Children &children = it->GetMemPoolChildrenConst();
308  for (const CTxMemPoolEntry &updateIt : children) {
309  UpdateParent(mapTx.iterator_to(updateIt), it, false);
310  }
311 }
312 
314  bool updateDescendants) {
315  // For each entry, walk back all ancestors and decrement size associated
316  // with this transaction.
317  const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
318  if (updateDescendants) {
319  // updateDescendants should be true whenever we're not recursively
320  // removing a tx and all its descendants, eg when a transaction is
321  // confirmed in a block.
322  // Here we only update statistics and not data in CTxMemPool::Parents
323  // and CTxMemPoolEntry::Children (which we need to preserve until we're
324  // finished with all operations that need to traverse the mempool).
325  for (txiter removeIt : entriesToRemove) {
326  setEntries setDescendants;
327  CalculateDescendants(removeIt, setDescendants);
328  setDescendants.erase(removeIt); // don't update state for self
329  int64_t modifySize = -int64_t(removeIt->GetTxSize());
330  Amount modifyFee = -1 * removeIt->GetModifiedFee();
331  int modifySigOps = -removeIt->GetSigOpCount();
332  for (txiter dit : setDescendants) {
333  mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee,
334  -1, modifySigOps));
335  }
336  }
337  }
338 
339  for (txiter removeIt : entriesToRemove) {
340  setEntries setAncestors;
341  const CTxMemPoolEntry &entry = *removeIt;
342  std::string dummy;
343  // Since this is a tx that is already in the mempool, we can call CMPA
344  // with fSearchForParents = false. If the mempool is in a consistent
345  // state, then using true or false should both be correct, though false
346  // should be a bit faster.
347  // However, if we happen to be in the middle of processing a reorg, then
348  // the mempool can be in an inconsistent state. In this case, the set
349  // of ancestors reachable via GetMemPoolParents()/GetMemPoolChildren()
350  // will be the same as the set of ancestors whose packages include this
351  // transaction, because when we add a new transaction to the mempool in
352  // addUnchecked(), we assume it has no children, and in the case of a
353  // reorg where that assumption is false, the in-mempool children aren't
354  // linked to the in-block tx's until UpdateTransactionsFromBlock() is
355  // called.
356  // So if we're being called during a reorg, ie before
357  // UpdateTransactionsFromBlock() has been called, then
358  // GetMemPoolParents()/GetMemPoolChildren() will differ from the set of
359  // mempool parents we'd calculate by searching, and it's important that
360  // we use the cached notion of ancestor transactions as the set of
361  // things to update for removal.
362  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit,
363  nNoLimit, nNoLimit, dummy, false);
364  // Note that UpdateAncestorsOf severs the child links that point to
365  // removeIt in the entries for the parents of removeIt.
366  UpdateAncestorsOf(false, removeIt, setAncestors);
367  }
368  // After updating all the ancestor sizes, we can now sever the link between
369  // each transaction being removed and any mempool children (ie, update
370  // CTxMemPoolEntry::m_parents for each direct child of a transaction being
371  // removed).
372  for (txiter removeIt : entriesToRemove) {
373  UpdateChildrenForRemoval(removeIt);
374  }
375 }
376 
378  Amount modifyFee,
379  int64_t modifyCount,
380  int64_t modifySigOpCount) {
381  nSizeWithDescendants += modifySize;
382  assert(int64_t(nSizeWithDescendants) > 0);
383  nModFeesWithDescendants += modifyFee;
384  nCountWithDescendants += modifyCount;
385  assert(int64_t(nCountWithDescendants) > 0);
386  nSigOpCountWithDescendants += modifySigOpCount;
387  assert(int64_t(nSigOpCountWithDescendants) >= 0);
388 }
389 
390 void CTxMemPoolEntry::UpdateAncestorState(int64_t modifySize, Amount modifyFee,
391  int64_t modifyCount,
392  int64_t modifySigOps) {
393  nSizeWithAncestors += modifySize;
394  assert(int64_t(nSizeWithAncestors) > 0);
395  nModFeesWithAncestors += modifyFee;
396  nCountWithAncestors += modifyCount;
397  assert(int64_t(nCountWithAncestors) > 0);
398  nSigOpCountWithAncestors += modifySigOps;
399  assert(int(nSigOpCountWithAncestors) >= 0);
400 }
401 
402 CTxMemPool::CTxMemPool(int check_ratio) : m_check_ratio(check_ratio) {
403  // lock free clear
404  _clear();
405 }
406 
408 
409 bool CTxMemPool::isSpent(const COutPoint &outpoint) const {
410  LOCK(cs);
411  return mapNextTx.count(outpoint);
412 }
413 
415  return nTransactionsUpdated;
416 }
417 
420 }
421 
422 void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry,
423  setEntries &setAncestors) {
424  // Add to memory pool without checking anything.
425  // Used by AcceptToMemoryPool(), which DOES do all the appropriate checks.
426  indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
427 
428  // Update transaction for any feeDelta created by PrioritiseTransaction
429  // TODO: refactor so that the fee delta is calculated before inserting into
430  // mapTx.
431  Amount feeDelta = Amount::zero();
432  ApplyDelta(entry.GetTx().GetId(), feeDelta);
433  if (feeDelta != Amount::zero()) {
434  mapTx.modify(newit, update_fee_delta(feeDelta));
435  }
436 
437  // Update cachedInnerUsage to include contained transaction's usage.
438  // (When we update the entry for in-mempool parents, memory usage will be
439  // further updated.)
441 
442  const CTransaction &tx = newit->GetTx();
443  std::set<TxId> setParentTransactions;
444  for (const CTxIn &in : tx.vin) {
445  mapNextTx.insert(std::make_pair(&in.prevout, &tx));
446  setParentTransactions.insert(in.prevout.GetTxId());
447  }
448  // Don't bother worrying about child transactions of this one. Normal case
449  // of a new transaction arriving is that there can't be any children,
450  // because such children would be orphans. An exception to that is if a
451  // transaction enters that used to be in a block. In that case, our
452  // disconnect block logic will call UpdateTransactionsFromBlock to clean up
453  // the mess we're leaving here.
454 
455  // Update ancestors with information about this tx
456  for (const auto &pit : GetIterSet(setParentTransactions)) {
457  UpdateParent(newit, pit, true);
458  }
459  UpdateAncestorsOf(true, newit, setAncestors);
460  UpdateEntryForAncestors(newit, setAncestors);
461 
463  totalTxSize += entry.GetTxSize();
464 
465  vTxHashes.emplace_back(tx.GetHash(), newit);
466  newit->vTxHashesIdx = vTxHashes.size() - 1;
467 }
468 
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
478  // BlockConnected notification.
480  it->GetSharedTx(), reason, mempool_sequence);
481  }
482 
483  for (const CTxIn &txin : it->GetTx().vin) {
484  mapNextTx.erase(txin.prevout);
485  }
486 
487  /* add logging because unchecked */
488  RemoveUnbroadcastTx(it->GetTx().GetId(), true);
489 
490  if (vTxHashes.size() > 1) {
491  vTxHashes[it->vTxHashesIdx] = std::move(vTxHashes.back());
492  vTxHashes[it->vTxHashesIdx].second->vTxHashesIdx = it->vTxHashesIdx;
493  vTxHashes.pop_back();
494  if (vTxHashes.size() * 2 < vTxHashes.capacity()) {
495  vTxHashes.shrink_to_fit();
496  }
497  } else {
498  vTxHashes.clear();
499  }
500 
501  totalTxSize -= it->GetTxSize();
502  cachedInnerUsage -= it->DynamicMemoryUsage();
503  cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) +
504  memusage::DynamicUsage(it->GetMemPoolChildrenConst());
505  mapTx.erase(it);
507 }
508 
509 // Calculates descendants of entry that are not already in setDescendants, and
510 // adds to setDescendants. Assumes entryit is already a tx in the mempool and
511 // CTxMemPoolEntry::m_children is correct for tx and all descendants. Also
512 // assumes that if an entry is in setDescendants already, then all in-mempool
513 // descendants of it are already in setDescendants as well, so that we can save
514 // time by not iterating over those entries.
516  setEntries &setDescendants) const {
517  setEntries stage;
518  if (setDescendants.count(entryit) == 0) {
519  stage.insert(entryit);
520  }
521  // Traverse down the children of entry, only adding children that are not
522  // accounted for in setDescendants already (because those children have
523  // either already been walked, or will be walked in this iteration).
524  while (!stage.empty()) {
525  txiter it = *stage.begin();
526  setDescendants.insert(it);
527  stage.erase(it);
528 
529  const CTxMemPoolEntry::Children &children =
530  it->GetMemPoolChildrenConst();
531  for (const CTxMemPoolEntry &child : children) {
532  txiter childiter = mapTx.iterator_to(child);
533  if (!setDescendants.count(childiter)) {
534  stage.insert(childiter);
535  }
536  }
537  }
538 }
539 
541  MemPoolRemovalReason reason) {
542  // Remove transaction from memory pool.
544  setEntries txToRemove;
545  txiter origit = mapTx.find(origTx.GetId());
546  if (origit != mapTx.end()) {
547  txToRemove.insert(origit);
548  } else {
549  // When recursively removing but origTx isn't in the mempool be sure to
550  // remove any children that are in the pool. This can happen during
551  // chain re-orgs if origTx isn't re-accepted into the mempool for any
552  // reason.
553  for (size_t i = 0; i < origTx.vout.size(); i++) {
554  auto it = mapNextTx.find(COutPoint(origTx.GetId(), i));
555  if (it == mapNextTx.end()) {
556  continue;
557  }
558 
559  txiter nextit = mapTx.find(it->second->GetId());
560  assert(nextit != mapTx.end());
561  txToRemove.insert(nextit);
562  }
563  }
564 
565  setEntries setAllRemoves;
566  for (txiter it : txToRemove) {
567  CalculateDescendants(it, setAllRemoves);
568  }
569 
570  RemoveStaged(setAllRemoves, false, reason);
571 }
572 
574  const CCoinsViewCache *pcoins,
575  unsigned int nMemPoolHeight, int flags) {
576  // Remove transactions spending a coinbase which are now immature and
577  // no-longer-final transactions.
579  setEntries txToRemove;
580  for (indexed_transaction_set::const_iterator it = mapTx.begin();
581  it != mapTx.end(); it++) {
582  const CTransaction &tx = it->GetTx();
583  LockPoints lp = it->GetLockPoints();
584  bool validLP = TestLockPointValidity(&lp);
585 
586  TxValidationState state;
588  config.GetChainParams().GetConsensus(), tx, state, flags) ||
589  !CheckSequenceLocks(*this, tx, flags, &lp, validLP)) {
590  // Note if CheckSequenceLocks fails the LockPoints may still be
591  // invalid. So it's critical that we remove the tx and not depend on
592  // the LockPoints.
593  txToRemove.insert(it);
594  } else if (it->GetSpendsCoinbase()) {
595  for (const CTxIn &txin : tx.vin) {
596  indexed_transaction_set::const_iterator it2 =
597  mapTx.find(txin.prevout.GetTxId());
598  if (it2 != mapTx.end()) {
599  continue;
600  }
601 
602  const Coin &coin = pcoins->AccessCoin(txin.prevout);
603  if (m_check_ratio != 0) {
604  assert(!coin.IsSpent());
605  }
606 
607  if (coin.IsSpent() ||
608  (coin.IsCoinBase() &&
609  int64_t(nMemPoolHeight) - coin.GetHeight() <
611  txToRemove.insert(it);
612  break;
613  }
614  }
615  }
616  if (!validLP) {
617  mapTx.modify(it, update_lock_points(lp));
618  }
619  }
620  setEntries setAllRemoves;
621  for (txiter it : txToRemove) {
622  CalculateDescendants(it, setAllRemoves);
623  }
624  RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
625 }
626 
628  // Remove transactions which depend on inputs of tx, recursively
630  for (const CTxIn &txin : tx.vin) {
631  auto it = mapNextTx.find(txin.prevout);
632  if (it != mapNextTx.end()) {
633  const CTransaction &txConflict = *it->second;
634  if (txConflict != tx) {
635  ClearPrioritisation(txConflict.GetId());
637  }
638  }
639  }
640 }
641 
646 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef> &vtx,
647  unsigned int nBlockHeight) {
649 
650  DisconnectedBlockTransactions disconnectpool;
651  disconnectpool.addForBlock(vtx, *this);
652 
653  std::vector<const CTxMemPoolEntry *> entries;
654  for (const CTransactionRef &tx :
655  reverse_iterate(disconnectpool.GetQueuedTx().get<insertion_order>())) {
656  const TxId &txid = tx->GetId();
657 
658  indexed_transaction_set::iterator i = mapTx.find(txid);
659  if (i != mapTx.end()) {
660  entries.push_back(&*i);
661  }
662  }
663 
664  for (const CTransactionRef &tx :
665  reverse_iterate(disconnectpool.GetQueuedTx().get<insertion_order>())) {
666  txiter it = mapTx.find(tx->GetId());
667  if (it != mapTx.end()) {
668  setEntries stage;
669  stage.insert(it);
671  }
672  removeConflicts(*tx);
673  ClearPrioritisation(tx->GetId());
674  }
675 
676  disconnectpool.clear();
677 
680 }
681 
683  mapTx.clear();
684  mapNextTx.clear();
685  vTxHashes.clear();
686  totalTxSize = 0;
687  cachedInnerUsage = 0;
692 }
693 
695  LOCK(cs);
696  _clear();
697 }
698 
700  CCoinsViewCache &mempoolDuplicate,
701  const int64_t spendheight) {
702  // Not used. CheckTxInputs() should always pass
703  TxValidationState dummy_state;
704  Amount txfee = Amount::zero();
705  bool fCheckResult =
706  tx.IsCoinBase() ||
707  Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight,
708  txfee);
709  assert(fCheckResult);
710  UpdateCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
711 }
712 
713 void CTxMemPool::check(const CCoinsViewCache *pcoins) const {
714  if (m_check_ratio == 0) {
715  return;
716  }
717 
718  if (GetRand(m_check_ratio) >= 1) {
719  return;
720  }
721 
723  LOCK(cs);
725  "Checking mempool with %u transactions and %u inputs\n",
726  (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
727 
728  uint64_t checkTotal = 0;
729  uint64_t innerUsage = 0;
730 
731  CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache *>(pcoins));
732  const int64_t spendheight = GetSpendHeight(mempoolDuplicate);
733 
734  std::list<const CTxMemPoolEntry *> waitingOnDependants;
735  for (indexed_transaction_set::const_iterator it = mapTx.begin();
736  it != mapTx.end(); it++) {
737  unsigned int i = 0;
738  checkTotal += it->GetTxSize();
739  innerUsage += it->DynamicMemoryUsage();
740  const CTransaction &tx = it->GetTx();
741  innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) +
742  memusage::DynamicUsage(it->GetMemPoolChildrenConst());
743  bool fDependsWait = false;
744  CTxMemPoolEntry::Parents setParentCheck;
745  for (const CTxIn &txin : tx.vin) {
746  // Check that every mempool transaction's inputs refer to available
747  // coins, or other mempool tx's.
748  indexed_transaction_set::const_iterator it2 =
749  mapTx.find(txin.prevout.GetTxId());
750  if (it2 != mapTx.end()) {
751  const CTransaction &tx2 = it2->GetTx();
752  assert(tx2.vout.size() > txin.prevout.GetN() &&
753  !tx2.vout[txin.prevout.GetN()].IsNull());
754  fDependsWait = true;
755  setParentCheck.insert(*it2);
756  } else {
757  assert(pcoins->HaveCoin(txin.prevout));
758  }
759  // Check whether its inputs are marked in mapNextTx.
760  auto it3 = mapNextTx.find(txin.prevout);
761  assert(it3 != mapNextTx.end());
762  assert(it3->first == &txin.prevout);
763  assert(it3->second == &tx);
764  i++;
765  }
766  auto comp = [](const CTxMemPoolEntry &a,
767  const CTxMemPoolEntry &b) -> bool {
768  return a.GetTx().GetId() == b.GetTx().GetId();
769  };
770  assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
771  assert(std::equal(setParentCheck.begin(), setParentCheck.end(),
772  it->GetMemPoolParentsConst().begin(), comp));
773  // Verify ancestor state is correct.
774  setEntries setAncestors;
775  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
776  std::string dummy;
777  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit,
778  nNoLimit, nNoLimit, dummy);
779  uint64_t nCountCheck = setAncestors.size() + 1;
780  uint64_t nSizeCheck = it->GetTxSize();
781  Amount nFeesCheck = it->GetModifiedFee();
782  int64_t nSigOpCheck = it->GetSigOpCount();
783 
784  for (txiter ancestorIt : setAncestors) {
785  nSizeCheck += ancestorIt->GetTxSize();
786  nFeesCheck += ancestorIt->GetModifiedFee();
787  nSigOpCheck += ancestorIt->GetSigOpCount();
788  }
789 
790  assert(it->GetCountWithAncestors() == nCountCheck);
791  assert(it->GetSizeWithAncestors() == nSizeCheck);
792  assert(it->GetSigOpCountWithAncestors() == nSigOpCheck);
793  assert(it->GetModFeesWithAncestors() == nFeesCheck);
794 
795  // Check children against mapNextTx
796  CTxMemPoolEntry::Children setChildrenCheck;
797  auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetId(), 0));
798  uint64_t child_sizes = 0;
799  int64_t child_sigop_counts = 0;
800  for (; iter != mapNextTx.end() &&
801  iter->first->GetTxId() == it->GetTx().GetId();
802  ++iter) {
803  txiter childit = mapTx.find(iter->second->GetId());
804  // mapNextTx points to in-mempool transactions
805  assert(childit != mapTx.end());
806  if (setChildrenCheck.insert(*childit).second) {
807  child_sizes += childit->GetTxSize();
808  child_sigop_counts += childit->GetSigOpCount();
809  }
810  }
811  assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
812  assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(),
813  it->GetMemPoolChildrenConst().begin(), comp));
814  // Also check to make sure size is greater than sum with immediate
815  // children. Just a sanity check, not definitive that this calc is
816  // correct...
817  assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
818  assert(it->GetSigOpCountWithDescendants() >=
819  child_sigop_counts + it->GetSigOpCount());
820 
821  if (fDependsWait) {
822  waitingOnDependants.push_back(&(*it));
823  } else {
824  CheckInputsAndUpdateCoins(tx, mempoolDuplicate, spendheight);
825  }
826  }
827 
828  unsigned int stepsSinceLastRemove = 0;
829  while (!waitingOnDependants.empty()) {
830  const CTxMemPoolEntry *entry = waitingOnDependants.front();
831  waitingOnDependants.pop_front();
832  if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
833  waitingOnDependants.push_back(entry);
834  stepsSinceLastRemove++;
835  assert(stepsSinceLastRemove < waitingOnDependants.size());
836  } else {
837  CheckInputsAndUpdateCoins(entry->GetTx(), mempoolDuplicate,
838  spendheight);
839  stepsSinceLastRemove = 0;
840  }
841  }
842 
843  for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
844  const TxId &txid = it->second->GetId();
845  indexed_transaction_set::const_iterator it2 = mapTx.find(txid);
846  const CTransaction &tx = it2->GetTx();
847  assert(it2 != mapTx.end());
848  assert(&tx == it->second);
849  }
850 
851  assert(totalTxSize == checkTotal);
852  assert(innerUsage == cachedInnerUsage);
853 }
854 
855 bool CTxMemPool::CompareDepthAndScore(const TxId &txida, const TxId &txidb) {
856  LOCK(cs);
857  indexed_transaction_set::const_iterator i = mapTx.find(txida);
858  if (i == mapTx.end()) {
859  return false;
860  }
861  indexed_transaction_set::const_iterator j = mapTx.find(txidb);
862  if (j == mapTx.end()) {
863  return true;
864  }
865  uint64_t counta = i->GetCountWithAncestors();
866  uint64_t countb = j->GetCountWithAncestors();
867  if (counta == countb) {
868  return CompareTxMemPoolEntryByScore()(*i, *j);
869  }
870  return counta < countb;
871 }
872 
873 namespace {
874 class DepthAndScoreComparator {
875 public:
876  bool
877  operator()(const CTxMemPool::indexed_transaction_set::const_iterator &a,
878  const CTxMemPool::indexed_transaction_set::const_iterator &b) {
879  uint64_t counta = a->GetCountWithAncestors();
880  uint64_t countb = b->GetCountWithAncestors();
881  if (counta == countb) {
882  return CompareTxMemPoolEntryByScore()(*a, *b);
883  }
884  return counta < countb;
885  }
886 };
887 } // namespace
888 
889 std::vector<CTxMemPool::indexed_transaction_set::const_iterator>
891  std::vector<indexed_transaction_set::const_iterator> iters;
893 
894  iters.reserve(mapTx.size());
895  for (indexed_transaction_set::iterator mi = mapTx.begin();
896  mi != mapTx.end(); ++mi) {
897  iters.push_back(mi);
898  }
899 
900  std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
901  return iters;
902 }
903 
904 void CTxMemPool::queryHashes(std::vector<uint256> &vtxid) const {
905  LOCK(cs);
906  auto iters = GetSortedDepthAndScore();
907 
908  vtxid.clear();
909  vtxid.reserve(mapTx.size());
910 
911  for (auto it : iters) {
912  vtxid.push_back(it->GetTx().GetId());
913  }
914 }
915 
916 static TxMempoolInfo
917 GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
918  return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(),
919  it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
920 }
921 
922 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const {
923  LOCK(cs);
924  auto iters = GetSortedDepthAndScore();
925 
926  std::vector<TxMempoolInfo> ret;
927  ret.reserve(mapTx.size());
928  for (auto it : iters) {
929  ret.push_back(GetInfo(it));
930  }
931 
932  return ret;
933 }
934 
936  LOCK(cs);
937  indexed_transaction_set::const_iterator i = mapTx.find(txid);
938  if (i == mapTx.end()) {
939  return nullptr;
940  }
941 
942  return i->GetSharedTx();
943 }
944 
945 TxMempoolInfo CTxMemPool::info(const TxId &txid) const {
946  LOCK(cs);
947  indexed_transaction_set::const_iterator i = mapTx.find(txid);
948  if (i == mapTx.end()) {
949  return TxMempoolInfo();
950  }
951 
952  return GetInfo(i);
953 }
954 
956  LOCK(cs);
957 
958  uint64_t maxMempoolSize =
959  gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
960  // minerPolicy uses recent blocks to figure out a reasonable fee. This
961  // may disagree with the rollingMinimumFeerate under certain scenarios
962  // where the mempool increases rapidly, or blocks are being mined which
963  // do not contain propagated transactions.
964  return std::max(::minRelayTxFee, GetMinFee(maxMempoolSize));
965 }
966 
968  const Amount nFeeDelta) {
969  {
970  LOCK(cs);
971  Amount &delta = mapDeltas[txid];
972  delta += nFeeDelta;
973  txiter it = mapTx.find(txid);
974  if (it != mapTx.end()) {
975  mapTx.modify(it, update_fee_delta(delta));
976  // Now update all ancestors' modified fees with descendants
977  setEntries setAncestors;
978  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
979  std::string dummy;
980  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit,
981  nNoLimit, nNoLimit, dummy, false);
982  for (txiter ancestorIt : setAncestors) {
983  mapTx.modify(ancestorIt,
984  update_descendant_state(0, nFeeDelta, 0, 0));
985  }
986 
987  // Now update all descendants' modified fees with ancestors
988  setEntries setDescendants;
989  CalculateDescendants(it, setDescendants);
990  setDescendants.erase(it);
991  for (txiter descendantIt : setDescendants) {
992  mapTx.modify(descendantIt,
993  update_ancestor_state(0, nFeeDelta, 0, 0));
994  }
996  }
997  }
998  LogPrintf("PrioritiseTransaction: %s fee += %s\n", txid.ToString(),
999  FormatMoney(nFeeDelta));
1000 }
1001 
1002 void CTxMemPool::ApplyDelta(const TxId &txid, Amount &nFeeDelta) const {
1003  AssertLockHeld(cs);
1004  std::map<TxId, Amount>::const_iterator pos = mapDeltas.find(txid);
1005  if (pos == mapDeltas.end()) {
1006  return;
1007  }
1008 
1009  nFeeDelta += pos->second;
1010 }
1011 
1013  AssertLockHeld(cs);
1014  mapDeltas.erase(txid);
1015 }
1016 
1017 const CTransaction *CTxMemPool::GetConflictTx(const COutPoint &prevout) const {
1018  const auto it = mapNextTx.find(prevout);
1019  return it == mapNextTx.end() ? nullptr : it->second;
1020 }
1021 
1022 std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const TxId &txid) const {
1023  auto it = mapTx.find(txid);
1024  if (it != mapTx.end()) {
1025  return it;
1026  }
1027  return std::optional<txiter>{std::nullopt};
1028 }
1029 
1031 CTxMemPool::GetIterSet(const std::set<TxId> &txids) const {
1033  for (const auto &txid : txids) {
1034  const auto mi = GetIter(txid);
1035  if (mi) {
1036  ret.insert(*mi);
1037  }
1038  }
1039  return ret;
1040 }
1041 
1043  for (const CTxIn &in : tx.vin) {
1044  if (exists(in.prevout.GetTxId())) {
1045  return false;
1046  }
1047  }
1048 
1049  return true;
1050 }
1051 
1053  const CTxMemPool &mempoolIn)
1054  : CCoinsViewBacked(baseIn), mempool(mempoolIn) {}
1055 
1056 bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
1057  // If an entry in the mempool exists, always return that one, as it's
1058  // guaranteed to never conflict with the underlying cache, and it cannot
1059  // have pruned entries (as it contains full) transactions. First checking
1060  // the underlying cache risks returning a pruned entry instead.
1061  CTransactionRef ptx = mempool.get(outpoint.GetTxId());
1062  if (ptx) {
1063  if (outpoint.GetN() < ptx->vout.size()) {
1064  coin = Coin(ptx->vout[outpoint.GetN()], MEMPOOL_HEIGHT, false);
1065  return true;
1066  }
1067  return false;
1068  }
1069  return base->GetCoin(outpoint, coin);
1070 }
1071 
1073  LOCK(cs);
1074  // Estimate the overhead of mapTx to be 12 pointers + an allocation, as no
1075  // exact formula for boost::multi_index_contained is implemented.
1076  return memusage::MallocUsage(sizeof(CTxMemPoolEntry) +
1077  12 * sizeof(void *)) *
1078  mapTx.size() +
1079  memusage::DynamicUsage(mapNextTx) +
1082 }
1083 
1084 void CTxMemPool::RemoveUnbroadcastTx(const TxId &txid, const bool unchecked) {
1085  LOCK(cs);
1086 
1087  if (m_unbroadcast_txids.erase(txid)) {
1088  LogPrint(
1089  BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n",
1090  txid.GetHex(),
1091  (unchecked ? " before confirmation that txn was sent out" : ""));
1092  }
1093 }
1094 
1095 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants,
1096  MemPoolRemovalReason reason) {
1097  AssertLockHeld(cs);
1098  UpdateForRemoveFromMempool(stage, updateDescendants);
1099  for (txiter it : stage) {
1100  removeUnchecked(it, reason);
1101  }
1102 }
1103 
1104 int CTxMemPool::Expire(std::chrono::seconds time) {
1105  AssertLockHeld(cs);
1106  indexed_transaction_set::index<entry_time>::type::iterator it =
1107  mapTx.get<entry_time>().begin();
1108  setEntries toremove;
1109  while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1110  toremove.insert(mapTx.project<0>(it));
1111  it++;
1112  }
1113 
1114  setEntries stage;
1115  for (txiter removeit : toremove) {
1116  CalculateDescendants(removeit, stage);
1117  }
1118 
1120  return stage.size();
1121 }
1122 
1123 void CTxMemPool::LimitSize(size_t limit, std::chrono::seconds age) {
1124  int expired = Expire(GetTime<std::chrono::seconds>() - age);
1125  if (expired != 0) {
1127  "Expired %i transactions from the memory pool\n", expired);
1128  }
1129 
1130  std::vector<COutPoint> vNoSpendsRemaining;
1131  TrimToSize(limit, &vNoSpendsRemaining);
1132  for (const COutPoint &removed : vNoSpendsRemaining) {
1133  ::ChainstateActive().CoinsTip().Uncache(removed);
1134  }
1135 }
1136 
1137 void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry) {
1138  setEntries setAncestors;
1139  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
1140  std::string dummy;
1141  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit,
1142  nNoLimit, dummy);
1143  return addUnchecked(entry, setAncestors);
1144 }
1145 
1146 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add) {
1147  AssertLockHeld(cs);
1149  if (add && entry->GetMemPoolChildren().insert(*child).second) {
1151  } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
1153  }
1154 }
1155 
1156 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add) {
1157  AssertLockHeld(cs);
1159  if (add && entry->GetMemPoolParents().insert(*parent).second) {
1161  } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
1163  }
1164 }
1165 
1166 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1167  LOCK(cs);
1169  return CFeeRate(int64_t(ceill(rollingMinimumFeeRate)) * SATOSHI);
1170  }
1171 
1172  int64_t time = GetTime();
1173  if (time > lastRollingFeeUpdate + 10) {
1174  double halflife = ROLLING_FEE_HALFLIFE;
1175  if (DynamicMemoryUsage() < sizelimit / 4) {
1176  halflife /= 4;
1177  } else if (DynamicMemoryUsage() < sizelimit / 2) {
1178  halflife /= 2;
1179  }
1180 
1183  pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1184  lastRollingFeeUpdate = time;
1185  }
1186  return CFeeRate(int64_t(ceill(rollingMinimumFeeRate)) * SATOSHI);
1187 }
1188 
1190  AssertLockHeld(cs);
1191  if ((rate.GetFeePerK() / SATOSHI) > rollingMinimumFeeRate) {
1194  }
1195 }
1196 
1197 void CTxMemPool::TrimToSize(size_t sizelimit,
1198  std::vector<COutPoint> *pvNoSpendsRemaining) {
1199  AssertLockHeld(cs);
1200 
1201  unsigned nTxnRemoved = 0;
1202  CFeeRate maxFeeRateRemoved(Amount::zero());
1203  while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1204  indexed_transaction_set::index<descendant_score>::type::iterator it =
1205  mapTx.get<descendant_score>().begin();
1206 
1207  // We set the new mempool min fee to the feerate of the removed set,
1208  // plus the "minimum reasonable fee rate" (ie some value under which we
1209  // consider txn to have 0 fee). This way, we don't allow txn to enter
1210  // mempool with feerate equal to txn which were removed with no block in
1211  // between.
1212  CFeeRate removed(it->GetModFeesWithDescendants(),
1213  it->GetVirtualSizeWithDescendants());
1214  removed += MEMPOOL_FULL_FEE_INCREMENT;
1215 
1216  trackPackageRemoved(removed);
1217  maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1218 
1219  setEntries stage;
1220  CalculateDescendants(mapTx.project<0>(it), stage);
1221  nTxnRemoved += stage.size();
1222 
1223  std::vector<CTransaction> txn;
1224  if (pvNoSpendsRemaining) {
1225  txn.reserve(stage.size());
1226  for (txiter iter : stage) {
1227  txn.push_back(iter->GetTx());
1228  }
1229  }
1231  if (pvNoSpendsRemaining) {
1232  for (const CTransaction &tx : txn) {
1233  for (const CTxIn &txin : tx.vin) {
1234  if (exists(txin.prevout.GetTxId())) {
1235  continue;
1236  }
1237  pvNoSpendsRemaining->push_back(txin.prevout);
1238  }
1239  }
1240  }
1241  }
1242 
1243  if (maxFeeRateRemoved > CFeeRate(Amount::zero())) {
1245  "Removed %u txn, rolling minimum fee bumped to %s\n",
1246  nTxnRemoved, maxFeeRateRemoved.ToString());
1247  }
1248 }
1249 
1251  // find parent with highest descendant count
1252  std::vector<txiter> candidates;
1253  setEntries counted;
1254  candidates.push_back(entry);
1255  uint64_t maximum = 0;
1256  while (candidates.size()) {
1257  txiter candidate = candidates.back();
1258  candidates.pop_back();
1259  if (!counted.insert(candidate).second) {
1260  continue;
1261  }
1262  const CTxMemPoolEntry::Parents &parents =
1263  candidate->GetMemPoolParentsConst();
1264  if (parents.size() == 0) {
1265  maximum = std::max(maximum, candidate->GetCountWithDescendants());
1266  } else {
1267  for (const CTxMemPoolEntry &i : parents) {
1268  candidates.push_back(mapTx.iterator_to(i));
1269  }
1270  }
1271  }
1272  return maximum;
1273 }
1274 
1275 void CTxMemPool::GetTransactionAncestry(const TxId &txid, size_t &ancestors,
1276  size_t &descendants) const {
1277  LOCK(cs);
1278  auto it = mapTx.find(txid);
1279  ancestors = descendants = 0;
1280  if (it != mapTx.end()) {
1281  ancestors = it->GetCountWithAncestors();
1282  descendants = CalculateDescendantMaximum(it);
1283  }
1284 }
1285 
1286 bool CTxMemPool::IsLoaded() const {
1287  LOCK(cs);
1288  return m_is_loaded;
1289 }
1290 
1291 void CTxMemPool::SetIsLoaded(bool loaded) {
1292  LOCK(cs);
1293  m_is_loaded = loaded;
1294 }
1295 
1298 
1300  const std::vector<CTransactionRef> &vtx, CTxMemPool &pool) {
1301  AssertLockHeld(pool.cs);
1302  for (const auto &tx : reverse_iterate(vtx)) {
1303  // If we already added it, just skip.
1304  auto it = queuedTx.find(tx->GetId());
1305  if (it != queuedTx.end()) {
1306  continue;
1307  }
1308 
1309  // Insert the transaction into the pool.
1310  addTransaction(tx);
1311 
1312  // Fill in the set of parents.
1313  std::unordered_set<TxId, SaltedTxIdHasher> parents;
1314  for (const CTxIn &in : tx->vin) {
1315  parents.insert(in.prevout.GetTxId());
1316  }
1317 
1318  // In order to make sure we keep things in topological order, we check
1319  // if we already know of the parent of the current transaction. If so,
1320  // we remove them from the set and then add them back.
1321  while (parents.size() > 0) {
1322  std::unordered_set<TxId, SaltedTxIdHasher> worklist(
1323  std::move(parents));
1324  parents.clear();
1325 
1326  for (const TxId &txid : worklist) {
1327  // If we do not have that txid in the set, nothing needs to be
1328  // done.
1329  auto pit = queuedTx.find(txid);
1330  if (pit == queuedTx.end()) {
1331  continue;
1332  }
1333 
1334  // We have parent in our set, we reinsert them at the right
1335  // position.
1336  const CTransactionRef ptx = *pit;
1337  queuedTx.erase(pit);
1338  queuedTx.insert(ptx);
1339 
1340  // And we make sure ancestors are covered.
1341  for (const CTxIn &in : ptx->vin) {
1342  parents.insert(in.prevout.GetTxId());
1343  }
1344  }
1345  }
1346  }
1347 
1348  // Keep the size under control.
1350  // Drop the earliest entry, and remove its children from the
1351  // mempool.
1352  auto it = queuedTx.get<insertion_order>().begin();
1354  removeEntry(it);
1355  }
1356 }
1357 
1359  AssertLockHeld(pool.cs);
1360  // addForBlock's algorithm sorts a vector of transactions back into
1361  // topological order. We use it in a separate object to create a valid
1362  // ordering of all mempool transactions, which we then splice in front of
1363  // the current queuedTx. This results in a valid sequence of transactions to
1364  // be reprocessed in updateMempoolForReorg.
1365 
1366  // We create vtx in order of the entry_time index to facilitate for
1367  // addForBlocks (which iterates in reverse order), as vtx probably end in
1368  // the correct ordering for queuedTx.
1369  std::vector<CTransactionRef> vtx;
1370 
1371  vtx.reserve(pool.mapTx.size());
1372  for (const CTxMemPoolEntry &e : pool.mapTx.get<entry_time>()) {
1373  vtx.push_back(e.GetSharedTx());
1374  }
1375  pool.clear();
1376 
1377  // Use addForBlocks to sort the transactions and then splice them in front
1378  // of queuedTx
1379  DisconnectedBlockTransactions orderedTxnPool;
1380  orderedTxnPool.addForBlock(vtx, pool);
1381  cachedInnerUsage += orderedTxnPool.cachedInnerUsage;
1382  queuedTx.get<insertion_order>().splice(
1383  queuedTx.get<insertion_order>().begin(),
1384  orderedTxnPool.queuedTx.get<insertion_order>());
1385 
1386  // We limit memory usage because we can't know if more blocks will be
1387  // disconnected
1389  // Drop the earliest entry which, by definition, has no children
1390  removeEntry(queuedTx.get<insertion_order>().begin());
1391  }
1392 }
1393 
1395  bool fAddToMempool,
1396  CTxMemPool &pool) {
1398  AssertLockHeld(pool.cs);
1399  std::vector<TxId> txidsUpdate;
1400 
1401  // disconnectpool's insertion_order index sorts the entries from oldest to
1402  // newest, but the oldest entry will be the last tx from the latest mined
1403  // block that was disconnected.
1404  // Iterate disconnectpool in reverse, so that we add transactions back to
1405  // the mempool starting with the earliest transaction that had been
1406  // previously seen in a block.
1407  for (const CTransactionRef &tx :
1409  // ignore validation errors in resurrected transactions
1410  TxValidationState stateDummy;
1411  if (!fAddToMempool || tx->IsCoinBase() ||
1412  !AcceptToMemoryPool(config, pool, stateDummy, tx,
1413  true /* bypass_limits */)) {
1414  // If the transaction doesn't make it in to the mempool, remove any
1415  // transactions that depend on it (which would now be orphans).
1417  } else if (pool.exists(tx->GetId())) {
1418  txidsUpdate.push_back(tx->GetId());
1419  }
1420  }
1421 
1422  queuedTx.clear();
1423 
1424  // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
1425  // no in-mempool children, which is generally not true when adding
1426  // previously-confirmed transactions back to the mempool.
1427  // UpdateTransactionsFromBlock finds descendants of any transactions in the
1428  // disconnectpool that were added back and cleans up the mempool state.
1429  pool.UpdateTransactionsFromBlock(txidsUpdate);
1430 
1431  // We also need to remove any now-immature transactions
1432  pool.removeForReorg(config, &::ChainstateActive().CoinsTip(),
1433  ::ChainActive().Tip()->nHeight + 1,
1435 
1436  // Re-limit mempool size, in case we added any transactions
1437  pool.LimitSize(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) *
1438  1000000,
1439  std::chrono::hours{
1440  gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
1441 }
1442 
1444  return EpochGuard(*this);
1445 }
1446 
1448  assert(!pool.m_has_epoch_guard);
1449  ++pool.m_epoch;
1450  pool.m_has_epoch_guard = true;
1451 }
1452 
1454  // prevents stale results being used
1455  ++pool.m_epoch;
1456  pool.m_has_epoch_guard = false;
1457 }
CTxMemPoolEntry::GetTxVirtualSize
size_t GetTxVirtualSize() const
Definition: txmempool.cpp:49
CTxMemPool::GetIterSet
setEntries GetIterSet(const std::set< TxId > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of txids into a set of pool iterators to avoid repeated lookups.
Definition: txmempool.cpp:1031
CTxIn
An input of a transaction.
Definition: transaction.h:61
CTxMemPoolEntry::nCountWithDescendants
uint64_t nCountWithDescendants
number of descendant transactions
Definition: txmempool.h:119
policy.h
UpdateCoins
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Definition: validation.cpp:1086
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:210
CTxMemPool::AddTransactionsUpdated
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:418
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:1166
CTxMemPool::EpochGuard::EpochGuard
EpochGuard(const CTxMemPool &in)
Definition: txmempool.cpp:1447
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:469
update_fee_delta
Definition: txmempool.h:229
CTxMemPoolEntry::nModFeesWithAncestors
Amount nModFeesWithAncestors
Definition: txmempool.h:130
CTxMemPoolEntry::nCountWithAncestors
uint64_t nCountWithAncestors
Definition: txmempool.h:128
CTxMemPool::ROLLING_FEE_HALFLIFE
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:526
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:32
settings.h
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:13
ChainActive
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:86
flags
int flags
Definition: bitcoin-tx.cpp:532
CTxMemPool::EpochGuard::~EpochGuard
~EpochGuard()
Definition: txmempool.cpp:1453
CTxMemPool::removeForReorg
void removeForReorg(const Config &config, const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags) EXCLUSIVE_LOCKS_REQUIRED(cs
Definition: txmempool.cpp:573
CTxMemPoolEntry::lockPoints
LockPoints lockPoints
Track the height and time at which tx was final.
Definition: txmempool.h:113
update_lock_points
Definition: txmempool.h:238
CTxMemPool::GetSortedDepthAndScore
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:890
CTxMemPoolEntry::Children
std::set< CTxMemPoolEntryRef, CompareIteratorById > Children
Definition: txmempool.h:84
CCoinsViewCache::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:188
moneystr.h
CTxMemPool::txiter
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:580
CTxMemPool::IsLoaded
bool IsLoaded() const
Definition: txmempool.cpp:1286
CTxMemPoolEntry::feeDelta
Amount feeDelta
Used for determining the priority of the transaction for mining in a block.
Definition: txmempool.h:111
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:495
CTxMemPool::estimateFee
CFeeRate estimateFee() const
Definition: txmempool.cpp:955
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:1197
validationinterface.h
validation.h
minRelayTxFee
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:122
GetTime
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:27
CTxMemPool::SetIsLoaded
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1291
descendant_score
Definition: txmempool.h:372
MemPoolRemovalReason::EXPIRY
@ EXPIRY
Expired from mempool.
CChainParams::GetConsensus
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:59
ChainstateActive
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:80
CTxMemPoolEntry::nModFeesWithDescendants
Amount nModFeesWithDescendants
... and total fees (all including us)
Definition: txmempool.h:123
clientversion.h
CTxMemPool::setEntries
std::set< txiter, CompareIteratorById > setEntries
Definition: txmempool.h:584
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:180
CTxMemPool::UpdateChildrenForRemoval
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:306
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:187
CTxMemPoolEntry::sigOpCount
const int64_t sigOpCount
Total sigop plus P2SH sigops count.
Definition: txmempool.h:108
memusage::DynamicUsage
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:26
DisconnectedBlockTransactions::addTransaction
void addTransaction(const CTransactionRef &tx)
Definition: txmempool.h:1000
chainparams.h
CheckSequenceLocks
bool CheckSequenceLocks(const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Definition: validation.cpp:200
CTransaction::GetHash
const TxHash GetHash() const
Definition: transaction.h:245
CTxMemPool::GetTransactionsUpdated
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:414
CTxMemPool::info
TxMempoolInfo info(const TxId &txid) const
Definition: txmempool.cpp:945
CTxMemPool::visited
bool visited(txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs)
visited marks a CTxMemPoolEntry as having been traversed during the lifetime of the most recently cre...
Definition: txmempool.h:928
CTxMemPool::CalculateDescendantMaximum
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1250
CTxMemPoolEntry::UpdateFeeDelta
void UpdateFeeDelta(Amount feeDelta)
Definition: txmempool.cpp:67
update_ancestor_state
Definition: txmempool.h:211
version.h
CTxMemPoolEntry::nSizeWithAncestors
uint64_t nSizeWithAncestors
Definition: txmempool.h:129
Consensus::CheckTxInputs
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, Amount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts).
Definition: tx_verify.cpp:158
CTxMemPoolEntry::Parents
std::set< CTxMemPoolEntryRef, CompareIteratorById > Parents
Definition: txmempool.h:83
CCoinsViewMemPool::CCoinsViewMemPool
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:1052
GetRand
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:650
CTxMemPool::m_has_epoch_guard
bool m_has_epoch_guard
Definition: txmempool.h:513
CTxMemPoolEntry::nFee
const Amount nFee
Cached to avoid expensive parent-transaction lookups.
Definition: txmempool.h:91
CFeeRate
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
DisconnectedBlockTransactions::clear
void clear()
Definition: txmempool.h:1063
CTxMemPool::queryHashes
void queryHashes(std::vector< uint256 > &vtxid) const
Definition: txmempool.cpp:904
CTxMemPool::UpdateEntryForAncestors
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs)
Set ancestor state for an entry.
Definition: txmempool.cpp:290
DisconnectedBlockTransactions::cachedInnerUsage
uint64_t cachedInnerUsage
Definition: txmempool.h:998
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
CCoinsViewBacked::base
CCoinsView * base
Definition: coins.h:214
CTxMemPool::addUnchecked
void check(const CCoinsViewCache *pcoins) const EXCLUSIVE_LOCKS_REQUIRED(voi addUnchecked)(const CTxMemPoolEntry &entry) EXCLUSIVE_LOCKS_REQUIRED(cs
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.h:638
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
CTxMemPool::~CTxMemPool
~CTxMemPool()
Definition: txmempool.cpp:407
GetMainSignals
CMainSignals & GetMainSignals()
Definition: validationinterface.cpp:122
Amount::zero
static constexpr Amount zero()
Definition: amount.h:42
txmempool.h
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:175
CTxMemPoolEntry::nSizeWithDescendants
uint64_t nSizeWithDescendants
... and size
Definition: txmempool.h:121
CCoinsViewMemPool::mempool
const CTxMemPool & mempool
Definition: txmempool.h:955
TxValidationState
Definition: validation.h:137
CTxMemPool::PrioritiseTransaction
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:967
DisconnectedBlockTransactions::importMempool
void importMempool(CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
Definition: txmempool.cpp:1358
SATOSHI
static constexpr Amount SATOSHI
Definition: amount.h:153
insertion_order
Definition: txmempool.h:982
Config
Definition: config.h:17
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:256
CFeeRate::GetFeePerK
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
COutPoint::GetTxId
const TxId & GetTxId() const
Definition: transaction.h:37
CTxMemPool::lastRollingFeeUpdate
int64_t lastRollingFeeUpdate
Definition: txmempool.h:508
RecursiveDynamicUsage
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
entry_time
Definition: txmempool.h:373
CTxMemPool::cs
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:577
CTxMemPool::GetAndIncrementSequence
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:832
CTxMemPoolEntry::nTxSize
const size_t nTxSize
... and avoid recomputing tx size
Definition: txmempool.h:93
STANDARD_LOCKTIME_VERIFY_FLAGS
static constexpr uint32_t STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
Definition: policy.h:109
update_descendant_state
Definition: txmempool.h:193
GetSpendHeight
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
Definition: validation.cpp:1126
CTransaction::GetId
const TxId GetId() const
Definition: transaction.h:244
cs_main
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:103
tx_verify.h
Coin
A UTXO entry.
Definition: coins.h:27
CTxMemPool::UpdateForDescendants
void UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set< TxId > &setExclude) EXCLUSIVE_LOCKS_REQUIRED(cs)
UpdateForDescendants is used by UpdateTransactionsFromBlock to update the descendants for a single tr...
Definition: txmempool.cpp:80
CTxMemPool::GetIter
std::optional< txiter > GetIter(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given txid, if found.
Definition: txmempool.cpp:1022
DisconnectedBlockTransactions::queuedTx
indexed_disconnected_transactions queuedTx
Definition: txmempool.h:997
CTxMemPool::UpdateChild
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1146
CTransaction::vout
const std::vector< CTxOut > vout
Definition: transaction.h:211
reverse_iterator.h
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:1042
CMainSignals::TransactionRemovedFromMempool
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)
Definition: validationinterface.cpp:217
CheckInputsAndUpdateCoins
static void CheckInputsAndUpdateCoins(const CTransaction &tx, CCoinsViewCache &mempoolDuplicate, const int64_t spendheight)
Definition: txmempool.cpp:699
consensus.h
CTxMemPool::EpochGuard::pool
const CTxMemPool & pool
Definition: txmempool.h:909
time.h
TestLockPointValidity
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain.
Definition: validation.cpp:181
DEFAULT_MAX_BLOCK_SIZE
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition: consensus.h:20
DisconnectedBlockTransactions::GetQueuedTx
const indexed_disconnected_transactions & GetQueuedTx() const
Definition: txmempool.h:1025
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:582
CTxMemPool::m_epoch
uint64_t m_epoch
Definition: txmempool.h:512
base_blob::GetHex
std::string GetHex() const
Definition: uint256.cpp:16
CTxMemPoolEntry::GetVirtualSizeWithAncestors
uint64_t GetVirtualSizeWithAncestors() const
Definition: txmempool.cpp:60
MemPoolRemovalReason::SIZELIMIT
@ SIZELIMIT
Removed in size limiting.
CTxMemPoolEntry::UpdateDescendantState
void UpdateDescendantState(int64_t modifySize, Amount modifyFee, int64_t modifyCount, int64_t modifySigOpCount)
Definition: txmempool.cpp:377
DisconnectedBlockTransactions::removeEntry
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
Definition: txmempool.h:1055
CTxMemPool::removeConflicts
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:627
CTxMemPool::m_check_ratio
const int m_check_ratio
Value n means that 1 times in n we check.
Definition: txmempool.h:498
CTxMemPool::UpdateParent
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1156
CTxMemPool::exists
bool exists(const TxId &txid) const
Definition: txmempool.h:794
CTxMemPool::nTransactionsUpdated
std::atomic< uint32_t > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:500
base_blob::ToString
std::string ToString() const
Definition: uint256.h:78
TxId
A TxId is the identifier of a transaction.
Definition: txid.h:14
CTxMemPoolEntry::nSigOpCountWithDescendants
int64_t nSigOpCountWithDescendants
... and sigop count
Definition: txmempool.h:125
CTxMemPool::get
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:935
CTxMemPool::totalTxSize
uint64_t totalTxSize
sum of all mempool tx's sizes.
Definition: txmempool.h:503
CTxMemPool::cacheMap
std::map< txiter, setEntries, CompareIteratorById > cacheMap
Definition: txmempool.h:590
Amount
Definition: amount.h:19
LogPrint
#define LogPrint(category,...)
Definition: logging.h:193
CompareTxMemPoolEntryByScore
Definition: txmempool.h:309
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:1056
CTxMemPool::mapDeltas
std::map< TxId, Amount > mapDeltas
Definition: txmempool.h:608
CTxMemPool::UpdateTransactionsFromBlock
void UpdateTransactionsFromBlock(const std::vector< TxId > &txidsToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
Definition: txmempool.cpp:137
CTxMemPoolEntry::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Definition: txmempool.h:148
CTxMemPool::ApplyDelta
void ApplyDelta(const TxId &txid, Amount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1002
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:313
CTxMemPoolEntry::GetMemPoolChildrenConst
const Children & GetMemPoolChildrenConst() const
Definition: txmempool.h:182
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:1104
GetInfo
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.cpp:917
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:1201
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:272
BCLog::MEMPOOL
@ MEMPOOL
Definition: logging.h:40
fees.h
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:231
CCoinsViewBacked
CCoinsView backed by another CCoinsView.
Definition: coins.h:212
CTxMemPool::CompareDepthAndScore
bool CompareDepthAndScore(const TxId &txida, const TxId &txidb)
Definition: txmempool.cpp:855
MAX_DISCONNECTED_TX_POOL_SIZE
static const size_t MAX_DISCONNECTED_TX_POOL_SIZE
Maximum bytes for transactions to store for processing during reorg.
Definition: txmempool.cpp:1297
Config::GetChainParams
virtual const CChainParams & GetChainParams() const =0
CTxMemPoolEntry
Definition: txmempool.h:79
LOCK
#define LOCK(cs)
Definition: sync.h:241
MemPoolRemovalReason
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:400
gArgs
ArgsManager gArgs
Definition: system.cpp:76
CTxMemPool::GetTransactionAncestry
void GetTransactionAncestry(const TxId &txid, size_t &ancestors, size_t &descendants) const
Calculate the ancestor and descendant count for the given transaction.
Definition: txmempool.cpp:1275
CTxMemPool::infoAll
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:922
CTxMemPool::blockSinceLastRollingFeeBump
bool blockSinceLastRollingFeeBump
Definition: txmempool.h:509
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:1017
memusage::IncrementalDynamicUsage
static size_t IncrementalDynamicUsage(const std::set< X, Y > &s)
Definition: memusage.h:122
FormatMoney
std::string FormatMoney(const Amount amt)
Money parsing/formatting utilities.
Definition: moneystr.cpp:12
LockPoints
Definition: txmempool.h:41
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:63
CTxMemPool::trackPackageRemoved
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1189
CTxMemPool::rollingMinimumFeeRate
double rollingMinimumFeeRate
minimum fee to get into the pool, decreases exponentially
Definition: txmempool.h:511
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:1095
CTxMemPool::size
unsigned long size() const
Definition: txmempool.h:784
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:319
spendsCoinbase
bool spendsCoinbase
Definition: mempool_eviction.cpp:14
TxMempoolInfo
Information about a mempool transaction.
Definition: txmempool.h:379
Coin::GetHeight
uint32_t GetHeight() const
Definition: coins.h:44
CTxMemPoolEntry::UpdateLockPoints
void UpdateLockPoints(const LockPoints &lp)
Definition: txmempool.cpp:73
CTxMemPoolEntry::UpdateAncestorState
void UpdateAncestorState(int64_t modifySize, Amount modifyFee, int64_t modifyCount, int64_t modifySigOps)
Definition: txmempool.cpp:390
memusage::MallocUsage
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
Definition: memusage.h:72
CFeeRate::ToString
std::string ToString() const
Definition: feerate.cpp:59
CTxMemPool::RemoveUnbroadcastTx
void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:1084
CCoinsViewCache::Uncache
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:278
MEMPOOL_HEIGHT
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
Definition: txmempool.h:39
config.h
CTxMemPool::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1072
CTxMemPoolEntry::GetTxSize
size_t GetTxSize() const
Definition: txmempool.h:141
GetVirtualTransactionSize
int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigOpCount, unsigned int bytes_per_sigop)
Compute the virtual transaction size (size, or more if sigops are too dense).
Definition: policy.cpp:162
COutPoint::GetN
uint32_t GetN() const
Definition: transaction.h:38
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
lp
LockPoints lp
Definition: mempool_eviction.cpp:16
DisconnectedBlockTransactions::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Definition: txmempool.h:1018
DisconnectedBlockTransactions
Definition: txmempool.h:984
ContextualCheckTransactionForCurrentBlock
bool ContextualCheckTransactionForCurrentBlock(const Consensus::Params &params, const CTransaction &tx, TxValidationState &state, int flags)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition: validation.cpp:3922
DisconnectedBlockTransactions::addForBlock
void addForBlock(const std::vector< CTransactionRef > &vtx, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
Definition: txmempool.cpp:1299
MemPoolRemovalReason::BLOCK
@ BLOCK
Removed for block.
Coin::IsSpent
bool IsSpent() const
Definition: coins.h:46
AcceptToMemoryPool
bool AcceptToMemoryPool(const Config &config, CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, bool bypass_limits, bool test_accept, Amount *fee_out)
(try to) add transaction to memory pool
Definition: validation.cpp:779
CTxMemPool::GetFreshEpoch
EpochGuard GetFreshEpoch() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1443
CTxMemPool::cachedInnerUsage
uint64_t cachedInnerUsage
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
Definition: txmempool.h:506
CTxMemPool::isSpent
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:409
DisconnectedBlockTransactions::updateMempoolForReorg
void updateMempoolForReorg(const Config &config, bool fAddToMempool, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
Definition: txmempool.cpp:1394
CTxMemPool::clear
void clear()
Definition: txmempool.cpp:694
CTxMemPool::CTxMemPool
CTxMemPool(int check_ratio=0)
Create a new CTxMemPool.
Definition: txmempool.cpp:402
CTxMemPool::_clear
void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:682
CTxMemPoolEntry::nSigOpCountWithAncestors
int64_t nSigOpCountWithAncestors
Definition: txmempool.h:131
reverse_iterate
reverse_range< T > reverse_iterate(T &x)
Definition: reverse_iterator.h:25
MemPoolRemovalReason::CONFLICT
@ CONFLICT
Removed for conflict with in-block transaction.
MemPoolRemovalReason::REORG
@ REORG
Removed for reorganization.
LogPrintf
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:175
CChainState::CoinsTip
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:837
AssertLockHeld
AssertLockHeld(g_cs_orphans)
CTxMemPool::EpochGuard
EpochGuard: RAII-style guard for using epoch-based graph traversal algorithms.
Definition: txmempool.h:908
CTxMemPool::ClearPrioritisation
void ClearPrioritisation(const TxId &txid) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1012
CTxMemPool::cs_main
void check(const CCoinsViewCache *pcoins) const EXCLUSIVE_LOCKS_REQUIRED(voi cs_main)
Definition: txmempool.h:639
CTxMemPoolEntry::CTxMemPoolEntry
CTxMemPoolEntry(const CTransactionRef &_tx, const Amount _nFee, int64_t _nTime, unsigned int _entryHeight, bool spendsCoinbase, int64_t _nSigOpCount, LockPoints lp)
Definition: txmempool.cpp:28
CTxMemPool::LimitSize
void LimitSize(size_t limit, std::chrono::seconds age) EXCLUSIVE_LOCKS_REQUIRED(cs
Reduce the size of the mempool by expiring and then trimming the mempool.
Definition: txmempool.cpp:1123
DEFAULT_MAX_MEMPOOL_SIZE
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:48
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:646
CTxMemPool::removeRecursive
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:540
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:515
Coin::IsCoinBase
bool IsCoinBase() const
Definition: coins.h:45
CTxMemPoolEntry::GetTx
const CTransaction & GetTx() const
Definition: txmempool.h:138
CTxMemPoolEntry::GetVirtualSizeWithDescendants
uint64_t GetVirtualSizeWithDescendants() const
Definition: txmempool.cpp:53
MEMPOOL_FULL_FEE_INCREMENT
static const CFeeRate MEMPOOL_FULL_FEE_INCREMENT(1000 *SATOSHI)
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...