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