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