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