Bitcoin Core  0.20.99
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 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  // 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  mapLinks.insert(make_pair(newit, TxLinks()));
363 
364  // Update transaction for any feeDelta created by PrioritiseTransaction
365  // TODO: refactor so that the fee delta is calculated before inserting
366  // into mapTx.
367  CAmount delta{0};
368  ApplyDelta(entry.GetTx().GetHash(), delta);
369  if (delta) {
370  mapTx.modify(newit, update_fee_delta(delta));
371  }
372 
373  // Update cachedInnerUsage to include contained transaction's usage.
374  // (When we update the entry for in-mempool parents, memory usage will be
375  // further updated.)
377 
378  const CTransaction& tx = newit->GetTx();
379  std::set<uint256> setParentTransactions;
380  for (unsigned int i = 0; i < tx.vin.size(); i++) {
381  mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
382  setParentTransactions.insert(tx.vin[i].prevout.hash);
383  }
384  // Don't bother worrying about child transactions of this one.
385  // Normal case of a new transaction arriving is that there can't be any
386  // children, because such children would be orphans.
387  // An exception to that is if a transaction enters that used to be in a block.
388  // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
389  // to clean up the mess we're leaving here.
390 
391  // Update ancestors with information about this tx
392  for (const auto& pit : GetIterSet(setParentTransactions)) {
393  UpdateParent(newit, pit, true);
394  }
395  UpdateAncestorsOf(true, newit, setAncestors);
396  UpdateEntryForAncestors(newit, setAncestors);
397 
399  totalTxSize += entry.GetTxSize();
400  if (minerPolicyEstimator) {minerPolicyEstimator->processTransaction(entry, validFeeEstimate);}
401 
402  vTxHashes.emplace_back(tx.GetWitnessHash(), newit);
403  newit->vTxHashesIdx = vTxHashes.size() - 1;
404 }
405 
407 {
408  if (reason != MemPoolRemovalReason::BLOCK) {
409  // Notify clients that a transaction has been removed from the mempool
410  // for any reason except being included in a block. Clients interested
411  // in transactions included in blocks can subscribe to the BlockConnected
412  // notification.
413  GetMainSignals().TransactionRemovedFromMempool(it->GetSharedTx());
414  }
415 
416  const uint256 hash = it->GetTx().GetHash();
417  for (const CTxIn& txin : it->GetTx().vin)
418  mapNextTx.erase(txin.prevout);
419 
420  RemoveUnbroadcastTx(hash, true /* add logging because unchecked */ );
421 
422  if (vTxHashes.size() > 1) {
423  vTxHashes[it->vTxHashesIdx] = std::move(vTxHashes.back());
424  vTxHashes[it->vTxHashesIdx].second->vTxHashesIdx = it->vTxHashesIdx;
425  vTxHashes.pop_back();
426  if (vTxHashes.size() * 2 < vTxHashes.capacity())
427  vTxHashes.shrink_to_fit();
428  } else
429  vTxHashes.clear();
430 
431  totalTxSize -= it->GetTxSize();
432  cachedInnerUsage -= it->DynamicMemoryUsage();
434  mapLinks.erase(it);
435  mapTx.erase(it);
438 }
439 
440 // Calculates descendants of entry that are not already in setDescendants, and adds to
441 // setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
442 // is correct for tx and all descendants.
443 // Also assumes that if an entry is in setDescendants already, then all
444 // in-mempool descendants of it are already in setDescendants as well, so that we
445 // can save time by not iterating over those entries.
446 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
447 {
448  setEntries stage;
449  if (setDescendants.count(entryit) == 0) {
450  stage.insert(entryit);
451  }
452  // Traverse down the children of entry, only adding children that are not
453  // accounted for in setDescendants already (because those children have either
454  // already been walked, or will be walked in this iteration).
455  while (!stage.empty()) {
456  txiter it = *stage.begin();
457  setDescendants.insert(it);
458  stage.erase(it);
459 
460  const setEntries &setChildren = GetMemPoolChildren(it);
461  for (txiter childiter : setChildren) {
462  if (!setDescendants.count(childiter)) {
463  stage.insert(childiter);
464  }
465  }
466  }
467 }
468 
470 {
471  // Remove transaction from memory pool
473  setEntries txToRemove;
474  txiter origit = mapTx.find(origTx.GetHash());
475  if (origit != mapTx.end()) {
476  txToRemove.insert(origit);
477  } else {
478  // When recursively removing but origTx isn't in the mempool
479  // be sure to remove any children that are in the pool. This can
480  // happen during chain re-orgs if origTx isn't re-accepted into
481  // the mempool for any reason.
482  for (unsigned int i = 0; i < origTx.vout.size(); i++) {
483  auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
484  if (it == mapNextTx.end())
485  continue;
486  txiter nextit = mapTx.find(it->second->GetHash());
487  assert(nextit != mapTx.end());
488  txToRemove.insert(nextit);
489  }
490  }
491  setEntries setAllRemoves;
492  for (txiter it : txToRemove) {
493  CalculateDescendants(it, setAllRemoves);
494  }
495 
496  RemoveStaged(setAllRemoves, false, reason);
497 }
498 
499 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
500 {
501  // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
503  setEntries txToRemove;
504  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
505  const CTransaction& tx = it->GetTx();
506  LockPoints lp = it->GetLockPoints();
507  bool validLP = TestLockPointValidity(&lp);
508  if (!CheckFinalTx(tx, flags) || !CheckSequenceLocks(*this, tx, flags, &lp, validLP)) {
509  // Note if CheckSequenceLocks fails the LockPoints may still be invalid
510  // So it's critical that we remove the tx and not depend on the LockPoints.
511  txToRemove.insert(it);
512  } else if (it->GetSpendsCoinbase()) {
513  for (const CTxIn& txin : tx.vin) {
514  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
515  if (it2 != mapTx.end())
516  continue;
517  const Coin &coin = pcoins->AccessCoin(txin.prevout);
518  if (nCheckFrequency != 0) assert(!coin.IsSpent());
519  if (coin.IsSpent() || (coin.IsCoinBase() && ((signed long)nMemPoolHeight) - coin.nHeight < COINBASE_MATURITY)) {
520  txToRemove.insert(it);
521  break;
522  }
523  }
524  }
525  if (!validLP) {
526  mapTx.modify(it, update_lock_points(lp));
527  }
528  }
529  setEntries setAllRemoves;
530  for (txiter it : txToRemove) {
531  CalculateDescendants(it, setAllRemoves);
532  }
533  RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
534 }
535 
537 {
538  // Remove transactions which depend on inputs of tx, recursively
540  for (const CTxIn &txin : tx.vin) {
541  auto it = mapNextTx.find(txin.prevout);
542  if (it != mapNextTx.end()) {
543  const CTransaction &txConflict = *it->second;
544  if (txConflict != tx)
545  {
546  ClearPrioritisation(txConflict.GetHash());
548  }
549  }
550  }
551 }
552 
556 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
557 {
559  std::vector<const CTxMemPoolEntry*> entries;
560  for (const auto& tx : vtx)
561  {
562  uint256 hash = tx->GetHash();
563 
564  indexed_transaction_set::iterator i = mapTx.find(hash);
565  if (i != mapTx.end())
566  entries.push_back(&*i);
567  }
568  // Before the txs in the new block have been removed from the mempool, update policy estimates
569  if (minerPolicyEstimator) {minerPolicyEstimator->processBlock(nBlockHeight, entries);}
570  for (const auto& tx : vtx)
571  {
572  txiter it = mapTx.find(tx->GetHash());
573  if (it != mapTx.end()) {
574  setEntries stage;
575  stage.insert(it);
577  }
578  removeConflicts(*tx);
579  ClearPrioritisation(tx->GetHash());
580  }
583 }
584 
586 {
587  mapLinks.clear();
588  mapTx.clear();
589  mapNextTx.clear();
590  totalTxSize = 0;
591  cachedInnerUsage = 0;
596 }
597 
599 {
600  LOCK(cs);
601  _clear();
602 }
603 
604 static void CheckInputsAndUpdateCoins(const CTransaction& tx, CCoinsViewCache& mempoolDuplicate, const int64_t spendheight)
605 {
606  TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
607  CAmount txfee = 0;
608  bool fCheckResult = tx.IsCoinBase() || Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee);
609  assert(fCheckResult);
610  UpdateCoins(tx, mempoolDuplicate, std::numeric_limits<int>::max());
611 }
612 
613 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
614 {
615  LOCK(cs);
616  if (nCheckFrequency == 0)
617  return;
618 
619  if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)
620  return;
621 
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  txlinksMap::const_iterator linksiter = mapLinks.find(it);
637  assert(linksiter != mapLinks.end());
638  const TxLinks &links = linksiter->second;
639  innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
640  bool fDependsWait = false;
641  setEntries setParentCheck;
642  for (const CTxIn &txin : tx.vin) {
643  // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
644  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
645  if (it2 != mapTx.end()) {
646  const CTransaction& tx2 = it2->GetTx();
647  assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
648  fDependsWait = true;
649  setParentCheck.insert(it2);
650  } else {
651  assert(pcoins->HaveCoin(txin.prevout));
652  }
653  // Check whether its inputs are marked in mapNextTx.
654  auto it3 = mapNextTx.find(txin.prevout);
655  assert(it3 != mapNextTx.end());
656  assert(it3->first == &txin.prevout);
657  assert(it3->second == &tx);
658  i++;
659  }
660  assert(setParentCheck == GetMemPoolParents(it));
661  // Verify ancestor state is correct.
662  setEntries setAncestors;
663  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
664  std::string dummy;
665  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
666  uint64_t nCountCheck = setAncestors.size() + 1;
667  uint64_t nSizeCheck = it->GetTxSize();
668  CAmount nFeesCheck = it->GetModifiedFee();
669  int64_t nSigOpCheck = it->GetSigOpCost();
670 
671  for (txiter ancestorIt : setAncestors) {
672  nSizeCheck += ancestorIt->GetTxSize();
673  nFeesCheck += ancestorIt->GetModifiedFee();
674  nSigOpCheck += ancestorIt->GetSigOpCost();
675  }
676 
677  assert(it->GetCountWithAncestors() == nCountCheck);
678  assert(it->GetSizeWithAncestors() == nSizeCheck);
679  assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
680  assert(it->GetModFeesWithAncestors() == nFeesCheck);
681 
682  // Check children against mapNextTx
683  CTxMemPool::setEntries setChildrenCheck;
684  auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
685  uint64_t child_sizes = 0;
686  for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
687  txiter childit = mapTx.find(iter->second->GetHash());
688  assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
689  if (setChildrenCheck.insert(childit).second) {
690  child_sizes += childit->GetTxSize();
691  }
692  }
693  assert(setChildrenCheck == GetMemPoolChildren(it));
694  // Also check to make sure size is greater than sum with immediate children.
695  // just a sanity check, not definitive that this calc is correct...
696  assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
697 
698  if (fDependsWait)
699  waitingOnDependants.push_back(&(*it));
700  else {
701  CheckInputsAndUpdateCoins(tx, mempoolDuplicate, spendheight);
702  }
703  }
704  unsigned int stepsSinceLastRemove = 0;
705  while (!waitingOnDependants.empty()) {
706  const CTxMemPoolEntry* entry = waitingOnDependants.front();
707  waitingOnDependants.pop_front();
708  if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
709  waitingOnDependants.push_back(entry);
710  stepsSinceLastRemove++;
711  assert(stepsSinceLastRemove < waitingOnDependants.size());
712  } else {
713  CheckInputsAndUpdateCoins(entry->GetTx(), mempoolDuplicate, spendheight);
714  stepsSinceLastRemove = 0;
715  }
716  }
717  for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
718  uint256 hash = it->second->GetHash();
719  indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
720  const CTransaction& tx = it2->GetTx();
721  assert(it2 != mapTx.end());
722  assert(&tx == it->second);
723  }
724 
725  assert(totalTxSize == checkTotal);
726  assert(innerUsage == cachedInnerUsage);
727 }
728 
729 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)
730 {
731  LOCK(cs);
732  indexed_transaction_set::const_iterator i = mapTx.find(hasha);
733  if (i == mapTx.end()) return false;
734  indexed_transaction_set::const_iterator j = mapTx.find(hashb);
735  if (j == mapTx.end()) return true;
736  uint64_t counta = i->GetCountWithAncestors();
737  uint64_t countb = j->GetCountWithAncestors();
738  if (counta == countb) {
739  return CompareTxMemPoolEntryByScore()(*i, *j);
740  }
741  return counta < countb;
742 }
743 
744 namespace {
745 class DepthAndScoreComparator
746 {
747 public:
748  bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
749  {
750  uint64_t counta = a->GetCountWithAncestors();
751  uint64_t countb = b->GetCountWithAncestors();
752  if (counta == countb) {
753  return CompareTxMemPoolEntryByScore()(*a, *b);
754  }
755  return counta < countb;
756  }
757 };
758 } // namespace
759 
760 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
761 {
762  std::vector<indexed_transaction_set::const_iterator> iters;
764 
765  iters.reserve(mapTx.size());
766 
767  for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
768  iters.push_back(mi);
769  }
770  std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
771  return iters;
772 }
773 
774 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) const
775 {
776  LOCK(cs);
777  auto iters = GetSortedDepthAndScore();
778 
779  vtxid.clear();
780  vtxid.reserve(mapTx.size());
781 
782  for (auto it : iters) {
783  vtxid.push_back(it->GetTx().GetHash());
784  }
785 }
786 
787 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
788  return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
789 }
790 
791 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
792 {
793  LOCK(cs);
794  auto iters = GetSortedDepthAndScore();
795 
796  std::vector<TxMempoolInfo> ret;
797  ret.reserve(mapTx.size());
798  for (auto it : iters) {
799  ret.push_back(GetInfo(it));
800  }
801 
802  return ret;
803 }
804 
806 {
807  LOCK(cs);
808  indexed_transaction_set::const_iterator i = mapTx.find(hash);
809  if (i == mapTx.end())
810  return nullptr;
811  return i->GetSharedTx();
812 }
813 
815 {
816  LOCK(cs);
817  indexed_transaction_set::const_iterator i = mapTx.find(hash);
818  if (i == mapTx.end())
819  return TxMempoolInfo();
820  return GetInfo(i);
821 }
822 
823 void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
824 {
825  {
826  LOCK(cs);
827  CAmount &delta = mapDeltas[hash];
828  delta += nFeeDelta;
829  txiter it = mapTx.find(hash);
830  if (it != mapTx.end()) {
831  mapTx.modify(it, update_fee_delta(delta));
832  // Now update all ancestors' modified fees with descendants
833  setEntries setAncestors;
834  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
835  std::string dummy;
836  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
837  for (txiter ancestorIt : setAncestors) {
838  mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
839  }
840  // Now update all descendants' modified fees with ancestors
841  setEntries setDescendants;
842  CalculateDescendants(it, setDescendants);
843  setDescendants.erase(it);
844  for (txiter descendantIt : setDescendants) {
845  mapTx.modify(descendantIt, update_ancestor_state(0, nFeeDelta, 0, 0));
846  }
848  }
849  }
850  LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
851 }
852 
853 void CTxMemPool::ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
854 {
855  LOCK(cs);
856  std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
857  if (pos == mapDeltas.end())
858  return;
859  const CAmount &delta = pos->second;
860  nFeeDelta += delta;
861 }
862 
864 {
865  LOCK(cs);
866  mapDeltas.erase(hash);
867 }
868 
870 {
871  const auto it = mapNextTx.find(prevout);
872  return it == mapNextTx.end() ? nullptr : it->second;
873 }
874 
876 {
877  auto it = mapTx.find(txid);
878  if (it != mapTx.end()) return it;
879  return Optional<txiter>{};
880 }
881 
882 CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<uint256>& hashes) const
883 {
885  for (const auto& h : hashes) {
886  const auto mi = GetIter(h);
887  if (mi) ret.insert(*mi);
888  }
889  return ret;
890 }
891 
893 {
894  for (unsigned int i = 0; i < tx.vin.size(); i++)
895  if (exists(tx.vin[i].prevout.hash))
896  return false;
897  return true;
898 }
899 
900 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
901 
902 bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
903  // If an entry in the mempool exists, always return that one, as it's guaranteed to never
904  // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
905  // transactions. First checking the underlying cache risks returning a pruned entry instead.
906  CTransactionRef ptx = mempool.get(outpoint.hash);
907  if (ptx) {
908  if (outpoint.n < ptx->vout.size()) {
909  coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
910  return true;
911  } else {
912  return false;
913  }
914  }
915  return base->GetCoin(outpoint, coin);
916 }
917 
919  LOCK(cs);
920  // Estimate the overhead of mapTx to be 12 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
921  return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 12 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapLinks) + memusage::DynamicUsage(vTxHashes) + cachedInnerUsage;
922 }
923 
924 void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) {
925  LOCK(cs);
926 
927  if (m_unbroadcast_txids.erase(txid))
928  {
929  LogPrint(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
930  }
931 }
932 
933 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
935  UpdateForRemoveFromMempool(stage, updateDescendants);
936  for (txiter it : stage) {
937  removeUnchecked(it, reason);
938  }
939 }
940 
941 int CTxMemPool::Expire(std::chrono::seconds time)
942 {
944  indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
945  setEntries toremove;
946  while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
947  toremove.insert(mapTx.project<0>(it));
948  it++;
949  }
950  setEntries stage;
951  for (txiter removeit : toremove) {
952  CalculateDescendants(removeit, stage);
953  }
954  RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
955  return stage.size();
956 }
957 
958 void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry, bool validFeeEstimate)
959 {
960  setEntries setAncestors;
961  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
962  std::string dummy;
963  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
964  return addUnchecked(entry, setAncestors, validFeeEstimate);
965 }
966 
967 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
968 {
969  setEntries s;
970  if (add && mapLinks[entry].children.insert(child).second) {
971  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
972  } else if (!add && mapLinks[entry].children.erase(child)) {
973  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
974  }
975 }
976 
977 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
978 {
979  setEntries s;
980  if (add && mapLinks[entry].parents.insert(parent).second) {
981  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
982  } else if (!add && mapLinks[entry].parents.erase(parent)) {
983  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
984  }
985 }
986 
988 {
989  assert (entry != mapTx.end());
990  txlinksMap::const_iterator it = mapLinks.find(entry);
991  assert(it != mapLinks.end());
992  return it->second.parents;
993 }
994 
996 {
997  assert (entry != mapTx.end());
998  txlinksMap::const_iterator it = mapLinks.find(entry);
999  assert(it != mapLinks.end());
1000  return it->second.children;
1001 }
1002 
1003 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1004  LOCK(cs);
1005  if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1006  return CFeeRate(llround(rollingMinimumFeeRate));
1007 
1008  int64_t time = GetTime();
1009  if (time > lastRollingFeeUpdate + 10) {
1010  double halflife = ROLLING_FEE_HALFLIFE;
1011  if (DynamicMemoryUsage() < sizelimit / 4)
1012  halflife /= 4;
1013  else if (DynamicMemoryUsage() < sizelimit / 2)
1014  halflife /= 2;
1015 
1016  rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1017  lastRollingFeeUpdate = time;
1018 
1019  if (rollingMinimumFeeRate < (double)incrementalRelayFee.GetFeePerK() / 2) {
1020  rollingMinimumFeeRate = 0;
1021  return CFeeRate(0);
1022  }
1023  }
1024  return std::max(CFeeRate(llround(rollingMinimumFeeRate)), incrementalRelayFee);
1025 }
1026 
1028  AssertLockHeld(cs);
1029  if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1030  rollingMinimumFeeRate = rate.GetFeePerK();
1031  blockSinceLastRollingFeeBump = false;
1032  }
1033 }
1034 
1035 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1036  AssertLockHeld(cs);
1037 
1038  unsigned nTxnRemoved = 0;
1039  CFeeRate maxFeeRateRemoved(0);
1040  while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1041  indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1042 
1043  // We set the new mempool min fee to the feerate of the removed set, plus the
1044  // "minimum reasonable fee rate" (ie some value under which we consider txn
1045  // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1046  // equal to txn which were removed with no block in between.
1047  CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1048  removed += incrementalRelayFee;
1049  trackPackageRemoved(removed);
1050  maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1051 
1052  setEntries stage;
1053  CalculateDescendants(mapTx.project<0>(it), stage);
1054  nTxnRemoved += stage.size();
1055 
1056  std::vector<CTransaction> txn;
1057  if (pvNoSpendsRemaining) {
1058  txn.reserve(stage.size());
1059  for (txiter iter : stage)
1060  txn.push_back(iter->GetTx());
1061  }
1062  RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1063  if (pvNoSpendsRemaining) {
1064  for (const CTransaction& tx : txn) {
1065  for (const CTxIn& txin : tx.vin) {
1066  if (exists(txin.prevout.hash)) continue;
1067  pvNoSpendsRemaining->push_back(txin.prevout);
1068  }
1069  }
1070  }
1071  }
1072 
1073  if (maxFeeRateRemoved > CFeeRate(0)) {
1074  LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1075  }
1076 }
1077 
1079  // find parent with highest descendant count
1080  std::vector<txiter> candidates;
1081  setEntries counted;
1082  candidates.push_back(entry);
1083  uint64_t maximum = 0;
1084  while (candidates.size()) {
1085  txiter candidate = candidates.back();
1086  candidates.pop_back();
1087  if (!counted.insert(candidate).second) continue;
1088  const setEntries& parents = GetMemPoolParents(candidate);
1089  if (parents.size() == 0) {
1090  maximum = std::max(maximum, candidate->GetCountWithDescendants());
1091  } else {
1092  for (txiter i : parents) {
1093  candidates.push_back(i);
1094  }
1095  }
1096  }
1097  return maximum;
1098 }
1099 
1100 void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) const {
1101  LOCK(cs);
1102  auto it = mapTx.find(txid);
1103  ancestors = descendants = 0;
1104  if (it != mapTx.end()) {
1105  ancestors = it->GetCountWithAncestors();
1106  descendants = CalculateDescendantMaximum(it);
1107  }
1108 }
1109 
1111 {
1112  LOCK(cs);
1113  return m_is_loaded;
1114 }
1115 
1116 void CTxMemPool::SetIsLoaded(bool loaded)
1117 {
1118  LOCK(cs);
1119  m_is_loaded = loaded;
1120 }
1121 
1122 
1124 {
1125  return EpochGuard(*this);
1126 }
1128 {
1129  assert(!pool.m_has_epoch_guard);
1130  ++pool.m_epoch;
1131  pool.m_has_epoch_guard = true;
1132 }
1133 
1135 {
1136  // prevents stale results being used
1137  ++pool.m_epoch;
1138  pool.m_has_epoch_guard = false;
1139 }
1140 
1141 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:387
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:133
CTxMemPool mempool
void queryHashes(std::vector< uint256 > &vtxid) const
Definition: txmempool.cpp:774
bool IsSpent() const
Definition: coins.h:76
Information about a mempool transaction.
Definition: txmempool.h:327
bool IsCoinBase() const
Definition: coins.h:55
const CTransactionRef tx
Definition: txmempool.h:67
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:586
bool m_has_epoch_guard
Definition: txmempool.h:457
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:83
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:875
uint64_t m_epoch
Definition: txmempool.h:456
#define LogPrint(category,...)
Definition: logging.h:182
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:523
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:791
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:131
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
#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:446
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:918
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:902
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:814
Removed in size limiting.
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:536
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:933
void clear()
Definition: txmempool.cpp:598
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:131
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:531
void TransactionRemovedFromMempool(const CTransactionRef &)
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:348
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:447
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:469
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:499
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:236
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:256
uint64_t nCountWithDescendants
number of descendant transactions
Definition: txmempool.h:81
int64_t lastRollingFeeUpdate
Definition: txmempool.h:453
bool IsLoaded() const
Definition: txmempool.cpp:1110
bool IsCoinBase() const
Definition: transaction.h:316
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:340
const std::vector< CTxIn > vin
Definition: transaction.h:268
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:64
void addUnchecked(const CTxMemPoolEntry &entry, bool validFeeEstimate=true) EXCLUSIVE_LOCKS_REQUIRED(cs
Definition: txmempool.cpp:958
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:613
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:454
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:89
const size_t nTxWeight
... and avoid recomputing tx weight (also used for GetTxSize())
Definition: txmempool.h:69
void UpdateFeeDelta(int64_t feeDelta)
Definition: txmempool.cpp:40
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:206
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.cpp:787
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
uint64_t nSizeWithAncestors
Definition: txmempool.h:87
int64_t feeDelta
Used for determining the priority of the transaction for mining in a block.
Definition: txmempool.h:75
Abstract view on the open txout dataset.
Definition: coins.h:180
size_t DynamicMemoryUsage() const
Definition: txmempool.h:106
void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
Definition: txmempool.cpp:853
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:941
bool exists(const uint256 &hash) const
Definition: txmempool.h:692
An input of a transaction.
Definition: transaction.h:57
const uint256 & GetWitnessHash() const
Definition: transaction.h:304
#define LOCK(cs)
Definition: sync.h:220
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:220
const uint256 & GetHash() const
Definition: transaction.h:303
Removed for conflict with in-block transaction.
Removed for block.
void UpdateParent(txiter entry, txiter parent, bool add)
Definition: txmempool.cpp:977
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:406
std::map< uint256, CAmount > mapDeltas
Definition: txmempool.h:557
uint32_t n
Definition: transaction.h:22
const std::vector< CTxOut > vout
Definition: transaction.h:269
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:451
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain. ...
Definition: validation.cpp:238
CAmount nModFeesWithAncestors
Definition: txmempool.h:88
std::string ToString() const
Definition: uint256.cpp:60
const setEntries & GetMemPoolChildren(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:995
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:869
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:82
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:1003
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:450
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1078
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
const int64_t sigOpCost
Total sigop cost.
Definition: txmempool.h:74
int flags
Definition: bitcoin-tx.cpp:509
EpochGuard(const CTxMemPool &in)
Definition: txmempool.cpp:1127
256-bit opaque blob.
Definition: uint256.h:120
static void CheckInputsAndUpdateCoins(const CTransaction &tx, CCoinsViewCache &mempoolDuplicate, const int64_t spendheight)
Definition: txmempool.cpp:604
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:760
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:443
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:892
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb)
Definition: txmempool.cpp:729
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:537
EpochGuard GetFreshEpoch() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1123
LockPoints lockPoints
Track the height and time at which tx was final.
Definition: txmempool.h:76
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:97
void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:585
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:882
std::string GetHex() const
Definition: uint256.cpp:20
uint64_t nCountWithAncestors
Definition: txmempool.h:86
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
void UpdateChild(txiter entry, txiter child, bool add)
Definition: txmempool.cpp:967
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:346
const CAmount nFee
Cached to avoid expensive parent-transaction lookups.
Definition: txmempool.h:68
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
const setEntries & GetMemPoolParents(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:987
void ClearPrioritisation(const uint256 hash)
Definition: txmempool.cpp:863
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:1035
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:805
void RemoveUnbroadcastTx(const uint256 &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:924
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1027
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:900
std::string ToString() const
Definition: feerate.cpp:40
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:251
CCoinsView backed by another CCoinsView.
Definition: coins.h:217
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:236
Sort by feerate of entry (fee/size) in descending order This is only used for transaction relay...
Definition: txmempool.h:250
AssertLockHeld(g_cs_orphans)
const CTxMemPool & mempool
Definition: txmempool.h:831
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:23
auto it
Definition: validation.cpp:380
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1116
txlinksMap mapLinks
Definition: txmempool.h:545
COutPoint prevout
Definition: transaction.h:60
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:448
double rollingMinimumFeeRate
minimum fee to get into the pool, decreases exponentially
Definition: txmempool.h:455
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:556
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:823
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:785
const CTxMemPool & pool
Definition: txmempool.h:786
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:520
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:1100
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:140
uint256 hash
Definition: transaction.h:21