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