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