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