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