Dash Core  0.12.2.1
P2P Digital Currency
txmempool.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 "clientversion.h"
9 #include "consensus/consensus.h"
10 #include "consensus/validation.h"
11 #include "validation.h"
12 #include "policy/fees.h"
13 #include "random.h"
14 #include "streams.h"
15 #include "timedata.h"
16 #include "util.h"
17 #include "utilmoneystr.h"
18 #include "utiltime.h"
19 #include "version.h"
20 
21 using namespace std;
22 
24  int64_t _nTime, double _entryPriority, unsigned int _entryHeight,
25  bool poolHasNoInputsOf, CAmount _inChainInputValue,
26  bool _spendsCoinbase, unsigned int _sigOps, LockPoints lp):
27  tx(_tx), nFee(_nFee), nTime(_nTime), entryPriority(_entryPriority), entryHeight(_entryHeight),
28  hadNoDependencies(poolHasNoInputsOf), inChainInputValue(_inChainInputValue),
29  spendsCoinbase(_spendsCoinbase), sigOpCount(_sigOps), lockPoints(lp)
30 {
34 
38  CAmount nValueIn = tx.GetValueOut()+nFee;
39  assert(inChainInputValue <= nValueIn);
40 
41  feeDelta = 0;
42 }
43 
45 {
46  *this = other;
47 }
48 
49 double
50 CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
51 {
52  double deltaPriority = ((double)(currentHeight-entryHeight)*inChainInputValue)/nModSize;
53  double dResult = entryPriority + deltaPriority;
54  if (dResult < 0) // This should only happen if it was called with a height below entry height
55  dResult = 0;
56  return dResult;
57 }
58 
59 void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
60 {
61  nModFeesWithDescendants += newFeeDelta - feeDelta;
62  feeDelta = newFeeDelta;
63 }
64 
66 {
67  lockPoints = lp;
68 }
69 
70 // Update the given tx for any in-mempool descendants.
71 // Assumes that setMemPoolChildren is correct for the given tx and all
72 // descendants.
73 bool CTxMemPool::UpdateForDescendants(txiter updateIt, int maxDescendantsToVisit, cacheMap &cachedDescendants, const std::set<uint256> &setExclude)
74 {
75  // Track the number of entries (outside setExclude) that we'd need to visit
76  // (will bail out if it exceeds maxDescendantsToVisit)
77  int nChildrenToVisit = 0;
78 
79  setEntries stageEntries, setAllDescendants;
80  stageEntries = GetMemPoolChildren(updateIt);
81 
82  while (!stageEntries.empty()) {
83  const txiter cit = *stageEntries.begin();
84  if (cit->IsDirty()) {
85  // Don't consider any more children if any descendant is dirty
86  return false;
87  }
88  setAllDescendants.insert(cit);
89  stageEntries.erase(cit);
90  const setEntries &setChildren = GetMemPoolChildren(cit);
91  BOOST_FOREACH(const txiter childEntry, setChildren) {
92  cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
93  if (cacheIt != cachedDescendants.end()) {
94  // We've already calculated this one, just add the entries for this set
95  // but don't traverse again.
96  BOOST_FOREACH(const txiter cacheEntry, cacheIt->second) {
97  // update visit count only for new child transactions
98  // (outside of setExclude and stageEntries)
99  if (setAllDescendants.insert(cacheEntry).second &&
100  !setExclude.count(cacheEntry->GetTx().GetHash()) &&
101  !stageEntries.count(cacheEntry)) {
102  nChildrenToVisit++;
103  }
104  }
105  } else if (!setAllDescendants.count(childEntry)) {
106  // Schedule for later processing and update our visit count
107  if (stageEntries.insert(childEntry).second && !setExclude.count(childEntry->GetTx().GetHash())) {
108  nChildrenToVisit++;
109  }
110  }
111  if (nChildrenToVisit > maxDescendantsToVisit) {
112  return false;
113  }
114  }
115  }
116  // setAllDescendants now contains all in-mempool descendants of updateIt.
117  // Update and add to cached descendant map
118  int64_t modifySize = 0;
119  CAmount modifyFee = 0;
120  int64_t modifyCount = 0;
121  BOOST_FOREACH(txiter cit, setAllDescendants) {
122  if (!setExclude.count(cit->GetTx().GetHash())) {
123  modifySize += cit->GetTxSize();
124  modifyFee += cit->GetModifiedFee();
125  modifyCount++;
126  cachedDescendants[updateIt].insert(cit);
127  }
128  }
129  mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));
130  return true;
131 }
132 
133 // vHashesToUpdate is the set of transaction hashes from a disconnected block
134 // which has been re-added to the mempool.
135 // for each entry, look for descendants that are outside hashesToUpdate, and
136 // add fee/size information for such descendants to the parent.
137 void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)
138 {
139  LOCK(cs);
140  // For each entry in vHashesToUpdate, store the set of in-mempool, but not
141  // in-vHashesToUpdate transactions, so that we don't have to recalculate
142  // descendants when we come across a previously seen entry.
143  cacheMap mapMemPoolDescendantsToUpdate;
144 
145  // Use a set for lookups into vHashesToUpdate (these entries are already
146  // accounted for in the state of their ancestors)
147  std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
148 
149  // Iterate in reverse, so that whenever we are looking at at a transaction
150  // we are sure that all in-mempool descendants have already been processed.
151  // This maximizes the benefit of the descendant cache and guarantees that
152  // setMemPoolChildren will be updated, an assumption made in
153  // UpdateForDescendants.
154  BOOST_REVERSE_FOREACH(const uint256 &hash, vHashesToUpdate) {
155  // we cache the in-mempool children to avoid duplicate updates
156  setEntries setChildren;
157  // calculate children from mapNextTx
158  txiter it = mapTx.find(hash);
159  if (it == mapTx.end()) {
160  continue;
161  }
162  std::map<COutPoint, CInPoint>::iterator iter = mapNextTx.lower_bound(COutPoint(hash, 0));
163  // First calculate the children, and update setMemPoolChildren to
164  // include them, and update their setMemPoolParents to include this tx.
165  for (; iter != mapNextTx.end() && iter->first.hash == hash; ++iter) {
166  const uint256 &childHash = iter->second.ptx->GetHash();
167  txiter childIter = mapTx.find(childHash);
168  assert(childIter != mapTx.end());
169  // We can skip updating entries we've encountered before or that
170  // are in the block (which are already accounted for).
171  if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash)) {
172  UpdateChild(it, childIter, true);
173  UpdateParent(childIter, it, true);
174  }
175  }
176  if (!UpdateForDescendants(it, 100, mapMemPoolDescendantsToUpdate, setAlreadyIncluded)) {
177  // Mark as dirty if we can't do the calculation.
178  mapTx.modify(it, set_dirty());
179  }
180  }
181 }
182 
183 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 */)
184 {
185  setEntries parentHashes;
186  const CTransaction &tx = entry.GetTx();
187 
188  if (fSearchForParents) {
189  // Get parents of this transaction that are in the mempool
190  // GetMemPoolParents() is only valid for entries in the mempool, so we
191  // iterate mapTx to find parents.
192  for (unsigned int i = 0; i < tx.vin.size(); i++) {
193  txiter piter = mapTx.find(tx.vin[i].prevout.hash);
194  if (piter != mapTx.end()) {
195  parentHashes.insert(piter);
196  if (parentHashes.size() + 1 > limitAncestorCount) {
197  errString = strprintf("too many unconfirmed parents [limit: %u]", limitAncestorCount);
198  return false;
199  }
200  }
201  }
202  } else {
203  // If we're not searching for parents, we require this to be an
204  // entry in the mempool already.
205  txiter it = mapTx.iterator_to(entry);
206  parentHashes = GetMemPoolParents(it);
207  }
208 
209  size_t totalSizeWithAncestors = entry.GetTxSize();
210 
211  while (!parentHashes.empty()) {
212  txiter stageit = *parentHashes.begin();
213 
214  setAncestors.insert(stageit);
215  parentHashes.erase(stageit);
216  totalSizeWithAncestors += stageit->GetTxSize();
217 
218  if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize) {
219  errString = strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantSize);
220  return false;
221  } else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {
222  errString = strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantCount);
223  return false;
224  } else if (totalSizeWithAncestors > limitAncestorSize) {
225  errString = strprintf("exceeds ancestor size limit [limit: %u]", limitAncestorSize);
226  return false;
227  }
228 
229  const setEntries & setMemPoolParents = GetMemPoolParents(stageit);
230  BOOST_FOREACH(const txiter &phash, setMemPoolParents) {
231  // If this is a new ancestor, add it.
232  if (setAncestors.count(phash) == 0) {
233  parentHashes.insert(phash);
234  }
235  if (parentHashes.size() + setAncestors.size() + 1 > limitAncestorCount) {
236  errString = strprintf("too many unconfirmed ancestors [limit: %u]", limitAncestorCount);
237  return false;
238  }
239  }
240  }
241 
242  return true;
243 }
244 
245 void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
246 {
247  setEntries parentIters = GetMemPoolParents(it);
248  // add or remove this tx as a child of each parent
249  BOOST_FOREACH(txiter piter, parentIters) {
250  UpdateChild(piter, it, add);
251  }
252  const int64_t updateCount = (add ? 1 : -1);
253  const int64_t updateSize = updateCount * it->GetTxSize();
254  const CAmount updateFee = updateCount * it->GetModifiedFee();
255  BOOST_FOREACH(txiter ancestorIt, setAncestors) {
256  mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
257  }
258 }
259 
261 {
262  const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
263  BOOST_FOREACH(txiter updateIt, setMemPoolChildren) {
264  UpdateParent(updateIt, it, false);
265  }
266 }
267 
269 {
270  // For each entry, walk back all ancestors and decrement size associated with this
271  // transaction
272  const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
273  BOOST_FOREACH(txiter removeIt, entriesToRemove) {
274  setEntries setAncestors;
275  const CTxMemPoolEntry &entry = *removeIt;
276  std::string dummy;
277  // Since this is a tx that is already in the mempool, we can call CMPA
278  // with fSearchForParents = false. If the mempool is in a consistent
279  // state, then using true or false should both be correct, though false
280  // should be a bit faster.
281  // However, if we happen to be in the middle of processing a reorg, then
282  // the mempool can be in an inconsistent state. In this case, the set
283  // of ancestors reachable via mapLinks will be the same as the set of
284  // ancestors whose packages include this transaction, because when we
285  // add a new transaction to the mempool in addUnchecked(), we assume it
286  // has no children, and in the case of a reorg where that assumption is
287  // false, the in-mempool children aren't linked to the in-block tx's
288  // until UpdateTransactionsFromBlock() is called.
289  // So if we're being called during a reorg, ie before
290  // UpdateTransactionsFromBlock() has been called, then mapLinks[] will
291  // differ from the set of mempool parents we'd calculate by searching,
292  // and it's important that we use the mapLinks[] notion of ancestor
293  // transactions as the set of things to update for removal.
294  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
295  // Note that UpdateAncestorsOf severs the child links that point to
296  // removeIt in the entries for the parents of removeIt. This is
297  // fine since we don't need to use the mempool children of any entries
298  // to walk back over our ancestors (but we do need the mempool
299  // parents!)
300  UpdateAncestorsOf(false, removeIt, setAncestors);
301  }
302  // After updating all the ancestor sizes, we can now sever the link between each
303  // transaction being removed and any mempool children (ie, update setMemPoolParents
304  // for each direct child of a transaction being removed).
305  BOOST_FOREACH(txiter removeIt, entriesToRemove) {
306  UpdateChildrenForRemoval(removeIt);
307  }
308 }
309 
311 {
315 }
316 
317 void CTxMemPoolEntry::UpdateState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
318 {
319  if (!IsDirty()) {
320  nSizeWithDescendants += modifySize;
321  assert(int64_t(nSizeWithDescendants) > 0);
322  nModFeesWithDescendants += modifyFee;
323  nCountWithDescendants += modifyCount;
324  assert(int64_t(nCountWithDescendants) > 0);
325  }
326 }
327 
328 CTxMemPool::CTxMemPool(const CFeeRate& _minReasonableRelayFee) :
329  nTransactionsUpdated(0)
330 {
331  _clear(); //lock free clear
332 
333  // Sanity checks off by default for performance, because otherwise
334  // accepting transactions becomes O(N^2) where N is the number
335  // of transactions in the pool
336  nCheckFrequency = 0;
337 
338  minerPolicyEstimator = new CBlockPolicyEstimator(_minReasonableRelayFee);
339  minReasonableRelayFee = _minReasonableRelayFee;
340 }
341 
343 {
344  delete minerPolicyEstimator;
345 }
346 
347 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
348 {
349  LOCK(cs);
350 
351  std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
352 
353  // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
354  while (it != mapNextTx.end() && it->first.hash == hashTx) {
355  coins.Spend(it->first.n); // and remove those outputs from coins
356  it++;
357  }
358 }
359 
361 {
362  LOCK(cs);
363  return nTransactionsUpdated;
364 }
365 
367 {
368  LOCK(cs);
370 }
371 
372 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool fCurrentEstimate)
373 {
374  // Add to memory pool without checking anything.
375  // Used by main.cpp AcceptToMemoryPool(), which DOES do
376  // all the appropriate checks.
377  LOCK(cs);
378  indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
379  mapLinks.insert(make_pair(newit, TxLinks()));
380 
381  // Update transaction for any feeDelta created by PrioritiseTransaction
382  // TODO: refactor so that the fee delta is calculated before inserting
383  // into mapTx.
384  std::map<uint256, std::pair<double, CAmount> >::const_iterator pos = mapDeltas.find(hash);
385  if (pos != mapDeltas.end()) {
386  const std::pair<double, CAmount> &deltas = pos->second;
387  if (deltas.second) {
388  mapTx.modify(newit, update_fee_delta(deltas.second));
389  }
390  }
391 
392  // Update cachedInnerUsage to include contained transaction's usage.
393  // (When we update the entry for in-mempool parents, memory usage will be
394  // further updated.)
396 
397  const CTransaction& tx = newit->GetTx();
398  std::set<uint256> setParentTransactions;
399  for (unsigned int i = 0; i < tx.vin.size(); i++) {
400  mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
401  setParentTransactions.insert(tx.vin[i].prevout.hash);
402  }
403  // Don't bother worrying about child transactions of this one.
404  // Normal case of a new transaction arriving is that there can't be any
405  // children, because such children would be orphans.
406  // An exception to that is if a transaction enters that used to be in a block.
407  // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
408  // to clean up the mess we're leaving here.
409 
410  // Update ancestors with information about this tx
411  BOOST_FOREACH (const uint256 &phash, setParentTransactions) {
412  txiter pit = mapTx.find(phash);
413  if (pit != mapTx.end()) {
414  UpdateParent(newit, pit, true);
415  }
416  }
417  UpdateAncestorsOf(true, newit, setAncestors);
418 
420  totalTxSize += entry.GetTxSize();
421  minerPolicyEstimator->processTransaction(entry, fCurrentEstimate);
422 
423  return true;
424 }
425 
427 {
428  LOCK(cs);
429  const CTransaction& tx = entry.GetTx();
430  std::vector<CMempoolAddressDeltaKey> inserted;
431 
432  uint256 txhash = tx.GetHash();
433  for (unsigned int j = 0; j < tx.vin.size(); j++) {
434  const CTxIn input = tx.vin[j];
435  const CTxOut &prevout = view.GetOutputFor(input);
436  if (prevout.scriptPubKey.IsPayToScriptHash()) {
437  vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22);
438  CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, j, 1);
439  CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
440  mapAddress.insert(make_pair(key, delta));
441  inserted.push_back(key);
442  } else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
443  vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23);
444  CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, j, 1);
445  CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
446  mapAddress.insert(make_pair(key, delta));
447  inserted.push_back(key);
448  }
449  }
450 
451  for (unsigned int k = 0; k < tx.vout.size(); k++) {
452  const CTxOut &out = tx.vout[k];
453  if (out.scriptPubKey.IsPayToScriptHash()) {
454  vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
455  CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, k, 0);
456  mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
457  inserted.push_back(key);
458  } else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
459  vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
460  std::pair<addressDeltaMap::iterator,bool> ret;
461  CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, k, 0);
462  mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
463  inserted.push_back(key);
464  }
465  }
466 
467  mapAddressInserted.insert(make_pair(txhash, inserted));
468 }
469 
470 bool CTxMemPool::getAddressIndex(std::vector<std::pair<uint160, int> > &addresses,
471  std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
472 {
473  LOCK(cs);
474  for (std::vector<std::pair<uint160, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
475  addressDeltaMap::iterator ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
476  while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
477  results.push_back(*ait);
478  ait++;
479  }
480  }
481  return true;
482 }
483 
485 {
486  LOCK(cs);
487  addressDeltaMapInserted::iterator it = mapAddressInserted.find(txhash);
488 
489  if (it != mapAddressInserted.end()) {
490  std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
491  for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
492  mapAddress.erase(*mit);
493  }
494  mapAddressInserted.erase(it);
495  }
496 
497  return true;
498 }
499 
501 {
502  LOCK(cs);
503 
504  const CTransaction& tx = entry.GetTx();
505  std::vector<CSpentIndexKey> inserted;
506 
507  uint256 txhash = tx.GetHash();
508  for (unsigned int j = 0; j < tx.vin.size(); j++) {
509  const CTxIn input = tx.vin[j];
510  const CTxOut &prevout = view.GetOutputFor(input);
511  uint160 addressHash;
512  int addressType;
513 
514  if (prevout.scriptPubKey.IsPayToScriptHash()) {
515  addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22));
516  addressType = 2;
517  } else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
518  addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23));
519  addressType = 1;
520  } else {
521  addressHash.SetNull();
522  addressType = 0;
523  }
524 
526  CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue, addressType, addressHash);
527 
528  mapSpent.insert(make_pair(key, value));
529  inserted.push_back(key);
530 
531  }
532 
533  mapSpentInserted.insert(make_pair(txhash, inserted));
534 }
535 
537 {
538  LOCK(cs);
539  mapSpentIndex::iterator it;
540 
541  it = mapSpent.find(key);
542  if (it != mapSpent.end()) {
543  value = it->second;
544  return true;
545  }
546  return false;
547 }
548 
550 {
551  LOCK(cs);
552  mapSpentIndexInserted::iterator it = mapSpentInserted.find(txhash);
553 
554  if (it != mapSpentInserted.end()) {
555  std::vector<CSpentIndexKey> keys = (*it).second;
556  for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
557  mapSpent.erase(*mit);
558  }
559  mapSpentInserted.erase(it);
560  }
561 
562  return true;
563 }
564 
566 {
567  const uint256 hash = it->GetTx().GetHash();
568  BOOST_FOREACH(const CTxIn& txin, it->GetTx().vin)
569  mapNextTx.erase(txin.prevout);
570 
571  totalTxSize -= it->GetTxSize();
572  cachedInnerUsage -= it->DynamicMemoryUsage();
574  mapLinks.erase(it);
575  mapTx.erase(it);
578  removeAddressIndex(hash);
579  removeSpentIndex(hash);
580 }
581 
582 // Calculates descendants of entry that are not already in setDescendants, and adds to
583 // setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
584 // is correct for tx and all descendants.
585 // Also assumes that if an entry is in setDescendants already, then all
586 // in-mempool descendants of it are already in setDescendants as well, so that we
587 // can save time by not iterating over those entries.
588 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
589 {
590  setEntries stage;
591  if (setDescendants.count(entryit) == 0) {
592  stage.insert(entryit);
593  }
594  // Traverse down the children of entry, only adding children that are not
595  // accounted for in setDescendants already (because those children have either
596  // already been walked, or will be walked in this iteration).
597  while (!stage.empty()) {
598  txiter it = *stage.begin();
599  setDescendants.insert(it);
600  stage.erase(it);
601 
602  const setEntries &setChildren = GetMemPoolChildren(it);
603  BOOST_FOREACH(const txiter &childiter, setChildren) {
604  if (!setDescendants.count(childiter)) {
605  stage.insert(childiter);
606  }
607  }
608  }
609 }
610 
611 void CTxMemPool::remove(const CTransaction &origTx, std::list<CTransaction>& removed, bool fRecursive)
612 {
613  // Remove transaction from memory pool
614  {
615  LOCK(cs);
616  setEntries txToRemove;
617  txiter origit = mapTx.find(origTx.GetHash());
618  if (origit != mapTx.end()) {
619  txToRemove.insert(origit);
620  } else if (fRecursive) {
621  // If recursively removing but origTx isn't in the mempool
622  // be sure to remove any children that are in the pool. This can
623  // happen during chain re-orgs if origTx isn't re-accepted into
624  // the mempool for any reason.
625  for (unsigned int i = 0; i < origTx.vout.size(); i++) {
626  std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
627  if (it == mapNextTx.end())
628  continue;
629  txiter nextit = mapTx.find(it->second.ptx->GetHash());
630  assert(nextit != mapTx.end());
631  txToRemove.insert(nextit);
632  }
633  }
634  setEntries setAllRemoves;
635  if (fRecursive) {
636  BOOST_FOREACH(txiter it, txToRemove) {
637  CalculateDescendants(it, setAllRemoves);
638  }
639  } else {
640  setAllRemoves.swap(txToRemove);
641  }
642  BOOST_FOREACH(txiter it, setAllRemoves) {
643  removed.push_back(it->GetTx());
644  }
645  RemoveStaged(setAllRemoves);
646  }
647 }
648 
649 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
650 {
651  // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
652  LOCK(cs);
653  list<CTransaction> transactionsToRemove;
654  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
655  const CTransaction& tx = it->GetTx();
656  LockPoints lp = it->GetLockPoints();
657  bool validLP = TestLockPointValidity(&lp);
658  if (!CheckFinalTx(tx, flags) || !CheckSequenceLocks(tx, flags, &lp, validLP)) {
659  // Note if CheckSequenceLocks fails the LockPoints may still be invalid
660  // So it's critical that we remove the tx and not depend on the LockPoints.
661  transactionsToRemove.push_back(tx);
662  } else if (it->GetSpendsCoinbase()) {
663  BOOST_FOREACH(const CTxIn& txin, tx.vin) {
664  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
665  if (it2 != mapTx.end())
666  continue;
667  const CCoins *coins = pcoins->AccessCoins(txin.prevout.hash);
668  if (nCheckFrequency != 0) assert(coins);
669  if (!coins || (coins->IsCoinBase() && ((signed long)nMemPoolHeight) - coins->nHeight < COINBASE_MATURITY)) {
670  transactionsToRemove.push_back(tx);
671  break;
672  }
673  }
674  }
675  if (!validLP) {
676  mapTx.modify(it, update_lock_points(lp));
677  }
678  }
679  BOOST_FOREACH(const CTransaction& tx, transactionsToRemove) {
680  list<CTransaction> removed;
681  remove(tx, removed, true);
682  }
683 }
684 
685 void CTxMemPool::removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed)
686 {
687  // Remove transactions which depend on inputs of tx, recursively
688  list<CTransaction> result;
689  LOCK(cs);
690  BOOST_FOREACH(const CTxIn &txin, tx.vin) {
691  std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
692  if (it != mapNextTx.end()) {
693  const CTransaction &txConflict = *it->second.ptx;
694  if (txConflict != tx)
695  {
696  remove(txConflict, removed, true);
697  ClearPrioritisation(txConflict.GetHash());
698  }
699  }
700  }
701 }
702 
706 void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
707  std::list<CTransaction>& conflicts, bool fCurrentEstimate)
708 {
709  LOCK(cs);
710  std::vector<CTxMemPoolEntry> entries;
711  BOOST_FOREACH(const CTransaction& tx, vtx)
712  {
713  uint256 hash = tx.GetHash();
714 
715  indexed_transaction_set::iterator i = mapTx.find(hash);
716  if (i != mapTx.end())
717  entries.push_back(*i);
718  }
719  BOOST_FOREACH(const CTransaction& tx, vtx)
720  {
721  std::list<CTransaction> dummy;
722  remove(tx, dummy, false);
723  removeConflicts(tx, conflicts);
725  }
726  // After the txs in the new block have been removed from the mempool, update policy estimates
727  minerPolicyEstimator->processBlock(nBlockHeight, entries, fCurrentEstimate);
730 }
731 
733 {
734  mapLinks.clear();
735  mapTx.clear();
736  mapNextTx.clear();
737  totalTxSize = 0;
738  cachedInnerUsage = 0;
743 }
744 
746 {
747  LOCK(cs);
748  _clear();
749 }
750 
751 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
752 {
753  if (nCheckFrequency == 0)
754  return;
755 
757  return;
758 
759  LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
760 
761  uint64_t checkTotal = 0;
762  uint64_t innerUsage = 0;
763 
764  CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
765 
766  LOCK(cs);
767  list<const CTxMemPoolEntry*> waitingOnDependants;
768  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
769  unsigned int i = 0;
770  checkTotal += it->GetTxSize();
771  innerUsage += it->DynamicMemoryUsage();
772  const CTransaction& tx = it->GetTx();
773  txlinksMap::const_iterator linksiter = mapLinks.find(it);
774  assert(linksiter != mapLinks.end());
775  const TxLinks &links = linksiter->second;
776  innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
777  bool fDependsWait = false;
778  setEntries setParentCheck;
779  BOOST_FOREACH(const CTxIn &txin, tx.vin) {
780  // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
781  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
782  if (it2 != mapTx.end()) {
783  const CTransaction& tx2 = it2->GetTx();
784  assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
785  fDependsWait = true;
786  setParentCheck.insert(it2);
787  } else {
788  const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
789  assert(coins && coins->IsAvailable(txin.prevout.n));
790  }
791  // Check whether its inputs are marked in mapNextTx.
792  std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
793  assert(it3 != mapNextTx.end());
794  assert(it3->second.ptx == &tx);
795  assert(it3->second.n == i);
796  i++;
797  }
798  assert(setParentCheck == GetMemPoolParents(it));
799  // Check children against mapNextTx
800  CTxMemPool::setEntries setChildrenCheck;
801  std::map<COutPoint, CInPoint>::const_iterator iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
802  int64_t childSizes = 0;
803  CAmount childModFee = 0;
804  for (; iter != mapNextTx.end() && iter->first.hash == it->GetTx().GetHash(); ++iter) {
805  txiter childit = mapTx.find(iter->second.ptx->GetHash());
806  assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
807  if (setChildrenCheck.insert(childit).second) {
808  childSizes += childit->GetTxSize();
809  childModFee += childit->GetModifiedFee();
810  }
811  }
812  assert(setChildrenCheck == GetMemPoolChildren(it));
813  // Also check to make sure size is greater than sum with immediate children.
814  // just a sanity check, not definitive that this calc is correct...
815  if (!it->IsDirty()) {
816  assert(it->GetSizeWithDescendants() >= childSizes + it->GetTxSize());
817  } else {
818  assert(it->GetSizeWithDescendants() == it->GetTxSize());
819  assert(it->GetModFeesWithDescendants() == it->GetModifiedFee());
820  }
821 
822  if (fDependsWait)
823  waitingOnDependants.push_back(&(*it));
824  else {
825  CValidationState state;
826  assert(CheckInputs(tx, state, mempoolDuplicate, false, 0, false, NULL));
827  UpdateCoins(tx, state, mempoolDuplicate, 1000000);
828  }
829  }
830  unsigned int stepsSinceLastRemove = 0;
831  while (!waitingOnDependants.empty()) {
832  const CTxMemPoolEntry* entry = waitingOnDependants.front();
833  waitingOnDependants.pop_front();
834  CValidationState state;
835  if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
836  waitingOnDependants.push_back(entry);
837  stepsSinceLastRemove++;
838  assert(stepsSinceLastRemove < waitingOnDependants.size());
839  } else {
840  assert(CheckInputs(entry->GetTx(), state, mempoolDuplicate, false, 0, false, NULL));
841  UpdateCoins(entry->GetTx(), state, mempoolDuplicate, 1000000);
842  stepsSinceLastRemove = 0;
843  }
844  }
845  for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
846  uint256 hash = it->second.ptx->GetHash();
847  indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
848  const CTransaction& tx = it2->GetTx();
849  assert(it2 != mapTx.end());
850  assert(&tx == it->second.ptx);
851  assert(tx.vin.size() > it->second.n);
852  assert(it->first == it->second.ptx->vin[it->second.n].prevout);
853  }
854 
855  assert(totalTxSize == checkTotal);
856  assert(innerUsage == cachedInnerUsage);
857 }
858 
859 void CTxMemPool::queryHashes(vector<uint256>& vtxid)
860 {
861  vtxid.clear();
862 
863  LOCK(cs);
864  vtxid.reserve(mapTx.size());
865  for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
866  vtxid.push_back(mi->GetTx().GetHash());
867 }
868 
870 {
871  LOCK(cs);
872  indexed_transaction_set::const_iterator i = mapTx.find(hash);
873  if (i == mapTx.end()) return false;
874  result = i->GetTx();
875  return true;
876 }
877 
879 {
880  LOCK(cs);
881  return minerPolicyEstimator->estimateFee(nBlocks);
882 }
883 CFeeRate CTxMemPool::estimateSmartFee(int nBlocks, int *answerFoundAtBlocks) const
884 {
885  LOCK(cs);
886  return minerPolicyEstimator->estimateSmartFee(nBlocks, answerFoundAtBlocks, *this);
887 }
888 double CTxMemPool::estimatePriority(int nBlocks) const
889 {
890  LOCK(cs);
891  return minerPolicyEstimator->estimatePriority(nBlocks);
892 }
893 double CTxMemPool::estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks) const
894 {
895  LOCK(cs);
896  return minerPolicyEstimator->estimateSmartPriority(nBlocks, answerFoundAtBlocks, *this);
897 }
898 
899 bool
901 {
902  try {
903  LOCK(cs);
904  fileout << 120000; // version required to read: 0.12.00 or later
905  fileout << CLIENT_VERSION; // version that wrote the file
907  }
908  catch (const std::exception&) {
909  LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy estimator data (non-fatal)\n");
910  return false;
911  }
912  return true;
913 }
914 
915 bool
917 {
918  try {
919  int nVersionRequired, nVersionThatWrote;
920  filein >> nVersionRequired >> nVersionThatWrote;
921  if (nVersionRequired > CLIENT_VERSION)
922  return error("CTxMemPool::ReadFeeEstimates(): up-version (%d) fee estimate file", nVersionRequired);
923 
924  LOCK(cs);
925  minerPolicyEstimator->Read(filein);
926  }
927  catch (const std::exception&) {
928  LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy estimator data (non-fatal)\n");
929  return false;
930  }
931  return true;
932 }
933 
934 void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
935 {
936  {
937  LOCK(cs);
938  std::pair<double, CAmount> &deltas = mapDeltas[hash];
939  deltas.first += dPriorityDelta;
940  deltas.second += nFeeDelta;
941  txiter it = mapTx.find(hash);
942  if (it != mapTx.end()) {
943  mapTx.modify(it, update_fee_delta(deltas.second));
944  // Now update all ancestors' modified fees with descendants
945  setEntries setAncestors;
946  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
947  std::string dummy;
948  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
949  BOOST_FOREACH(txiter ancestorIt, setAncestors) {
950  mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
951  }
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 
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  CTransaction tx;
989  if (mempool.lookup(txid, tx)) {
990  coins = CCoins(tx, 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 12 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1004 }
1005 
1007  AssertLockHeld(cs);
1009  BOOST_FOREACH(const txiter& it, stage) {
1010  removeUnchecked(it);
1011  }
1012 }
1013 
1014 int CTxMemPool::Expire(int64_t time) {
1015  LOCK(cs);
1016  indexed_transaction_set::nth_index<2>::type::iterator it = mapTx.get<2>().begin();
1017  setEntries toremove;
1018  while (it != mapTx.get<2>().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  }
1026  RemoveStaged(stage);
1027  return stage.size();
1028 }
1029 
1030 bool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate)
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, fCurrentEstimate);
1038 }
1039 
1041 {
1042  setEntries s;
1043  if (add && mapLinks[entry].children.insert(child).second) {
1045  } else if (!add && mapLinks[entry].children.erase(child)) {
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) {
1055  } else if (!add && mapLinks[entry].parents.erase(parent)) {
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 
1100 void CTxMemPool::UpdateMinFee(const CFeeRate& _minReasonableRelayFee)
1101 {
1102  LOCK(cs);
1103  delete minerPolicyEstimator;
1104  minerPolicyEstimator = new CBlockPolicyEstimator(_minReasonableRelayFee);
1105  minReasonableRelayFee = _minReasonableRelayFee;
1106 }
1107 
1109  AssertLockHeld(cs);
1110  if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1113  }
1114 }
1115 
1116 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<uint256>* pvNoSpendsRemaining) {
1117  LOCK(cs);
1118 
1119  unsigned nTxnRemoved = 0;
1120  CFeeRate maxFeeRateRemoved(0);
1121  while (DynamicMemoryUsage() > sizelimit) {
1122  indexed_transaction_set::nth_index<1>::type::iterator it = mapTx.get<1>().begin();
1123 
1124  // We set the new mempool min fee to the feerate of the removed set, plus the
1125  // "minimum reasonable fee rate" (ie some value under which we consider txn
1126  // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1127  // equal to txn which were removed with no block in between.
1128  CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1129  removed += minReasonableRelayFee;
1130  trackPackageRemoved(removed);
1131  maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1132 
1133  setEntries stage;
1134  CalculateDescendants(mapTx.project<0>(it), stage);
1135  nTxnRemoved += stage.size();
1136 
1137  std::vector<CTransaction> txn;
1138  if (pvNoSpendsRemaining) {
1139  txn.reserve(stage.size());
1140  BOOST_FOREACH(txiter it, stage)
1141  txn.push_back(it->GetTx());
1142  }
1143  RemoveStaged(stage);
1144  if (pvNoSpendsRemaining) {
1145  BOOST_FOREACH(const CTransaction& tx, txn) {
1146  BOOST_FOREACH(const CTxIn& txin, tx.vin) {
1147  if (exists(txin.prevout.hash))
1148  continue;
1149  std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(txin.prevout.hash, 0));
1150  if (it == mapNextTx.end() || it->first.hash != txin.prevout.hash)
1151  pvNoSpendsRemaining->push_back(txin.prevout.hash);
1152  }
1153  }
1154  }
1155  }
1156 
1157  if (maxFeeRateRemoved > CFeeRate(0))
1158  LogPrint("mempool", "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1159 }
int64_t lastRollingFeeUpdate
Definition: txmempool.h:369
void TrimToSize(size_t sizelimit, std::vector< uint256 > *pvNoSpendsRemaining=NULL)
Definition: txmempool.cpp:1116
void removeConflicts(const CTransaction &tx, std::list< CTransaction > &removed)
Definition: txmempool.cpp:685
uint32_t n
Definition: transaction.h:19
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove)
Definition: txmempool.cpp:268
double estimateSmartPriority(int confTarget, int *answerFoundAtTarget, const CTxMemPool &pool)
Definition: fees.cpp:542
void UpdateFeeDelta(int64_t feeDelta)
Definition: txmempool.cpp:59
bool IsPayToPublicKeyHash() const
Definition: script.cpp:227
void processTransaction(const CTxMemPoolEntry &entry, bool fCurrentEstimate)
Definition: fees.cpp:344
bool IsCoinBase() const
Definition: coins.h:151
unsigned int entryHeight
Priority when entering the mempool.
Definition: txmempool.h:86
int Expire(int64_t time)
Definition: txmempool.cpp:1014
void remove(const CTransaction &tx, std::list< CTransaction > &removed, bool fRecursive=false)
Definition: txmempool.cpp:611
Definition: coins.h:73
void SetNull()
Definition: uint256.h:41
addressDeltaMapInserted mapAddressInserted
Definition: txmempool.h:429
size_t nUsageSize
... and modified size for priority
Definition: txmempool.h:83
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:859
bool IsDirty() const
Definition: txmempool.h:139
CCoinsView * base
Definition: coins.h:344
size_t GetTxSize() const
Definition: txmempool.h:117
#define strprintf
Definition: tinyformat.h:1011
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector< CScriptCheck > *pvChecks)
uint64_t GetHash(const uint256 &salt) const
Definition: uint256.cpp:126
static size_t DynamicUsage(const int8_t &v)
Definition: memusage.h:25
bool ReadFeeEstimates(CAutoFile &filein)
Definition: txmempool.cpp:916
CFeeRate estimateSmartFee(int nBlocks, int *answerFoundAtBlocks=NULL) const
Definition: txmempool.cpp:883
uint64_t totalTxSize
Definition: txmempool.h:364
static FILE * fileout
Definition: util.cpp:210
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
Definition: txmempool.h:415
unsigned int nTransactionsUpdated
Value n means that n times in 2^32 we check.
Definition: txmempool.h:361
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: txmempool.cpp:984
bool removeAddressIndex(const uint256 txhash)
Definition: txmempool.cpp:484
double estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks=NULL) const
Definition: txmempool.cpp:893
bool IsAvailable(unsigned int nPos) const
check whether a particular output is still available
Definition: coins.h:245
CAmount nValue
Definition: transaction.h:136
CAmount nModFeesWithDescendants
... and size
Definition: txmempool.h:101
int64_t feeDelta
Legacy sig ops plus P2SH sig op count.
Definition: txmempool.h:91
double entryPriority
Local time when entering the mempool.
Definition: txmempool.h:85
static const int COINBASE_MATURITY
Definition: consensus.h:23
std::map< COutPoint, CInPoint > mapNextTx
Definition: txmempool.h:441
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors)
Definition: txmempool.cpp:245
int flags
Definition: dash-tx.cpp:326
CFeeRate minReasonableRelayFee
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
Definition: txmempool.h:367
void UpdateParent(txiter entry, txiter parent, bool add)
Definition: txmempool.cpp:1050
CAmount GetValueOut() const
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:366
const CTxOut & GetOutputFor(const CTxIn &input) const
Definition: coins.cpp:227
indexed_transaction_set mapTx
Definition: txmempool.h:403
void UpdateTransactionsFromBlock(const std::vector< uint256 > &hashesToUpdate)
Definition: txmempool.cpp:137
uint32_t nCheckFrequency
Definition: txmempool.h:360
CTxMemPool(const CFeeRate &_minReasonableRelayFee)
Definition: txmempool.cpp:328
static uint32_t insecure_rand(void)
Definition: random.h:42
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)
Definition: txmempool.cpp:183
mapSpentIndex mapSpent
Definition: txmempool.h:432
CFeeRate estimateFee(int confTarget)
Definition: fees.cpp:492
bool removeSpentIndex(const uint256 txhash)
Definition: txmempool.cpp:549
void UpdateLockPoints(const LockPoints &lp)
Definition: txmempool.cpp:65
virtual bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: coins.cpp:44
bool lookup(uint256 hash, CTransaction &result) const
Definition: txmempool.cpp:869
void ClearPrioritisation(const uint256 hash)
Definition: txmempool.cpp:968
mapSpentIndexInserted mapSpentInserted
Definition: txmempool.h:435
void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const
Definition: txmempool.cpp:957
int64_t CAmount
Definition: amount.h:14
bool getSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
Definition: txmempool.cpp:536
bool exists(uint256 hash) const
Definition: txmempool.h:563
#define AssertLockHeld(cs)
Definition: sync.h:96
LockPoints lockPoints
Used for determining the priority of the transaction for mining in a block.
Definition: txmempool.h:92
CFeeRate estimateSmartFee(int confTarget, int *answerFoundAtTarget, const CTxMemPool &pool)
Definition: fees.cpp:506
bool HasNoInputsOf(const CTransaction &tx) const
Definition: txmempool.cpp:974
bool IsPruned() const
Definition: coins.h:251
CCriticalSection cs
Definition: txmempool.h:402
#define LogPrintf(...)
Definition: util.h:98
bool CheckFinalTx(const CTransaction &tx, int flags)
Definition: validation.cpp:213
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:404
bool blockSinceLastRollingFeeBump
Definition: txmempool.h:370
uint64_t nSizeWithDescendants
number of descendant transactions
Definition: txmempool.h:100
COutPoint prevout
Definition: transaction.h:61
void CalculateDescendants(txiter it, setEntries &setDescendants)
Definition: txmempool.cpp:588
const setEntries & GetMemPoolParents(txiter entry) const
Definition: txmempool.cpp:1060
unsigned int GetSerializeSize(char a, int, int=0)
Definition: serialize.h:202
void UpdateMinFee(const CFeeRate &_minReasonableRelayFee)
Definition: txmempool.cpp:1100
bool Spend(uint32_t nPos)
mark a vout spent
Definition: coins.cpp:35
static int LogPrint(const char *category, const char *format)
Definition: util.h:126
void removeForBlock(const std::vector< CTransaction > &vtx, unsigned int nBlockHeight, std::list< CTransaction > &conflicts, bool fCurrentEstimate=true)
Definition: txmempool.cpp:706
#define LOCK(cs)
Definition: sync.h:168
const CTransaction & GetTx() const
Definition: txmempool.h:110
std::string ToString() const
Definition: amount.cpp:30
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1000
uint64_t cachedInnerUsage
sum of all mempool tx&#39; byte sizes
Definition: txmempool.h:365
addressDeltaMap mapAddress
Definition: txmempool.h:426
void clear()
Definition: txmempool.cpp:745
CTxMemPoolEntry(const CTransaction &_tx, const CAmount &_nFee, int64_t _nTime, double _entryPriority, unsigned int _entryHeight, bool poolHasNoInputsOf, CAmount _inChainInputValue, bool spendsCoinbase, unsigned int nSigOps, LockPoints lp)
... and total fees (all including us)
Definition: txmempool.cpp:23
CAmount GetFeePerK() const
Definition: amount.h:47
void UpdateChildrenForRemoval(txiter entry)
Definition: txmempool.cpp:260
static bool error(const char *format)
Definition: util.h:131
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:377
void check(const CCoinsViewCache *pcoins) const
Definition: txmempool.cpp:751
size_t nTxSize
Cached to avoid expensive parent-transaction lookups.
Definition: txmempool.h:81
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:246
size_t nModSize
... and avoid recomputing tx size
Definition: txmempool.h:82
bool TestLockPointValidity(const LockPoints *lp)
Definition: validation.cpp:328
virtual bool HaveCoins(const uint256 &txid) const
Definition: coins.cpp:45
bool IsPayToScriptHash() const
Definition: script.cpp:238
void removeUnchecked(txiter entry)
Definition: txmempool.cpp:565
std::string FormatMoney(const CAmount &n)
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Definition: validation.cpp:346
void addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
Definition: txmempool.cpp:426
CAmount inChainInputValue
Not dependent on any other txs when it entered the mempool.
Definition: txmempool.h:88
CScript scriptPubKey
Definition: transaction.h:137
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:410
void trackPackageRemoved(const CFeeRate &rate)
minimum fee to get into the pool, decreases exponentially
Definition: txmempool.cpp:1108
static size_t MallocUsage(size_t alloc)
Definition: memusage.h:46
unsigned int CalculateModifiedSize(unsigned int nTxSize=0) const
int64_t GetTime() const
Definition: txmempool.h:118
txlinksMap mapLinks
Definition: txmempool.h:423
size_t DynamicMemoryUsage() const
Definition: txmempool.h:123
std::map< uint256, std::pair< double, CAmount > > mapDeltas
Definition: txmempool.h:442
bool getAddressIndex(std::vector< std::pair< uint160, int > > &addresses, std::vector< std::pair< CMempoolAddressDeltaKey, CMempoolAddressDelta > > &results)
Definition: txmempool.cpp:470
const std::vector< CTxIn > vin
Definition: transaction.h:233
int64_t GetModifiedFee() const
Definition: txmempool.h:122
CTxMemPool mempool
const setEntries & GetMemPoolChildren(txiter entry) const
Definition: txmempool.cpp:1068
bool HaveCoins(const uint256 &txid) const
Definition: txmempool.cpp:996
uint64_t nCountWithDescendants
Track the height and time at which tx was final.
Definition: txmempool.h:99
static const int PROTOCOL_VERSION
Definition: version.h:13
const uint256 & GetHash() const
Definition: transaction.h:262
void UpdateChild(txiter entry, txiter child, bool add)
Definition: txmempool.cpp:1040
CAmount nFee
Definition: txmempool.h:80
void removeTx(uint256 hash)
Definition: fees.cpp:285
double rollingMinimumFeeRate
Definition: txmempool.h:371
void addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
Definition: txmempool.cpp:500
bool WriteFeeEstimates(CAutoFile &fileout) const
Definition: txmempool.cpp:900
void pruneSpent(const uint256 &hash, CCoins &coins)
Definition: txmempool.cpp:347
CFeeRate GetMinFee(size_t sizelimit) const
Definition: txmempool.cpp:1076
void Read(CAutoFile &filein)
Definition: fees.cpp:573
const std::vector< CTxOut > vout
Definition: transaction.h:234
void _clear()
Definition: txmempool.cpp:732
void processBlock(unsigned int nBlockHeight, std::vector< CTxMemPoolEntry > &entries, bool fCurrentEstimate)
Definition: fees.cpp:434
iterator begin()
Definition: prevector.h:270
CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn)
Definition: txmempool.cpp:982
static size_t IncrementalDynamicUsage(const std::set< X, Y > &s)
Definition: memusage.h:92
static size_t RecursiveDynamicUsage(const CScript &script)
Definition: core_memusage.h:12
CTransaction tx
Definition: txmempool.h:79
double GetPriority(unsigned int currentHeight) const
Definition: txmempool.cpp:50
void PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount &nFeeDelta)
Definition: txmempool.cpp:934
static const unsigned int MEMPOOL_HEIGHT
Definition: txmempool.h:40
int64_t GetTime()
For unit testing.
Definition: utiltime.cpp:20
CFeeRate estimateFee(int nBlocks) const
Definition: txmempool.cpp:878
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
CBlockPolicyEstimator * minerPolicyEstimator
Definition: txmempool.h:362
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
Definition: txmempool.cpp:649
CTxMemPool & mempool
Definition: txmempool.h:641
void RemoveStaged(setEntries &stage)
Definition: txmempool.cpp:1006
static const int CLIENT_VERSION
Definition: clientversion.h:54
void Write(CAutoFile &fileout)
Definition: fees.cpp:566
bool UpdateForDescendants(txiter updateIt, int maxDescendantsToVisit, cacheMap &cachedDescendants, const std::set< uint256 > &setExclude)
Definition: txmempool.cpp:73
uint256 hash
Definition: transaction.h:18
void UpdateState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
Definition: txmempool.cpp:317
double estimatePriority(int nBlocks) const
Definition: txmempool.cpp:888
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate=true)
Definition: txmempool.cpp:1030
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:360
double estimatePriority(int confTarget)
Definition: fees.cpp:533
int nHeight
at which height this transaction was included in the active block chain
Definition: coins.h:83
result
Definition: rpcuser.py:37
const CCoins * AccessCoins(const uint256 &txid) const
Definition: coins.cpp:129