Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-2022 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 <chain.h>
9 : : #include <coins.h>
10 : : #include <common/system.h>
11 : : #include <consensus/consensus.h>
12 : : #include <consensus/tx_verify.h>
13 : : #include <consensus/validation.h>
14 : : #include <logging.h>
15 : : #include <policy/policy.h>
16 : : #include <policy/settings.h>
17 : : #include <random.h>
18 : : #include <reverse_iterator.h>
19 : : #include <util/check.h>
20 : : #include <util/feefrac.h>
21 : : #include <util/moneystr.h>
22 : : #include <util/overflow.h>
23 : : #include <util/result.h>
24 : : #include <util/time.h>
25 : : #include <util/trace.h>
26 : : #include <util/translation.h>
27 : : #include <validationinterface.h>
28 : :
29 : : #include <cmath>
30 : : #include <numeric>
31 : : #include <optional>
32 : : #include <string_view>
33 : : #include <utility>
34 : :
35 : 0 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
36 : : {
37 : 0 : AssertLockHeld(cs_main);
38 : : // If there are relative lock times then the maxInputBlock will be set
39 : : // If there are no relative lock times, the LockPoints don't depend on the chain
40 [ # # ]: 0 : if (lp.maxInputBlock) {
41 : : // Check whether active_chain is an extension of the block at which the LockPoints
42 : : // calculation was valid. If not LockPoints are no longer valid
43 [ # # ]: 0 : if (!active_chain.Contains(lp.maxInputBlock)) {
44 : 0 : return false;
45 : : }
46 : 0 : }
47 : :
48 : : // LockPoints still valid
49 : 0 : return true;
50 : 0 : }
51 : :
52 : 0 : void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
53 : : const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove)
54 : : {
55 : 0 : CTxMemPoolEntry::Children stageEntries, descendants;
56 [ # # # # : 0 : stageEntries = updateIt->GetMemPoolChildrenConst();
# # ]
57 : :
58 [ # # ]: 0 : while (!stageEntries.empty()) {
59 : 0 : const CTxMemPoolEntry& descendant = *stageEntries.begin();
60 [ # # ]: 0 : descendants.insert(descendant);
61 [ # # ]: 0 : stageEntries.erase(descendant);
62 [ # # ]: 0 : const CTxMemPoolEntry::Children& children = descendant.GetMemPoolChildrenConst();
63 [ # # ]: 0 : for (const CTxMemPoolEntry& childEntry : children) {
64 [ # # # # ]: 0 : cacheMap::iterator cacheIt = cachedDescendants.find(mapTx.iterator_to(childEntry));
65 [ # # ]: 0 : if (cacheIt != cachedDescendants.end()) {
66 : : // We've already calculated this one, just add the entries for this set
67 : : // but don't traverse again.
68 [ # # ]: 0 : for (txiter cacheEntry : cacheIt->second) {
69 [ # # # # ]: 0 : descendants.insert(*cacheEntry);
70 : 0 : }
71 [ # # # # ]: 0 : } else if (!descendants.count(childEntry)) {
72 : : // Schedule for later processing
73 [ # # ]: 0 : stageEntries.insert(childEntry);
74 : 1 : }
75 : 0 : }
76 : 0 : }
77 : : // descendants now contains all in-mempool descendants of updateIt.
78 : : // Update and add to cached descendant map
79 : 0 : int32_t modifySize = 0;
80 : 0 : CAmount modifyFee = 0;
81 : 0 : int64_t modifyCount = 0;
82 [ # # ]: 0 : for (const CTxMemPoolEntry& descendant : descendants) {
83 [ # # # # : 0 : if (!setExclude.count(descendant.GetTx().GetHash())) {
# # # # #
# ]
84 [ # # ]: 0 : modifySize += descendant.GetTxSize();
85 [ # # ]: 0 : modifyFee += descendant.GetModifiedFee();
86 : 0 : modifyCount++;
87 [ # # # # : 0 : cachedDescendants[updateIt].insert(mapTx.iterator_to(descendant));
# # ]
88 : : // Update ancestor state for each descendant
89 [ # # # # ]: 0 : mapTx.modify(mapTx.iterator_to(descendant), [=](CTxMemPoolEntry& e) {
90 : 0 : e.UpdateAncestorState(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost());
91 : 0 : });
92 : : // Don't directly remove the transaction here -- doing so would
93 : : // invalidate iterators in cachedDescendants. Mark it for removal
94 : : // by inserting into descendants_to_remove.
95 [ # # # # : 0 : if (descendant.GetCountWithAncestors() > uint64_t(m_opts.limits.ancestor_count) || descendant.GetSizeWithAncestors() > m_opts.limits.ancestor_size_vbytes) {
# # # # ]
96 [ # # # # : 0 : descendants_to_remove.insert(descendant.GetTx().GetHash());
# # # # ]
97 : 0 : }
98 : 0 : }
99 : 0 : }
100 [ # # ]: 0 : mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); });
101 : 0 : }
102 : :
103 : 0 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate)
104 : : {
105 : 0 : AssertLockHeld(cs);
106 : : // For each entry in vHashesToUpdate, store the set of in-mempool, but not
107 : : // in-vHashesToUpdate transactions, so that we don't have to recalculate
108 : : // descendants when we come across a previously seen entry.
109 : 0 : cacheMap mapMemPoolDescendantsToUpdate;
110 : :
111 : : // Use a set for lookups into vHashesToUpdate (these entries are already
112 : : // accounted for in the state of their ancestors)
113 [ # # ]: 0 : std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
114 : :
115 : 0 : std::set<uint256> descendants_to_remove;
116 : :
117 : : // Iterate in reverse, so that whenever we are looking at a transaction
118 : : // we are sure that all in-mempool descendants have already been processed.
119 : : // This maximizes the benefit of the descendant cache and guarantees that
120 : : // CTxMemPoolEntry::m_children will be updated, an assumption made in
121 : : // UpdateForDescendants.
122 [ # # # # : 0 : for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) {
# # # # #
# # # #
# ]
123 : : // calculate children from mapNextTx
124 [ # # ]: 0 : txiter it = mapTx.find(hash);
125 [ # # # # ]: 0 : if (it == mapTx.end()) {
126 : 0 : continue;
127 : : }
128 [ # # # # : 0 : auto iter = mapNextTx.lower_bound(COutPoint(Txid::FromUint256(hash), 0));
# # ]
129 : : // First calculate the children, and update CTxMemPoolEntry::m_children to
130 : : // include them, and update their CTxMemPoolEntry::m_parents to include this tx.
131 : : // we cache the in-mempool children to avoid duplicate updates
132 : : {
133 [ # # ]: 0 : WITH_FRESH_EPOCH(m_epoch);
134 [ # # # # : 0 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
# # # # ]
135 [ # # # # ]: 0 : const uint256 &childHash = iter->second->GetHash();
136 [ # # ]: 0 : txiter childIter = mapTx.find(childHash);
137 [ # # # # ]: 0 : assert(childIter != mapTx.end());
138 : : // We can skip updating entries we've encountered before or that
139 : : // are in the block (which are already accounted for).
140 [ # # # # : 0 : if (!visited(childIter) && !setAlreadyIncluded.count(childHash)) {
# # # # ]
141 [ # # ]: 0 : UpdateChild(it, childIter, true);
142 [ # # ]: 0 : UpdateParent(childIter, it, true);
143 : 0 : }
144 : 0 : }
145 : 0 : } // release epoch guard for UpdateForDescendants
146 [ # # ]: 0 : UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded, descendants_to_remove);
147 [ # # # # : 0 : }
# ]
148 : :
149 [ # # ]: 0 : for (const auto& txid : descendants_to_remove) {
150 : : // This txid may have been removed already in a prior call to removeRecursive.
151 : : // Therefore we ensure it is not yet removed already.
152 [ # # # # ]: 0 : if (const std::optional<txiter> txiter = GetIter(txid)) {
153 [ # # # # : 0 : removeRecursive((*txiter)->GetTx(), MemPoolRemovalReason::SIZELIMIT);
# # ]
154 : 0 : }
155 : 0 : }
156 : 0 : }
157 : :
158 : 1323810 : util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateAncestorsAndCheckLimits(
159 : : int64_t entry_size,
160 : : size_t entry_count,
161 : : CTxMemPoolEntry::Parents& staged_ancestors,
162 : : const Limits& limits) const
163 : : {
164 : 1323810 : int64_t totalSizeWithAncestors = entry_size;
165 : 1323810 : setEntries ancestors;
166 : :
167 [ + + ]: 15657457 : while (!staged_ancestors.empty()) {
168 : 14361593 : const CTxMemPoolEntry& stage = staged_ancestors.begin()->get();
169 [ + - ]: 14361593 : txiter stageit = mapTx.iterator_to(stage);
170 : :
171 [ + - ]: 14361593 : ancestors.insert(stageit);
172 [ + - ]: 14361593 : staged_ancestors.erase(stage);
173 [ + - + - ]: 14361593 : totalSizeWithAncestors += stageit->GetTxSize();
174 : :
175 [ + - + - : 14361593 : if (stageit->GetSizeWithDescendants() + entry_size > limits.descendant_size_vbytes) {
+ + ]
176 [ + - + - : 16121 : return util::Error{Untranslated(strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_size_vbytes))};
+ - + - +
- - + +
- ]
177 [ + - + - : 14345472 : } else if (stageit->GetCountWithDescendants() + entry_count > static_cast<uint64_t>(limits.descendant_count)) {
+ + ]
178 [ + - + - : 4004 : return util::Error{Untranslated(strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_count))};
+ - + - +
- + - +
- ]
179 [ + + ]: 14341468 : } else if (totalSizeWithAncestors > limits.ancestor_size_vbytes) {
180 [ + - - + : 5885 : return util::Error{Untranslated(strprintf("exceeds ancestor size limit [limit: %u]", limits.ancestor_size_vbytes))};
- + ]
181 : : }
182 : :
183 [ + - + - ]: 14335583 : const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst();
184 [ + + + + ]: 33763478 : for (const CTxMemPoolEntry& parent : parents) {
185 [ + - ]: 19427895 : txiter parent_it = mapTx.iterator_to(parent);
186 : :
187 : : // If this is a new ancestor, add it.
188 [ + - + + ]: 19427895 : if (ancestors.count(parent_it) == 0) {
189 [ + - ]: 15649702 : staged_ancestors.insert(parent);
190 : 15649702 : }
191 [ + + ]: 19427895 : if (staged_ancestors.size() + ancestors.size() + entry_count > static_cast<uint64_t>(limits.ancestor_count)) {
192 [ + - + - : 1936 : return util::Error{Untranslated(strprintf("too many unconfirmed ancestors [limit: %u]", limits.ancestor_count))};
+ - ]
193 : : }
194 [ + + + + ]: 19427895 : }
195 [ + + ]: 14361593 : }
196 : :
197 [ + - ]: 1295864 : return ancestors;
198 : 1323810 : }
199 : :
200 : 36136 : util::Result<void> CTxMemPool::CheckPackageLimits(const Package& package,
201 : : const int64_t total_vsize) const
202 : : {
203 : 36136 : size_t pack_count = package.size();
204 : :
205 : : // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist
206 [ + + ]: 36136 : if (pack_count > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
207 [ + - + - ]: 12 : return util::Error{Untranslated(strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_opts.limits.ancestor_count))};
208 [ + + ]: 36124 : } else if (pack_count > static_cast<uint64_t>(m_opts.limits.descendant_count)) {
209 [ + - + - ]: 9 : return util::Error{Untranslated(strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_opts.limits.descendant_count))};
210 [ + + ]: 36115 : } else if (total_vsize > m_opts.limits.ancestor_size_vbytes) {
211 [ + - + - ]: 15 : return util::Error{Untranslated(strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_opts.limits.ancestor_size_vbytes))};
212 [ + + ]: 36100 : } else if (total_vsize > m_opts.limits.descendant_size_vbytes) {
213 [ + - + - ]: 8 : return util::Error{Untranslated(strprintf("package size %u exceeds descendant size limit [limit: %u]", total_vsize, m_opts.limits.descendant_size_vbytes))};
214 : : }
215 : :
216 : 36092 : CTxMemPoolEntry::Parents staged_ancestors;
217 [ + + - + ]: 72299 : for (const auto& tx : package) {
218 [ + + - + ]: 159662 : for (const auto& input : tx->vin) {
219 [ + - + - ]: 123455 : std::optional<txiter> piter = GetIter(input.prevout.hash);
220 [ + + ]: 123455 : if (piter) {
221 [ + - + - ]: 8 : staged_ancestors.insert(**piter);
222 [ - + ]: 8 : if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
223 [ # # # # : 0 : return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", m_opts.limits.ancestor_count))};
# # ]
224 : : }
225 : 8 : }
226 [ - + - + ]: 123455 : }
227 [ + - ]: 36207 : }
228 : : // When multiple transactions are passed in, the ancestors and descendants of all transactions
229 : : // considered together must be within limits even if they are not interdependent. This may be
230 : : // stricter than the limits for each individual transaction.
231 [ + - + - ]: 72184 : const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(),
232 : 36092 : staged_ancestors, m_opts.limits)};
233 : : // It's possible to overestimate the ancestor/descendant totals.
234 [ + - # # : 36092 : if (!ancestors.has_value()) return util::Error{Untranslated("possibly " + util::ErrorString(ancestors).original)};
# # # # #
# ]
235 [ + - ]: 36092 : return {};
236 : 36136 : }
237 : :
238 : 1311893 : util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateMemPoolAncestors(
239 : : const CTxMemPoolEntry &entry,
240 : : const Limits& limits,
241 : : bool fSearchForParents /* = true */) const
242 : : {
243 : 1311893 : CTxMemPoolEntry::Parents staged_ancestors;
244 [ + - ]: 1311893 : const CTransaction &tx = entry.GetTx();
245 : :
246 [ + + ]: 1311893 : if (fSearchForParents) {
247 : : // Get parents of this transaction that are in the mempool
248 : : // GetMemPoolParents() is only valid for entries in the mempool, so we
249 : : // iterate mapTx to find parents.
250 [ + + + + ]: 4047080 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
251 [ + - + - ]: 2990641 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
252 [ + + ]: 2990641 : if (piter) {
253 [ + - + - ]: 1410824 : staged_ancestors.insert(**piter);
254 [ + + ]: 1410824 : if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) {
255 [ + - - + : 24175 : return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", limits.ancestor_count))};
+ - ]
256 : : }
257 : 1386649 : }
258 [ + + ]: 2990641 : }
259 : 1032264 : } else {
260 : : // If we're not searching for parents, we require this to already be an
261 : : // entry in the mempool and use the entry's cached parents.
262 [ + - ]: 255454 : txiter it = mapTx.iterator_to(entry);
263 [ + - + - : 255454 : staged_ancestors = it->GetMemPoolParentsConst();
+ - ]
264 : 255454 : }
265 : :
266 [ + - + - : 1287718 : return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
+ - ]
267 : 1287718 : limits);
268 : 1311893 : }
269 : :
270 : 1095281 : CTxMemPool::setEntries CTxMemPool::AssumeCalculateMemPoolAncestors(
271 : : std::string_view calling_fn_name,
272 : : const CTxMemPoolEntry &entry,
273 : : const Limits& limits,
274 : : bool fSearchForParents /* = true */) const
275 : : {
276 : 1095281 : auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
277 [ + - + - ]: 1095281 : if (!Assume(result)) {
278 [ # # # # : 0 : LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Error, "%s: CalculateMemPoolAncestors failed unexpectedly, continuing with empty ancestor set (%s)\n",
# # # # #
# # # ]
279 : : calling_fn_name, util::ErrorString(result).original);
280 : 0 : }
281 [ + - ]: 1095281 : return std::move(result).value_or(CTxMemPool::setEntries{});
282 : 1095281 : }
283 : :
284 : 894477 : void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
285 : : {
286 : 894477 : const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
287 : : // add or remove this tx as a child of each parent
288 [ + + ]: 1327545 : for (const CTxMemPoolEntry& parent : parents) {
289 : 433068 : UpdateChild(mapTx.iterator_to(parent), it, add);
290 : 433068 : }
291 : 894477 : const int32_t updateCount = (add ? 1 : -1);
292 : 894477 : const int32_t updateSize{updateCount * it->GetTxSize()};
293 : 894477 : const CAmount updateFee = updateCount * it->GetModifiedFee();
294 [ + + ]: 14864740 : for (txiter ancestorIt : setAncestors) {
295 : 27940526 : mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
296 : 13970263 : }
297 : 894477 : }
298 : :
299 : 851724 : void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
300 : : {
301 : 851724 : int64_t updateCount = setAncestors.size();
302 : 851724 : int64_t updateSize = 0;
303 : 851724 : CAmount updateFee = 0;
304 : 866390 : int64_t updateSigOpsCost = 0;
305 [ + + ]: 14806552 : for (txiter ancestorIt : setAncestors) {
306 : 13969494 : updateSize += ancestorIt->GetTxSize();
307 : 13969494 : updateFee += ancestorIt->GetModifiedFee();
308 : 13969494 : updateSigOpsCost += ancestorIt->GetSigOpCost();
309 : 13954828 : }
310 : 1718114 : mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
311 : 866390 : }
312 : 14666 :
313 : 57419 : void CTxMemPool::UpdateChildrenForRemoval(txiter it)
314 : : {
315 : 42753 : const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
316 [ + - ]: 42753 : for (const CTxMemPoolEntry& updateIt : children) {
317 : 0 : UpdateParent(mapTx.iterator_to(updateIt), it, false);
318 : 14666 : }
319 : 42753 : }
320 : :
321 : 106583 : void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
322 : 14666 : {
323 : : // For each entry, walk back all ancestors and decrement size associated with this
324 : : // transaction
325 [ + - ]: 106583 : if (updateDescendants) {
326 : : // updateDescendants should be true whenever we're not recursively
327 : : // removing a tx and all its descendants, eg when a transaction is
328 : : // confirmed in a block.
329 : : // Here we only update statistics and not data in CTxMemPool::Parents
330 : : // and CTxMemPoolEntry::Children (which we need to preserve until we're
331 : : // finished with all operations that need to traverse the mempool).
332 [ # # ]: 0 : for (txiter removeIt : entriesToRemove) {
333 : 0 : setEntries setDescendants;
334 [ # # ]: 0 : CalculateDescendants(removeIt, setDescendants);
335 [ # # ]: 0 : setDescendants.erase(removeIt); // don't update state for self
336 [ # # # # ]: 0 : int32_t modifySize = -removeIt->GetTxSize();
337 [ # # # # ]: 0 : CAmount modifyFee = -removeIt->GetModifiedFee();
338 [ # # # # ]: 0 : int modifySigOps = -removeIt->GetSigOpCost();
339 [ # # ]: 0 : for (txiter dit : setDescendants) {
340 [ # # ]: 0 : mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); });
341 : 0 : }
342 : 0 : }
343 : 0 : }
344 [ + + ]: 149336 : for (txiter removeIt : entriesToRemove) {
345 : 42753 : const CTxMemPoolEntry &entry = *removeIt;
346 : : // Since this is a tx that is already in the mempool, we can call CMPA
347 : : // with fSearchForParents = false. If the mempool is in a consistent
348 : : // state, then using true or false should both be correct, though false
349 : : // should be a bit faster.
350 : : // However, if we happen to be in the middle of processing a reorg, then
351 : : // the mempool can be in an inconsistent state. In this case, the set
352 : : // of ancestors reachable via GetMemPoolParents()/GetMemPoolChildren()
353 : : // will be the same as the set of ancestors whose packages include this
354 : : // transaction, because when we add a new transaction to the mempool in
355 : : // addUnchecked(), we assume it has no children, and in the case of a
356 : : // reorg where that assumption is false, the in-mempool children aren't
357 : : // linked to the in-block tx's until UpdateTransactionsFromBlock() is
358 : : // called.
359 : : // So if we're being called during a reorg, ie before
360 : : // UpdateTransactionsFromBlock() has been called, then
361 : : // GetMemPoolParents()/GetMemPoolChildren() will differ from the set of
362 : : // mempool parents we'd calculate by searching, and it's important that
363 : : // we use the cached notion of ancestor transactions as the set of
364 : : // things to update for removal.
365 : 42753 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits(), /*fSearchForParents=*/false)};
366 : : // Note that UpdateAncestorsOf severs the child links that point to
367 : : // removeIt in the entries for the parents of removeIt.
368 [ + - ]: 42753 : UpdateAncestorsOf(false, removeIt, ancestors);
369 : 42753 : }
370 : : // After updating all the ancestor sizes, we can now sever the link between each
371 : : // transaction being removed and any mempool children (ie, update CTxMemPoolEntry::m_parents
372 : : // for each direct child of a transaction being removed).
373 [ + + ]: 149336 : for (txiter removeIt : entriesToRemove) {
374 : 42753 : UpdateChildrenForRemoval(removeIt);
375 : 42753 : }
376 : 106583 : }
377 : :
378 : 14132985 : void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
379 : : {
380 : 14132985 : nSizeWithDescendants += modifySize;
381 [ + - ]: 14132985 : assert(nSizeWithDescendants > 0);
382 : 14132985 : nModFeesWithDescendants = SaturatingAdd(nModFeesWithDescendants, modifyFee);
383 : 14132985 : m_count_with_descendants += modifyCount;
384 [ + - ]: 14132985 : assert(m_count_with_descendants > 0);
385 : 14132985 : }
386 : :
387 : 882669 : void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
388 : : {
389 : 882669 : nSizeWithAncestors += modifySize;
390 [ + - ]: 882669 : assert(nSizeWithAncestors > 0);
391 : 882669 : nModFeesWithAncestors = SaturatingAdd(nModFeesWithAncestors, modifyFee);
392 : 882669 : m_count_with_ancestors += modifyCount;
393 [ + - ]: 882669 : assert(m_count_with_ancestors > 0);
394 : 882669 : nSigOpCostWithAncestors += modifySigOps;
395 [ + - ]: 882669 : assert(int(nSigOpCostWithAncestors) >= 0);
396 : 882669 : }
397 : :
398 [ + - + - ]: 29332 : CTxMemPool::CTxMemPool(const Options& opts)
399 : 14666 : : m_opts{opts}
400 : : {
401 : 14666 : }
402 : :
403 : 0 : bool CTxMemPool::isSpent(const COutPoint& outpoint) const
404 : : {
405 : 0 : LOCK(cs);
406 [ # # ]: 0 : return mapNextTx.count(outpoint);
407 : 0 : }
408 : :
409 : 0 : unsigned int CTxMemPool::GetTransactionsUpdated() const
410 : : {
411 : 0 : return nTransactionsUpdated;
412 : : }
413 : :
414 : 85235 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
415 : : {
416 : 85235 : nTransactionsUpdated += n;
417 : 85235 : }
418 : :
419 : 851724 : void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry, setEntries &setAncestors)
420 : : {
421 : : // Add to memory pool without checking anything.
422 : : // Used by AcceptToMemoryPool(), which DOES do
423 : : // all the appropriate checks.
424 : 851724 : indexed_transaction_set::iterator newit = mapTx.emplace(CTxMemPoolEntry::ExplicitCopy, entry).first;
425 : :
426 : : // Update transaction for any feeDelta created by PrioritiseTransaction
427 : 851724 : CAmount delta{0};
428 : 851724 : ApplyDelta(entry.GetTx().GetHash(), delta);
429 : : // The following call to UpdateModifiedFee assumes no previous fee modifications
430 : 851724 : Assume(entry.GetFee() == entry.GetModifiedFee());
431 [ + + ]: 851724 : if (delta) {
432 : 146144 : mapTx.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
433 : 73072 : }
434 : :
435 : : // Update cachedInnerUsage to include contained transaction's usage.
436 : : // (When we update the entry for in-mempool parents, memory usage will be
437 : : // further updated.)
438 : 851724 : cachedInnerUsage += entry.DynamicMemoryUsage();
439 : :
440 : 851724 : const CTransaction& tx = newit->GetTx();
441 : 851724 : std::set<Txid> setParentTransactions;
442 [ + + ]: 2967126 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
443 [ + - + - ]: 2115402 : mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
444 [ + - ]: 2115402 : setParentTransactions.insert(tx.vin[i].prevout.hash);
445 : 2115402 : }
446 : : // Don't bother worrying about child transactions of this one.
447 : : // Normal case of a new transaction arriving is that there can't be any
448 : : // children, because such children would be orphans.
449 : : // An exception to that is if a transaction enters that used to be in a block.
450 : : // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
451 : : // to clean up the mess we're leaving here.
452 : :
453 : : // Update ancestors with information about this tx
454 [ + - + + ]: 1271450 : for (const auto& pit : GetIterSet(setParentTransactions)) {
455 [ + - ]: 419726 : UpdateParent(newit, pit, true);
456 : 419726 : }
457 [ + - ]: 851724 : UpdateAncestorsOf(true, newit, setAncestors);
458 [ + - ]: 851724 : UpdateEntryForAncestors(newit, setAncestors);
459 : :
460 : 851724 : nTransactionsUpdated++;
461 [ + - ]: 851724 : totalTxSize += entry.GetTxSize();
462 [ + - ]: 851724 : m_total_fee += entry.GetFee();
463 : :
464 [ + - + - : 851724 : txns_randomized.emplace_back(newit->GetSharedTx());
+ - ]
465 [ + - ]: 851724 : newit->idx_randomized = txns_randomized.size() - 1;
466 : :
467 : : TRACE3(mempool, added,
468 : : entry.GetTx().GetHash().data(),
469 : : entry.GetTxSize(),
470 : : entry.GetFee()
471 : : );
472 : 851724 : }
473 : :
474 : 42753 : void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
475 : : {
476 : : // We increment mempool sequence value no matter removal reason
477 : : // even if not directly reported below.
478 : 42753 : uint64_t mempool_sequence = GetAndIncrementSequence();
479 : :
480 [ + + - + ]: 42753 : if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
481 : : // Notify clients that a transaction has been removed from the mempool
482 : : // for any reason except being included in a block. Clients interested
483 : : // in transactions included in blocks can subscribe to the BlockConnected
484 : : // notification.
485 [ + - ]: 38579 : m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
486 : 38579 : }
487 : : TRACE5(mempool, removed,
488 : : it->GetTx().GetHash().data(),
489 : : RemovalReasonToString(reason).c_str(),
490 : : it->GetTxSize(),
491 : : it->GetFee(),
492 : : std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
493 : : );
494 : :
495 [ + + ]: 128319 : for (const CTxIn& txin : it->GetTx().vin)
496 : 85566 : mapNextTx.erase(txin.prevout);
497 : :
498 : 42753 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
499 : :
500 [ + + ]: 42753 : if (txns_randomized.size() > 1) {
501 : : // Update idx_randomized of the to-be-moved entry.
502 : 38452 : Assert(GetEntry(txns_randomized.back()->GetHash()))->idx_randomized = it->idx_randomized;
503 : : // Remove entry from txns_randomized by replacing it with the back and deleting the back.
504 : 38452 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
505 : 38452 : txns_randomized.pop_back();
506 [ + + ]: 38452 : if (txns_randomized.size() * 2 < txns_randomized.capacity())
507 : 4999 : txns_randomized.shrink_to_fit();
508 : 38452 : } else
509 : 4301 : txns_randomized.clear();
510 : :
511 : 42753 : totalTxSize -= it->GetTxSize();
512 : 42753 : m_total_fee -= it->GetFee();
513 : 42753 : cachedInnerUsage -= it->DynamicMemoryUsage();
514 : 42753 : cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
515 : 42753 : mapTx.erase(it);
516 : 42753 : nTransactionsUpdated++;
517 : 42753 : }
518 : :
519 : : // Calculates descendants of entry that are not already in setDescendants, and adds to
520 : : // setDescendants. Assumes entryit is already a tx in the mempool and CTxMemPoolEntry::m_children
521 : : // is correct for tx and all descendants.
522 : : // Also assumes that if an entry is in setDescendants already, then all
523 : : // in-mempool descendants of it are already in setDescendants as well, so that we
524 : : // can save time by not iterating over those entries.
525 : 760438 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
526 : : {
527 : 760438 : setEntries stage;
528 [ + - + + ]: 760438 : if (setDescendants.count(entryit) == 0) {
529 [ + - ]: 722163 : stage.insert(entryit);
530 : 722163 : }
531 : : // Traverse down the children of entry, only adding children that are not
532 : : // accounted for in setDescendants already (because those children have either
533 : : // already been walked, or will be walked in this iteration).
534 [ + + ]: 31835393 : while (!stage.empty()) {
535 : 31074955 : txiter it = *stage.begin();
536 [ + - ]: 31074955 : setDescendants.insert(it);
537 [ + - ]: 31074955 : stage.erase(it);
538 : :
539 [ + - + - ]: 31074955 : const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
540 [ + + ]: 73406384 : for (const CTxMemPoolEntry& child : children) {
541 [ + - ]: 42331429 : txiter childiter = mapTx.iterator_to(child);
542 [ + - + + ]: 42331429 : if (!setDescendants.count(childiter)) {
543 [ + - ]: 34536488 : stage.insert(childiter);
544 : 34536488 : }
545 : 42331429 : }
546 : 31074955 : }
547 : 760438 : }
548 : :
549 : 2887 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
550 : : {
551 : : // Remove transaction from memory pool
552 : 2887 : AssertLockHeld(cs);
553 : 2887 : setEntries txToRemove;
554 [ + - + - ]: 2887 : txiter origit = mapTx.find(origTx.GetHash());
555 [ + - + - ]: 2887 : if (origit != mapTx.end()) {
556 [ + - ]: 2887 : txToRemove.insert(origit);
557 : 2887 : } else {
558 : : // When recursively removing but origTx isn't in the mempool
559 : : // be sure to remove any children that are in the pool. This can
560 : : // happen during chain re-orgs if origTx isn't re-accepted into
561 : : // the mempool for any reason.
562 [ # # ]: 0 : for (unsigned int i = 0; i < origTx.vout.size(); i++) {
563 [ # # # # : 0 : auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
# # ]
564 [ # # # # ]: 0 : if (it == mapNextTx.end())
565 : 0 : continue;
566 [ # # # # ]: 0 : txiter nextit = mapTx.find(it->second->GetHash());
567 [ # # # # ]: 0 : assert(nextit != mapTx.end());
568 [ # # ]: 0 : txToRemove.insert(nextit);
569 [ # # # ]: 0 : }
570 : : }
571 : 2887 : setEntries setAllRemoves;
572 [ + + ]: 5774 : for (txiter it : txToRemove) {
573 [ + - ]: 2887 : CalculateDescendants(it, setAllRemoves);
574 : 2887 : }
575 : :
576 [ + - ]: 2887 : RemoveStaged(setAllRemoves, false, reason);
577 : 2887 : }
578 : :
579 : 0 : void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
580 : : {
581 : : // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
582 : 0 : AssertLockHeld(cs);
583 : 0 : AssertLockHeld(::cs_main);
584 : :
585 : 0 : setEntries txToRemove;
586 [ # # # # : 0 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
# # ]
587 [ # # # # : 0 : if (check_final_and_mature(it)) txToRemove.insert(it);
# # ]
588 : 0 : }
589 : 0 : setEntries setAllRemoves;
590 [ # # ]: 0 : for (txiter it : txToRemove) {
591 [ # # ]: 0 : CalculateDescendants(it, setAllRemoves);
592 : 0 : }
593 [ # # ]: 0 : RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
594 [ # # # # : 0 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
# # ]
595 [ # # # # : 0 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
# # # # ]
596 : 0 : }
597 : 0 : }
598 : :
599 : 85608 : void CTxMemPool::removeConflicts(const CTransaction &tx)
600 : : {
601 : : // Remove transactions which depend on inputs of tx, recursively
602 : 85608 : AssertLockHeld(cs);
603 [ + + ]: 171287 : for (const CTxIn &txin : tx.vin) {
604 : 85679 : auto it = mapNextTx.find(txin.prevout);
605 [ + - ]: 85679 : if (it != mapNextTx.end()) {
606 : 0 : const CTransaction &txConflict = *it->second;
607 [ # # ]: 0 : if (txConflict != tx)
608 : : {
609 : 0 : ClearPrioritisation(txConflict.GetHash());
610 : 0 : removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
611 : 0 : }
612 : 0 : }
613 : 85679 : }
614 : 85608 : }
615 : :
616 : : /**
617 : : * Called when a block is connected. Removes from mempool.
618 : : */
619 : 85235 : void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
620 : : {
621 : 85235 : AssertLockHeld(cs);
622 : 85235 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
623 [ + - ]: 85235 : txs_removed_for_block.reserve(vtx.size());
624 [ + + ]: 170843 : for (const auto& tx : vtx)
625 : : {
626 [ + - + - ]: 85608 : txiter it = mapTx.find(tx->GetHash());
627 [ + - + - ]: 85608 : if (it != mapTx.end()) {
628 : 0 : setEntries stage;
629 [ # # ]: 0 : stage.insert(it);
630 [ # # # # ]: 0 : txs_removed_for_block.emplace_back(*it);
631 [ # # ]: 0 : RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
632 : 0 : }
633 [ + - ]: 85608 : removeConflicts(*tx);
634 [ + - + - : 85608 : ClearPrioritisation(tx->GetHash());
+ - ]
635 : 85608 : }
636 [ + - ]: 85235 : if (m_opts.signals) {
637 [ + - ]: 85235 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
638 : 85235 : }
639 [ + - ]: 85235 : lastRollingFeeUpdate = GetTime();
640 : 85235 : blockSinceLastRollingFeeBump = true;
641 : 85235 : }
642 : :
643 : 107606 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
644 : : {
645 [ + - ]: 107606 : if (m_opts.check_ratio == 0) return;
646 : :
647 [ - + ]: 107606 : if (GetRand(m_opts.check_ratio) >= 1) return;
648 : :
649 : 107606 : AssertLockHeld(::cs_main);
650 : 107606 : LOCK(cs);
651 [ + - + + : 107606 : LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - - + +
- + - ]
652 : :
653 : 107606 : uint64_t checkTotal = 0;
654 : 107606 : CAmount check_total_fee{0};
655 : 107606 : uint64_t innerUsage = 0;
656 : 107606 : uint64_t prev_ancestor_count{0};
657 : :
658 [ + - ]: 107606 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
659 : :
660 [ + - + + ]: 167039 : for (const auto& it : GetSortedDepthAndScore()) {
661 [ + - + - ]: 59433 : checkTotal += it->GetTxSize();
662 [ + - + - ]: 59433 : check_total_fee += it->GetFee();
663 [ + - + - ]: 59433 : innerUsage += it->DynamicMemoryUsage();
664 [ + - + - ]: 59433 : const CTransaction& tx = it->GetTx();
665 [ + - + - : 59433 : innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
+ - + - +
- + - ]
666 : 59433 : CTxMemPoolEntry::Parents setParentCheck;
667 [ + + ]: 157004 : for (const CTxIn &txin : tx.vin) {
668 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
669 [ + - ]: 97571 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
670 [ + - + + ]: 97571 : if (it2 != mapTx.end()) {
671 [ + - + - ]: 23162 : const CTransaction& tx2 = it2->GetTx();
672 [ + - + - : 23162 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
+ - ]
673 [ + - + - ]: 23162 : setParentCheck.insert(*it2);
674 : 23162 : }
675 : : // We are iterating through the mempool entries sorted in order by ancestor count.
676 : : // All parents must have been checked before their children and their coins added to
677 : : // the mempoolDuplicate coins cache.
678 [ + - - + ]: 97571 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
679 : : // Check whether its inputs are marked in mapNextTx.
680 [ - + ]: 97571 : auto it3 = mapNextTx.find(txin.prevout);
681 [ - + - + ]: 97571 : assert(it3 != mapNextTx.end());
682 [ - + ]: 97571 : assert(it3->first == &txin.prevout);
683 [ - + ]: 97571 : assert(it3->second == &tx);
684 : 97571 : }
685 : 91507 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
686 : 32074 : return a.GetTx().GetHash() == b.GetTx().GetHash();
687 : : };
688 [ + - + - : 59433 : assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
+ - ]
689 [ + - + - : 59433 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
+ - + - ]
690 : : // Verify ancestor state is correct.
691 [ + - + - : 59433 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
+ - ]
692 : 59433 : uint64_t nCountCheck = ancestors.size() + 1;
693 [ + - + - ]: 59433 : int32_t nSizeCheck = it->GetTxSize();
694 [ + - + - ]: 59433 : CAmount nFeesCheck = it->GetModifiedFee();
695 [ + - + - ]: 59433 : int64_t nSigOpCheck = it->GetSigOpCost();
696 : :
697 [ + + ]: 82910 : for (txiter ancestorIt : ancestors) {
698 [ + - + - ]: 23477 : nSizeCheck += ancestorIt->GetTxSize();
699 [ + - + - ]: 23477 : nFeesCheck += ancestorIt->GetModifiedFee();
700 [ + - + - ]: 23477 : nSigOpCheck += ancestorIt->GetSigOpCost();
701 : 23477 : }
702 : :
703 [ + - + - : 59433 : assert(it->GetCountWithAncestors() == nCountCheck);
+ - ]
704 [ + - + - : 59433 : assert(it->GetSizeWithAncestors() == nSizeCheck);
+ - ]
705 [ + - + - : 59433 : assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
+ - ]
706 [ + - + - : 59433 : assert(it->GetModFeesWithAncestors() == nFeesCheck);
+ - ]
707 : : // Sanity check: we are walking in ascending ancestor count order.
708 [ + - + - : 59433 : assert(prev_ancestor_count <= it->GetCountWithAncestors());
+ - ]
709 [ + - + - ]: 59433 : prev_ancestor_count = it->GetCountWithAncestors();
710 : :
711 : : // Check children against mapNextTx
712 : 59433 : CTxMemPoolEntry::Children setChildrenCheck;
713 [ + - + - : 59433 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
+ - + - +
- ]
714 : 59433 : int32_t child_sizes{0};
715 [ + - + + : 160110 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
+ - + - +
- + - +
+ ]
716 [ + - + - ]: 23162 : txiter childit = mapTx.find(iter->second->GetHash());
717 [ + - + - ]: 23162 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
718 [ + - + - : 23162 : if (setChildrenCheck.insert(*childit).second) {
+ + ]
719 [ + - + - ]: 16037 : child_sizes += childit->GetTxSize();
720 : 16037 : }
721 : 23162 : }
722 [ + - + - : 59433 : assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
+ - ]
723 [ + - + - : 59433 : assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), it->GetMemPoolChildrenConst().begin(), comp));
+ - + - ]
724 : : // Also check to make sure size is greater than sum with immediate children.
725 : : // just a sanity check, not definitive that this calc is correct...
726 [ + - + - : 59433 : assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
+ - + - +
- ]
727 : :
728 : 59433 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
729 : 59433 : CAmount txfee = 0;
730 [ + - + - ]: 59433 : assert(!tx.IsCoinBase());
731 [ + - + - ]: 59433 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
732 [ + + + - ]: 157004 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
733 [ + - ]: 59433 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
734 : 59433 : }
735 [ + - + - : 205177 : for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
+ + ]
736 [ + - + - ]: 97571 : uint256 hash = it->second->GetHash();
737 [ + - ]: 97571 : indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
738 [ + - + - ]: 97571 : const CTransaction& tx = it2->GetTx();
739 [ + - + - ]: 97571 : assert(it2 != mapTx.end());
740 [ + - ]: 97571 : assert(&tx == it->second);
741 : 97571 : }
742 : :
743 [ + - ]: 107606 : assert(totalTxSize == checkTotal);
744 [ + - ]: 107606 : assert(m_total_fee == check_total_fee);
745 [ + - ]: 107606 : assert(innerUsage == cachedInnerUsage);
746 : 107606 : }
747 : :
748 : 0 : bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid)
749 : : {
750 : : /* Return `true` if hasha should be considered sooner than hashb. Namely when:
751 : : * a is not in the mempool, but b is
752 : : * both are in the mempool and a has fewer ancestors than b
753 : : * both are in the mempool and a has a higher score than b
754 : : */
755 : 0 : LOCK(cs);
756 [ # # # # : 0 : indexed_transaction_set::const_iterator j = wtxid ? get_iter_from_wtxid(hashb) : mapTx.find(hashb);
# # ]
757 [ # # # # ]: 0 : if (j == mapTx.end()) return false;
758 [ # # # # : 0 : indexed_transaction_set::const_iterator i = wtxid ? get_iter_from_wtxid(hasha) : mapTx.find(hasha);
# # ]
759 [ # # # # ]: 0 : if (i == mapTx.end()) return true;
760 [ # # # # ]: 0 : uint64_t counta = i->GetCountWithAncestors();
761 [ # # # # ]: 0 : uint64_t countb = j->GetCountWithAncestors();
762 [ # # ]: 0 : if (counta == countb) {
763 [ # # # # : 0 : return CompareTxMemPoolEntryByScore()(*i, *j);
# # ]
764 : : }
765 : 0 : return counta < countb;
766 : 0 : }
767 : :
768 : : namespace {
769 : : class DepthAndScoreComparator
770 : : {
771 : : public:
772 : 5005894 : bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
773 : : {
774 : 5005894 : uint64_t counta = a->GetCountWithAncestors();
775 : 5005894 : uint64_t countb = b->GetCountWithAncestors();
776 [ + + ]: 5005894 : if (counta == countb) {
777 : 4349437 : return CompareTxMemPoolEntryByScore()(*a, *b);
778 : : }
779 : 656457 : return counta < countb;
780 : 5005894 : }
781 : : };
782 : : } // namespace
783 : :
784 : 205344 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
785 : : {
786 : 205344 : std::vector<indexed_transaction_set::const_iterator> iters;
787 [ + - ]: 205344 : AssertLockHeld(cs);
788 : :
789 [ + - ]: 205344 : iters.reserve(mapTx.size());
790 : :
791 [ + - + + : 1210066 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
+ - ]
792 [ + - ]: 1004722 : iters.push_back(mi);
793 : 1004722 : }
794 [ + - ]: 205344 : std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
795 : 205344 : return iters;
796 [ + - ]: 205344 : }
797 : :
798 : 945289 : static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
799 [ + - + - : 945289 : return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
+ - + - +
- + - +
- ]
800 : 0 : }
801 : :
802 : 4 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
803 : : {
804 : 4 : AssertLockHeld(cs);
805 : :
806 : 4 : std::vector<CTxMemPoolEntryRef> ret;
807 [ + - ]: 4 : ret.reserve(mapTx.size());
808 [ - + - + ]: 4 : for (const auto& it : GetSortedDepthAndScore()) {
809 [ # # # # ]: 0 : ret.emplace_back(*it);
810 : 0 : }
811 : 4 : return ret;
812 [ + - ]: 4 : }
813 : :
814 : 97734 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
815 : : {
816 : 97734 : LOCK(cs);
817 [ + - ]: 97734 : auto iters = GetSortedDepthAndScore();
818 : :
819 : 97734 : std::vector<TxMempoolInfo> ret;
820 [ - + ]: 97734 : ret.reserve(mapTx.size());
821 [ + + ]: 1043023 : for (auto it : iters) {
822 [ + - + - ]: 945289 : ret.push_back(GetInfo(it));
823 : 945289 : }
824 : :
825 : 97734 : return ret;
826 [ + - ]: 97734 : }
827 : :
828 : 953119 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
829 : : {
830 : 953119 : AssertLockHeld(cs);
831 : 953119 : const auto i = mapTx.find(txid);
832 [ + + ]: 953119 : return i == mapTx.end() ? nullptr : &(*i);
833 : 953119 : }
834 : :
835 : 22475001 : CTransactionRef CTxMemPool::get(const uint256& hash) const
836 : : {
837 : 22475001 : LOCK(cs);
838 [ + - ]: 22475001 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
839 [ + - + + ]: 22475001 : if (i == mapTx.end())
840 : 15623461 : return nullptr;
841 [ + - + - ]: 6851540 : return i->GetSharedTx();
842 : 22475001 : }
843 : :
844 : 0 : TxMempoolInfo CTxMemPool::info(const GenTxid& gtxid) const
845 : : {
846 : 0 : LOCK(cs);
847 [ # # # # : 0 : indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
# # # # #
# # # ]
848 [ # # # # ]: 0 : if (i == mapTx.end())
849 : 0 : return TxMempoolInfo();
850 [ # # ]: 0 : return GetInfo(i);
851 : 0 : }
852 : :
853 : 25384 : TxMempoolInfo CTxMemPool::info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const
854 : : {
855 : 25384 : LOCK(cs);
856 [ + - + + : 25384 : indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
+ - + - +
- + - ]
857 [ + - - + : 25384 : if (i != mapTx.end() && i->GetSequence() < last_sequence) {
# # # # -
+ ]
858 [ # # ]: 0 : return GetInfo(i);
859 : : } else {
860 : 25384 : return TxMempoolInfo();
861 : : }
862 : 25384 : }
863 : :
864 : 698156 : void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
865 : : {
866 : : {
867 : 698156 : LOCK(cs);
868 [ + - ]: 698156 : CAmount &delta = mapDeltas[hash];
869 : 698156 : delta = SaturatingAdd(delta, nFeeDelta);
870 [ + - ]: 698156 : txiter it = mapTx.find(hash);
871 [ + - + + ]: 698156 : if (it != mapTx.end()) {
872 [ + - ]: 368190 : mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
873 : : // Now update all ancestors' modified fees with descendants
874 [ + - + - : 184095 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
+ - ]
875 [ + + ]: 346817 : for (txiter ancestorIt : ancestors) {
876 [ + - ]: 325444 : mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
877 : 162722 : }
878 : : // Now update all descendants' modified fees with ancestors
879 : 184095 : setEntries setDescendants;
880 [ + - ]: 184095 : CalculateDescendants(it, setDescendants);
881 [ + - ]: 184095 : setDescendants.erase(it);
882 [ + + ]: 215040 : for (txiter descendantIt : setDescendants) {
883 [ + - ]: 61890 : mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
884 : 30945 : }
885 : 184095 : ++nTransactionsUpdated;
886 : 184095 : }
887 [ + + ]: 698156 : if (delta == 0) {
888 [ + - ]: 3805 : mapDeltas.erase(hash);
889 [ + - + - : 3805 : LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
+ - + - +
- ]
890 : 3805 : } else {
891 [ + - + - : 694351 : LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
+ - + - +
- + - +
- ]
892 : : hash.ToString(),
893 : : it == mapTx.end() ? "not " : "",
894 : : FormatMoney(nFeeDelta),
895 : : FormatMoney(delta));
896 : : }
897 : 698156 : }
898 : 698156 : }
899 : :
900 : 1053228 : void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
901 : : {
902 : 1053228 : AssertLockHeld(cs);
903 : 1053228 : std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
904 [ + + ]: 1053228 : if (pos == mapDeltas.end())
905 : 866181 : return;
906 : 187047 : const CAmount &delta = pos->second;
907 : 187047 : nFeeDelta += delta;
908 [ - + ]: 1053228 : }
909 : :
910 : 85608 : void CTxMemPool::ClearPrioritisation(const uint256& hash)
911 : : {
912 : 85608 : AssertLockHeld(cs);
913 : 85608 : mapDeltas.erase(hash);
914 : 85608 : }
915 : :
916 : 21 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
917 : : {
918 : 21 : AssertLockNotHeld(cs);
919 : 21 : LOCK(cs);
920 : 21 : std::vector<delta_info> result;
921 [ + - ]: 21 : result.reserve(mapDeltas.size());
922 [ + + ]: 409 : for (const auto& [txid, delta] : mapDeltas) {
923 [ + - + - ]: 388 : const auto iter{mapTx.find(txid)};
924 [ + - ]: 194 : const bool in_mempool{iter != mapTx.end()};
925 : 194 : std::optional<CAmount> modified_fee;
926 [ + - # # : 194 : if (in_mempool) modified_fee = iter->GetModifiedFee();
# # ]
927 [ + - + - : 582 : result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
+ - ]
928 : 194 : }
929 : 21 : return result;
930 [ + - ]: 21 : }
931 : :
932 : 2810018 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
933 : : {
934 : 2810018 : const auto it = mapNextTx.find(prevout);
935 [ + + ]: 2810018 : return it == mapNextTx.end() ? nullptr : it->second;
936 : 2810018 : }
937 : :
938 : 4773763 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const uint256& txid) const
939 : : {
940 : 4773763 : auto it = mapTx.find(txid);
941 [ + + ]: 4773763 : if (it != mapTx.end()) return it;
942 : 2429997 : return std::nullopt;
943 : 4773763 : }
944 : :
945 : 1030134 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
946 : : {
947 : 1030134 : CTxMemPool::setEntries ret;
948 [ + + ]: 2263264 : for (const auto& h : hashes) {
949 [ + - + - ]: 1233130 : const auto mi = GetIter(h);
950 [ + + + - ]: 1233130 : if (mi) ret.insert(*mi);
951 : 1233130 : }
952 : 1030134 : return ret;
953 [ + - ]: 1030134 : }
954 : :
955 : 2101 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<uint256>& txids) const
956 : : {
957 : 2101 : AssertLockHeld(cs);
958 : 2101 : std::vector<txiter> ret;
959 [ + - ]: 2101 : ret.reserve(txids.size());
960 [ + + - + ]: 195207 : for (const auto& txid : txids) {
961 [ + - ]: 193106 : const auto it{GetIter(txid)};
962 [ + - ]: 193106 : if (!it) return {};
963 [ + - ]: 193106 : ret.push_back(*it);
964 [ - + - + ]: 193106 : }
965 : 2101 : return ret;
966 : 2101 : }
967 : :
968 : 67092 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
969 : : {
970 [ + + - + : 170509 : for (unsigned int i = 0; i < tx.vin.size(); i++)
+ ]
971 [ + + ]: 103417 : if (exists(GenTxid::Txid(tx.vin[i].prevout.hash)))
972 : 17856 : return false;
973 : 49236 : return true;
974 : 67092 : }
975 : :
976 [ + - - + ]: 956397 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
977 : :
978 : 22347815 : bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
979 : : // Check to see if the inputs are made available by another tx in the package.
980 : : // These Coins would not be available in the underlying CoinsView.
981 [ + + - + : 22354849 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
+ ]
982 : 7034 : coin = it->second;
983 : 7034 : return true;
984 : : }
985 : :
986 : : // If an entry in the mempool exists, always return that one, as it's guaranteed to never
987 : : // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
988 : : // transactions. First checking the underlying cache risks returning a pruned entry instead.
989 : 22340781 : CTransactionRef ptx = mempool.get(outpoint.hash);
990 [ + + ]: 22340781 : if (ptx) {
991 [ + + ]: 6819524 : if (outpoint.n < ptx->vout.size()) {
992 [ + - ]: 6817792 : coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
993 [ + - ]: 6817792 : m_non_base_coins.emplace(outpoint);
994 : 6817792 : return true;
995 : : } else {
996 : 1732 : return false;
997 : : }
998 : : }
999 [ + - ]: 15521257 : return base->GetCoin(outpoint, coin);
1000 : 22347815 : }
1001 : :
1002 : 11339 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
1003 : : {
1004 [ + + ]: 238587 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
1005 [ + - ]: 227248 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
1006 : 227248 : m_non_base_coins.emplace(tx->GetHash(), n);
1007 : 227248 : }
1008 : 11339 : }
1009 : 15966 : void CCoinsViewMemPool::Reset()
1010 : : {
1011 : 15966 : m_temp_added.clear();
1012 : 15966 : m_non_base_coins.clear();
1013 : 15966 : }
1014 : :
1015 : 1163726 : size_t CTxMemPool::DynamicMemoryUsage() const {
1016 : 1163726 : LOCK(cs);
1017 : : // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1018 [ + - + - : 1163726 : return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
+ - + - ]
1019 : 1163726 : }
1020 : :
1021 : 42753 : void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) {
1022 : 42753 : LOCK(cs);
1023 : :
1024 [ + - + - ]: 42753 : if (m_unbroadcast_txids.erase(txid))
1025 : : {
1026 [ # # # # : 0 : LogPrint(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
# # # # #
# # # ]
1027 : 0 : }
1028 : 42753 : }
1029 : :
1030 : 106583 : void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1031 : 106583 : AssertLockHeld(cs);
1032 : 106583 : UpdateForRemoveFromMempool(stage, updateDescendants);
1033 [ + + ]: 149336 : for (txiter it : stage) {
1034 : 42753 : removeUnchecked(it, reason);
1035 : 42753 : }
1036 : 106583 : }
1037 : :
1038 : 27499 : int CTxMemPool::Expire(std::chrono::seconds time)
1039 : : {
1040 : 27499 : AssertLockHeld(cs);
1041 : 27499 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1042 : 27499 : setEntries toremove;
1043 [ + - + + : 45369 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
+ - + - +
- + + ]
1044 [ + - + - ]: 17870 : toremove.insert(mapTx.project<0>(it));
1045 [ + - ]: 17870 : it++;
1046 : : }
1047 : 27499 : setEntries stage;
1048 [ + + ]: 45369 : for (txiter removeit : toremove) {
1049 [ + - ]: 17870 : CalculateDescendants(removeit, stage);
1050 : 17870 : }
1051 [ - + ]: 27499 : RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
1052 : 27499 : return stage.size();
1053 : 27499 : }
1054 : :
1055 : 780394 : void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry)
1056 : : {
1057 : 780394 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits())};
1058 [ + - ]: 780394 : return addUnchecked(entry, ancestors);
1059 : 780394 : }
1060 : :
1061 : 433068 : void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1062 : : {
1063 : 433068 : AssertLockHeld(cs);
1064 : 433068 : CTxMemPoolEntry::Children s;
1065 [ + + + - : 433068 : if (add && entry->GetMemPoolChildren().insert(*child).second) {
+ - + - +
- + + ]
1066 [ + - ]: 365193 : cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1067 [ + + + - : 433068 : } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
+ - + - +
- + + ]
1068 [ + - ]: 13342 : cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1069 : 13342 : }
1070 : 433068 : }
1071 : :
1072 : 419726 : void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1073 : : {
1074 : 419726 : AssertLockHeld(cs);
1075 : 419726 : CTxMemPoolEntry::Parents s;
1076 [ - + + - : 419726 : if (add && entry->GetMemPoolParents().insert(*parent).second) {
+ - + - +
- + + ]
1077 [ + - ]: 365193 : cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1078 [ - + # # : 419726 : } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
# # # # #
# - + ]
1079 [ # # ]: 0 : cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1080 : 0 : }
1081 : 419726 : }
1082 : :
1083 : 447883 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1084 : 447883 : LOCK(cs);
1085 [ + + + + ]: 447883 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1086 [ + - ]: 438722 : return CFeeRate(llround(rollingMinimumFeeRate));
1087 : :
1088 [ + - ]: 9161 : int64_t time = GetTime();
1089 [ + + ]: 9161 : if (time > lastRollingFeeUpdate + 10) {
1090 : 826 : double halflife = ROLLING_FEE_HALFLIFE;
1091 [ + - + - ]: 826 : if (DynamicMemoryUsage() < sizelimit / 4)
1092 : 0 : halflife /= 4;
1093 [ + - + - ]: 826 : else if (DynamicMemoryUsage() < sizelimit / 2)
1094 : 0 : halflife /= 2;
1095 : :
1096 : 826 : rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1097 : 826 : lastRollingFeeUpdate = time;
1098 : :
1099 [ + - + + ]: 826 : if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
1100 : 720 : rollingMinimumFeeRate = 0;
1101 [ + - ]: 720 : return CFeeRate(0);
1102 : : }
1103 [ + + ]: 826 : }
1104 [ + - + - ]: 8441 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
1105 : 447883 : }
1106 : :
1107 : 4867 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1108 : 4867 : AssertLockHeld(cs);
1109 [ + + ]: 4867 : if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1110 : 3787 : rollingMinimumFeeRate = rate.GetFeePerK();
1111 : 3787 : blockSinceLastRollingFeeBump = false;
1112 : 3787 : }
1113 : 4867 : }
1114 : :
1115 : 27499 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1116 : 27499 : AssertLockHeld(cs);
1117 : :
1118 : 27499 : unsigned nTxnRemoved = 0;
1119 : 27499 : CFeeRate maxFeeRateRemoved(0);
1120 [ + + + + ]: 32366 : while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1121 : 4867 : indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1122 : :
1123 : : // We set the new mempool min fee to the feerate of the removed set, plus the
1124 : : // "minimum reasonable fee rate" (ie some value under which we consider txn
1125 : : // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1126 : : // equal to txn which were removed with no block in between.
1127 : 4867 : CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1128 : 4867 : removed += m_opts.incremental_relay_feerate;
1129 : 4867 : trackPackageRemoved(removed);
1130 : 4867 : maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1131 : :
1132 : 4867 : setEntries stage;
1133 [ + - + - ]: 4867 : CalculateDescendants(mapTx.project<0>(it), stage);
1134 : 4867 : nTxnRemoved += stage.size();
1135 : :
1136 : 4867 : std::vector<CTransaction> txn;
1137 [ + - ]: 4867 : if (pvNoSpendsRemaining) {
1138 [ + - ]: 4867 : txn.reserve(stage.size());
1139 [ + + ]: 9991 : for (txiter iter : stage)
1140 [ + - + - : 5124 : txn.push_back(iter->GetTx());
+ - ]
1141 : 4867 : }
1142 [ + - ]: 4867 : RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1143 [ - + ]: 4867 : if (pvNoSpendsRemaining) {
1144 [ + + ]: 9991 : for (const CTransaction& tx : txn) {
1145 [ + + ]: 16345 : for (const CTxIn& txin : tx.vin) {
1146 [ + - + - : 11221 : if (exists(GenTxid::Txid(txin.prevout.hash))) continue;
+ - + + ]
1147 [ + - ]: 10478 : pvNoSpendsRemaining->push_back(txin.prevout);
1148 [ - + + ]: 11221 : }
1149 : 5124 : }
1150 : 4867 : }
1151 : 4867 : }
1152 : :
1153 [ + + ]: 27499 : if (maxFeeRateRemoved > CFeeRate(0)) {
1154 [ + - # # : 2576 : LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
# # # # #
# ]
1155 : 2576 : }
1156 : 27499 : }
1157 : :
1158 : 0 : uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const {
1159 : : // find parent with highest descendant count
1160 : 0 : std::vector<txiter> candidates;
1161 : 0 : setEntries counted;
1162 [ # # ]: 0 : candidates.push_back(entry);
1163 : 0 : uint64_t maximum = 0;
1164 [ # # ]: 0 : while (candidates.size()) {
1165 : 0 : txiter candidate = candidates.back();
1166 : 0 : candidates.pop_back();
1167 [ # # # # ]: 0 : if (!counted.insert(candidate).second) continue;
1168 [ # # # # ]: 0 : const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst();
1169 [ # # ]: 0 : if (parents.size() == 0) {
1170 [ # # # # : 0 : maximum = std::max(maximum, candidate->GetCountWithDescendants());
# # ]
1171 : 0 : } else {
1172 [ # # ]: 0 : for (const CTxMemPoolEntry& i : parents) {
1173 [ # # # # ]: 0 : candidates.push_back(mapTx.iterator_to(i));
1174 : 0 : }
1175 : : }
1176 [ # # # ]: 0 : }
1177 : 0 : return maximum;
1178 : 0 : }
1179 : :
1180 : 2060409 : void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
1181 : 2060409 : LOCK(cs);
1182 [ + - ]: 2060409 : auto it = mapTx.find(txid);
1183 : 2060409 : ancestors = descendants = 0;
1184 [ + - - + ]: 2060409 : if (it != mapTx.end()) {
1185 [ # # # # ]: 0 : ancestors = it->GetCountWithAncestors();
1186 [ # # # # : 0 : if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
# # ]
1187 [ # # # # : 0 : if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
# # ]
1188 [ # # ]: 0 : descendants = CalculateDescendantMaximum(it);
1189 : 0 : }
1190 : 2060409 : }
1191 : :
1192 : 1 : bool CTxMemPool::GetLoadTried() const
1193 : : {
1194 : 1 : LOCK(cs);
1195 : 1 : return m_load_tried;
1196 : 1 : }
1197 : :
1198 : 1284 : void CTxMemPool::SetLoadTried(bool load_tried)
1199 : : {
1200 : 1284 : LOCK(cs);
1201 : 1284 : m_load_tried = load_tried;
1202 : 1284 : }
1203 : :
1204 : 2101 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<uint256>& txids) const
1205 : : {
1206 : 2101 : AssertLockHeld(cs);
1207 : 2101 : std::vector<txiter> clustered_txs{GetIterVec(txids)};
1208 : : // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not
1209 : : // necessarily mean the entry has been processed.
1210 [ + - ]: 2101 : WITH_FRESH_EPOCH(m_epoch);
1211 [ + + ]: 195207 : for (const auto& it : clustered_txs) {
1212 [ + - ]: 193106 : visited(it);
1213 : 193106 : }
1214 : : // i = index of where the list of entries to process starts
1215 [ + + - + ]: 267097 : for (size_t i{0}; i < clustered_txs.size(); ++i) {
1216 : : // DoS protection: if there are 500 or more entries to process, just quit.
1217 [ + - ]: 264996 : if (clustered_txs.size() > 500) return {};
1218 [ + - ]: 264996 : const txiter& tx_iter = clustered_txs.at(i);
1219 [ + - + - : 794988 : for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
+ - + - +
- + - +
+ ]
1220 [ + + ]: 1179592 : for (const CTxMemPoolEntry& entry : entries) {
1221 [ + - ]: 649600 : const auto entry_it = mapTx.iterator_to(entry);
1222 [ + - + + ]: 649600 : if (!visited(entry_it)) {
1223 [ + - ]: 71890 : clustered_txs.push_back(entry_it);
1224 : 71890 : }
1225 : 649600 : }
1226 : 529992 : }
1227 : 264996 : }
1228 : 2101 : return clustered_txs;
1229 : 2101 : }
1230 : :
1231 : 1388 : std::optional<std::string> CTxMemPool::CheckConflictTopology(const setEntries& direct_conflicts)
1232 : : {
1233 [ + + - + : 205888 : for (const auto& direct_conflict : direct_conflicts) {
+ ]
1234 : : // Ancestor and descendant counts are inclusive of the tx itself.
1235 : 204500 : const auto ancestor_count{direct_conflict->GetCountWithAncestors()};
1236 : 204500 : const auto descendant_count{direct_conflict->GetCountWithDescendants()};
1237 : 204500 : const bool has_ancestor{ancestor_count > 1};
1238 : 204500 : const bool has_descendant{descendant_count > 1};
1239 [ + - + - ]: 204500 : const auto& txid_string{direct_conflict->GetSharedTx()->GetHash().ToString()};
1240 : : // The only allowed configurations are:
1241 : : // 1 ancestor and 0 descendant
1242 : : // 0 ancestor and 1 descendant
1243 : : // 0 ancestor and 0 descendant
1244 [ + + ]: 204500 : if (ancestor_count > 2) {
1245 [ + - ]: 90 : return strprintf("%s has %u ancestors, max 1 allowed", txid_string, ancestor_count - 1);
1246 [ + + ]: 204410 : } else if (descendant_count > 2) {
1247 [ - + ]: 48 : return strprintf("%s has %u descendants, max 1 allowed", txid_string, descendant_count - 1);
1248 [ + + + - ]: 204362 : } else if (has_ancestor && has_descendant) {
1249 [ # # ]: 0 : return strprintf("%s has both ancestor and descendant, exceeding cluster limit of 2", txid_string);
1250 : : }
1251 : : // Additionally enforce that:
1252 : : // If we have a child, we are its only parent.
1253 : : // If we have a parent, we are its only child.
1254 [ + + ]: 204362 : if (has_descendant) {
1255 [ + - + - ]: 74598 : const auto& our_child = direct_conflict->GetMemPoolChildrenConst().begin();
1256 [ - + + + ]: 74598 : if (our_child->get().GetCountWithAncestors() > 2) {
1257 [ - + ]: 76 : return strprintf("%s is not the only parent of child %s",
1258 [ - + + - : 38 : txid_string, our_child->get().GetSharedTx()->GetHash().ToString());
+ - ]
1259 : : }
1260 [ + + + + ]: 204362 : } else if (has_ancestor) {
1261 [ + - + - ]: 74828 : const auto& our_parent = direct_conflict->GetMemPoolParentsConst().begin();
1262 [ - + + + ]: 74828 : if (our_parent->get().GetCountWithDescendants() > 2) {
1263 [ + - ]: 24 : return strprintf("%s is not the only child of parent %s",
1264 [ + - + - : 12 : txid_string, our_parent->get().GetSharedTx()->GetHash().ToString());
+ - ]
1265 : : }
1266 [ + + ]: 74828 : }
1267 [ + + + + ]: 204500 : }
1268 : 1200 : return std::nullopt;
1269 : 1388 : }
1270 : :
1271 : 1388 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::CalculateChunksForRBF(CAmount replacement_fees, int64_t replacement_vsize, const setEntries& direct_conflicts, const setEntries& all_conflicts)
1272 : : {
1273 : 1388 : Assume(replacement_vsize > 0);
1274 : :
1275 : 1388 : auto err_string{CheckConflictTopology(direct_conflicts)};
1276 [ + + ]: 1388 : if (err_string.has_value()) {
1277 : : // Unsupported topology for calculating a feerate diagram
1278 [ + - + - : 188 : return util::Error{Untranslated(err_string.value())};
+ - + - ]
1279 : : }
1280 : :
1281 : : // new diagram will have chunks that consist of each ancestor of
1282 : : // direct_conflicts that is at its own fee/size, along with the replacement
1283 : : // tx/package at its own fee/size
1284 : :
1285 : : // old diagram will consist of the ancestors and descendants of each element of
1286 : : // all_conflicts. every such transaction will either be at its own feerate (followed
1287 : : // by any descendant at its own feerate), or as a single chunk at the descendant's
1288 : : // ancestor feerate.
1289 : :
1290 : 1200 : std::vector<FeeFrac> old_chunks;
1291 : : // Step 1: build the old diagram.
1292 : :
1293 : : // The above clusters are all trivially linearized;
1294 : : // they have a strict topology of 1 or two connected transactions.
1295 : :
1296 : : // OLD: Compute existing chunks from all affected clusters
1297 [ + + ]: 164788 : for (auto txiter : all_conflicts) {
1298 : : // Does this transaction have descendants?
1299 [ + - + - : 163588 : if (txiter->GetCountWithDescendants() > 1) {
+ + ]
1300 : : // Consider this tx when we consider the descendant.
1301 : 50304 : continue;
1302 : : }
1303 : : // Does this transaction have ancestors?
1304 [ + - + - : 113284 : FeeFrac individual{txiter->GetModifiedFee(), txiter->GetTxSize()};
+ - + - ]
1305 [ + - + - : 113284 : if (txiter->GetCountWithAncestors() > 1) {
+ + ]
1306 : : // We'll add chunks for either the ancestor by itself and this tx
1307 : : // by itself, or for a combined package.
1308 [ + - + - : 58382 : FeeFrac package{txiter->GetModFeesWithAncestors(), static_cast<int32_t>(txiter->GetSizeWithAncestors())};
+ - + - ]
1309 [ + + ]: 58382 : if (individual >> package) {
1310 : : // The individual feerate is higher than the package, and
1311 : : // therefore higher than the parent's fee. Chunk these
1312 : : // together.
1313 [ + - ]: 45920 : old_chunks.emplace_back(package);
1314 : 45920 : } else {
1315 : : // Add two points, one for the parent and one for this child.
1316 [ + - ]: 12462 : old_chunks.emplace_back(package - individual);
1317 [ + - ]: 12462 : old_chunks.emplace_back(individual);
1318 : : }
1319 : 58382 : } else {
1320 [ + - ]: 54902 : old_chunks.emplace_back(individual);
1321 : : }
1322 [ - + + ]: 163588 : }
1323 : :
1324 : : // No topology restrictions post-chunking; sort
1325 [ + - ]: 1200 : std::sort(old_chunks.begin(), old_chunks.end(), std::greater());
1326 : :
1327 : 1200 : std::vector<FeeFrac> new_chunks;
1328 : :
1329 : : /* Step 2: build the NEW diagram
1330 : : * CON = Conflicts of proposed chunk
1331 : : * CNK = Proposed chunk
1332 : : * NEW = OLD - CON + CNK: New diagram includes all chunks in OLD, minus
1333 : : * the conflicts, plus the proposed chunk
1334 : : */
1335 : :
1336 : : // OLD - CON: Add any parents of direct conflicts that are not conflicted themselves
1337 [ + + ]: 157384 : for (auto direct_conflict : direct_conflicts) {
1338 : : // If a direct conflict has an ancestor that is not in all_conflicts,
1339 : : // it can be affected by the replacement of the child.
1340 [ + - + - : 156184 : if (direct_conflict->GetMemPoolParentsConst().size() > 0) {
+ + ]
1341 : : // Grab the parent.
1342 [ + - + - ]: 50978 : const CTxMemPoolEntry& parent = direct_conflict->GetMemPoolParentsConst().begin()->get();
1343 [ + - + - : 50978 : if (!all_conflicts.count(mapTx.iterator_to(parent))) {
+ + ]
1344 : : // This transaction would be left over, so add to the NEW
1345 : : // diagram.
1346 [ + - + - : 8078 : new_chunks.emplace_back(parent.GetModifiedFee(), parent.GetTxSize());
+ - ]
1347 : 8078 : }
1348 : 50978 : }
1349 : 156184 : }
1350 : : // + CNK: Add the proposed chunk itself
1351 [ + - ]: 1200 : new_chunks.emplace_back(replacement_fees, int32_t(replacement_vsize));
1352 : :
1353 : : // No topology restrictions post-chunking; sort
1354 [ + - ]: 1200 : std::sort(new_chunks.begin(), new_chunks.end(), std::greater());
1355 [ + - + - ]: 1200 : return std::make_pair(old_chunks, new_chunks);
1356 : 1388 : }
|