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  // 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  if (vTxHashes.size() > 1) {
421  vTxHashes[it->vTxHashesIdx] = std::move(vTxHashes.back());
422  vTxHashes[it->vTxHashesIdx].second->vTxHashesIdx = it->vTxHashesIdx;
423  vTxHashes.pop_back();
424  if (vTxHashes.size() * 2 < vTxHashes.capacity())
425  vTxHashes.shrink_to_fit();
426  } else
427  vTxHashes.clear();
428 
429  totalTxSize -= it->GetTxSize();
430  cachedInnerUsage -= it->DynamicMemoryUsage();
432  mapLinks.erase(it);
433  mapTx.erase(it);
436 }
437 
438 // Calculates descendants of entry that are not already in setDescendants, and adds to
439 // setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
440 // is correct for tx and all descendants.
441 // Also assumes that if an entry is in setDescendants already, then all
442 // in-mempool descendants of it are already in setDescendants as well, so that we
443 // can save time by not iterating over those entries.
444 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
445 {
446  setEntries stage;
447  if (setDescendants.count(entryit) == 0) {
448  stage.insert(entryit);
449  }
450  // Traverse down the children of entry, only adding children that are not
451  // accounted for in setDescendants already (because those children have either
452  // already been walked, or will be walked in this iteration).
453  while (!stage.empty()) {
454  txiter it = *stage.begin();
455  setDescendants.insert(it);
456  stage.erase(it);
457 
458  const setEntries &setChildren = GetMemPoolChildren(it);
459  for (txiter childiter : setChildren) {
460  if (!setDescendants.count(childiter)) {
461  stage.insert(childiter);
462  }
463  }
464  }
465 }
466 
468 {
469  // Remove transaction from memory pool
471  setEntries txToRemove;
472  txiter origit = mapTx.find(origTx.GetHash());
473  if (origit != mapTx.end()) {
474  txToRemove.insert(origit);
475  } else {
476  // When recursively removing but origTx isn't in the mempool
477  // be sure to remove any children that are in the pool. This can
478  // happen during chain re-orgs if origTx isn't re-accepted into
479  // the mempool for any reason.
480  for (unsigned int i = 0; i < origTx.vout.size(); i++) {
481  auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
482  if (it == mapNextTx.end())
483  continue;
484  txiter nextit = mapTx.find(it->second->GetHash());
485  assert(nextit != mapTx.end());
486  txToRemove.insert(nextit);
487  }
488  }
489  setEntries setAllRemoves;
490  for (txiter it : txToRemove) {
491  CalculateDescendants(it, setAllRemoves);
492  }
493 
494  RemoveStaged(setAllRemoves, false, reason);
495 }
496 
497 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
498 {
499  // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
501  setEntries txToRemove;
502  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
503  const CTransaction& tx = it->GetTx();
504  LockPoints lp = it->GetLockPoints();
505  bool validLP = TestLockPointValidity(&lp);
506  if (!CheckFinalTx(tx, flags) || !CheckSequenceLocks(*this, tx, flags, &lp, validLP)) {
507  // Note if CheckSequenceLocks fails the LockPoints may still be invalid
508  // So it's critical that we remove the tx and not depend on the LockPoints.
509  txToRemove.insert(it);
510  } else if (it->GetSpendsCoinbase()) {
511  for (const CTxIn& txin : tx.vin) {
512  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
513  if (it2 != mapTx.end())
514  continue;
515  const Coin &coin = pcoins->AccessCoin(txin.prevout);
516  if (nCheckFrequency != 0) assert(!coin.IsSpent());
517  if (coin.IsSpent() || (coin.IsCoinBase() && ((signed long)nMemPoolHeight) - coin.nHeight < COINBASE_MATURITY)) {
518  txToRemove.insert(it);
519  break;
520  }
521  }
522  }
523  if (!validLP) {
524  mapTx.modify(it, update_lock_points(lp));
525  }
526  }
527  setEntries setAllRemoves;
528  for (txiter it : txToRemove) {
529  CalculateDescendants(it, setAllRemoves);
530  }
531  RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
532 }
533 
535 {
536  // Remove transactions which depend on inputs of tx, recursively
538  for (const CTxIn &txin : tx.vin) {
539  auto it = mapNextTx.find(txin.prevout);
540  if (it != mapNextTx.end()) {
541  const CTransaction &txConflict = *it->second;
542  if (txConflict != tx)
543  {
544  ClearPrioritisation(txConflict.GetHash());
546  }
547  }
548  }
549 }
550 
554 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
555 {
557  std::vector<const CTxMemPoolEntry*> entries;
558  for (const auto& tx : vtx)
559  {
560  uint256 hash = tx->GetHash();
561 
562  indexed_transaction_set::iterator i = mapTx.find(hash);
563  if (i != mapTx.end())
564  entries.push_back(&*i);
565  }
566  // Before the txs in the new block have been removed from the mempool, update policy estimates
567  if (minerPolicyEstimator) {minerPolicyEstimator->processBlock(nBlockHeight, entries);}
568  for (const auto& tx : vtx)
569  {
570  txiter it = mapTx.find(tx->GetHash());
571  if (it != mapTx.end()) {
572  setEntries stage;
573  stage.insert(it);
575  }
576  removeConflicts(*tx);
577  ClearPrioritisation(tx->GetHash());
578  }
581 }
582 
584 {
585  mapLinks.clear();
586  mapTx.clear();
587  mapNextTx.clear();
588  totalTxSize = 0;
589  cachedInnerUsage = 0;
594 }
595 
597 {
598  LOCK(cs);
599  _clear();
600 }
601 
602 static void CheckInputsAndUpdateCoins(const CTransaction& tx, CCoinsViewCache& mempoolDuplicate, const int64_t spendheight)
603 {
604  TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
605  CAmount txfee = 0;
606  bool fCheckResult = tx.IsCoinBase() || Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee);
607  assert(fCheckResult);
608  UpdateCoins(tx, mempoolDuplicate, std::numeric_limits<int>::max());
609 }
610 
611 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
612 {
613  LOCK(cs);
614  if (nCheckFrequency == 0)
615  return;
616 
617  if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)
618  return;
619 
620  LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
621 
622  uint64_t checkTotal = 0;
623  uint64_t innerUsage = 0;
624 
625  CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
626  const int64_t spendheight = GetSpendHeight(mempoolDuplicate);
627 
628  std::list<const CTxMemPoolEntry*> waitingOnDependants;
629  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
630  unsigned int i = 0;
631  checkTotal += it->GetTxSize();
632  innerUsage += it->DynamicMemoryUsage();
633  const CTransaction& tx = it->GetTx();
634  txlinksMap::const_iterator linksiter = mapLinks.find(it);
635  assert(linksiter != mapLinks.end());
636  const TxLinks &links = linksiter->second;
637  innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
638  bool fDependsWait = false;
639  setEntries setParentCheck;
640  for (const CTxIn &txin : tx.vin) {
641  // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
642  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
643  if (it2 != mapTx.end()) {
644  const CTransaction& tx2 = it2->GetTx();
645  assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
646  fDependsWait = true;
647  setParentCheck.insert(it2);
648  } else {
649  assert(pcoins->HaveCoin(txin.prevout));
650  }
651  // Check whether its inputs are marked in mapNextTx.
652  auto it3 = mapNextTx.find(txin.prevout);
653  assert(it3 != mapNextTx.end());
654  assert(it3->first == &txin.prevout);
655  assert(it3->second == &tx);
656  i++;
657  }
658  assert(setParentCheck == GetMemPoolParents(it));
659  // Verify ancestor state is correct.
660  setEntries setAncestors;
661  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
662  std::string dummy;
663  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
664  uint64_t nCountCheck = setAncestors.size() + 1;
665  uint64_t nSizeCheck = it->GetTxSize();
666  CAmount nFeesCheck = it->GetModifiedFee();
667  int64_t nSigOpCheck = it->GetSigOpCost();
668 
669  for (txiter ancestorIt : setAncestors) {
670  nSizeCheck += ancestorIt->GetTxSize();
671  nFeesCheck += ancestorIt->GetModifiedFee();
672  nSigOpCheck += ancestorIt->GetSigOpCost();
673  }
674 
675  assert(it->GetCountWithAncestors() == nCountCheck);
676  assert(it->GetSizeWithAncestors() == nSizeCheck);
677  assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
678  assert(it->GetModFeesWithAncestors() == nFeesCheck);
679 
680  // Check children against mapNextTx
681  CTxMemPool::setEntries setChildrenCheck;
682  auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
683  uint64_t child_sizes = 0;
684  for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
685  txiter childit = mapTx.find(iter->second->GetHash());
686  assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
687  if (setChildrenCheck.insert(childit).second) {
688  child_sizes += childit->GetTxSize();
689  }
690  }
691  assert(setChildrenCheck == GetMemPoolChildren(it));
692  // Also check to make sure size is greater than sum with immediate children.
693  // just a sanity check, not definitive that this calc is correct...
694  assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
695 
696  if (fDependsWait)
697  waitingOnDependants.push_back(&(*it));
698  else {
699  CheckInputsAndUpdateCoins(tx, mempoolDuplicate, spendheight);
700  }
701  }
702  unsigned int stepsSinceLastRemove = 0;
703  while (!waitingOnDependants.empty()) {
704  const CTxMemPoolEntry* entry = waitingOnDependants.front();
705  waitingOnDependants.pop_front();
706  if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
707  waitingOnDependants.push_back(entry);
708  stepsSinceLastRemove++;
709  assert(stepsSinceLastRemove < waitingOnDependants.size());
710  } else {
711  CheckInputsAndUpdateCoins(entry->GetTx(), mempoolDuplicate, spendheight);
712  stepsSinceLastRemove = 0;
713  }
714  }
715  for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
716  uint256 hash = it->second->GetHash();
717  indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
718  const CTransaction& tx = it2->GetTx();
719  assert(it2 != mapTx.end());
720  assert(&tx == it->second);
721  }
722 
723  assert(totalTxSize == checkTotal);
724  assert(innerUsage == cachedInnerUsage);
725 }
726 
727 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)
728 {
729  LOCK(cs);
730  indexed_transaction_set::const_iterator i = mapTx.find(hasha);
731  if (i == mapTx.end()) return false;
732  indexed_transaction_set::const_iterator j = mapTx.find(hashb);
733  if (j == mapTx.end()) return true;
734  uint64_t counta = i->GetCountWithAncestors();
735  uint64_t countb = j->GetCountWithAncestors();
736  if (counta == countb) {
737  return CompareTxMemPoolEntryByScore()(*i, *j);
738  }
739  return counta < countb;
740 }
741 
742 namespace {
743 class DepthAndScoreComparator
744 {
745 public:
746  bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
747  {
748  uint64_t counta = a->GetCountWithAncestors();
749  uint64_t countb = b->GetCountWithAncestors();
750  if (counta == countb) {
751  return CompareTxMemPoolEntryByScore()(*a, *b);
752  }
753  return counta < countb;
754  }
755 };
756 } // namespace
757 
758 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
759 {
760  std::vector<indexed_transaction_set::const_iterator> iters;
762 
763  iters.reserve(mapTx.size());
764 
765  for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
766  iters.push_back(mi);
767  }
768  std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
769  return iters;
770 }
771 
772 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) const
773 {
774  LOCK(cs);
775  auto iters = GetSortedDepthAndScore();
776 
777  vtxid.clear();
778  vtxid.reserve(mapTx.size());
779 
780  for (auto it : iters) {
781  vtxid.push_back(it->GetTx().GetHash());
782  }
783 }
784 
785 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
786  return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
787 }
788 
789 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
790 {
791  LOCK(cs);
792  auto iters = GetSortedDepthAndScore();
793 
794  std::vector<TxMempoolInfo> ret;
795  ret.reserve(mapTx.size());
796  for (auto it : iters) {
797  ret.push_back(GetInfo(it));
798  }
799 
800  return ret;
801 }
802 
804 {
805  LOCK(cs);
806  indexed_transaction_set::const_iterator i = mapTx.find(hash);
807  if (i == mapTx.end())
808  return nullptr;
809  return i->GetSharedTx();
810 }
811 
813 {
814  LOCK(cs);
815  indexed_transaction_set::const_iterator i = mapTx.find(hash);
816  if (i == mapTx.end())
817  return TxMempoolInfo();
818  return GetInfo(i);
819 }
820 
821 void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
822 {
823  {
824  LOCK(cs);
825  CAmount &delta = mapDeltas[hash];
826  delta += nFeeDelta;
827  txiter it = mapTx.find(hash);
828  if (it != mapTx.end()) {
829  mapTx.modify(it, update_fee_delta(delta));
830  // Now update all ancestors' modified fees with descendants
831  setEntries setAncestors;
832  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
833  std::string dummy;
834  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
835  for (txiter ancestorIt : setAncestors) {
836  mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
837  }
838  // Now update all descendants' modified fees with ancestors
839  setEntries setDescendants;
840  CalculateDescendants(it, setDescendants);
841  setDescendants.erase(it);
842  for (txiter descendantIt : setDescendants) {
843  mapTx.modify(descendantIt, update_ancestor_state(0, nFeeDelta, 0, 0));
844  }
846  }
847  }
848  LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
849 }
850 
851 void CTxMemPool::ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
852 {
853  LOCK(cs);
854  std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
855  if (pos == mapDeltas.end())
856  return;
857  const CAmount &delta = pos->second;
858  nFeeDelta += delta;
859 }
860 
862 {
863  LOCK(cs);
864  mapDeltas.erase(hash);
865 }
866 
868 {
869  const auto it = mapNextTx.find(prevout);
870  return it == mapNextTx.end() ? nullptr : it->second;
871 }
872 
874 {
875  auto it = mapTx.find(txid);
876  if (it != mapTx.end()) return it;
877  return Optional<txiter>{};
878 }
879 
880 CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<uint256>& hashes) const
881 {
883  for (const auto& h : hashes) {
884  const auto mi = GetIter(h);
885  if (mi) ret.insert(*mi);
886  }
887  return ret;
888 }
889 
891 {
892  for (unsigned int i = 0; i < tx.vin.size(); i++)
893  if (exists(tx.vin[i].prevout.hash))
894  return false;
895  return true;
896 }
897 
898 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
899 
900 bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
901  // If an entry in the mempool exists, always return that one, as it's guaranteed to never
902  // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
903  // transactions. First checking the underlying cache risks returning a pruned entry instead.
904  CTransactionRef ptx = mempool.get(outpoint.hash);
905  if (ptx) {
906  if (outpoint.n < ptx->vout.size()) {
907  coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
908  return true;
909  } else {
910  return false;
911  }
912  }
913  return base->GetCoin(outpoint, coin);
914 }
915 
917  LOCK(cs);
918  // Estimate the overhead of mapTx to be 12 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
919  return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 12 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapLinks) + memusage::DynamicUsage(vTxHashes) + cachedInnerUsage;
920 }
921 
922 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
924  UpdateForRemoveFromMempool(stage, updateDescendants);
925  for (txiter it : stage) {
926  removeUnchecked(it, reason);
927  }
928 }
929 
930 int CTxMemPool::Expire(std::chrono::seconds time)
931 {
933  indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
934  setEntries toremove;
935  while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
936  toremove.insert(mapTx.project<0>(it));
937  it++;
938  }
939  setEntries stage;
940  for (txiter removeit : toremove) {
941  CalculateDescendants(removeit, stage);
942  }
943  RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
944  return stage.size();
945 }
946 
947 void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry, bool validFeeEstimate)
948 {
949  setEntries setAncestors;
950  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
951  std::string dummy;
952  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
953  return addUnchecked(entry, setAncestors, validFeeEstimate);
954 }
955 
956 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
957 {
958  setEntries s;
959  if (add && mapLinks[entry].children.insert(child).second) {
960  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
961  } else if (!add && mapLinks[entry].children.erase(child)) {
962  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
963  }
964 }
965 
966 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
967 {
968  setEntries s;
969  if (add && mapLinks[entry].parents.insert(parent).second) {
970  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
971  } else if (!add && mapLinks[entry].parents.erase(parent)) {
972  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
973  }
974 }
975 
977 {
978  assert (entry != mapTx.end());
979  txlinksMap::const_iterator it = mapLinks.find(entry);
980  assert(it != mapLinks.end());
981  return it->second.parents;
982 }
983 
985 {
986  assert (entry != mapTx.end());
987  txlinksMap::const_iterator it = mapLinks.find(entry);
988  assert(it != mapLinks.end());
989  return it->second.children;
990 }
991 
992 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
993  LOCK(cs);
994  if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
995  return CFeeRate(llround(rollingMinimumFeeRate));
996 
997  int64_t time = GetTime();
998  if (time > lastRollingFeeUpdate + 10) {
999  double halflife = ROLLING_FEE_HALFLIFE;
1000  if (DynamicMemoryUsage() < sizelimit / 4)
1001  halflife /= 4;
1002  else if (DynamicMemoryUsage() < sizelimit / 2)
1003  halflife /= 2;
1004 
1005  rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1006  lastRollingFeeUpdate = time;
1007 
1008  if (rollingMinimumFeeRate < (double)incrementalRelayFee.GetFeePerK() / 2) {
1009  rollingMinimumFeeRate = 0;
1010  return CFeeRate(0);
1011  }
1012  }
1013  return std::max(CFeeRate(llround(rollingMinimumFeeRate)), incrementalRelayFee);
1014 }
1015 
1017  AssertLockHeld(cs);
1018  if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1019  rollingMinimumFeeRate = rate.GetFeePerK();
1020  blockSinceLastRollingFeeBump = false;
1021  }
1022 }
1023 
1024 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1025  AssertLockHeld(cs);
1026 
1027  unsigned nTxnRemoved = 0;
1028  CFeeRate maxFeeRateRemoved(0);
1029  while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1030  indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1031 
1032  // We set the new mempool min fee to the feerate of the removed set, plus the
1033  // "minimum reasonable fee rate" (ie some value under which we consider txn
1034  // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1035  // equal to txn which were removed with no block in between.
1036  CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1037  removed += incrementalRelayFee;
1038  trackPackageRemoved(removed);
1039  maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1040 
1041  setEntries stage;
1042  CalculateDescendants(mapTx.project<0>(it), stage);
1043  nTxnRemoved += stage.size();
1044 
1045  std::vector<CTransaction> txn;
1046  if (pvNoSpendsRemaining) {
1047  txn.reserve(stage.size());
1048  for (txiter iter : stage)
1049  txn.push_back(iter->GetTx());
1050  }
1051  RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1052  if (pvNoSpendsRemaining) {
1053  for (const CTransaction& tx : txn) {
1054  for (const CTxIn& txin : tx.vin) {
1055  if (exists(txin.prevout.hash)) continue;
1056  pvNoSpendsRemaining->push_back(txin.prevout);
1057  }
1058  }
1059  }
1060  }
1061 
1062  if (maxFeeRateRemoved > CFeeRate(0)) {
1063  LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1064  }
1065 }
1066 
1068  // find parent with highest descendant count
1069  std::vector<txiter> candidates;
1070  setEntries counted;
1071  candidates.push_back(entry);
1072  uint64_t maximum = 0;
1073  while (candidates.size()) {
1074  txiter candidate = candidates.back();
1075  candidates.pop_back();
1076  if (!counted.insert(candidate).second) continue;
1077  const setEntries& parents = GetMemPoolParents(candidate);
1078  if (parents.size() == 0) {
1079  maximum = std::max(maximum, candidate->GetCountWithDescendants());
1080  } else {
1081  for (txiter i : parents) {
1082  candidates.push_back(i);
1083  }
1084  }
1085  }
1086  return maximum;
1087 }
1088 
1089 void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) const {
1090  LOCK(cs);
1091  auto it = mapTx.find(txid);
1092  ancestors = descendants = 0;
1093  if (it != mapTx.end()) {
1094  ancestors = it->GetCountWithAncestors();
1095  descendants = CalculateDescendantMaximum(it);
1096  }
1097 }
1098 
1100 {
1101  LOCK(cs);
1102  return m_is_loaded;
1103 }
1104 
1105 void CTxMemPool::SetIsLoaded(bool loaded)
1106 {
1107  LOCK(cs);
1108  m_is_loaded = loaded;
1109 }
1110 
1111 
1113 {
1114  return EpochGuard(*this);
1115 }
1117 {
1118  assert(!pool.m_has_epoch_guard);
1119  ++pool.m_epoch;
1120  pool.m_has_epoch_guard = true;
1121 }
1122 
1124 {
1125  // prevents stale results being used
1126  ++pool.m_epoch;
1127  pool.m_has_epoch_guard = false;
1128 }
1129 
1130 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:133
CTxMemPool mempool
void queryHashes(std::vector< uint256 > &vtxid) const
Definition: txmempool.cpp:772
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
Definition: random.cpp:585
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:873
uint64_t m_epoch
Definition: txmempool.h:456
#define LogPrint(category,...)
Definition: logging.h:179
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:789
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
#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:444
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:916
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:900
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:812
Removed in size limiting.
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:534
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:922
void clear()
Definition: txmempool.cpp:596
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:163
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:467
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:497
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:237
uint64_t nCountWithDescendants
number of descendant transactions
Definition: txmempool.h:81
int64_t lastRollingFeeUpdate
Definition: txmempool.h:453
bool IsLoaded() const
Definition: txmempool.cpp:1099
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:64
void addUnchecked(const CTxMemPoolEntry &entry, bool validFeeEstimate=true) EXCLUSIVE_LOCKS_REQUIRED(cs
Definition: txmempool.cpp:947
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:611
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:187
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.cpp:785
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:154
size_t DynamicMemoryUsage() const
Definition: txmempool.h:106
void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
Definition: txmempool.cpp:851
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:930
bool exists(const uint256 &hash) const
Definition: txmempool.h:689
An input of a transaction.
Definition: transaction.h:63
const uint256 & GetWitnessHash() const
Definition: transaction.h:323
#define LOCK(cs)
Definition: sync.h:218
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.
Removed for block.
void UpdateParent(txiter entry, txiter parent, bool add)
Definition: txmempool.cpp:966
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:554
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:451
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain. ...
Definition: validation.cpp:219
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:984
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:867
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:992
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:1067
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:1116
256-bit opaque blob.
Definition: uint256.h:120
static void CheckInputsAndUpdateCoins(const CTransaction &tx, CCoinsViewCache &mempoolDuplicate, const int64_t spendheight)
Definition: txmempool.cpp:602
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:758
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:890
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb)
Definition: txmempool.cpp:727
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:1112
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:583
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:880
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:956
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:976
void ClearPrioritisation(const uint256 hash)
Definition: txmempool.cpp:861
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:1024
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:803
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1016
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:898
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:250
AssertLockHeld(g_cs_orphans)
const CTxMemPool & mempool
Definition: txmempool.h:804
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:23
auto it
Definition: validation.cpp:361
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1105
txlinksMap mapLinks
Definition: txmempool.h:545
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: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:554
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:821
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:758
const CTxMemPool & pool
Definition: txmempool.h:759
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:1089
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