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