Raven Core  3.0.0
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 // Copyright (c) 2017-2019 The Raven Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "txmempool.h"
8 
9 #include "consensus/consensus.h"
10 #include "consensus/tx_verify.h"
11 #include "consensus/validation.h"
12 #include "validation.h"
13 #include "policy/policy.h"
14 #include "policy/fees.h"
15 #include "reverse_iterator.h"
16 #include "streams.h"
17 #include "timedata.h"
18 #include "util.h"
19 #include "utilmoneystr.h"
20 #include "utiltime.h"
21 #include "hash.h"
22 
24  int64_t _nTime, unsigned int _entryHeight,
25  bool _spendsCoinbase, int64_t _sigOpsCost, LockPoints lp):
26  tx(_tx), nFee(_nFee), nTime(_nTime), entryHeight(_entryHeight),
27  spendsCoinbase(_spendsCoinbase), sigOpCost(_sigOpsCost), lockPoints(lp)
28 {
29  nTxWeight = GetTransactionWeight(*tx);
30  nUsageSize = RecursiveDynamicUsage(tx);
31 
35 
36  feeDelta = 0;
37 
42 }
43 
44 void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
45 {
46  nModFeesWithDescendants += newFeeDelta - feeDelta;
47  nModFeesWithAncestors += newFeeDelta - feeDelta;
48  feeDelta = newFeeDelta;
49 }
50 
52 {
53  lockPoints = lp;
54 }
55 
57 {
59 }
60 
61 // Update the given tx for any in-mempool descendants.
62 // Assumes that setMemPoolChildren is correct for the given tx and all
63 // descendants.
64 void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set<uint256> &setExclude)
65 {
66  setEntries stageEntries, setAllDescendants;
67  stageEntries = GetMemPoolChildren(updateIt);
68 
69  while (!stageEntries.empty()) {
70  const txiter cit = *stageEntries.begin();
71  setAllDescendants.insert(cit);
72  stageEntries.erase(cit);
73  const setEntries &setChildren = GetMemPoolChildren(cit);
74  for (const txiter childEntry : setChildren) {
75  cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
76  if (cacheIt != cachedDescendants.end()) {
77  // We've already calculated this one, just add the entries for this set
78  // but don't traverse again.
79  for (const txiter cacheEntry : cacheIt->second) {
80  setAllDescendants.insert(cacheEntry);
81  }
82  } else if (!setAllDescendants.count(childEntry)) {
83  // Schedule for later processing
84  stageEntries.insert(childEntry);
85  }
86  }
87  }
88  // setAllDescendants now contains all in-mempool descendants of updateIt.
89  // Update and add to cached descendant map
90  int64_t modifySize = 0;
91  CAmount modifyFee = 0;
92  int64_t modifyCount = 0;
93  for (txiter cit : setAllDescendants) {
94  if (!setExclude.count(cit->GetTx().GetHash())) {
95  modifySize += cit->GetTxSize();
96  modifyFee += cit->GetModifiedFee();
97  modifyCount++;
98  cachedDescendants[updateIt].insert(cit);
99  // Update ancestor state for each descendant
100  mapTx.modify(cit, update_ancestor_state(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost()));
101  }
102  }
103  mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));
104 }
105 
106 // vHashesToUpdate is the set of transaction hashes from a disconnected block
107 // which has been re-added to the mempool.
108 // for each entry, look for descendants that are outside vHashesToUpdate, and
109 // add fee/size information for such descendants to the parent.
110 // for each such descendant, also update the ancestor state to include the parent.
111 void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)
112 {
113  LOCK(cs);
114  // For each entry in vHashesToUpdate, store the set of in-mempool, but not
115  // in-vHashesToUpdate transactions, so that we don't have to recalculate
116  // descendants when we come across a previously seen entry.
117  cacheMap mapMemPoolDescendantsToUpdate;
118 
119  // Use a set for lookups into vHashesToUpdate (these entries are already
120  // accounted for in the state of their ancestors)
121  std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
122 
123  // Iterate in reverse, so that whenever we are looking at a transaction
124  // we are sure that all in-mempool descendants have already been processed.
125  // This maximizes the benefit of the descendant cache and guarantees that
126  // setMemPoolChildren will be updated, an assumption made in
127  // UpdateForDescendants.
128  for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) {
129  // we cache the in-mempool children to avoid duplicate updates
130  setEntries setChildren;
131  // calculate children from mapNextTx
132  txiter it = mapTx.find(hash);
133  if (it == mapTx.end()) {
134  continue;
135  }
136  auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
137  // First calculate the children, and update setMemPoolChildren to
138  // include them, and update their setMemPoolParents to include this tx.
139  for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
140  const uint256 &childHash = iter->second->GetHash();
141  txiter childIter = mapTx.find(childHash);
142  assert(childIter != mapTx.end());
143  // We can skip updating entries we've encountered before or that
144  // are in the block (which are already accounted for).
145  if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash)) {
146  UpdateChild(it, childIter, true);
147  UpdateParent(childIter, it, true);
148  }
149  }
150  UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded);
151  }
152 }
153 
154 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
155 {
156  LOCK(cs);
157 
158  setEntries parentHashes;
159  const CTransaction &tx = entry.GetTx();
160 
161  if (fSearchForParents) {
162  // Get parents of this transaction that are in the mempool
163  // GetMemPoolParents() is only valid for entries in the mempool, so we
164  // iterate mapTx to find parents.
165  for (unsigned int i = 0; i < tx.vin.size(); i++) {
166  txiter piter = mapTx.find(tx.vin[i].prevout.hash);
167  if (piter != mapTx.end()) {
168  parentHashes.insert(piter);
169  if (parentHashes.size() + 1 > limitAncestorCount) {
170  errString = strprintf("too many unconfirmed parents [limit: %u]", limitAncestorCount);
171  return false;
172  }
173  }
174  }
175  } else {
176  // If we're not searching for parents, we require this to be an
177  // entry in the mempool already.
178  txiter it = mapTx.iterator_to(entry);
179  parentHashes = GetMemPoolParents(it);
180  }
181 
182  size_t totalSizeWithAncestors = entry.GetTxSize();
183 
184  while (!parentHashes.empty()) {
185  txiter stageit = *parentHashes.begin();
186 
187  setAncestors.insert(stageit);
188  parentHashes.erase(stageit);
189  totalSizeWithAncestors += stageit->GetTxSize();
190 
191  if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize) {
192  errString = strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantSize);
193  return false;
194  } else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {
195  errString = strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantCount);
196  return false;
197  } else if (totalSizeWithAncestors > limitAncestorSize) {
198  errString = strprintf("exceeds ancestor size limit [limit: %u]", limitAncestorSize);
199  return false;
200  }
201 
202  const setEntries & setMemPoolParents = GetMemPoolParents(stageit);
203  for (const txiter &phash : setMemPoolParents) {
204  // If this is a new ancestor, add it.
205  if (setAncestors.count(phash) == 0) {
206  parentHashes.insert(phash);
207  }
208  if (parentHashes.size() + setAncestors.size() + 1 > limitAncestorCount) {
209  errString = strprintf("too many unconfirmed ancestors [limit: %u]", limitAncestorCount);
210  return false;
211  }
212  }
213  }
214 
215  return true;
216 }
217 
218 void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
219 {
220  setEntries parentIters = GetMemPoolParents(it);
221  // add or remove this tx as a child of each parent
222  for (txiter piter : parentIters) {
223  UpdateChild(piter, it, add);
224  }
225  const int64_t updateCount = (add ? 1 : -1);
226  const int64_t updateSize = updateCount * it->GetTxSize();
227  const CAmount updateFee = updateCount * it->GetModifiedFee();
228  for (txiter ancestorIt : setAncestors) {
229  mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
230  }
231 }
232 
234 {
235  int64_t updateCount = setAncestors.size();
236  int64_t updateSize = 0;
237  CAmount updateFee = 0;
238  int64_t updateSigOpsCost = 0;
239  for (txiter ancestorIt : setAncestors) {
240  updateSize += ancestorIt->GetTxSize();
241  updateFee += ancestorIt->GetModifiedFee();
242  updateSigOpsCost += ancestorIt->GetSigOpCost();
243  }
244  mapTx.modify(it, update_ancestor_state(updateSize, updateFee, updateCount, updateSigOpsCost));
245 }
246 
248 {
249  const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
250  for (txiter updateIt : setMemPoolChildren) {
251  UpdateParent(updateIt, it, false);
252  }
253 }
254 
255 void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
256 {
257  // For each entry, walk back all ancestors and decrement size associated with this
258  // transaction
259  const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
260  if (updateDescendants) {
261  // updateDescendants should be true whenever we're not recursively
262  // removing a tx and all its descendants, eg when a transaction is
263  // confirmed in a block.
264  // Here we only update statistics and not data in mapLinks (which
265  // we need to preserve until we're finished with all operations that
266  // need to traverse the mempool).
267  for (txiter removeIt : entriesToRemove) {
268  setEntries setDescendants;
269  CalculateDescendants(removeIt, setDescendants);
270  setDescendants.erase(removeIt); // don't update state for self
271  int64_t modifySize = -((int64_t)removeIt->GetTxSize());
272  CAmount modifyFee = -removeIt->GetModifiedFee();
273  int modifySigOps = -removeIt->GetSigOpCost();
274  for (txiter dit : setDescendants) {
275  mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee, -1, modifySigOps));
276  }
277  }
278  }
279  for (txiter removeIt : entriesToRemove) {
280  setEntries setAncestors;
281  const CTxMemPoolEntry &entry = *removeIt;
282  std::string dummy;
283  // Since this is a tx that is already in the mempool, we can call CMPA
284  // with fSearchForParents = false. If the mempool is in a consistent
285  // state, then using true or false should both be correct, though false
286  // should be a bit faster.
287  // However, if we happen to be in the middle of processing a reorg, then
288  // the mempool can be in an inconsistent state. In this case, the set
289  // of ancestors reachable via mapLinks will be the same as the set of
290  // ancestors whose packages include this transaction, because when we
291  // add a new transaction to the mempool in addUnchecked(), we assume it
292  // has no children, and in the case of a reorg where that assumption is
293  // false, the in-mempool children aren't linked to the in-block tx's
294  // until UpdateTransactionsFromBlock() is called.
295  // So if we're being called during a reorg, ie before
296  // UpdateTransactionsFromBlock() has been called, then mapLinks[] will
297  // differ from the set of mempool parents we'd calculate by searching,
298  // and it's important that we use the mapLinks[] notion of ancestor
299  // transactions as the set of things to update for removal.
300  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
301  // Note that UpdateAncestorsOf severs the child links that point to
302  // removeIt in the entries for the parents of removeIt.
303  UpdateAncestorsOf(false, removeIt, setAncestors);
304  }
305  // After updating all the ancestor sizes, we can now sever the link between each
306  // transaction being removed and any mempool children (ie, update setMemPoolParents
307  // for each direct child of a transaction being removed).
308  for (txiter removeIt : entriesToRemove) {
309  UpdateChildrenForRemoval(removeIt);
310  }
311 }
312 
313 void CTxMemPoolEntry::UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
314 {
315  nSizeWithDescendants += modifySize;
316  assert(int64_t(nSizeWithDescendants) > 0);
317  nModFeesWithDescendants += modifyFee;
318  nCountWithDescendants += modifyCount;
319  assert(int64_t(nCountWithDescendants) > 0);
320 }
321 
322 void CTxMemPoolEntry::UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps)
323 {
324  nSizeWithAncestors += modifySize;
325  assert(int64_t(nSizeWithAncestors) > 0);
326  nModFeesWithAncestors += modifyFee;
327  nCountWithAncestors += modifyCount;
328  assert(int64_t(nCountWithAncestors) > 0);
329  nSigOpCostWithAncestors += modifySigOps;
330  assert(int(nSigOpCostWithAncestors) >= 0);
331 }
332 
334  nTransactionsUpdated(0), minerPolicyEstimator(estimator)
335 {
336  _clear(); //lock free clear
337 
338  // Sanity checks off by default for performance, because otherwise
339  // accepting transactions becomes O(N^2) where N is the number
340  // of transactions in the pool
341  nCheckFrequency = 0;
342 }
343 
344 bool CTxMemPool::isSpent(const COutPoint& outpoint)
345 {
346  LOCK(cs);
347  return mapNextTx.count(outpoint);
348 }
349 
351 {
352  LOCK(cs);
353  return nTransactionsUpdated;
354 }
355 
357 {
358  LOCK(cs);
360 }
361 
362 bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate)
363 {
364  NotifyEntryAdded(entry.GetSharedTx());
365  // Add to memory pool without checking anything.
366  // Used by AcceptToMemoryPool(), which DOES do
367  // all the appropriate checks.
368  LOCK(cs);
369  indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
370  mapLinks.insert(std::make_pair(newit, TxLinks()));
371 
372  // Update transaction for any feeDelta created by PrioritiseTransaction
373  // TODO: refactor so that the fee delta is calculated before inserting
374  // into mapTx.
375  std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
376  if (pos != mapDeltas.end()) {
377  const CAmount &delta = pos->second;
378  if (delta) {
379  mapTx.modify(newit, update_fee_delta(delta));
380  }
381  }
382 
383  // Update cachedInnerUsage to include contained transaction's usage.
384  // (When we update the entry for in-mempool parents, memory usage will be
385  // further updated.)
387 
388  const CTransaction& tx = newit->GetTx();
389  std::set<uint256> setParentTransactions;
390  for (unsigned int i = 0; i < tx.vin.size(); i++) {
391  mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
392  setParentTransactions.insert(tx.vin[i].prevout.hash);
393  }
394  // Don't bother worrying about child transactions of this one.
395  // Normal case of a new transaction arriving is that there can't be any
396  // children, because such children would be orphans.
397  // An exception to that is if a transaction enters that used to be in a block.
398  // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
399  // to clean up the mess we're leaving here.
400 
401  // Update ancestors with information about this tx
402  for (const uint256 &phash : setParentTransactions) {
403  txiter pit = mapTx.find(phash);
404  if (pit != mapTx.end()) {
405  UpdateParent(newit, pit, true);
406  }
407  }
408  UpdateAncestorsOf(true, newit, setAncestors);
409  UpdateEntryForAncestors(newit, setAncestors);
410 
412  totalTxSize += entry.GetTxSize();
413  if (minerPolicyEstimator) {minerPolicyEstimator->processTransaction(entry, validFeeEstimate);}
414 
415  vTxHashes.emplace_back(tx.GetWitnessHash(), newit);
416  newit->vTxHashesIdx = vTxHashes.size() - 1;
417 
418  return true;
419 }
420 
422 {
423  LOCK(cs);
424  const CTransaction& tx = entry.GetTx();
425  std::vector<CMempoolAddressDeltaKey> inserted;
426 
427  uint256 txhash = tx.GetHash();
428  for (unsigned int j = 0; j < tx.vin.size(); j++) {
429  const CTxIn input = tx.vin[j];
430  const CTxOut &prevout = view.AccessCoin(input.prevout).out;
431  if (prevout.scriptPubKey.IsPayToScriptHash()) {
432  std::vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22);
433  CMempoolAddressDeltaKey key(2, uint160(hashBytes), RVN, txhash, j, 1);
434  CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
435  mapAddress.insert(std::make_pair(key, delta));
436  inserted.push_back(key);
437  } else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
438  std::vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23);
439  CMempoolAddressDeltaKey key(1, uint160(hashBytes), RVN, txhash, j, 1);
440  CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
441  mapAddress.insert(std::make_pair(key, delta));
442  inserted.push_back(key);
443  } else if (prevout.scriptPubKey.IsPayToPublicKey()) {
444  uint160 hashBytes(Hash160(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.end()-1));
445  CMempoolAddressDeltaKey key(1, hashBytes, RVN, txhash, j, 1);
446  CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
447  mapAddress.insert(std::make_pair(key, delta));
448  inserted.push_back(key);
449  } else {
451  if (AreAssetsDeployed()) {
452  uint160 hashBytes;
453  std::string assetName;
454  CAmount assetAmount;
455  if (ParseAssetScript(prevout.scriptPubKey, hashBytes, assetName, assetAmount)) {
456  CMempoolAddressDeltaKey key(1, hashBytes, assetName, txhash, j, 1);
457  CMempoolAddressDelta delta(entry.GetTime(), assetAmount * -1, input.prevout.hash, input.prevout.n);
458  mapAddress.insert(std::make_pair(key, delta));
459  inserted.push_back(key);
460  }
461  }
463  }
464  }
465 
466  for (unsigned int k = 0; k < tx.vout.size(); k++) {
467  const CTxOut &out = tx.vout[k];
468  if (out.scriptPubKey.IsPayToScriptHash()) {
469  std::vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
470  CMempoolAddressDeltaKey key(2, uint160(hashBytes), RVN, txhash, k, 0);
471  mapAddress.insert(std::make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
472  inserted.push_back(key);
473  } else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
474  std::vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
475  std::pair<addressDeltaMap::iterator,bool> ret;
476  CMempoolAddressDeltaKey key(1, uint160(hashBytes), RVN, txhash, k, 0);
477  mapAddress.insert(std::make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
478  inserted.push_back(key);
479  } else if (out.scriptPubKey.IsPayToPublicKey()) {
480  uint160 hashBytes(Hash160(out.scriptPubKey.begin()+1, out.scriptPubKey.end()-1));
481  std::pair<addressDeltaMap::iterator,bool> ret;
482  CMempoolAddressDeltaKey key(1, hashBytes, RVN, txhash, k, 0);
483  mapAddress.insert(std::make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
484  inserted.push_back(key);
485  } else {
487  if (AreAssetsDeployed()) {
488  uint160 hashBytes;
489  std::string assetName;
490  CAmount assetAmount;
491  if (ParseAssetScript(out.scriptPubKey, hashBytes, assetName, assetAmount)) {
492  std::pair<addressDeltaMap::iterator, bool> ret;
493  CMempoolAddressDeltaKey key(1, hashBytes, assetName, txhash, k, 0);
494  mapAddress.insert(std::make_pair(key, CMempoolAddressDelta(entry.GetTime(), assetAmount)));
495  inserted.push_back(key);
496  }
497  }
499  }
500  }
501 
502  mapAddressInserted.insert(std::make_pair(txhash, inserted));
503 }
504 
505 bool CTxMemPool::getAddressIndex(std::vector<std::pair<uint160, int> > &addresses, std::string assetName,
506  std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
507 {
508  LOCK(cs);
509  for (std::vector<std::pair<uint160, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
510  addressDeltaMap::iterator ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first,
511  assetName));
512  while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second
513  && (*ait).first.asset == assetName) {
514  results.push_back(*ait);
515  ait++;
516  }
517  }
518  return true;
519 }
520 
521 bool CTxMemPool::getAddressIndex(std::vector<std::pair<uint160, int> > &addresses,
522  std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results)
523 {
524  LOCK(cs);
525  for (std::vector<std::pair<uint160, int> >::iterator it = addresses.begin(); it != addresses.end(); it++) {
526  addressDeltaMap::iterator ait = mapAddress.lower_bound(CMempoolAddressDeltaKey((*it).second, (*it).first));
527  while (ait != mapAddress.end() && (*ait).first.addressBytes == (*it).first && (*ait).first.type == (*it).second) {
528  results.push_back(*ait);
529  ait++;
530  }
531  }
532  return true;
533 }
534 
536 {
537  LOCK(cs);
538  addressDeltaMapInserted::iterator it = mapAddressInserted.find(txhash);
539 
540  if (it != mapAddressInserted.end()) {
541  std::vector<CMempoolAddressDeltaKey> keys = (*it).second;
542  for (std::vector<CMempoolAddressDeltaKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
543  mapAddress.erase(*mit);
544  }
545  mapAddressInserted.erase(it);
546  }
547 
548  return true;
549 }
550 
552 {
553  LOCK(cs);
554 
555  const CTransaction& tx = entry.GetTx();
556  std::vector<CSpentIndexKey> inserted;
557 
558  uint256 txhash = tx.GetHash();
559  for (unsigned int j = 0; j < tx.vin.size(); j++) {
560  const CTxIn input = tx.vin[j];
561  const CTxOut &prevout = view.AccessCoin(input.prevout).out;
562  uint160 addressHash;
563  int addressType = 0;
564 
565  if (prevout.scriptPubKey.IsPayToScriptHash()) {
566  addressHash = uint160(std::vector<unsigned char> (prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22));
567  addressType = 2;
568  } else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
569  addressHash = uint160(std::vector<unsigned char> (prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23));
570  addressType = 1;
571  } else if (prevout.scriptPubKey.IsPayToPublicKey()) {
572  addressHash = Hash160(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.end()-1);
573  addressType = 1;
574  } else {
575  addressHash.SetNull();
576  addressType = 0;
577  }
578 
579  CSpentIndexKey key = CSpentIndexKey(input.prevout.hash, input.prevout.n);
580  CSpentIndexValue value = CSpentIndexValue(txhash, j, -1, prevout.nValue, addressType, addressHash);
581 
582  mapSpent.insert(std::make_pair(key, value));
583  inserted.push_back(key);
584 
585  }
586 
587  mapSpentInserted.insert(std::make_pair(txhash, inserted));
588 }
589 
591 {
592  LOCK(cs);
593  mapSpentIndex::iterator it;
594 
595  it = mapSpent.find(key);
596  if (it != mapSpent.end()) {
597  value = it->second;
598  return true;
599  }
600  return false;
601 }
602 
604 {
605  LOCK(cs);
606  mapSpentIndexInserted::iterator it = mapSpentInserted.find(txhash);
607 
608  if (it != mapSpentInserted.end()) {
609  std::vector<CSpentIndexKey> keys = (*it).second;
610  for (std::vector<CSpentIndexKey>::iterator mit = keys.begin(); mit != keys.end(); mit++) {
611  mapSpent.erase(*mit);
612  }
613  mapSpentInserted.erase(it);
614  }
615 
616  return true;
617 }
618 
620 {
621  NotifyEntryRemoved(it->GetSharedTx(), reason);
622  const uint256 hash = it->GetTx().GetHash();
623  for (const CTxIn& txin : it->GetTx().vin)
624  mapNextTx.erase(txin.prevout);
625 
626  if (vTxHashes.size() > 1) {
627  vTxHashes[it->vTxHashesIdx] = std::move(vTxHashes.back());
628  vTxHashes[it->vTxHashesIdx].second->vTxHashesIdx = it->vTxHashesIdx;
629  vTxHashes.pop_back();
630  if (vTxHashes.size() * 2 < vTxHashes.capacity())
631  vTxHashes.shrink_to_fit();
632  } else
633  vTxHashes.clear();
634 
635  totalTxSize -= it->GetTxSize();
636  cachedInnerUsage -= it->DynamicMemoryUsage();
637  cachedInnerUsage -= memusage::DynamicUsage(mapLinks[it].parents) + memusage::DynamicUsage(mapLinks[it].children);
638  mapLinks.erase(it);
639  mapTx.erase(it);
642  removeAddressIndex(hash);
643  removeSpentIndex(hash);
644 
646  // If the transaction being removed from the mempool is locking other reissues. Free them
647  if (mapReissuedTx.count(hash)) {
648  if (mapReissuedAssets.count(mapReissuedTx.at(hash))) {
649  mapReissuedAssets.erase(mapReissuedTx.at((hash)));
650  mapReissuedTx.erase(hash);
651  }
652  }
653 
654  // Erase from the asset mempool maps if they match txid
655  if (mapHashToAsset.count(hash)) {
656  mapAssetToHash.erase(mapHashToAsset.at(hash));
657  mapHashToAsset.erase(hash);
658  }
659 
660  // Erase from the restricted asset mempool maps if they match txids
661  if (mapHashToAddressMarkedFrozen.count(hash)) {
662  for (auto item : mapHashToAddressMarkedFrozen.at(hash))
663  mapAddressesMarkedFrozen.at(item).erase(hash);
664  mapHashToAddressMarkedFrozen.erase(hash);
665  }
666 
667  if (mapHashMarkedGlobalFrozen.count(hash)) {
668  for (auto item : mapHashMarkedGlobalFrozen.at(hash))
669  mapAssetMarkedGlobalFrozen.at(item).erase(hash);
670  mapHashMarkedGlobalFrozen.erase(hash);
671  }
672 
673  if (mapHashQualifiersChanged.count(hash)) {
674  for (auto item : mapHashQualifiersChanged.at(hash))
675  mapAddressesQualifiersChanged.at(item).erase(hash);
676  mapHashQualifiersChanged.erase(hash);
677  }
678 
679  if (mapHashVerifierChanged.count(hash)) {
680  for (auto item : mapHashVerifierChanged.at(hash))
681  mapAssetVerifierChanged.at(item).erase(hash);
682  mapHashVerifierChanged.erase(hash);
683  }
685 }
686 
687 // Calculates descendants of entry that are not already in setDescendants, and adds to
688 // setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
689 // is correct for tx and all descendants.
690 // Also assumes that if an entry is in setDescendants already, then all
691 // in-mempool descendants of it are already in setDescendants as well, so that we
692 // can save time by not iterating over those entries.
693 void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
694 {
695  setEntries stage;
696  if (setDescendants.count(entryit) == 0) {
697  stage.insert(entryit);
698  }
699  // Traverse down the children of entry, only adding children that are not
700  // accounted for in setDescendants already (because those children have either
701  // already been walked, or will be walked in this iteration).
702  while (!stage.empty()) {
703  txiter it = *stage.begin();
704  setDescendants.insert(it);
705  stage.erase(it);
706 
707  const setEntries &setChildren = GetMemPoolChildren(it);
708  for (const txiter &childiter : setChildren) {
709  if (!setDescendants.count(childiter)) {
710  stage.insert(childiter);
711  }
712  }
713  }
714 }
715 
717 {
718  // Remove transaction from memory pool
719  {
720  LOCK(cs);
721  setEntries txToRemove;
722  txiter origit = mapTx.find(origTx.GetHash());
723  if (origit != mapTx.end()) {
724  txToRemove.insert(origit);
725  } else {
726  // When recursively removing but origTx isn't in the mempool
727  // be sure to remove any children that are in the pool. This can
728  // happen during chain re-orgs if origTx isn't re-accepted into
729  // the mempool for any reason.
730  for (unsigned int i = 0; i < origTx.vout.size(); i++) {
731  auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
732  if (it == mapNextTx.end())
733  continue;
734  txiter nextit = mapTx.find(it->second->GetHash());
735  assert(nextit != mapTx.end());
736  txToRemove.insert(nextit);
737  }
738  }
739  setEntries setAllRemoves;
740  for (txiter it : txToRemove) {
741  CalculateDescendants(it, setAllRemoves);
742  }
743 
744  RemoveStaged(setAllRemoves, false, reason);
745  }
746 }
747 
748 void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
749 {
750  // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
751  LOCK(cs);
752  setEntries txToRemove;
753  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
754  const CTransaction& tx = it->GetTx();
755  LockPoints lp = it->GetLockPoints();
756  bool validLP = TestLockPointValidity(&lp);
757  if (!CheckFinalTx(tx, flags) || !CheckSequenceLocks(tx, flags, &lp, validLP)) {
758  // Note if CheckSequenceLocks fails the LockPoints may still be invalid
759  // So it's critical that we remove the tx and not depend on the LockPoints.
760  txToRemove.insert(it);
761  } else if (it->GetSpendsCoinbase()) {
762  for (const CTxIn& txin : tx.vin) {
763  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
764  if (it2 != mapTx.end())
765  continue;
766  const Coin &coin = pcoins->AccessCoin(txin.prevout);
767  if (nCheckFrequency != 0) assert(!coin.IsSpent());
768  if (coin.IsSpent() || (coin.IsCoinBase() && ((signed long)nMemPoolHeight) - coin.nHeight < COINBASE_MATURITY)) {
769  txToRemove.insert(it);
770  break;
771  }
772  }
773  }
774  if (!validLP) {
775  mapTx.modify(it, update_lock_points(lp));
776  }
777  }
778  setEntries setAllRemoves;
779  for (txiter it : txToRemove) {
780  CalculateDescendants(it, setAllRemoves);
781  }
782  RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
783 }
784 
786 {
787  // Remove transactions which depend on inputs of tx, recursively
788  LOCK(cs);
789  for (const CTxIn &txin : tx.vin) {
790  auto it = mapNextTx.find(txin.prevout);
791  if (it != mapNextTx.end()) {
792  const CTransaction &txConflict = *it->second;
793  if (txConflict != tx)
794  {
795  ClearPrioritisation(txConflict.GetHash());
797  }
798  }
799  }
800 }
801 
802 
806 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
807 {
808  ConnectedBlockAssetData connectedBlockAssetData;
809  removeForBlock(vtx, nBlockHeight, connectedBlockAssetData);
810 }
811 
815 void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight, ConnectedBlockAssetData& connectedBlockData)
816 {
817  LOCK(cs);
818  std::set<uint256> setAlreadyRemoving;
819 
820  std::vector<const CTxMemPoolEntry*> entries;
821  for (const auto& tx : vtx)
822  {
823  uint256 hash = tx->GetHash();
824 
825  indexed_transaction_set::iterator i = mapTx.find(hash);
826  if (i != mapTx.end())
827  entries.push_back(&*i);
828  }
829 
831  // Get the newly added assets, and make sure they are in the entries
832  std::vector<CTransaction> trans;
833  for (auto it : connectedBlockData.newAssetsToAdd) {
834  if (mapAssetToHash.count(it.asset.strName)) {
835  indexed_transaction_set::iterator i = mapTx.find(mapAssetToHash.at(it.asset.strName));
836  if (i != mapTx.end()) {
837  entries.push_back(&*i);
838  trans.emplace_back(i->GetTx());
839  setAlreadyRemoving.insert(mapAssetToHash.at(it.asset.strName));
840  }
841  }
842  }
843 
844  for (auto it : connectedBlockData.newVerifiersToAdd) {
845  if (mapAssetVerifierChanged.count(it.assetName)) {
846  for (auto hash : mapAssetVerifierChanged.at(it.assetName)) {
847  indexed_transaction_set::iterator i = mapTx.find(hash);
848  if (i != mapTx.end()) {
849  CValidationState state;
850  if (!setAlreadyRemoving.count(hash) && !CheckTransaction(i->GetTx(), state, passets)) {
851  entries.push_back(&*i);
852  trans.emplace_back(i->GetTx());
853  setAlreadyRemoving.insert(hash);
854  }
855  }
856  }
857  }
858  }
859 
860  for (auto it : connectedBlockData.newQualifiersToAdd) {
861  if (mapAddressesQualifiersChanged.count(it.address)) {
862  for (auto hash : mapAddressesQualifiersChanged.at(it.address)) {
863  indexed_transaction_set::iterator i = mapTx.find(hash);
864  if (i != mapTx.end()) {
865  CValidationState state;
866  if (!setAlreadyRemoving.count(hash) && !CheckTransaction(i->GetTx(), state, passets)) {
867  entries.push_back(&*i);
868  trans.emplace_back(i->GetTx());
869  setAlreadyRemoving.insert(hash);
870  }
871  }
872  }
873  }
874  }
875 
876  for (auto it : connectedBlockData.newGlobalRestrictionsToAdd) {
877  if (it.type == RestrictedType::GLOBAL_FREEZE) {
878  if (mapAssetMarkedGlobalFrozen.count(it.assetName)) {
879  for (auto hash : mapAssetMarkedGlobalFrozen.at(it.assetName)) {
880  indexed_transaction_set::iterator i = mapTx.find(hash);
881  if (i != mapTx.end()) {
882  CValidationState state;
883  if (!setAlreadyRemoving.count(hash) && !CheckTransaction(i->GetTx(), state, passets)) {
884  entries.push_back(&*i);
885  trans.emplace_back(i->GetTx());
886  setAlreadyRemoving.insert(hash);
887  }
888  }
889  }
890  }
891  }
892  }
893 
894  for (auto it : connectedBlockData.newAddressRestrictionsToAdd) {
895  if (it.type == RestrictedType::FREEZE_ADDRESS) {
896  auto pair = std::make_pair(it.address, it.assetName);
897  if (mapAddressesMarkedFrozen.count(pair)) {
898  for (auto hash : mapAddressesMarkedFrozen.at(pair)) {
899  indexed_transaction_set::iterator i = mapTx.find(hash);
900  if (i != mapTx.end()) {
901  CValidationState state;
902  std::vector<std::pair<std::string, uint256>> vReissueAssets;
903  if (!setAlreadyRemoving.count(hash) && !Consensus::CheckTxAssets(i->GetTx(), state, pcoinsTip, passets, false, vReissueAssets)) {
904  entries.push_back(&*i);
905  trans.emplace_back(i->GetTx());
906  setAlreadyRemoving.insert(hash);
907  }
908  }
909  }
910  }
911  }
912  }
915  // Before the txs in the new block have been removed from the mempool, update policy estimates
916  if (minerPolicyEstimator) {minerPolicyEstimator->processBlock(nBlockHeight, entries);}
917  for (const auto& tx : vtx)
918  {
919  txiter it = mapTx.find(tx->GetHash());
920  if (it != mapTx.end()) {
921  setEntries stage;
922  stage.insert(it);
924  }
925  removeConflicts(*tx);
926  ClearPrioritisation(tx->GetHash());
927  }
928 
930  // Remove newly added asset issue transactions from the mempool if they haven't been removed already
931  for (auto tx : trans)
932  {
933  txiter it = mapTx.find(tx.GetHash());
934  if (it != mapTx.end()) {
935  setEntries stage;
936  stage.insert(it);
938  }
939  removeConflicts(tx);
940  ClearPrioritisation(tx.GetHash());
941  }
946 }
947 
949 {
950  mapLinks.clear();
951  mapTx.clear();
952  mapNextTx.clear();
953  totalTxSize = 0;
954  cachedInnerUsage = 0;
959  mapAssetToHash.clear();
960  mapHashToAsset.clear();
961 
962  mapAddressesMarkedFrozen.clear();
967  mapHashQualifiersChanged.clear();
968  mapAssetVerifierChanged.clear();
969  mapHashVerifierChanged.clear();
970 }
971 
973 {
974  LOCK(cs);
975  _clear();
976 }
977 
978 static void CheckInputsAndUpdateCoins(const CTransaction& tx, CCoinsViewCache& mempoolDuplicate, const int64_t spendheight) {
979  CValidationState state;
980  CAmount txfee = 0;
981  bool fCheckResult = tx.IsCoinBase() || Consensus::CheckTxInputs(tx, state, mempoolDuplicate, spendheight, txfee);
983  if (AreAssetsDeployed()) {
984  std::vector<std::pair<std::string, uint256>> vReissueAssets;
985  bool fCheckAssets = Consensus::CheckTxAssets(tx, state, mempoolDuplicate, passets, false, vReissueAssets);
986  assert(fCheckResult && fCheckAssets);
987  } else
988  assert(fCheckResult);
990  UpdateCoins(tx, mempoolDuplicate, 1000000);
991 }
992 
993 void CTxMemPool::check(const CCoinsViewCache *pcoins) const
994 {
995  if (nCheckFrequency == 0)
996  return;
997 
998  if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)
999  return;
1000 
1001  LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
1002 
1003  uint64_t checkTotal = 0;
1004  uint64_t innerUsage = 0;
1005 
1006  CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
1007  const int64_t spendheight = GetSpendHeight(mempoolDuplicate);
1008 
1009  LOCK(cs);
1010  std::list<const CTxMemPoolEntry*> waitingOnDependants;
1011  for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
1012  unsigned int i = 0;
1013  checkTotal += it->GetTxSize();
1014  innerUsage += it->DynamicMemoryUsage();
1015  const CTransaction& tx = it->GetTx();
1016  txlinksMap::const_iterator linksiter = mapLinks.find(it);
1017  assert(linksiter != mapLinks.end());
1018  const TxLinks &links = linksiter->second;
1019  innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
1020  bool fDependsWait = false;
1021  setEntries setParentCheck;
1022  int64_t parentSizes = 0;
1023  int64_t parentSigOpCost = 0;
1024  for (const CTxIn &txin : tx.vin) {
1025  // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
1026  indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
1027  if (it2 != mapTx.end()) {
1028  const CTransaction& tx2 = it2->GetTx();
1029  assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
1030  fDependsWait = true;
1031  if (setParentCheck.insert(it2).second) {
1032  parentSizes += it2->GetTxSize();
1033  parentSigOpCost += it2->GetSigOpCost();
1034  }
1035  } else {
1036  assert(pcoins->HaveCoin(txin.prevout));
1037  }
1038  // Check whether its inputs are marked in mapNextTx.
1039  auto it3 = mapNextTx.find(txin.prevout);
1040  assert(it3 != mapNextTx.end());
1041  assert(it3->first == &txin.prevout);
1042  assert(it3->second == &tx);
1043  i++;
1044  }
1045  assert(setParentCheck == GetMemPoolParents(it));
1046  // Verify ancestor state is correct.
1047  setEntries setAncestors;
1048  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
1049  std::string dummy;
1050  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
1051  uint64_t nCountCheck = setAncestors.size() + 1;
1052  uint64_t nSizeCheck = it->GetTxSize();
1053  CAmount nFeesCheck = it->GetModifiedFee();
1054  int64_t nSigOpCheck = it->GetSigOpCost();
1055 
1056  for (txiter ancestorIt : setAncestors) {
1057  nSizeCheck += ancestorIt->GetTxSize();
1058  nFeesCheck += ancestorIt->GetModifiedFee();
1059  nSigOpCheck += ancestorIt->GetSigOpCost();
1060  }
1061 
1062  assert(it->GetCountWithAncestors() == nCountCheck);
1063  assert(it->GetSizeWithAncestors() == nSizeCheck);
1064  assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
1065  assert(it->GetModFeesWithAncestors() == nFeesCheck);
1066 
1067  // Check children against mapNextTx
1068  CTxMemPool::setEntries setChildrenCheck;
1069  auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
1070  int64_t childSizes = 0;
1071  for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
1072  txiter childit = mapTx.find(iter->second->GetHash());
1073  assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
1074  if (setChildrenCheck.insert(childit).second) {
1075  childSizes += childit->GetTxSize();
1076  }
1077  }
1078  assert(setChildrenCheck == GetMemPoolChildren(it));
1079  // Also check to make sure size is greater than sum with immediate children.
1080  // just a sanity check, not definitive that this calc is correct...
1081  assert(it->GetSizeWithDescendants() >= childSizes + it->GetTxSize());
1082 
1083  if (fDependsWait)
1084  waitingOnDependants.push_back(&(*it));
1085  else {
1086  CheckInputsAndUpdateCoins(tx, mempoolDuplicate, spendheight);
1087  }
1088  }
1089  unsigned int stepsSinceLastRemove = 0;
1090  while (!waitingOnDependants.empty()) {
1091  const CTxMemPoolEntry* entry = waitingOnDependants.front();
1092  waitingOnDependants.pop_front();
1093  CValidationState state;
1094  if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
1095  waitingOnDependants.push_back(entry);
1096  stepsSinceLastRemove++;
1097  assert(stepsSinceLastRemove < waitingOnDependants.size());
1098  } else {
1099  CheckInputsAndUpdateCoins(entry->GetTx(), mempoolDuplicate, spendheight);
1100  stepsSinceLastRemove = 0;
1101  }
1102  }
1103  for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
1104  uint256 hash = it->second->GetHash();
1105  indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
1106  const CTransaction& tx = it2->GetTx();
1107  assert(it2 != mapTx.end());
1108  assert(&tx == it->second);
1109  }
1110 
1111  assert(totalTxSize == checkTotal);
1112  assert(innerUsage == cachedInnerUsage);
1113 }
1114 
1115 bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)
1116 {
1117  LOCK(cs);
1118  indexed_transaction_set::const_iterator i = mapTx.find(hasha);
1119  if (i == mapTx.end()) return false;
1120  indexed_transaction_set::const_iterator j = mapTx.find(hashb);
1121  if (j == mapTx.end()) return true;
1122  uint64_t counta = i->GetCountWithAncestors();
1123  uint64_t countb = j->GetCountWithAncestors();
1124  if (counta == countb) {
1125  return CompareTxMemPoolEntryByScore()(*i, *j);
1126  }
1127  return counta < countb;
1128 }
1129 
1130 namespace {
1131 class DepthAndScoreComparator
1132 {
1133 public:
1134  bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
1135  {
1136  uint64_t counta = a->GetCountWithAncestors();
1137  uint64_t countb = b->GetCountWithAncestors();
1138  if (counta == countb) {
1139  return CompareTxMemPoolEntryByScore()(*a, *b);
1140  }
1141  return counta < countb;
1142  }
1143 };
1144 } // namespace
1145 
1146 std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
1147 {
1148  std::vector<indexed_transaction_set::const_iterator> iters;
1149  AssertLockHeld(cs);
1150 
1151  iters.reserve(mapTx.size());
1152 
1153  for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
1154  iters.push_back(mi);
1155  }
1156  std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
1157  return iters;
1158 }
1159 
1160 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
1161 {
1162  LOCK(cs);
1163  auto iters = GetSortedDepthAndScore();
1164 
1165  vtxid.clear();
1166  vtxid.reserve(mapTx.size());
1167 
1168  for (auto it : iters) {
1169  vtxid.push_back(it->GetTx().GetHash());
1170  }
1171 }
1172 
1173 static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
1174  return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), CFeeRate(it->GetFee(), it->GetTxSize()), it->GetModifiedFee() - it->GetFee()};
1175 }
1176 
1177 std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
1178 {
1179  LOCK(cs);
1180  auto iters = GetSortedDepthAndScore();
1181 
1182  std::vector<TxMempoolInfo> ret;
1183  ret.reserve(mapTx.size());
1184  for (auto it : iters) {
1185  ret.push_back(GetInfo(it));
1186  }
1187 
1188  return ret;
1189 }
1190 
1192 {
1193  LOCK(cs);
1194  indexed_transaction_set::const_iterator i = mapTx.find(hash);
1195  if (i == mapTx.end())
1196  return nullptr;
1197  return i->GetSharedTx();
1198 }
1199 
1201 {
1202  LOCK(cs);
1203  indexed_transaction_set::const_iterator i = mapTx.find(hash);
1204  if (i == mapTx.end())
1205  return TxMempoolInfo();
1206  return GetInfo(i);
1207 }
1208 
1209 void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
1210 {
1211  {
1212  LOCK(cs);
1213  CAmount &delta = mapDeltas[hash];
1214  delta += nFeeDelta;
1215  txiter it = mapTx.find(hash);
1216  if (it != mapTx.end()) {
1217  mapTx.modify(it, update_fee_delta(delta));
1218  // Now update all ancestors' modified fees with descendants
1219  setEntries setAncestors;
1220  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
1221  std::string dummy;
1222  CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
1223  for (txiter ancestorIt : setAncestors) {
1224  mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
1225  }
1226  // Now update all descendants' modified fees with ancestors
1227  setEntries setDescendants;
1228  CalculateDescendants(it, setDescendants);
1229  setDescendants.erase(it);
1230  for (txiter descendantIt : setDescendants) {
1231  mapTx.modify(descendantIt, update_ancestor_state(0, nFeeDelta, 0, 0));
1232  }
1234  }
1235  }
1236  LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
1237 }
1238 
1239 void CTxMemPool::ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
1240 {
1241  LOCK(cs);
1242  std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
1243  if (pos == mapDeltas.end())
1244  return;
1245  const CAmount &delta = pos->second;
1246  nFeeDelta += delta;
1247 }
1248 
1250 {
1251  LOCK(cs);
1252  mapDeltas.erase(hash);
1253 }
1254 
1256 {
1257  for (unsigned int i = 0; i < tx.vin.size(); i++)
1258  if (exists(tx.vin[i].prevout.hash))
1259  return false;
1260  return true;
1261 }
1262 
1263 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1264 
1265 bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
1266  // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1267  // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1268  // transactions. First checking the underlying cache risks returning a pruned entry instead.
1269  CTransactionRef ptx = mempool.get(outpoint.hash);
1270  if (ptx) {
1271  if (outpoint.n < ptx->vout.size()) {
1272  coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
1273  return true;
1274  } else {
1275  return false;
1276  }
1277  }
1278  return base->GetCoin(outpoint, coin);
1279 }
1280 
1282  LOCK(cs);
1283  // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1284  return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(mapLinks) + memusage::DynamicUsage(vTxHashes) + cachedInnerUsage;
1285 }
1286 
1287 void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1288  AssertLockHeld(cs);
1289  UpdateForRemoveFromMempool(stage, updateDescendants);
1290  for (const txiter& it : stage) {
1291  removeUnchecked(it, reason);
1292  }
1293 }
1294 
1295 int CTxMemPool::Expire(int64_t time) {
1296  LOCK(cs);
1297  indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1298  setEntries toremove;
1299  while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1300  toremove.insert(mapTx.project<0>(it));
1301  it++;
1302  }
1303  setEntries stage;
1304  for (txiter removeit : toremove) {
1305  CalculateDescendants(removeit, stage);
1306  }
1307  RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
1308  return stage.size();
1309 }
1310 
1311 bool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry, bool validFeeEstimate)
1312 {
1313  LOCK(cs);
1314  setEntries setAncestors;
1315  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
1316  std::string dummy;
1317  CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
1318  return addUnchecked(hash, entry, setAncestors, validFeeEstimate);
1319 }
1320 
1321 void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1322 {
1323  setEntries s;
1324  if (add && mapLinks[entry].children.insert(child).second) {
1325  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1326  } else if (!add && mapLinks[entry].children.erase(child)) {
1327  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1328  }
1329 }
1330 
1331 void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1332 {
1333  setEntries s;
1334  if (add && mapLinks[entry].parents.insert(parent).second) {
1335  cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1336  } else if (!add && mapLinks[entry].parents.erase(parent)) {
1337  cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1338  }
1339 }
1340 
1342 {
1343  assert (entry != mapTx.end());
1344  txlinksMap::const_iterator it = mapLinks.find(entry);
1345  assert(it != mapLinks.end());
1346  return it->second.parents;
1347 }
1348 
1350 {
1351  assert (entry != mapTx.end());
1352  txlinksMap::const_iterator it = mapLinks.find(entry);
1353  assert(it != mapLinks.end());
1354  return it->second.children;
1355 }
1356 
1357 CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1358  LOCK(cs);
1359  if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1360  return CFeeRate(llround(rollingMinimumFeeRate));
1361 
1362  int64_t time = GetTime();
1363  if (time > lastRollingFeeUpdate + 10) {
1364  double halflife = ROLLING_FEE_HALFLIFE;
1365  if (DynamicMemoryUsage() < sizelimit / 4)
1366  halflife /= 4;
1367  else if (DynamicMemoryUsage() < sizelimit / 2)
1368  halflife /= 2;
1369 
1370  rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1371  lastRollingFeeUpdate = time;
1372 
1373  if (rollingMinimumFeeRate < (double)incrementalRelayFee.GetFeePerK() / 2) {
1374  rollingMinimumFeeRate = 0;
1375  return CFeeRate(0);
1376  }
1377  }
1378  return std::max(CFeeRate(llround(rollingMinimumFeeRate)), incrementalRelayFee);
1379 }
1380 
1382  AssertLockHeld(cs);
1383  if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1384  rollingMinimumFeeRate = rate.GetFeePerK();
1385  blockSinceLastRollingFeeBump = false;
1386  }
1387 }
1388 
1389 void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1390  LOCK(cs);
1391 
1392  unsigned nTxnRemoved = 0;
1393  CFeeRate maxFeeRateRemoved(0);
1394  while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1395  indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1396 
1397  // We set the new mempool min fee to the feerate of the removed set, plus the
1398  // "minimum reasonable fee rate" (ie some value under which we consider txn
1399  // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1400  // equal to txn which were removed with no block in between.
1401  CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1402  removed += incrementalRelayFee;
1403  trackPackageRemoved(removed);
1404  maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1405 
1406  setEntries stage;
1407  CalculateDescendants(mapTx.project<0>(it), stage);
1408  nTxnRemoved += stage.size();
1409 
1410  std::vector<CTransaction> txn;
1411  if (pvNoSpendsRemaining) {
1412  txn.reserve(stage.size());
1413  for (txiter iter : stage)
1414  txn.push_back(iter->GetTx());
1415  }
1416  RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1417  if (pvNoSpendsRemaining) {
1418  for (const CTransaction& tx : txn) {
1419  for (const CTxIn& txin : tx.vin) {
1420  if (exists(txin.prevout.hash)) continue;
1421  pvNoSpendsRemaining->push_back(txin.prevout);
1422  }
1423  }
1424  }
1425  }
1426 
1427  if (maxFeeRateRemoved > CFeeRate(0)) {
1428  LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1429  }
1430 }
1431 
1432 bool CTxMemPool::TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const {
1433  LOCK(cs);
1434  auto it = mapTx.find(txid);
1435  return it == mapTx.end() || (it->GetCountWithAncestors() < chainLimit &&
1436  it->GetCountWithDescendants() < chainLimit);
1437 }
1438 
1439 SaltedTxidHasher::SaltedTxidHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
addressDeltaMapInserted mapAddressInserted
Definition: txmempool.h:518
size_type count(const K &key) const
Definition: indirectmap.h:42
CAmount nValue
Definition: transaction.h:140
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:266
CTxMemPool mempool
bool IsSpent() const
Definition: coins.h:78
Information about a mempool transaction.
Definition: txmempool.h:302
int Expire(int64_t time)
Expire all transaction (and their dependencies) in the mempool older than time.
Definition: txmempool.cpp:1295
bool IsCoinBase() const
Definition: coins.h:57
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
Set ancestor state for an entry.
Definition: txmempool.cpp:233
CAmount nModFeesWithDescendants
... and total fees (all including us)
Definition: txmempool.h:87
void UpdateLockPoints(const LockPoints &lp)
Definition: txmempool.cpp:51
void addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
Definition: txmempool.cpp:551
std::set< CAssetCacheNewAsset > newAssetsToAdd
Definition: txmempool.h:828
void removeConflicts(const CTransaction &tx)
Definition: txmempool.cpp:785
size_t nTxWeight
... and avoid recomputing tx weight (also used for GetTxSize())
Definition: txmempool.h:73
uint256 GetWitnessHash() const
Definition: transaction.cpp:79
void SetNull()
Definition: uint256.h:41
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:20
CScript scriptPubKey
Definition: transaction.h:141
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:1177
std::map< uint256, std::set< std::string > > mapHashQualifiersChanged
Definition: txmempool.h:485
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or a pruned one if not found.
Definition: coins.cpp:390
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Definition: txmempool.cpp:716
int flags
Definition: raven-tx.cpp:500
void trackPackageRemoved(const CFeeRate &rate)
Definition: txmempool.cpp:1381
A UTXO entry.
Definition: coins.h:32
addressDeltaMap mapAddress
Definition: txmempool.h:515
size_t GetTxSize() const
Definition: txmempool.cpp:56
boost::signals2::signal< void(CTransactionRef)> NotifyEntryAdded
Definition: txmempool.h:672
#define strprintf
Definition: tinyformat.h:1054
bool IsPayToScriptHash() const
Definition: script.cpp:221
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1281
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:1265
bool isSpent(const COutPoint &outpoint)
Definition: txmempool.cpp:344
bool removeTx(uint256 hash, bool inBlock)
Remove a transaction from the mempool tracking stats.
Definition: fees.cpp:524
reverse_range< T > reverse_iterate(T &x)
TxMempoolInfo info(const uint256 &hash) const
Definition: txmempool.cpp:1200
const_iterator cend() const
Definition: indirectmap.h:54
Expired from mempool.
std::map< uint256, std::set< std::string > > mapHashVerifierChanged
Definition: txmempool.h:489
std::map< uint256, std::set< std::string > > mapHashMarkedGlobalFrozen
Definition: txmempool.h:481
CTxOut out
unspent transaction output
Definition: coins.h:36
CTxMemPool(CBlockPolicyEstimator *estimator=nullptr)
Create a new CTxMemPool.
Definition: txmempool.cpp:333
std::set< CAssetCacheRestrictedGlobal > newGlobalRestrictionsToAdd
Definition: txmempool.h:831
void clear()
Definition: txmempool.cpp:972
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:1255
std::set< CAssetCacheRestrictedAddress > newAddressRestrictionsToAdd
Definition: txmempool.h:830
const_iterator cbegin() const
Definition: indirectmap.h:53
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:499
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:1160
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:320
int64_t sigOpCost
Total sigop cost.
Definition: txmempool.h:78
bool getAddressIndex(std::vector< std::pair< uint160, int > > &addresses, std::string assetName, std::vector< std::pair< CMempoolAddressDeltaKey, CMempoolAddressDelta > > &results)
Definition: txmempool.cpp:505
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:208
void TrimToSize(size_t sizelimit, std::vector< COutPoint > *pvNoSpendsRemaining=nullptr)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
Definition: txmempool.cpp:1389
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:507
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:436
uint64_t nCountWithDescendants
number of descendant transactions
Definition: txmempool.h:85
int64_t lastRollingFeeUpdate
Definition: txmempool.h:426
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight, ConnectedBlockAssetData &connectedBlockData)
Called when a block is connected.
Definition: txmempool.cpp:815
CAmount nFee
Cached to avoid expensive parent-transaction lookups.
Definition: txmempool.h:72
bool IsCoinBase() const
Definition: transaction.h:360
indirectmap< COutPoint, const CTransaction * > mapNextTx
Definition: txmempool.h:532
const std::vector< CTxIn > vin
Definition: transaction.h:287
void UpdateTransactionsFromBlock(const std::vector< uint256 > &vHashesToUpdate)
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
Definition: txmempool.cpp:111
void _clear()
Definition: txmempool.cpp:948
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:68
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:993
indexed_transaction_set mapTx
Definition: txmempool.h:469
int64_t CAmount
Amount in corbies (Can be negative)
Definition: amount.h:13
bool blockSinceLastRollingFeeBump
Definition: txmempool.h:427
#define AssertLockHeld(cs)
Definition: sync.h:86
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:42
Removed in size limiting.
iterator end()
Definition: prevector.h:293
int64_t nSigOpCostWithAncestors
Definition: txmempool.h:93
void clear()
Definition: indirectmap.h:48
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:223
bool IsPayToPublicKey() const
RVN END.
Definition: script.cpp:384
iterator end()
Definition: indirectmap.h:50
std::vector< std::pair< uint256, txiter > > vTxHashes
All tx witness hashes/entries in mapTx, in random order.
Definition: txmempool.h:492
void UpdateFeeDelta(int64_t feeDelta)
Definition: txmempool.cpp:44
#define LogPrintf(...)
Definition: util.h:149
std::map< uint256, std::string > mapHashToAsset
Definition: txmempool.h:472
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:255
size_t nUsageSize
... and total memory usage
Definition: txmempool.h:74
bool AreAssetsDeployed()
RVN START.
int GetSpendHeight(const CCoinsViewCache &inputs)
RVN END.
uint64_t nSizeWithAncestors
Definition: txmempool.h:91
int64_t feeDelta
Used for determining the priority of the transaction for mining in a block.
Definition: txmempool.h:79
Abstract view on the open txout dataset.
Definition: coins.h:152
size_t DynamicMemoryUsage() const
Definition: txmempool.h:110
void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
Definition: txmempool.cpp:1239
std::pair< iterator, bool > insert(const value_type &value)
Definition: indirectmap.h:34
An input of a transaction.
Definition: transaction.h:67
#define LOCK(cs)
Definition: sync.h:176
bool removeAddressIndex(const uint256 txhash)
Definition: txmempool.cpp:535
We want to be able to estimate feerates that are needed on tx&#39;s to be included in a certain number of...
Definition: fees.h:139
iterator lower_bound(const K &key)
Definition: indirectmap.h:39
bool CheckTxInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:525
CCoinsView * base
Definition: coins.h:192
const uint256 & GetHash() const
Definition: transaction.h:320
std::vector< indexed_transaction_set::const_iterator > GetSortedDepthAndScore() const
Definition: txmempool.cpp:1146
CTransactionRef GetSharedTx() const
Definition: txmempool.h:102
Removed for reorganization.
void UpdateParent(txiter entry, txiter parent, bool add)
Definition: txmempool.cpp:1331
std::map< std::string, uint256 > mapReissuedAssets
Definition: assets.cpp:41
std::map< uint256, CAmount > mapDeltas
Definition: txmempool.h:533
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:693
bool ParseAssetScript(CScript scriptPubKey, uint160 &hashBytes, std::string &assetName, CAmount &assetAmount)
Helper method for extracting address bytes, asset name and amount from an asset script.
Definition: assets.cpp:4317
uint32_t n
Definition: transaction.h:26
const setEntries & GetMemPoolChildren(txiter entry) const
Definition: txmempool.cpp:1349
const std::vector< CTxOut > vout
Definition: transaction.h:288
std::map< std::string, std::set< uint256 > > mapAssetVerifierChanged
Definition: txmempool.h:488
std::map< std::string, std::set< uint256 > > mapAddressesQualifiersChanged
Definition: txmempool.h:484
uint64_t cachedInnerUsage
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
Definition: txmempool.h:424
bool exists(uint256 hash) const
Definition: txmempool.h:660
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain. ...
Definition: validation.cpp:287
An output of a transaction.
Definition: transaction.h:137
CAmount nModFeesWithAncestors
Definition: txmempool.h:92
std::string ToString() const
Definition: uint256.cpp:63
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:154
unsigned int nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:420
void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps)
Definition: txmempool.cpp:322
Manually removed or unknown reason.
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
uint64_t nSizeWithDescendants
... and size
Definition: txmempool.h:86
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:356
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:1357
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Check if transaction will be BIP 68 final in the next block to be created.
Definition: validation.cpp:305
uint64_t totalTxSize
sum of all mempool tx&#39;s virtual sizes. Differs from serialized tx size since witness data is discount...
Definition: txmempool.h:423
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:491
CCriticalSection cs
Definition: txmempool.h:468
bool removeSpentIndex(const uint256 txhash)
Definition: txmempool.cpp:603
std::map< std::pair< std::string, std::string >, std::set< uint256 > > mapAddressesMarkedFrozen
Restricted assets maps.
Definition: txmempool.h:476
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:1432
#define LogPrint(category,...)
Definition: util.h:160
size_type size() const
Definition: indirectmap.h:46
RVN END.
Definition: validation.h:30
256-bit opaque blob.
Definition: uint256.h:123
mapSpentIndex mapSpent
Definition: txmempool.h:521
CAssetsCache * passets
Global variable that point to the active assets (protected by cs_main)
Definition: validation.cpp:227
void UpdateChildrenForRemoval(txiter entry)
Sever link between specified transaction and direct children.
Definition: txmempool.cpp:247
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:416
std::map< uint256, std::set< std::pair< std::string, std::string > > > mapHashToAddressMarkedFrozen
Definition: txmempool.h:477
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb)
Definition: txmempool.cpp:1115
void processBlock(unsigned int nBlockHeight, std::vector< const CTxMemPoolEntry *> &entries)
Process all the transactions that have been included in a block.
Definition: fees.cpp:630
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
Definition: txmempool.h:504
std::map< std::string, uint256 > mapAssetToHash
Definition: txmempool.h:471
int64_t GetTime() const
Definition: txmempool.h:106
LockPoints lockPoints
Track the height and time at which tx was final.
Definition: txmempool.h:80
uint32_t nCheckFrequency
Value n means that n times in 2^32 we check.
Definition: txmempool.h:419
std::set< CAssetCacheQualifierAddress > newQualifiersToAdd
Definition: txmempool.h:832
void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
Definition: txmempool.cpp:313
const CTransaction & GetTx() const
Definition: txmempool.h:101
std::map< uint256, std::string > mapReissuedTx
Definition: assets.cpp:40
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
For each transaction being removed, update ancestors and any direct children.
Definition: txmempool.cpp:255
uint64_t nCountWithAncestors
Definition: txmempool.h:90
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:20
160-bit opaque blob.
Definition: uint256.h:112
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, uint256 blockHash, CAssetsCache *assetCache, std::pair< std::string, CBlockAssetUndo > *undoAssetData)
void UpdateChild(txiter entry, txiter child, bool add)
Definition: txmempool.cpp:1321
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:350
bool CheckTransaction(const CTransaction &tx, CValidationState &state, bool fCheckDuplicateInputs)
Transaction validation functions.
Definition: tx_verify.cpp:168
const setEntries & GetMemPoolParents(txiter entry) const
Definition: txmempool.cpp:1341
iterator begin()
Definition: prevector.h:291
std::set< CAssetCacheRestrictedVerifiers > newVerifiersToAdd
Definition: txmempool.h:829
bool CheckTxAssets(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, CAssetsCache *assetCache, bool fCheckMempool, std::vector< std::pair< std::string, uint256 > > &vPairReissueAssets, const bool fRunningUnitTests=false, std::set< CMessage > *setMessages=nullptr, int64_t nBlocktime=0)
RVN START.
Definition: tx_verify.cpp:570
void ClearPrioritisation(const uint256 hash)
Definition: txmempool.cpp:1249
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:1191
CTransactionRef tx
Definition: txmempool.h:71
bool getSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
Definition: txmempool.cpp:590
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors)
Update ancestors of hash to add/remove it as a descendant transaction.
Definition: txmempool.cpp:218
boost::signals2::signal< void(CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved
Definition: txmempool.h:673
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool validFeeEstimate=true)
Definition: txmempool.cpp:1311
mapSpentIndexInserted mapSpentInserted
Definition: txmempool.h:524
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:1263
std::map< std::string, std::set< uint256 > > mapAssetMarkedGlobalFrozen
Definition: txmempool.h:480
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
std::string ToString() const
Definition: feerate.cpp:41
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
CCoinsView backed by another CCoinsView.
Definition: coins.h:189
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:208
Sort by score of entry ((fee+delta)/size) in descending order.
Definition: txmempool.h:245
const CTxMemPool & mempool
Definition: txmempool.h:728
void addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
Definition: txmempool.cpp:421
txlinksMap mapLinks
Definition: txmempool.h:512
COutPoint prevout
Definition: transaction.h:70
CBlockPolicyEstimator * minerPolicyEstimator
Definition: txmempool.h:421
double rollingMinimumFeeRate
minimum fee to get into the pool, decreases exponentially
Definition: txmempool.h:428
CFeeRate incrementalRelayFee
Definition: policy.cpp:262
bool IsPayToPublicKeyHash() const
Definition: script.cpp:210
iterator find(const K &key)
Definition: indirectmap.h:37
CTxMemPoolEntry(const CTransactionRef &_tx, const CAmount &_nFee, int64_t _nTime, unsigned int _entryHeight, bool spendsCoinbase, int64_t nSigOpsCost, LockPoints lp)
Definition: txmempool.cpp:23
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:1209
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
Definition: txmempool.cpp:748
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:42
void removeUnchecked(txiter entry, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Before calling removeUnchecked for a given transaction, UpdateForRemoveFromMempool must be called on ...
Definition: txmempool.cpp:619
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1287
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:353
void processTransaction(const CTxMemPoolEntry &entry, bool validFeeEstimate)
Process a transaction accepted to the mempool.
Definition: fees.cpp:564
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:24
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:399
uint256 hash
Definition: transaction.h:25
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:64
size_type erase(const K &key)
Definition: indirectmap.h:41