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