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 <tinyformat.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 <algorithm>
30 : : #include <cmath>
31 : : #include <numeric>
32 : : #include <optional>
33 : : #include <ranges>
34 : : #include <string_view>
35 : : #include <utility>
36 : :
37 : : TRACEPOINT_SEMAPHORE(mempool, added);
38 : : TRACEPOINT_SEMAPHORE(mempool, removed);
39 : :
40 : 2506 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41 : : {
42 : 2506 : AssertLockHeld(cs_main);
43 : : // If there are relative lock times then the maxInputBlock will be set
44 : : // If there are no relative lock times, the LockPoints don't depend on the chain
45 [ + - ]: 2506 : if (lp.maxInputBlock) {
46 : : // Check whether active_chain is an extension of the block at which the LockPoints
47 : : // calculation was valid. If not LockPoints are no longer valid
48 [ + + ]: 2506 : if (!active_chain.Contains(lp.maxInputBlock)) {
49 : 238 : return false;
50 : : }
51 : : }
52 : :
53 : : // LockPoints still valid
54 : : return true;
55 : : }
56 : :
57 : 646 : void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
58 : : const std::set<Txid>& setExclude, std::set<Txid>& descendants_to_remove)
59 : : {
60 [ + - ]: 646 : CTxMemPoolEntry::Children stageEntries, descendants;
61 [ + - ]: 646 : stageEntries = updateIt->GetMemPoolChildrenConst();
62 : :
63 [ + + ]: 10828 : while (!stageEntries.empty()) {
64 [ + - ]: 10182 : const CTxMemPoolEntry& descendant = *stageEntries.begin();
65 [ + - ]: 10182 : descendants.insert(descendant);
66 : 10182 : stageEntries.erase(descendant);
67 : 10182 : const CTxMemPoolEntry::Children& children = descendant.GetMemPoolChildrenConst();
68 [ + + ]: 174742 : for (const CTxMemPoolEntry& childEntry : children) {
69 : 164560 : cacheMap::iterator cacheIt = cachedDescendants.find(mapTx.iterator_to(childEntry));
70 [ + + ]: 164560 : if (cacheIt != cachedDescendants.end()) {
71 : : // We've already calculated this one, just add the entries for this set
72 : : // but don't traverse again.
73 [ + + ]: 1755660 : for (txiter cacheEntry : cacheIt->second) {
74 [ + - ]: 1688130 : descendants.insert(*cacheEntry);
75 : : }
76 [ + + ]: 97030 : } else if (!descendants.count(childEntry)) {
77 : : // Schedule for later processing
78 [ + - ]: 6978 : stageEntries.insert(childEntry);
79 : : }
80 : : }
81 : : }
82 : : // descendants now contains all in-mempool descendants of updateIt.
83 : : // Update and add to cached descendant map
84 : 646 : int32_t modifySize = 0;
85 : 646 : CAmount modifyFee = 0;
86 : 646 : int64_t modifyCount = 0;
87 [ + + ]: 10832 : for (const CTxMemPoolEntry& descendant : descendants) {
88 [ + + ]: 10186 : if (!setExclude.count(descendant.GetTx().GetHash())) {
89 [ + - ]: 2096 : modifySize += descendant.GetTxSize();
90 [ + - ]: 2096 : modifyFee += descendant.GetModifiedFee();
91 : 2096 : modifyCount++;
92 [ + - + - ]: 2096 : cachedDescendants[updateIt].insert(mapTx.iterator_to(descendant));
93 : : // Update ancestor state for each descendant
94 [ + - ]: 2096 : mapTx.modify(mapTx.iterator_to(descendant), [=](CTxMemPoolEntry& e) {
95 : 2096 : e.UpdateAncestorState(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost());
96 : 2096 : });
97 : : // Don't directly remove the transaction here -- doing so would
98 : : // invalidate iterators in cachedDescendants. Mark it for removal
99 : : // by inserting into descendants_to_remove.
100 [ + - - + ]: 2096 : if (descendant.GetCountWithAncestors() > uint64_t(m_opts.limits.ancestor_count) || descendant.GetSizeWithAncestors() > m_opts.limits.ancestor_size_vbytes) {
101 [ # # ]: 0 : descendants_to_remove.insert(descendant.GetTx().GetHash());
102 : : }
103 : : }
104 : : }
105 [ + - ]: 1938 : mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); });
106 : 646 : }
107 : :
108 : 3076 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
109 : : {
110 : 3076 : AssertLockHeld(cs);
111 : : // For each entry in vHashesToUpdate, store the set of in-mempool, but not
112 : : // in-vHashesToUpdate transactions, so that we don't have to recalculate
113 : : // descendants when we come across a previously seen entry.
114 [ + - ]: 3076 : cacheMap mapMemPoolDescendantsToUpdate;
115 : :
116 : : // Use a set for lookups into vHashesToUpdate (these entries are already
117 : : // accounted for in the state of their ancestors)
118 [ + - ]: 3076 : std::set<Txid> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
119 : :
120 : 3076 : std::set<Txid> descendants_to_remove;
121 : :
122 : : // Iterate in reverse, so that whenever we are looking at a transaction
123 : : // we are sure that all in-mempool descendants have already been processed.
124 : : // This maximizes the benefit of the descendant cache and guarantees that
125 : : // CTxMemPoolEntry::m_children will be updated, an assumption made in
126 : : // UpdateForDescendants.
127 [ + + ]: 3722 : for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
128 : : // calculate children from mapNextTx
129 [ + - ]: 646 : txiter it = mapTx.find(hash);
130 [ - + ]: 646 : if (it == mapTx.end()) {
131 : 0 : continue;
132 : : }
133 : 646 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
134 : : // First calculate the children, and update CTxMemPoolEntry::m_children to
135 : : // include them, and update their CTxMemPoolEntry::m_parents to include this tx.
136 : : // we cache the in-mempool children to avoid duplicate updates
137 : 646 : {
138 : 646 : WITH_FRESH_EPOCH(m_epoch);
139 [ + + + + ]: 5677 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
140 [ + - ]: 5031 : const Txid &childHash = iter->second->GetHash();
141 [ + - ]: 5031 : txiter childIter = mapTx.find(childHash);
142 [ - + ]: 5031 : 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 [ + + + + ]: 5031 : if (!visited(childIter) && !setAlreadyIncluded.count(childHash)) {
146 [ + - ]: 2090 : UpdateChild(it, childIter, true);
147 [ + - ]: 2090 : UpdateParent(childIter, it, true);
148 : : }
149 : : }
150 : 646 : } // release epoch guard for UpdateForDescendants
151 [ + - ]: 646 : UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded, descendants_to_remove);
152 : : }
153 : :
154 [ - + ]: 3076 : for (const auto& txid : descendants_to_remove) {
155 : : // This txid may have been removed already in a prior call to removeRecursive.
156 : : // Therefore we ensure it is not yet removed already.
157 [ # # # # ]: 0 : if (const std::optional<txiter> txiter = GetIter(txid)) {
158 [ # # ]: 0 : removeRecursive((*txiter)->GetTx(), MemPoolRemovalReason::SIZELIMIT);
159 : : }
160 : : }
161 : 3076 : }
162 : :
163 : 8750818 : util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateAncestorsAndCheckLimits(
164 : : int64_t entry_size,
165 : : size_t entry_count,
166 : : CTxMemPoolEntry::Parents& staged_ancestors,
167 : : const Limits& limits) const
168 : : {
169 : 8750818 : int64_t totalSizeWithAncestors = entry_size;
170 : 8750818 : setEntries ancestors;
171 : :
172 [ + + ]: 10889687 : while (!staged_ancestors.empty()) {
173 [ + - ]: 2139241 : const CTxMemPoolEntry& stage = staged_ancestors.begin()->get();
174 : 2139241 : txiter stageit = mapTx.iterator_to(stage);
175 : :
176 [ + - ]: 2139241 : ancestors.insert(stageit);
177 : 2139241 : staged_ancestors.erase(stage);
178 [ + - ]: 2139241 : totalSizeWithAncestors += stageit->GetTxSize();
179 : :
180 [ + + ]: 2139241 : if (stageit->GetSizeWithDescendants() + entry_size > limits.descendant_size_vbytes) {
181 [ + - + - : 66 : return util::Error{Untranslated(strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_size_vbytes))};
+ - ]
182 [ + + ]: 2139219 : } else if (stageit->GetCountWithDescendants() + entry_count > static_cast<uint64_t>(limits.descendant_count)) {
183 [ + - + - : 696 : return util::Error{Untranslated(strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_count))};
+ - ]
184 [ + + ]: 2138987 : } else if (totalSizeWithAncestors > limits.ancestor_size_vbytes) {
185 [ + - + - ]: 6 : return util::Error{Untranslated(strprintf("exceeds ancestor size limit [limit: %u]", limits.ancestor_size_vbytes))};
186 : : }
187 : :
188 : 2138985 : const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst();
189 [ + + ]: 5038463 : for (const CTxMemPoolEntry& parent : parents) {
190 : 2899594 : txiter parent_it = mapTx.iterator_to(parent);
191 : :
192 : : // If this is a new ancestor, add it.
193 [ + + ]: 2899594 : if (ancestors.count(parent_it) == 0) {
194 [ + - ]: 2452693 : staged_ancestors.insert(parent);
195 : : }
196 [ + + ]: 2899594 : if (staged_ancestors.size() + ancestors.size() + entry_count > static_cast<uint64_t>(limits.ancestor_count)) {
197 [ + - + - ]: 348 : return util::Error{Untranslated(strprintf("too many unconfirmed ancestors [limit: %u]", limits.ancestor_count))};
198 : : }
199 : : }
200 : : }
201 : :
202 : 8750446 : return ancestors;
203 : 8750818 : }
204 : :
205 : 3453 : util::Result<void> CTxMemPool::CheckPackageLimits(const Package& package,
206 : : const int64_t total_vsize) const
207 : : {
208 [ - + ]: 3453 : size_t pack_count = package.size();
209 : :
210 : : // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist
211 [ - + ]: 3453 : if (pack_count > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
212 [ # # ]: 0 : return util::Error{Untranslated(strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_opts.limits.ancestor_count))};
213 [ - + ]: 3453 : } else if (pack_count > static_cast<uint64_t>(m_opts.limits.descendant_count)) {
214 [ # # ]: 0 : return util::Error{Untranslated(strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_opts.limits.descendant_count))};
215 [ + + ]: 3453 : } else if (total_vsize > m_opts.limits.ancestor_size_vbytes) {
216 [ + - ]: 3 : return util::Error{Untranslated(strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_opts.limits.ancestor_size_vbytes))};
217 [ - + ]: 3452 : } else if (total_vsize > m_opts.limits.descendant_size_vbytes) {
218 [ # # ]: 0 : return util::Error{Untranslated(strprintf("package size %u exceeds descendant size limit [limit: %u]", total_vsize, m_opts.limits.descendant_size_vbytes))};
219 : : }
220 : :
221 : 3452 : CTxMemPoolEntry::Parents staged_ancestors;
222 [ + + ]: 7503 : for (const auto& tx : package) {
223 [ + + ]: 16389 : for (const auto& input : tx->vin) {
224 [ + - ]: 12338 : std::optional<txiter> piter = GetIter(input.prevout.hash);
225 [ + + ]: 12338 : if (piter) {
226 [ + - ]: 805 : staged_ancestors.insert(**piter);
227 [ - + + + ]: 805 : if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
228 [ + - + - ]: 3 : return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", m_opts.limits.ancestor_count))};
229 : : }
230 : : }
231 : : }
232 : : }
233 : : // When multiple transactions are passed in, the ancestors and descendants of all transactions
234 : : // considered together must be within limits even if they are not interdependent. This may be
235 : : // stricter than the limits for each individual transaction.
236 : 3451 : const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(),
237 [ - + + - ]: 3451 : staged_ancestors, m_opts.limits)};
238 : : // It's possible to overestimate the ancestor/descendant totals.
239 [ + + + - : 3481 : if (!ancestors.has_value()) return util::Error{Untranslated("possibly " + util::ErrorString(ancestors).original)};
+ - + - ]
240 : 3441 : return {};
241 : 6903 : }
242 : :
243 : 8747368 : util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateMemPoolAncestors(
244 : : const CTxMemPoolEntry &entry,
245 : : const Limits& limits,
246 : : bool fSearchForParents /* = true */) const
247 : : {
248 [ + + ]: 8747368 : CTxMemPoolEntry::Parents staged_ancestors;
249 [ + + ]: 8747368 : const CTransaction &tx = entry.GetTx();
250 : :
251 [ + + ]: 8747368 : if (fSearchForParents) {
252 : : // Get parents of this transaction that are in the mempool
253 : : // GetMemPoolParents() is only valid for entries in the mempool, so we
254 : : // iterate mapTx to find parents.
255 [ - + + + ]: 19912340 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
256 [ + - ]: 11220839 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
257 [ + + ]: 11220839 : if (piter) {
258 [ + - ]: 183872 : staged_ancestors.insert(**piter);
259 [ + + ]: 183872 : if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) {
260 [ + - + - ]: 3 : return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", limits.ancestor_count))};
261 : : }
262 : : }
263 : : }
264 : : } else {
265 : : // If we're not searching for parents, we require this to already be an
266 : : // entry in the mempool and use the entry's cached parents.
267 : 55866 : txiter it = mapTx.iterator_to(entry);
268 [ + - ]: 55866 : staged_ancestors = it->GetMemPoolParentsConst();
269 : : }
270 : :
271 [ + - ]: 8747367 : return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
272 [ + - ]: 8747367 : limits);
273 : 8747368 : }
274 : :
275 : 8688575 : CTxMemPool::setEntries CTxMemPool::AssumeCalculateMemPoolAncestors(
276 : : std::string_view calling_fn_name,
277 : : const CTxMemPoolEntry &entry,
278 : : const Limits& limits,
279 : : bool fSearchForParents /* = true */) const
280 : : {
281 : 8688575 : auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
282 [ - + ]: 8688575 : if (!Assume(result)) {
283 [ # # # # : 0 : LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Error, "%s: CalculateMemPoolAncestors failed unexpectedly, continuing with empty ancestor set (%s)\n",
# # # # ]
284 : : calling_fn_name, util::ErrorString(result).original);
285 : : }
286 : 8688575 : return std::move(result).value_or(CTxMemPool::setEntries{});
287 : 8688575 : }
288 : :
289 : 96971 : void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
290 : : {
291 : 96971 : const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
292 : : // add or remove this tx as a child of each parent
293 [ + + ]: 107776 : for (const CTxMemPoolEntry& parent : parents) {
294 : 10805 : UpdateChild(mapTx.iterator_to(parent), it, add);
295 : : }
296 [ + + ]: 96971 : const int32_t updateCount = (add ? 1 : -1);
297 : 96971 : const int32_t updateSize{updateCount * it->GetTxSize()};
298 : 96971 : const CAmount updateFee = updateCount * it->GetModifiedFee();
299 [ + + ]: 1260292 : for (txiter ancestorIt : setAncestors) {
300 : 2326642 : mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
301 : : }
302 : 96971 : }
303 : :
304 : 50924 : void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
305 : : {
306 : 50924 : int64_t updateCount = setAncestors.size();
307 : 50924 : int64_t updateSize = 0;
308 : 50924 : CAmount updateFee = 0;
309 : 50924 : int64_t updateSigOpsCost = 0;
310 [ + + ]: 1212334 : for (txiter ancestorIt : setAncestors) {
311 : 1161410 : updateSize += ancestorIt->GetTxSize();
312 : 1161410 : updateFee += ancestorIt->GetModifiedFee();
313 : 1161410 : updateSigOpsCost += ancestorIt->GetSigOpCost();
314 : : }
315 : 101848 : mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
316 : 50924 : }
317 : :
318 : 46047 : void CTxMemPool::UpdateChildrenForRemoval(txiter it)
319 : : {
320 : 46047 : const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
321 [ + + ]: 54494 : for (const CTxMemPoolEntry& updateIt : children) {
322 : 8447 : UpdateParent(mapTx.iterator_to(updateIt), it, false);
323 : : }
324 : 46047 : }
325 : :
326 : 142292 : void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
327 : : {
328 : : // For each entry, walk back all ancestors and decrement size associated with this
329 : : // transaction
330 [ + + ]: 142292 : if (updateDescendants) {
331 : : // updateDescendants should be true whenever we're not recursively
332 : : // removing a tx and all its descendants, eg when a transaction is
333 : : // confirmed in a block.
334 : : // Here we only update statistics and not data in CTxMemPool::Parents
335 : : // and CTxMemPoolEntry::Children (which we need to preserve until we're
336 : : // finished with all operations that need to traverse the mempool).
337 [ + + ]: 88652 : for (txiter removeIt : entriesToRemove) {
338 [ + - ]: 44326 : setEntries setDescendants;
339 [ + - ]: 44326 : CalculateDescendants(removeIt, setDescendants);
340 : 44326 : setDescendants.erase(removeIt); // don't update state for self
341 [ + - ]: 44326 : int32_t modifySize = -removeIt->GetTxSize();
342 : 44326 : CAmount modifyFee = -removeIt->GetModifiedFee();
343 : 44326 : int modifySigOps = -removeIt->GetSigOpCost();
344 [ + + ]: 63912 : for (txiter dit : setDescendants) {
345 [ + - ]: 58758 : mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); });
346 : : }
347 : 44326 : }
348 : : }
349 [ + + ]: 188339 : for (txiter removeIt : entriesToRemove) {
350 : 46047 : const CTxMemPoolEntry &entry = *removeIt;
351 : : // Since this is a tx that is already in the mempool, we can call CMPA
352 : : // with fSearchForParents = false. If the mempool is in a consistent
353 : : // state, then using true or false should both be correct, though false
354 : : // should be a bit faster.
355 : : // However, if we happen to be in the middle of processing a reorg, then
356 : : // the mempool can be in an inconsistent state. In this case, the set
357 : : // of ancestors reachable via GetMemPoolParents()/GetMemPoolChildren()
358 : : // will be the same as the set of ancestors whose packages include this
359 : : // transaction, because when we add a new transaction to the mempool in
360 : : // addNewTransaction(), we assume it has no children, and in the case of a
361 : : // reorg where that assumption is false, the in-mempool children aren't
362 : : // linked to the in-block tx's until UpdateTransactionsFromBlock() is
363 : : // called.
364 : : // So if we're being called during a reorg, ie before
365 : : // UpdateTransactionsFromBlock() has been called, then
366 : : // GetMemPoolParents()/GetMemPoolChildren() will differ from the set of
367 : : // mempool parents we'd calculate by searching, and it's important that
368 : : // we use the cached notion of ancestor transactions as the set of
369 : : // things to update for removal.
370 : 46047 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits(), /*fSearchForParents=*/false)};
371 : : // Note that UpdateAncestorsOf severs the child links that point to
372 : : // removeIt in the entries for the parents of removeIt.
373 [ + - ]: 46047 : UpdateAncestorsOf(false, removeIt, ancestors);
374 : 46047 : }
375 : : // After updating all the ancestor sizes, we can now sever the link between each
376 : : // transaction being removed and any mempool children (ie, update CTxMemPoolEntry::m_parents
377 : : // for each direct child of a transaction being removed).
378 [ + + ]: 188339 : for (txiter removeIt : entriesToRemove) {
379 : 46047 : UpdateChildrenForRemoval(removeIt);
380 : : }
381 : 142292 : }
382 : :
383 : 1164001 : void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
384 : : {
385 : 1164001 : nSizeWithDescendants += modifySize;
386 [ - + ]: 1164001 : assert(nSizeWithDescendants > 0);
387 : 1164001 : nModFeesWithDescendants = SaturatingAdd(nModFeesWithDescendants, modifyFee);
388 : 1164001 : m_count_with_descendants += modifyCount;
389 [ - + ]: 1164001 : assert(m_count_with_descendants > 0);
390 : 1164001 : }
391 : :
392 : 72661 : void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
393 : : {
394 : 72661 : nSizeWithAncestors += modifySize;
395 [ - + ]: 72661 : assert(nSizeWithAncestors > 0);
396 : 72661 : nModFeesWithAncestors = SaturatingAdd(nModFeesWithAncestors, modifyFee);
397 : 72661 : m_count_with_ancestors += modifyCount;
398 [ - + ]: 72661 : assert(m_count_with_ancestors > 0);
399 : 72661 : nSigOpCostWithAncestors += modifySigOps;
400 [ - + ]: 72661 : assert(int(nSigOpCostWithAncestors) >= 0);
401 : 72661 : }
402 : :
403 : : //! Clamp option values and populate the error if options are not valid.
404 : 1206 : static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
405 : : {
406 [ + - ]: 1206 : opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
407 : 1206 : int64_t descendant_limit_bytes = opts.limits.descendant_size_vbytes * 40;
408 [ + - + + ]: 1206 : if (opts.max_size_bytes < 0 || opts.max_size_bytes < descendant_limit_bytes) {
409 : 2 : error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(descendant_limit_bytes / 1'000'000.0));
410 : : }
411 : 1206 : return std::move(opts);
412 : : }
413 : :
414 : 1206 : CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
415 [ + - ]: 1206 : : m_opts{Flatten(std::move(opts), error)}
416 : : {
417 : 1206 : }
418 : :
419 : 54 : bool CTxMemPool::isSpent(const COutPoint& outpoint) const
420 : : {
421 : 54 : LOCK(cs);
422 [ + - ]: 54 : return mapNextTx.count(outpoint);
423 : 54 : }
424 : :
425 : 2081 : unsigned int CTxMemPool::GetTransactionsUpdated() const
426 : : {
427 : 2081 : return nTransactionsUpdated;
428 : : }
429 : :
430 : 143020 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
431 : : {
432 : 143020 : nTransactionsUpdated += n;
433 : 143020 : }
434 : :
435 : 50872 : void CTxMemPool::Apply(ChangeSet* changeset)
436 : : {
437 : 50872 : AssertLockHeld(cs);
438 : 50872 : RemoveStaged(changeset->m_to_remove, false, MemPoolRemovalReason::REPLACED);
439 : :
440 [ - + + + ]: 101796 : for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
441 [ + + ]: 50924 : auto tx_entry = changeset->m_entry_vec[i];
442 : 50924 : std::optional<CTxMemPool::setEntries> ancestors;
443 [ + + ]: 50924 : if (i == 0) {
444 : : // Note: ChangeSet::CalculateMemPoolAncestors() will return a
445 : : // cached value if mempool ancestors for this transaction were
446 : : // previously calculated.
447 : : // We can only use a cached ancestor calculation for the first
448 : : // transaction in a package, because in-package parents won't be
449 : : // present in the cached ancestor sets of in-package children.
450 : : // We pass in Limits::NoLimits() to ensure that this function won't fail
451 : : // (we're going to be applying this set of transactions whether or
452 : : // not the mempool policy limits are being respected).
453 [ + - + - ]: 101744 : ancestors = *Assume(changeset->CalculateMemPoolAncestors(tx_entry, Limits::NoLimits()));
454 : : }
455 : : // First splice this entry into mapTx.
456 : 50924 : auto node_handle = changeset->m_to_add.extract(tx_entry);
457 [ + - ]: 50924 : auto result = mapTx.insert(std::move(node_handle));
458 : :
459 : 50924 : Assume(result.inserted);
460 : 50924 : txiter it = result.position;
461 : :
462 : : // Now update the entry for ancestors/descendants.
463 [ + + ]: 50924 : if (ancestors.has_value()) {
464 [ + - ]: 50872 : addNewTransaction(it, *ancestors);
465 : : } else {
466 [ + - ]: 52 : addNewTransaction(it);
467 : : }
468 [ - + ]: 50924 : }
469 : 50872 : }
470 : :
471 : 52 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter it)
472 : : {
473 : 52 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
474 [ + - ]: 52 : return addNewTransaction(it, ancestors);
475 : 52 : }
476 : :
477 : 50924 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit, CTxMemPool::setEntries& setAncestors)
478 : : {
479 : 50924 : const CTxMemPoolEntry& entry = *newit;
480 : :
481 : : // Update cachedInnerUsage to include contained transaction's usage.
482 : : // (When we update the entry for in-mempool parents, memory usage will be
483 : : // further updated.)
484 : 50924 : cachedInnerUsage += entry.DynamicMemoryUsage();
485 : :
486 : 50924 : const CTransaction& tx = newit->GetTx();
487 : 50924 : std::set<Txid> setParentTransactions;
488 [ - + + + ]: 119062 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
489 [ + - ]: 68138 : mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
490 [ + - ]: 68138 : setParentTransactions.insert(tx.vin[i].prevout.hash);
491 : : }
492 : : // Don't bother worrying about child transactions of this one.
493 : : // Normal case of a new transaction arriving is that there can't be any
494 : : // children, because such children would be orphans.
495 : : // An exception to that is if a transaction enters that used to be in a block.
496 : : // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
497 : : // to clean up the mess we're leaving here.
498 : :
499 : : // Update ancestors with information about this tx
500 [ + - + + ]: 61136 : for (const auto& pit : GetIterSet(setParentTransactions)) {
501 [ + - ]: 10212 : UpdateParent(newit, pit, true);
502 : 0 : }
503 [ + - ]: 50924 : UpdateAncestorsOf(true, newit, setAncestors);
504 [ + - ]: 50924 : UpdateEntryForAncestors(newit, setAncestors);
505 : :
506 [ + - ]: 50924 : nTransactionsUpdated++;
507 [ + - ]: 50924 : totalTxSize += entry.GetTxSize();
508 : 50924 : m_total_fee += entry.GetFee();
509 : :
510 [ + - + - ]: 101848 : txns_randomized.emplace_back(newit->GetSharedTx());
511 [ - + ]: 50924 : newit->idx_randomized = txns_randomized.size() - 1;
512 : :
513 : : TRACEPOINT(mempool, added,
514 : : entry.GetTx().GetHash().data(),
515 : : entry.GetTxSize(),
516 : : entry.GetFee()
517 : 50924 : );
518 : 50924 : }
519 : :
520 : 46047 : void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
521 : : {
522 : : // We increment mempool sequence value no matter removal reason
523 : : // even if not directly reported below.
524 [ + + ]: 46047 : uint64_t mempool_sequence = GetAndIncrementSequence();
525 : :
526 [ + + + - ]: 46047 : if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
527 : : // Notify clients that a transaction has been removed from the mempool
528 : : // for any reason except being included in a block. Clients interested
529 : : // in transactions included in blocks can subscribe to the BlockConnected
530 : : // notification.
531 [ + - + - ]: 5163 : m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
532 : : }
533 : : TRACEPOINT(mempool, removed,
534 : : it->GetTx().GetHash().data(),
535 : : RemovalReasonToString(reason).c_str(),
536 : : it->GetTxSize(),
537 : : it->GetFee(),
538 : : std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
539 : 46047 : );
540 : :
541 [ + + ]: 107852 : for (const CTxIn& txin : it->GetTx().vin)
542 : 61805 : mapNextTx.erase(txin.prevout);
543 : :
544 : 46047 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
545 : :
546 [ - + + + ]: 46047 : if (txns_randomized.size() > 1) {
547 : : // Update idx_randomized of the to-be-moved entry.
548 : 43999 : Assert(GetEntry(txns_randomized.back()->GetHash()))->idx_randomized = it->idx_randomized;
549 : : // Remove entry from txns_randomized by replacing it with the back and deleting the back.
550 : 43999 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
551 : 43999 : txns_randomized.pop_back();
552 [ - + - + : 43999 : if (txns_randomized.size() * 2 < txns_randomized.capacity())
+ + ]
553 : 3158 : txns_randomized.shrink_to_fit();
554 : : } else
555 : 2048 : txns_randomized.clear();
556 : :
557 : 46047 : totalTxSize -= it->GetTxSize();
558 : 46047 : m_total_fee -= it->GetFee();
559 : 46047 : cachedInnerUsage -= it->DynamicMemoryUsage();
560 : 46047 : cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
561 : 46047 : mapTx.erase(it);
562 : 46047 : nTransactionsUpdated++;
563 : 46047 : }
564 : :
565 : : // Calculates descendants of entry that are not already in setDescendants, and adds to
566 : : // setDescendants. Assumes entryit is already a tx in the mempool and CTxMemPoolEntry::m_children
567 : : // is correct for tx and all descendants.
568 : : // Also assumes that if an entry is in setDescendants already, then all
569 : : // in-mempool descendants of it are already in setDescendants as well, so that we
570 : : // can save time by not iterating over those entries.
571 : 126410 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
572 : : {
573 : 126410 : setEntries stage;
574 [ + - ]: 126410 : if (setDescendants.count(entryit) == 0) {
575 [ + - ]: 126410 : stage.insert(entryit);
576 : : }
577 : : // Traverse down the children of entry, only adding children that are not
578 : : // accounted for in setDescendants already (because those children have either
579 : : // already been walked, or will be walked in this iteration).
580 [ + + ]: 1329065 : while (!stage.empty()) {
581 [ + - ]: 1202655 : txiter it = *stage.begin();
582 [ + - ]: 1202655 : setDescendants.insert(it);
583 : 1202655 : stage.erase(it);
584 : :
585 : 1202655 : const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
586 [ + + ]: 2616121 : for (const CTxMemPoolEntry& child : children) {
587 : 1413466 : txiter childiter = mapTx.iterator_to(child);
588 [ + + ]: 1413466 : if (!setDescendants.count(childiter)) {
589 [ + - ]: 1249481 : stage.insert(childiter);
590 : : }
591 : : }
592 : : }
593 : 126410 : }
594 : :
595 : 18270 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
596 : : {
597 : : // Remove transaction from memory pool
598 : 18270 : AssertLockHeld(cs);
599 : 18270 : Assume(!m_have_changeset);
600 [ + - ]: 18270 : setEntries txToRemove;
601 [ + - ]: 18270 : txiter origit = mapTx.find(origTx.GetHash());
602 [ + + ]: 18270 : if (origit != mapTx.end()) {
603 [ + - ]: 125 : txToRemove.insert(origit);
604 : : } else {
605 : : // When recursively removing but origTx isn't in the mempool
606 : : // be sure to remove any children that are in the pool. This can
607 : : // happen during chain re-orgs if origTx isn't re-accepted into
608 : : // the mempool for any reason.
609 [ - + + + ]: 45518 : for (unsigned int i = 0; i < origTx.vout.size(); i++) {
610 : 27373 : auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
611 [ + + ]: 27373 : if (it == mapNextTx.end())
612 : 27298 : continue;
613 [ + - ]: 75 : txiter nextit = mapTx.find(it->second->GetHash());
614 [ - + ]: 75 : assert(nextit != mapTx.end());
615 [ + - ]: 75 : txToRemove.insert(nextit);
616 : : }
617 : : }
618 : 18270 : setEntries setAllRemoves;
619 [ + + ]: 18470 : for (txiter it : txToRemove) {
620 [ + - ]: 200 : CalculateDescendants(it, setAllRemoves);
621 : : }
622 : :
623 [ + - ]: 18270 : RemoveStaged(setAllRemoves, false, reason);
624 : 18270 : }
625 : :
626 : 3076 : void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
627 : : {
628 : : // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
629 : 3076 : AssertLockHeld(cs);
630 : 3076 : AssertLockHeld(::cs_main);
631 : 3076 : Assume(!m_have_changeset);
632 : :
633 : 3076 : setEntries txToRemove;
634 [ + + ]: 4339 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
635 [ + - + + : 1263 : if (check_final_and_mature(it)) txToRemove.insert(it);
+ - ]
636 : : }
637 : 3076 : setEntries setAllRemoves;
638 [ + + ]: 3093 : for (txiter it : txToRemove) {
639 [ + - ]: 17 : CalculateDescendants(it, setAllRemoves);
640 : : }
641 [ + - ]: 3076 : RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
642 [ + + ]: 4322 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
643 [ + - - + ]: 1246 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
644 : : }
645 : 3076 : }
646 : :
647 : 55629 : void CTxMemPool::removeConflicts(const CTransaction &tx)
648 : : {
649 : : // Remove transactions which depend on inputs of tx, recursively
650 : 55629 : AssertLockHeld(cs);
651 [ + + ]: 127095 : for (const CTxIn &txin : tx.vin) {
652 : 71466 : auto it = mapNextTx.find(txin.prevout);
653 [ + + ]: 71466 : if (it != mapNextTx.end()) {
654 [ + - ]: 115 : const CTransaction &txConflict = *it->second;
655 [ + - ]: 115 : if (Assume(txConflict.GetHash() != tx.GetHash()))
656 : : {
657 : 115 : ClearPrioritisation(txConflict.GetHash());
658 : 115 : removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
659 : : }
660 : : }
661 : : }
662 : 55629 : }
663 : :
664 : 129518 : void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
665 : : {
666 : : // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
667 : 129518 : AssertLockHeld(cs);
668 : 129518 : Assume(!m_have_changeset);
669 : 129518 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
670 [ + + + - : 129518 : if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
+ + ]
671 [ - + + - ]: 6800 : txs_removed_for_block.reserve(vtx.size());
672 [ + + ]: 62429 : for (const auto& tx : vtx) {
673 [ + - ]: 55629 : txiter it = mapTx.find(tx->GetHash());
674 [ + + ]: 55629 : if (it != mapTx.end()) {
675 [ + - ]: 44326 : setEntries stage;
676 [ + - ]: 44326 : stage.insert(it);
677 [ + - ]: 44326 : txs_removed_for_block.emplace_back(*it);
678 [ + - ]: 44326 : RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
679 : 44326 : }
680 [ + - ]: 55629 : removeConflicts(*tx);
681 [ + - ]: 55629 : ClearPrioritisation(tx->GetHash());
682 : : }
683 : : }
684 [ + - ]: 129518 : if (m_opts.signals) {
685 [ + - ]: 129518 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
686 : : }
687 [ + - ]: 129518 : lastRollingFeeUpdate = GetTime();
688 : 129518 : blockSinceLastRollingFeeBump = true;
689 : 129518 : }
690 : :
691 : 154139 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
692 : : {
693 [ + + ]: 154139 : if (m_opts.check_ratio == 0) return;
694 : :
695 [ + - ]: 152092 : if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
696 : :
697 : 152092 : AssertLockHeld(::cs_main);
698 : 152092 : LOCK(cs);
699 [ + - + - : 152092 : LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - ]
700 : :
701 : 152092 : uint64_t checkTotal = 0;
702 : 152092 : CAmount check_total_fee{0};
703 : 152092 : uint64_t innerUsage = 0;
704 : 152092 : uint64_t prev_ancestor_count{0};
705 : :
706 [ + - ]: 152092 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
707 : :
708 [ + - + + ]: 8784749 : for (const auto& it : GetSortedDepthAndScore()) {
709 [ + - ]: 8632657 : checkTotal += it->GetTxSize();
710 : 8632657 : check_total_fee += it->GetFee();
711 : 8632657 : innerUsage += it->DynamicMemoryUsage();
712 : 8632657 : const CTransaction& tx = it->GetTx();
713 : 8632657 : innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
714 : 8632657 : CTxMemPoolEntry::Parents setParentCheck;
715 [ + + ]: 19771760 : for (const CTxIn &txin : tx.vin) {
716 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
717 [ + - ]: 11139103 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
718 [ + + ]: 11139103 : if (it2 != mapTx.end()) {
719 [ - + ]: 171758 : const CTransaction& tx2 = it2->GetTx();
720 [ - + + - : 171758 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
- + ]
721 [ + - ]: 171758 : setParentCheck.insert(*it2);
722 : : }
723 : : // We are iterating through the mempool entries sorted in order by ancestor count.
724 : : // All parents must have been checked before their children and their coins added to
725 : : // the mempoolDuplicate coins cache.
726 [ + - - + ]: 11139103 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
727 : : // Check whether its inputs are marked in mapNextTx.
728 : 11139103 : auto it3 = mapNextTx.find(txin.prevout);
729 [ - + ]: 11139103 : assert(it3 != mapNextTx.end());
730 [ - + ]: 11139103 : assert(it3->first == &txin.prevout);
731 [ - + ]: 11139103 : assert(it3->second == &tx);
732 : : }
733 : 8975745 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
734 [ + - ]: 343088 : return a.GetTx().GetHash() == b.GetTx().GetHash();
735 : : };
736 [ - + ]: 8632657 : assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
737 [ - + ]: 8632657 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
738 : : // Verify ancestor state is correct.
739 [ + - ]: 8632657 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
740 [ + - ]: 8632657 : uint64_t nCountCheck = ancestors.size() + 1;
741 [ + - ]: 8632657 : int32_t nSizeCheck = it->GetTxSize();
742 : 8632657 : CAmount nFeesCheck = it->GetModifiedFee();
743 : 8632657 : int64_t nSigOpCheck = it->GetSigOpCost();
744 : :
745 [ + + ]: 9571187 : for (txiter ancestorIt : ancestors) {
746 [ + - ]: 938530 : nSizeCheck += ancestorIt->GetTxSize();
747 : 938530 : nFeesCheck += ancestorIt->GetModifiedFee();
748 : 938530 : nSigOpCheck += ancestorIt->GetSigOpCost();
749 : : }
750 : :
751 [ - + ]: 8632657 : assert(it->GetCountWithAncestors() == nCountCheck);
752 [ - + ]: 8632657 : assert(it->GetSizeWithAncestors() == nSizeCheck);
753 [ - + ]: 8632657 : assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
754 [ - + ]: 8632657 : assert(it->GetModFeesWithAncestors() == nFeesCheck);
755 : : // Sanity check: we are walking in ascending ancestor count order.
756 [ - + ]: 8632657 : assert(prev_ancestor_count <= it->GetCountWithAncestors());
757 : 8632657 : prev_ancestor_count = it->GetCountWithAncestors();
758 : :
759 : : // Check children against mapNextTx
760 : 8632657 : CTxMemPoolEntry::Children setChildrenCheck;
761 : 8632657 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
762 : 8632657 : int32_t child_sizes{0};
763 [ + + + + ]: 8804415 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
764 [ + - ]: 171758 : txiter childit = mapTx.find(iter->second->GetHash());
765 [ - + ]: 171758 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
766 [ + - + + ]: 171758 : if (setChildrenCheck.insert(*childit).second) {
767 [ + - ]: 171544 : child_sizes += childit->GetTxSize();
768 : : }
769 : : }
770 [ - + ]: 8632657 : assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
771 [ - + ]: 8632657 : assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), it->GetMemPoolChildrenConst().begin(), comp));
772 : : // Also check to make sure size is greater than sum with immediate children.
773 : : // just a sanity check, not definitive that this calc is correct...
774 [ + - - + ]: 8632657 : assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
775 : :
776 [ - + ]: 8632657 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
777 : 8632657 : CAmount txfee = 0;
778 [ - + ]: 8632657 : assert(!tx.IsCoinBase());
779 [ + - - + ]: 8632657 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
780 [ + - + + ]: 19771760 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
781 [ + - ]: 8632657 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
782 : 8632657 : }
783 [ + - + + ]: 11291195 : for (const auto& [_, next_tx] : mapNextTx) {
784 [ + - ]: 11139103 : auto it = mapTx.find(next_tx->GetHash());
785 [ - + ]: 11139103 : const CTransaction& tx = it->GetTx();
786 [ - + ]: 11139103 : assert(it != mapTx.end());
787 [ - + ]: 11139103 : assert(&tx == next_tx);
788 : : }
789 : :
790 [ - + ]: 152092 : assert(totalTxSize == checkTotal);
791 [ - + ]: 152092 : assert(m_total_fee == check_total_fee);
792 [ - + ]: 152092 : assert(innerUsage == cachedInnerUsage);
793 [ + - ]: 304184 : }
794 : :
795 : 26752 : bool CTxMemPool::CompareDepthAndScore(const Wtxid& hasha, const Wtxid& hashb) const
796 : : {
797 : : /* Return `true` if hasha should be considered sooner than hashb. Namely when:
798 : : * a is not in the mempool, but b is
799 : : * both are in the mempool and a has fewer ancestors than b
800 : : * both are in the mempool and a has a higher score than b
801 : : */
802 : 26752 : LOCK(cs);
803 [ + - ]: 26752 : auto j{GetIter(hashb)};
804 [ + + ]: 26752 : if (!j.has_value()) return false;
805 [ + - ]: 23554 : auto i{GetIter(hasha)};
806 [ + + ]: 23554 : if (!i.has_value()) return true;
807 [ + + ]: 23043 : uint64_t counta = i.value()->GetCountWithAncestors();
808 : 23043 : uint64_t countb = j.value()->GetCountWithAncestors();
809 [ + + ]: 23043 : if (counta == countb) {
810 [ + - ]: 21581 : return CompareTxMemPoolEntryByScore()(*i.value(), *j.value());
811 : : }
812 : 1462 : return counta < countb;
813 : 26752 : }
814 : :
815 : : namespace {
816 : : class DepthAndScoreComparator
817 : : {
818 : : public:
819 : 98964394 : bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
820 : : {
821 [ + + ]: 98964394 : uint64_t counta = a->GetCountWithAncestors();
822 : 98964394 : uint64_t countb = b->GetCountWithAncestors();
823 [ + + ]: 98964394 : if (counta == countb) {
824 : 98504863 : return CompareTxMemPoolEntryByScore()(*a, *b);
825 : : }
826 : 459531 : return counta < countb;
827 : : }
828 : : };
829 : : } // namespace
830 : :
831 : 160971 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
832 : : {
833 : 160971 : std::vector<indexed_transaction_set::const_iterator> iters;
834 : 160971 : AssertLockHeld(cs);
835 : :
836 [ + - ]: 160971 : iters.reserve(mapTx.size());
837 : :
838 [ + + + + ]: 17855839 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
839 [ + - ]: 8847434 : iters.push_back(mi);
840 : : }
841 [ + - ]: 160971 : std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
842 : 160971 : return iters;
843 : 0 : }
844 : :
845 : 7975 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
846 : : {
847 : 7975 : AssertLockHeld(cs);
848 : :
849 : 7975 : std::vector<CTxMemPoolEntryRef> ret;
850 [ + - ]: 7975 : ret.reserve(mapTx.size());
851 [ + - + + ]: 221124 : for (const auto& it : GetSortedDepthAndScore()) {
852 [ + - ]: 213149 : ret.emplace_back(*it);
853 : : }
854 : 7975 : return ret;
855 : 0 : }
856 : :
857 : 904 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
858 : : {
859 : 904 : LOCK(cs);
860 [ + - ]: 904 : auto iters = GetSortedDepthAndScore();
861 : :
862 : 904 : std::vector<TxMempoolInfo> ret;
863 [ + - ]: 904 : ret.reserve(mapTx.size());
864 [ + + ]: 2532 : for (auto it : iters) {
865 [ + - - + ]: 3256 : ret.push_back(GetInfo(it));
866 : : }
867 : :
868 : 904 : return ret;
869 [ + - ]: 1808 : }
870 : :
871 : 46381 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
872 : : {
873 : 46381 : AssertLockHeld(cs);
874 : 46381 : const auto i = mapTx.find(txid);
875 [ + + ]: 46381 : return i == mapTx.end() ? nullptr : &(*i);
876 : : }
877 : :
878 : 217775 : CTransactionRef CTxMemPool::get(const Txid& hash) const
879 : : {
880 : 217775 : LOCK(cs);
881 [ + - ]: 217775 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
882 [ + + ]: 217775 : if (i == mapTx.end())
883 : 152167 : return nullptr;
884 [ + - + - ]: 283383 : return i->GetSharedTx();
885 : 217775 : }
886 : :
887 : 767 : void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
888 : : {
889 : 767 : {
890 : 767 : LOCK(cs);
891 [ + - ]: 767 : CAmount &delta = mapDeltas[hash];
892 : 767 : delta = SaturatingAdd(delta, nFeeDelta);
893 [ + - ]: 767 : txiter it = mapTx.find(hash);
894 [ + + ]: 767 : if (it != mapTx.end()) {
895 [ + - ]: 522 : mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
896 : : // Now update all ancestors' modified fees with descendants
897 [ + - ]: 261 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
898 [ + + ]: 295 : for (txiter ancestorIt : ancestors) {
899 [ + - + - ]: 102 : mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
900 : : }
901 : : // Now update all descendants' modified fees with ancestors
902 [ + - ]: 261 : setEntries setDescendants;
903 [ + - ]: 261 : CalculateDescendants(it, setDescendants);
904 : 261 : setDescendants.erase(it);
905 [ + + ]: 316 : for (txiter descendantIt : setDescendants) {
906 [ + - ]: 165 : mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
907 : : }
908 : 261 : ++nTransactionsUpdated;
909 : 261 : }
910 [ + + ]: 767 : if (delta == 0) {
911 : 9 : mapDeltas.erase(hash);
912 [ + + + - : 25 : LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
+ - ]
913 : : } else {
914 [ + - + - : 1770 : LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
+ + + - +
- ]
915 : : hash.ToString(),
916 : : it == mapTx.end() ? "not " : "",
917 : : FormatMoney(nFeeDelta),
918 : : FormatMoney(delta));
919 : : }
920 : 767 : }
921 : 767 : }
922 : :
923 : 58839 : void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
924 : : {
925 : 58839 : AssertLockHeld(cs);
926 : 58839 : std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
927 [ + + ]: 58839 : if (pos == mapDeltas.end())
928 : : return;
929 : 38 : const CAmount &delta = pos->second;
930 : 38 : nFeeDelta += delta;
931 : : }
932 : :
933 : 55745 : void CTxMemPool::ClearPrioritisation(const Txid& hash)
934 : : {
935 : 55745 : AssertLockHeld(cs);
936 : 55745 : mapDeltas.erase(hash);
937 : 55745 : }
938 : :
939 : 28 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
940 : : {
941 : 28 : AssertLockNotHeld(cs);
942 : 28 : LOCK(cs);
943 : 28 : std::vector<delta_info> result;
944 [ + - ]: 28 : result.reserve(mapDeltas.size());
945 [ + - + + ]: 56 : for (const auto& [txid, delta] : mapDeltas) {
946 [ + - ]: 28 : const auto iter{mapTx.find(txid)};
947 [ + + ]: 28 : const bool in_mempool{iter != mapTx.end()};
948 : 28 : std::optional<CAmount> modified_fee;
949 [ + + ]: 28 : if (in_mempool) modified_fee = iter->GetModifiedFee();
950 [ + - ]: 28 : result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
951 : : }
952 [ + - ]: 28 : return result;
953 : 28 : }
954 : :
955 : 114452 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
956 : : {
957 : 114452 : const auto it = mapNextTx.find(prevout);
958 [ + + ]: 114452 : return it == mapNextTx.end() ? nullptr : it->second;
959 : : }
960 : :
961 : 11374894 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
962 : : {
963 : 11374894 : AssertLockHeld(cs);
964 : 11374894 : auto it = mapTx.find(txid);
965 [ + + ]: 11374894 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
966 : : }
967 : :
968 : 82003 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
969 : : {
970 : 82003 : AssertLockHeld(cs);
971 [ + + ]: 82003 : auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
972 [ + + ]: 82003 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
973 : : }
974 : :
975 : 81950 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
976 : : {
977 : 81950 : CTxMemPool::setEntries ret;
978 [ + + ]: 150400 : for (const auto& h : hashes) {
979 [ + - ]: 68450 : const auto mi = GetIter(h);
980 [ + + + - ]: 68450 : if (mi) ret.insert(*mi);
981 : : }
982 : 81950 : return ret;
983 : 0 : }
984 : :
985 : 3053 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
986 : : {
987 : 3053 : AssertLockHeld(cs);
988 : 3053 : std::vector<txiter> ret;
989 [ - + + - ]: 3053 : ret.reserve(txids.size());
990 [ + + ]: 52707 : for (const auto& txid : txids) {
991 [ + - ]: 49654 : const auto it{GetIter(txid)};
992 [ - + ]: 49654 : if (!it) return {};
993 [ + - ]: 49654 : ret.push_back(*it);
994 : : }
995 : 3053 : return ret;
996 : 3053 : }
997 : :
998 : 23345 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
999 : : {
1000 [ - + + + ]: 56260 : for (unsigned int i = 0; i < tx.vin.size(); i++)
1001 [ + + ]: 36213 : if (exists(tx.vin[i].prevout.hash))
1002 : : return false;
1003 : : return true;
1004 : : }
1005 : :
1006 [ + - + - ]: 39159 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1007 : :
1008 : 67873 : std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
1009 : : {
1010 : : // Check to see if the inputs are made available by another tx in the package.
1011 : : // These Coins would not be available in the underlying CoinsView.
1012 [ + + ]: 67873 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
1013 : 613 : return it->second;
1014 : : }
1015 : :
1016 : : // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1017 : : // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1018 : : // transactions. First checking the underlying cache risks returning a pruned entry instead.
1019 : 67260 : CTransactionRef ptx = mempool.get(outpoint.hash);
1020 [ + + ]: 67260 : if (ptx) {
1021 [ - + + - ]: 11490 : if (outpoint.n < ptx->vout.size()) {
1022 : 11490 : Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
1023 [ + - ]: 11490 : m_non_base_coins.emplace(outpoint);
1024 : 11490 : return coin;
1025 : 11490 : }
1026 : 0 : return std::nullopt;
1027 : : }
1028 [ + - ]: 55770 : return base->GetCoin(outpoint);
1029 : 67260 : }
1030 : :
1031 : 775 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
1032 : : {
1033 [ - + + + ]: 1584 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
1034 [ + - ]: 809 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
1035 : 809 : m_non_base_coins.emplace(tx->GetHash(), n);
1036 : : }
1037 : 775 : }
1038 : 23049 : void CCoinsViewMemPool::Reset()
1039 : : {
1040 : 23049 : m_temp_added.clear();
1041 : 23049 : m_non_base_coins.clear();
1042 : 23049 : }
1043 : :
1044 : 517090 : size_t CTxMemPool::DynamicMemoryUsage() const {
1045 : 517090 : LOCK(cs);
1046 : : // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1047 [ - + + - ]: 1034180 : return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
1048 : 517090 : }
1049 : :
1050 : 58509 : void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
1051 : 58509 : LOCK(cs);
1052 : :
1053 [ + + ]: 58509 : if (m_unbroadcast_txids.erase(txid))
1054 : : {
1055 [ + - + - : 26748 : LogDebug(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
+ + + - +
- ]
1056 : : }
1057 : 58509 : }
1058 : :
1059 : 142292 : void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1060 : 142292 : AssertLockHeld(cs);
1061 : 142292 : UpdateForRemoveFromMempool(stage, updateDescendants);
1062 [ + + ]: 188339 : for (txiter it : stage) {
1063 : 46047 : removeUnchecked(it, reason);
1064 : : }
1065 : 142292 : }
1066 : :
1067 : 25691 : int CTxMemPool::Expire(std::chrono::seconds time)
1068 : : {
1069 : 25691 : AssertLockHeld(cs);
1070 : 25691 : Assume(!m_have_changeset);
1071 : 25691 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1072 : 25691 : setEntries toremove;
1073 [ + + + + ]: 25695 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1074 [ + - ]: 4 : toremove.insert(mapTx.project<0>(it));
1075 : 4 : it++;
1076 : : }
1077 : 25691 : setEntries stage;
1078 [ + + ]: 25695 : for (txiter removeit : toremove) {
1079 [ + - ]: 4 : CalculateDescendants(removeit, stage);
1080 : : }
1081 [ + - ]: 25691 : RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
1082 : 25691 : return stage.size();
1083 : 25691 : }
1084 : :
1085 : 12895 : void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1086 : : {
1087 : 12895 : AssertLockHeld(cs);
1088 [ + + ]: 12895 : CTxMemPoolEntry::Children s;
1089 [ + + + - : 12895 : if (add && entry->GetMemPoolChildren().insert(*child).second) {
+ - ]
1090 : 12302 : cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1091 [ + - + - ]: 593 : } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
1092 : 593 : cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1093 : : }
1094 : 12895 : }
1095 : :
1096 : 20749 : void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1097 : : {
1098 : 20749 : AssertLockHeld(cs);
1099 [ + + ]: 20749 : CTxMemPoolEntry::Parents s;
1100 [ + + + - : 20749 : if (add && entry->GetMemPoolParents().insert(*parent).second) {
+ - ]
1101 : 12302 : cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1102 [ + - + - ]: 8447 : } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
1103 : 8447 : cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1104 : : }
1105 : 20749 : }
1106 : :
1107 : 463600 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1108 : 463600 : LOCK(cs);
1109 [ + + + + ]: 463600 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1110 : 463551 : return CFeeRate(llround(rollingMinimumFeeRate));
1111 : :
1112 [ + - ]: 49 : int64_t time = GetTime();
1113 [ + + ]: 49 : if (time > lastRollingFeeUpdate + 10) {
1114 : 6 : double halflife = ROLLING_FEE_HALFLIFE;
1115 [ + - + + ]: 6 : if (DynamicMemoryUsage() < sizelimit / 4)
1116 : : halflife /= 4;
1117 [ + - + + ]: 5 : else if (DynamicMemoryUsage() < sizelimit / 2)
1118 : 1 : halflife /= 2;
1119 : :
1120 : 6 : rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1121 : 6 : lastRollingFeeUpdate = time;
1122 : :
1123 [ + + ]: 6 : if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
1124 : 1 : rollingMinimumFeeRate = 0;
1125 : 1 : return CFeeRate(0);
1126 : : }
1127 : : }
1128 : 48 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
1129 : 463600 : }
1130 : :
1131 : 57 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1132 : 57 : AssertLockHeld(cs);
1133 [ + + ]: 57 : if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1134 : 55 : rollingMinimumFeeRate = rate.GetFeePerK();
1135 : 55 : blockSinceLastRollingFeeBump = false;
1136 : : }
1137 : 57 : }
1138 : :
1139 : 25700 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1140 : 25700 : AssertLockHeld(cs);
1141 : 25700 : Assume(!m_have_changeset);
1142 : :
1143 : 25700 : unsigned nTxnRemoved = 0;
1144 : 25700 : CFeeRate maxFeeRateRemoved(0);
1145 [ + + + + ]: 25757 : while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1146 : 57 : indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1147 : :
1148 : : // We set the new mempool min fee to the feerate of the removed set, plus the
1149 : : // "minimum reasonable fee rate" (ie some value under which we consider txn
1150 : : // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1151 : : // equal to txn which were removed with no block in between.
1152 : 57 : CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1153 : 57 : removed += m_opts.incremental_relay_feerate;
1154 : 57 : trackPackageRemoved(removed);
1155 : 57 : maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1156 : :
1157 [ + - ]: 57 : setEntries stage;
1158 [ + - ]: 57 : CalculateDescendants(mapTx.project<0>(it), stage);
1159 [ + + ]: 57 : nTxnRemoved += stage.size();
1160 : :
1161 : 57 : std::vector<CTransaction> txn;
1162 [ + + ]: 57 : if (pvNoSpendsRemaining) {
1163 [ + - ]: 49 : txn.reserve(stage.size());
1164 [ + + ]: 99 : for (txiter iter : stage)
1165 [ + - ]: 50 : txn.push_back(iter->GetTx());
1166 : : }
1167 [ + - ]: 57 : RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1168 [ + + ]: 57 : if (pvNoSpendsRemaining) {
1169 [ + + ]: 99 : for (const CTransaction& tx : txn) {
1170 [ + + ]: 100 : for (const CTxIn& txin : tx.vin) {
1171 [ + - + + ]: 50 : if (exists(txin.prevout.hash)) continue;
1172 [ + - ]: 49 : pvNoSpendsRemaining->push_back(txin.prevout);
1173 : : }
1174 : : }
1175 : : }
1176 : 57 : }
1177 : :
1178 [ + + ]: 25700 : if (maxFeeRateRemoved > CFeeRate(0)) {
1179 [ + - + - ]: 90 : LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1180 : : }
1181 : 25700 : }
1182 : :
1183 : 47254 : uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const {
1184 : : // find parent with highest descendant count
1185 : 47254 : std::vector<txiter> candidates;
1186 [ + - ]: 47254 : setEntries counted;
1187 [ + - ]: 47254 : candidates.push_back(entry);
1188 : 47254 : uint64_t maximum = 0;
1189 [ - + + + ]: 112441 : while (candidates.size()) {
1190 : 65187 : txiter candidate = candidates.back();
1191 [ + - ]: 65187 : candidates.pop_back();
1192 [ + - + + ]: 65187 : if (!counted.insert(candidate).second) continue;
1193 [ + + ]: 65178 : const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst();
1194 [ + + ]: 65178 : if (parents.size() == 0) {
1195 [ + + ]: 47811 : maximum = std::max(maximum, candidate->GetCountWithDescendants());
1196 : : } else {
1197 [ + - + + ]: 35568 : for (const CTxMemPoolEntry& i : parents) {
1198 [ + - ]: 17933 : candidates.push_back(mapTx.iterator_to(i));
1199 : : }
1200 : : }
1201 : : }
1202 : 47254 : return maximum;
1203 : 47254 : }
1204 : :
1205 : 578820 : void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
1206 : 578820 : LOCK(cs);
1207 [ + - ]: 578820 : auto it = mapTx.find(txid);
1208 : 578820 : ancestors = descendants = 0;
1209 [ + + ]: 578820 : if (it != mapTx.end()) {
1210 [ + + ]: 47254 : ancestors = it->GetCountWithAncestors();
1211 [ + + ]: 47254 : if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
1212 [ + + ]: 47254 : if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
1213 [ + - ]: 47254 : descendants = CalculateDescendantMaximum(it);
1214 : : }
1215 : 578820 : }
1216 : :
1217 : 2263 : bool CTxMemPool::GetLoadTried() const
1218 : : {
1219 : 2263 : LOCK(cs);
1220 [ + - ]: 2263 : return m_load_tried;
1221 : 2263 : }
1222 : :
1223 : 985 : void CTxMemPool::SetLoadTried(bool load_tried)
1224 : : {
1225 : 985 : LOCK(cs);
1226 [ + - ]: 985 : m_load_tried = load_tried;
1227 : 985 : }
1228 : :
1229 : 3051 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
1230 : : {
1231 : 3051 : AssertLockHeld(cs);
1232 : 3051 : std::vector<txiter> clustered_txs{GetIterVec(txids)};
1233 : : // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not
1234 : : // necessarily mean the entry has been processed.
1235 : 3051 : WITH_FRESH_EPOCH(m_epoch);
1236 [ + + ]: 52106 : for (const auto& it : clustered_txs) {
1237 : 49055 : visited(it);
1238 : : }
1239 : : // i = index of where the list of entries to process starts
1240 [ - + + + ]: 72803 : for (size_t i{0}; i < clustered_txs.size(); ++i) {
1241 : : // DoS protection: if there are 500 or more entries to process, just quit.
1242 [ + + ]: 69753 : if (clustered_txs.size() > 500) return {};
1243 [ + - ]: 69752 : const txiter& tx_iter = clustered_txs.at(i);
1244 [ + - + - : 348760 : for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
+ + - - ]
1245 [ + + ]: 181221 : for (const CTxMemPoolEntry& entry : entries) {
1246 : 41717 : const auto entry_it = mapTx.iterator_to(entry);
1247 [ + + ]: 41717 : if (!visited(entry_it)) {
1248 [ - + ]: 20698 : clustered_txs.push_back(entry_it);
1249 : : }
1250 : : }
1251 [ + + - - ]: 209256 : }
1252 : : }
1253 : 3050 : return clustered_txs;
1254 : 3051 : }
1255 : :
1256 : 46 : std::optional<std::string> CTxMemPool::CheckConflictTopology(const setEntries& direct_conflicts)
1257 : : {
1258 [ + + ]: 197 : for (const auto& direct_conflict : direct_conflicts) {
1259 : : // Ancestor and descendant counts are inclusive of the tx itself.
1260 [ + - ]: 171 : const auto ancestor_count{direct_conflict->GetCountWithAncestors()};
1261 [ + - ]: 171 : const auto descendant_count{direct_conflict->GetCountWithDescendants()};
1262 : 171 : const bool has_ancestor{ancestor_count > 1};
1263 : 171 : const bool has_descendant{descendant_count > 1};
1264 [ + - + - : 342 : const auto& txid_string{direct_conflict->GetSharedTx()->GetHash().ToString()};
+ - ]
1265 : : // The only allowed configurations are:
1266 : : // 1 ancestor and 0 descendant
1267 : : // 0 ancestor and 1 descendant
1268 : : // 0 ancestor and 0 descendant
1269 [ + + ]: 171 : if (ancestor_count > 2) {
1270 [ + - ]: 10 : return strprintf("%s has %u ancestors, max 1 allowed", txid_string, ancestor_count - 1);
1271 [ + + ]: 166 : } else if (descendant_count > 2) {
1272 [ + - ]: 10 : return strprintf("%s has %u descendants, max 1 allowed", txid_string, descendant_count - 1);
1273 [ + + ]: 161 : } else if (has_ancestor && has_descendant) {
1274 [ + - ]: 4 : return strprintf("%s has both ancestor and descendant, exceeding cluster limit of 2", txid_string);
1275 : : }
1276 : : // Additionally enforce that:
1277 : : // If we have a child, we are its only parent.
1278 : : // If we have a parent, we are its only child.
1279 [ + + ]: 159 : if (has_descendant) {
1280 [ + + ]: 74 : const auto& our_child = direct_conflict->GetMemPoolChildrenConst().begin();
1281 [ + + ]: 74 : if (our_child->get().GetCountWithAncestors() > 2) {
1282 [ + - ]: 6 : return strprintf("%s is not the only parent of child %s",
1283 [ + - + - : 15 : txid_string, our_child->get().GetSharedTx()->GetHash().ToString());
+ - + - ]
1284 : : }
1285 [ + + ]: 85 : } else if (has_ancestor) {
1286 [ + + ]: 72 : const auto& our_parent = direct_conflict->GetMemPoolParentsConst().begin();
1287 [ + + ]: 72 : if (our_parent->get().GetCountWithDescendants() > 2) {
1288 [ + - ]: 10 : return strprintf("%s is not the only child of parent %s",
1289 [ + - + - : 25 : txid_string, our_parent->get().GetSharedTx()->GetHash().ToString());
+ - + - ]
1290 : : }
1291 : : }
1292 : 171 : }
1293 : 26 : return std::nullopt;
1294 : : }
1295 : :
1296 : 33 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1297 : : {
1298 : 33 : LOCK(m_pool->cs);
1299 : 33 : FeeFrac replacement_feerate{0, 0};
1300 [ + + ]: 90 : for (auto it : m_entry_vec) {
1301 [ + - ]: 57 : replacement_feerate += {it->GetModifiedFee(), it->GetTxSize()};
1302 : : }
1303 : :
1304 [ + - ]: 33 : auto err_string{m_pool->CheckConflictTopology(m_to_remove)};
1305 [ + + ]: 33 : if (err_string.has_value()) {
1306 : : // Unsupported topology for calculating a feerate diagram
1307 [ - + + - ]: 48 : return util::Error{Untranslated(err_string.value())};
1308 : : }
1309 : :
1310 : : // new diagram will have chunks that consist of each ancestor of
1311 : : // direct_conflicts that is at its own fee/size, along with the replacement
1312 : : // tx/package at its own fee/size
1313 : :
1314 : : // old diagram will consist of the ancestors and descendants of each element of
1315 : : // all_conflicts. every such transaction will either be at its own feerate (followed
1316 : : // by any descendant at its own feerate), or as a single chunk at the descendant's
1317 : : // ancestor feerate.
1318 : :
1319 : 21 : std::vector<FeeFrac> old_chunks;
1320 : : // Step 1: build the old diagram.
1321 : :
1322 : : // The above clusters are all trivially linearized;
1323 : : // they have a strict topology of 1 or two connected transactions.
1324 : :
1325 : : // OLD: Compute existing chunks from all affected clusters
1326 [ + + ]: 160 : for (auto txiter : m_to_remove) {
1327 : : // Does this transaction have descendants?
1328 [ + + ]: 139 : if (txiter->GetCountWithDescendants() > 1) {
1329 : : // Consider this tx when we consider the descendant.
1330 : 65 : continue;
1331 : : }
1332 : : // Does this transaction have ancestors?
1333 [ + - + + ]: 74 : FeeFrac individual{txiter->GetModifiedFee(), txiter->GetTxSize()};
1334 [ + + ]: 74 : if (txiter->GetCountWithAncestors() > 1) {
1335 : : // We'll add chunks for either the ancestor by itself and this tx
1336 : : // by itself, or for a combined package.
1337 [ + + ]: 66 : FeeFrac package{txiter->GetModFeesWithAncestors(), static_cast<int32_t>(txiter->GetSizeWithAncestors())};
1338 [ + + ]: 66 : if (individual >> package) {
1339 : : // The individual feerate is higher than the package, and
1340 : : // therefore higher than the parent's fee. Chunk these
1341 : : // together.
1342 [ + - ]: 8 : old_chunks.emplace_back(package);
1343 : : } else {
1344 : : // Add two points, one for the parent and one for this child.
1345 [ + - ]: 58 : old_chunks.emplace_back(package - individual);
1346 [ + - ]: 58 : old_chunks.emplace_back(individual);
1347 : : }
1348 : : } else {
1349 [ + - ]: 8 : old_chunks.emplace_back(individual);
1350 : : }
1351 : : }
1352 : :
1353 : : // No topology restrictions post-chunking; sort
1354 : 21 : std::sort(old_chunks.begin(), old_chunks.end(), std::greater());
1355 : :
1356 : 21 : std::vector<FeeFrac> new_chunks;
1357 : :
1358 : : /* Step 2: build the NEW diagram
1359 : : * CON = Conflicts of proposed chunk
1360 : : * CNK = Proposed chunk
1361 : : * NEW = OLD - CON + CNK: New diagram includes all chunks in OLD, minus
1362 : : * the conflicts, plus the proposed chunk
1363 : : */
1364 : :
1365 : : // OLD - CON: Add any parents of direct conflicts that are not conflicted themselves
1366 [ + + ]: 160 : for (auto direct_conflict : m_to_remove) {
1367 : : // If a direct conflict has an ancestor that is not in all_conflicts,
1368 : : // it can be affected by the replacement of the child.
1369 [ + + ]: 139 : if (direct_conflict->GetMemPoolParentsConst().size() > 0) {
1370 : : // Grab the parent.
1371 : 66 : const CTxMemPoolEntry& parent = direct_conflict->GetMemPoolParentsConst().begin()->get();
1372 [ + + ]: 66 : if (!m_to_remove.contains(m_pool->mapTx.iterator_to(parent))) {
1373 : : // This transaction would be left over, so add to the NEW
1374 : : // diagram.
1375 [ + - + - ]: 1 : new_chunks.emplace_back(parent.GetModifiedFee(), parent.GetTxSize());
1376 : : }
1377 : : }
1378 : : }
1379 : : // + CNK: Add the proposed chunk itself
1380 [ + - ]: 21 : new_chunks.emplace_back(replacement_feerate);
1381 : :
1382 : : // No topology restrictions post-chunking; sort
1383 : 21 : std::sort(new_chunks.begin(), new_chunks.end(), std::greater());
1384 [ + - ]: 42 : return std::make_pair(old_chunks, new_chunks);
1385 [ + - ]: 87 : }
1386 : :
1387 : 58839 : CTxMemPool::ChangeSet::TxHandle CTxMemPool::ChangeSet::StageAddition(const CTransactionRef& tx, const CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp)
1388 : : {
1389 : 58839 : LOCK(m_pool->cs);
1390 [ + - ]: 58839 : Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1391 [ + - ]: 58839 : auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1392 : 58839 : CAmount delta{0};
1393 [ + - ]: 58839 : m_pool->ApplyDelta(tx->GetHash(), delta);
1394 [ + + + - ]: 58877 : if (delta) m_to_add.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
1395 : :
1396 [ + - ]: 58839 : m_entry_vec.push_back(newit);
1397 [ + - ]: 58839 : return newit;
1398 : 58839 : }
1399 : :
1400 : 50872 : void CTxMemPool::ChangeSet::Apply()
1401 : : {
1402 : 50872 : LOCK(m_pool->cs);
1403 [ + - ]: 50872 : m_pool->Apply(this);
1404 : 50872 : m_to_add.clear();
1405 : 50872 : m_to_remove.clear();
1406 [ + - ]: 50872 : m_entry_vec.clear();
1407 [ + - ]: 50872 : m_ancestors.clear();
1408 : 50872 : }
|