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 : 0 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41 : : {
42 : 0 : 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 [ # # ]: 0 : 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 [ # # ]: 0 : if (!active_chain.Contains(lp.maxInputBlock)) {
49 : 0 : return false;
50 : : }
51 : : }
52 : :
53 : : // LockPoints still valid
54 : : return true;
55 : : }
56 : :
57 : 0 : void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
58 : : const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove)
59 : : {
60 [ # # ]: 0 : CTxMemPoolEntry::Children stageEntries, descendants;
61 [ # # ]: 0 : stageEntries = updateIt->GetMemPoolChildrenConst();
62 : :
63 [ # # ]: 0 : while (!stageEntries.empty()) {
64 [ # # ]: 0 : const CTxMemPoolEntry& descendant = *stageEntries.begin();
65 [ # # ]: 0 : descendants.insert(descendant);
66 : 0 : stageEntries.erase(descendant);
67 : 0 : const CTxMemPoolEntry::Children& children = descendant.GetMemPoolChildrenConst();
68 [ # # ]: 0 : for (const CTxMemPoolEntry& childEntry : children) {
69 : 0 : cacheMap::iterator cacheIt = cachedDescendants.find(mapTx.iterator_to(childEntry));
70 [ # # ]: 0 : 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 [ # # ]: 0 : for (txiter cacheEntry : cacheIt->second) {
74 [ # # ]: 0 : descendants.insert(*cacheEntry);
75 : : }
76 [ # # ]: 0 : } else if (!descendants.count(childEntry)) {
77 : : // Schedule for later processing
78 [ # # ]: 0 : 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 : 0 : int32_t modifySize = 0;
85 : 0 : CAmount modifyFee = 0;
86 : 0 : int64_t modifyCount = 0;
87 [ # # ]: 0 : for (const CTxMemPoolEntry& descendant : descendants) {
88 [ # # ]: 0 : if (!setExclude.count(descendant.GetTx().GetHash())) {
89 [ # # ]: 0 : modifySize += descendant.GetTxSize();
90 [ # # ]: 0 : modifyFee += descendant.GetModifiedFee();
91 : 0 : modifyCount++;
92 [ # # # # ]: 0 : cachedDescendants[updateIt].insert(mapTx.iterator_to(descendant));
93 : : // Update ancestor state for each descendant
94 [ # # ]: 0 : mapTx.modify(mapTx.iterator_to(descendant), [=](CTxMemPoolEntry& e) {
95 : 0 : e.UpdateAncestorState(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost());
96 : 0 : });
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 [ # # # # ]: 0 : 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 [ # # ]: 0 : mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); });
106 : 0 : }
107 : :
108 : 0 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate)
109 : : {
110 : 0 : 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 [ # # ]: 0 : 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 [ # # ]: 0 : std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
119 : :
120 : 0 : std::set<uint256> 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 [ # # ]: 0 : for (const uint256& hash : vHashesToUpdate | std::views::reverse) {
128 : : // calculate children from mapNextTx
129 [ # # ]: 0 : txiter it = mapTx.find(hash);
130 [ # # ]: 0 : if (it == mapTx.end()) {
131 : 0 : continue;
132 : : }
133 : 0 : auto iter = mapNextTx.lower_bound(COutPoint(Txid::FromUint256(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 : 0 : {
138 : 0 : WITH_FRESH_EPOCH(m_epoch);
139 [ # # # # ]: 0 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
140 [ # # ]: 0 : const uint256 &childHash = iter->second->GetHash();
141 [ # # ]: 0 : txiter childIter = mapTx.find(childHash);
142 [ # # ]: 0 : 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 [ # # # # ]: 0 : if (!visited(childIter) && !setAlreadyIncluded.count(childHash)) {
146 [ # # ]: 0 : UpdateChild(it, childIter, true);
147 [ # # ]: 0 : UpdateParent(childIter, it, true);
148 : : }
149 : : }
150 : 0 : } // release epoch guard for UpdateForDescendants
151 [ # # ]: 0 : UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded, descendants_to_remove);
152 : : }
153 : :
154 [ # # ]: 0 : 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::FromUint256(txid))) {
158 [ # # ]: 0 : removeRecursive((*txiter)->GetTx(), MemPoolRemovalReason::SIZELIMIT);
159 : : }
160 : : }
161 : 0 : }
162 : :
163 : 4064058 : 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 : 4064058 : int64_t totalSizeWithAncestors = entry_size;
170 : 4064058 : setEntries ancestors;
171 : :
172 [ + + ]: 26284893 : while (!staged_ancestors.empty()) {
173 [ + - ]: 22240385 : const CTxMemPoolEntry& stage = staged_ancestors.begin()->get();
174 : 22240385 : txiter stageit = mapTx.iterator_to(stage);
175 : :
176 [ + - ]: 22240385 : ancestors.insert(stageit);
177 : 22240385 : staged_ancestors.erase(stage);
178 [ + - ]: 22240385 : totalSizeWithAncestors += stageit->GetTxSize();
179 : :
180 [ + + ]: 22240385 : if (stageit->GetSizeWithDescendants() + entry_size > limits.descendant_size_vbytes) {
181 [ + - + - : 20016 : return util::Error{Untranslated(strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_size_vbytes))};
+ - ]
182 [ + + ]: 22233713 : } else if (stageit->GetCountWithDescendants() + entry_count > static_cast<uint64_t>(limits.descendant_count)) {
183 [ + - + - : 18087 : return util::Error{Untranslated(strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_count))};
+ - ]
184 [ + + ]: 22227684 : } else if (totalSizeWithAncestors > limits.ancestor_size_vbytes) {
185 [ + - + - ]: 12147 : return util::Error{Untranslated(strprintf("exceeds ancestor size limit [limit: %u]", limits.ancestor_size_vbytes))};
186 : : }
187 : :
188 : 22223635 : const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst();
189 [ + + ]: 51708987 : for (const CTxMemPoolEntry& parent : parents) {
190 : 29488152 : txiter parent_it = mapTx.iterator_to(parent);
191 : :
192 : : // If this is a new ancestor, add it.
193 [ + + ]: 29488152 : if (ancestors.count(parent_it) == 0) {
194 [ + - ]: 22971517 : staged_ancestors.insert(parent);
195 : : }
196 [ + + ]: 29488152 : if (staged_ancestors.size() + ancestors.size() + entry_count > static_cast<uint64_t>(limits.ancestor_count)) {
197 [ + - + - ]: 8400 : return util::Error{Untranslated(strprintf("too many unconfirmed ancestors [limit: %u]", limits.ancestor_count))};
198 : : }
199 : : }
200 : : }
201 : :
202 : 4044508 : return ancestors;
203 : 4064058 : }
204 : :
205 : 40273 : util::Result<void> CTxMemPool::CheckPackageLimits(const Package& package,
206 : : const int64_t total_vsize) const
207 : : {
208 [ + + ]: 40273 : size_t pack_count = package.size();
209 : :
210 : : // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist
211 [ + + ]: 40273 : if (pack_count > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
212 [ + - ]: 1122 : return util::Error{Untranslated(strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_opts.limits.ancestor_count))};
213 [ + + ]: 39899 : } else if (pack_count > static_cast<uint64_t>(m_opts.limits.descendant_count)) {
214 [ + - ]: 870 : return util::Error{Untranslated(strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_opts.limits.descendant_count))};
215 [ + + ]: 39609 : } else if (total_vsize > m_opts.limits.ancestor_size_vbytes) {
216 [ + - ]: 1356 : return util::Error{Untranslated(strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_opts.limits.ancestor_size_vbytes))};
217 [ + + ]: 39157 : } else if (total_vsize > m_opts.limits.descendant_size_vbytes) {
218 [ + - ]: 1203 : 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 : 38756 : CTxMemPoolEntry::Parents staged_ancestors;
222 [ + + ]: 123562 : for (const auto& tx : package) {
223 [ + + ]: 303052 : for (const auto& input : tx->vin) {
224 [ + - ]: 218246 : std::optional<txiter> piter = GetIter(input.prevout.hash);
225 [ + + ]: 218246 : if (piter) {
226 [ + - ]: 42667 : staged_ancestors.insert(**piter);
227 [ + + ]: 42667 : if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
228 [ + - + - ]: 417 : 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 : 38617 : const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(),
237 [ + - ]: 38617 : staged_ancestors, m_opts.limits)};
238 : : // It's possible to overestimate the ancestor/descendant totals.
239 [ + + + - : 39433 : if (!ancestors.has_value()) return util::Error{Untranslated("possibly " + util::ErrorString(ancestors).original)};
+ - + - ]
240 : 38345 : return {};
241 : 77373 : }
242 : :
243 : 4052274 : util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateMemPoolAncestors(
244 : : const CTxMemPoolEntry &entry,
245 : : const Limits& limits,
246 : : bool fSearchForParents /* = true */) const
247 : : {
248 [ + + ]: 4052274 : CTxMemPoolEntry::Parents staged_ancestors;
249 [ + + ]: 4052274 : const CTransaction &tx = entry.GetTx();
250 : :
251 [ + + ]: 4052274 : 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 [ + + ]: 10084098 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
256 [ + - ]: 7121174 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
257 [ + + ]: 7121174 : if (piter) {
258 [ + - ]: 3694934 : staged_ancestors.insert(**piter);
259 [ + + ]: 3694934 : if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) {
260 [ + - + - ]: 80499 : 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 : 1062517 : txiter it = mapTx.iterator_to(entry);
268 [ + - ]: 1062517 : staged_ancestors = it->GetMemPoolParentsConst();
269 : : }
270 : :
271 [ + - ]: 4025441 : return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
272 [ + - ]: 4025441 : limits);
273 : 4052274 : }
274 : :
275 : 1194518 : 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 : 1194518 : auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
282 [ + - - + ]: 1194518 : 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 : 1194518 : return std::move(result).value_or(CTxMemPool::setEntries{});
287 : 1194518 : }
288 : :
289 : 2432289 : void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
290 : : {
291 : 2432289 : const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
292 : : // add or remove this tx as a child of each parent
293 [ + + ]: 3685260 : for (const CTxMemPoolEntry& parent : parents) {
294 : 1252971 : UpdateChild(mapTx.iterator_to(parent), it, add);
295 : : }
296 [ + + ]: 2432289 : const int32_t updateCount = (add ? 1 : -1);
297 : 2432289 : const int32_t updateSize{updateCount * it->GetTxSize()};
298 : 2432289 : const CAmount updateFee = updateCount * it->GetModifiedFee();
299 [ + + ]: 22973633 : for (txiter ancestorIt : setAncestors) {
300 : 41082688 : mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
301 : : }
302 : 2432289 : }
303 : :
304 : 2341681 : void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
305 : : {
306 : 2341681 : int64_t updateCount = setAncestors.size();
307 : 2341681 : int64_t updateSize = 0;
308 : 2341681 : CAmount updateFee = 0;
309 : 2341681 : int64_t updateSigOpsCost = 0;
310 [ + + ]: 22821704 : for (txiter ancestorIt : setAncestors) {
311 : 20480023 : updateSize += ancestorIt->GetTxSize();
312 : 20480023 : updateFee += ancestorIt->GetModifiedFee();
313 : 20480023 : updateSigOpsCost += ancestorIt->GetSigOpCost();
314 : : }
315 : 4683362 : mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
316 : 2341681 : }
317 : :
318 : 90608 : void CTxMemPool::UpdateChildrenForRemoval(txiter it)
319 : : {
320 : 90608 : const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
321 [ - + ]: 90608 : for (const CTxMemPoolEntry& updateIt : children) {
322 : 0 : UpdateParent(mapTx.iterator_to(updateIt), it, false);
323 : : }
324 : 90608 : }
325 : :
326 : 2707027 : 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 [ - + ]: 2707027 : 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 [ # # ]: 0 : for (txiter removeIt : entriesToRemove) {
338 [ # # ]: 0 : setEntries setDescendants;
339 [ # # ]: 0 : CalculateDescendants(removeIt, setDescendants);
340 : 0 : setDescendants.erase(removeIt); // don't update state for self
341 [ # # ]: 0 : int32_t modifySize = -removeIt->GetTxSize();
342 : 0 : CAmount modifyFee = -removeIt->GetModifiedFee();
343 : 0 : int modifySigOps = -removeIt->GetSigOpCost();
344 [ # # ]: 0 : for (txiter dit : setDescendants) {
345 [ # # ]: 0 : mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); });
346 : : }
347 : 0 : }
348 : : }
349 [ + + ]: 2797635 : for (txiter removeIt : entriesToRemove) {
350 : 90608 : 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 : 90608 : 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 [ + - ]: 90608 : UpdateAncestorsOf(false, removeIt, ancestors);
374 : 90608 : }
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 [ + + ]: 2797635 : for (txiter removeIt : entriesToRemove) {
379 : 90608 : UpdateChildrenForRemoval(removeIt);
380 : : }
381 : 2707027 : }
382 : :
383 : 21483752 : void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
384 : : {
385 : 21483752 : nSizeWithDescendants += modifySize;
386 [ - + ]: 21483752 : assert(nSizeWithDescendants > 0);
387 : 21483752 : nModFeesWithDescendants = SaturatingAdd(nModFeesWithDescendants, modifyFee);
388 : 21483752 : m_count_with_descendants += modifyCount;
389 [ - + ]: 21483752 : assert(m_count_with_descendants > 0);
390 : 21483752 : }
391 : :
392 : 2409478 : void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
393 : : {
394 : 2409478 : nSizeWithAncestors += modifySize;
395 [ - + ]: 2409478 : assert(nSizeWithAncestors > 0);
396 : 2409478 : nModFeesWithAncestors = SaturatingAdd(nModFeesWithAncestors, modifyFee);
397 : 2409478 : m_count_with_ancestors += modifyCount;
398 [ - + ]: 2409478 : assert(m_count_with_ancestors > 0);
399 : 2409478 : nSigOpCostWithAncestors += modifySigOps;
400 [ - + ]: 2409478 : assert(int(nSigOpCostWithAncestors) >= 0);
401 : 2409478 : }
402 : :
403 : : //! Clamp option values and populate the error if options are not valid.
404 : 21280 : static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
405 : : {
406 [ + - ]: 21280 : opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
407 : 21280 : int64_t descendant_limit_bytes = opts.limits.descendant_size_vbytes * 40;
408 [ + - + + ]: 21280 : if (opts.max_size_bytes < 0 || opts.max_size_bytes < descendant_limit_bytes) {
409 : 2724 : error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(descendant_limit_bytes / 1'000'000.0));
410 : : }
411 : 21280 : return std::move(opts);
412 : : }
413 : :
414 : 21280 : CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
415 [ + - ]: 21280 : : m_opts{Flatten(std::move(opts), error)}
416 : : {
417 : 21280 : }
418 : :
419 : 15 : bool CTxMemPool::isSpent(const COutPoint& outpoint) const
420 : : {
421 : 15 : LOCK(cs);
422 [ + - ]: 15 : return mapNextTx.count(outpoint);
423 : 15 : }
424 : :
425 : 0 : unsigned int CTxMemPool::GetTransactionsUpdated() const
426 : : {
427 : 0 : return nTransactionsUpdated;
428 : : }
429 : :
430 : 139264 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
431 : : {
432 : 139264 : nTransactionsUpdated += n;
433 : 139264 : }
434 : :
435 : 2339034 : void CTxMemPool::Apply(ChangeSet* changeset)
436 : : {
437 : 2339034 : AssertLockHeld(cs);
438 : 2339034 : RemoveStaged(changeset->m_to_remove, false, MemPoolRemovalReason::REPLACED);
439 : :
440 [ + + ]: 4680715 : for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
441 [ + + ]: 2341681 : auto tx_entry = changeset->m_entry_vec[i];
442 : 2341681 : std::optional<CTxMemPool::setEntries> ancestors;
443 [ + + ]: 2341681 : 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 [ + - + - : 4678068 : ancestors = *Assume(changeset->CalculateMemPoolAncestors(tx_entry, Limits::NoLimits()));
+ - ]
454 : : }
455 : : // First splice this entry into mapTx.
456 : 2341681 : auto node_handle = changeset->m_to_add.extract(tx_entry);
457 [ + - ]: 2341681 : auto result = mapTx.insert(std::move(node_handle));
458 : :
459 [ + - ]: 2341681 : Assume(result.inserted);
460 : 2341681 : txiter it = result.position;
461 : :
462 : : // Now update the entry for ancestors/descendants.
463 [ + + ]: 2341681 : if (ancestors.has_value()) {
464 [ + - ]: 2339034 : addNewTransaction(it, *ancestors);
465 : : } else {
466 [ + - ]: 2647 : addNewTransaction(it);
467 : : }
468 [ - + ]: 2341681 : }
469 : 2339034 : }
470 : :
471 : 2647 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter it)
472 : : {
473 : 2647 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
474 [ + - ]: 2647 : return addNewTransaction(it, ancestors);
475 : 2647 : }
476 : :
477 : 2341681 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit, CTxMemPool::setEntries& setAncestors)
478 : : {
479 : 2341681 : 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 : 2341681 : cachedInnerUsage += entry.DynamicMemoryUsage();
485 : :
486 : 2341681 : const CTransaction& tx = newit->GetTx();
487 : 2341681 : std::set<Txid> setParentTransactions;
488 [ + + ]: 6608708 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
489 [ + - ]: 4267027 : mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
490 [ + - ]: 4267027 : 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 [ + - + + ]: 3563532 : for (const auto& pit : GetIterSet(setParentTransactions)) {
501 [ + - ]: 1221851 : UpdateParent(newit, pit, true);
502 : 0 : }
503 [ + - ]: 2341681 : UpdateAncestorsOf(true, newit, setAncestors);
504 [ + - ]: 2341681 : UpdateEntryForAncestors(newit, setAncestors);
505 : :
506 [ + - ]: 2341681 : nTransactionsUpdated++;
507 [ + - ]: 2341681 : totalTxSize += entry.GetTxSize();
508 : 2341681 : m_total_fee += entry.GetFee();
509 : :
510 [ + - + - ]: 4683362 : txns_randomized.emplace_back(newit->GetSharedTx());
511 : 2341681 : newit->idx_randomized = txns_randomized.size() - 1;
512 : :
513 : : TRACEPOINT(mempool, added,
514 : : entry.GetTx().GetHash().data(),
515 : : entry.GetTxSize(),
516 : : entry.GetFee()
517 : 2341681 : );
518 : 2341681 : }
519 : :
520 : 90608 : 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 [ + + ]: 90608 : uint64_t mempool_sequence = GetAndIncrementSequence();
525 : :
526 [ + + + - ]: 90608 : 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 [ + - + - ]: 255102 : 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 : 90608 : );
540 : :
541 [ + + ]: 240168 : for (const CTxIn& txin : it->GetTx().vin)
542 : 149560 : mapNextTx.erase(txin.prevout);
543 : :
544 : 90608 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
545 : :
546 [ + + ]: 90608 : if (txns_randomized.size() > 1) {
547 : : // Update idx_randomized of the to-be-moved entry.
548 : 75349 : 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 : 75349 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
551 : 75349 : txns_randomized.pop_back();
552 [ + + ]: 75349 : if (txns_randomized.size() * 2 < txns_randomized.capacity())
553 : 10446 : txns_randomized.shrink_to_fit();
554 : : } else
555 : 15259 : txns_randomized.clear();
556 : :
557 : 90608 : totalTxSize -= it->GetTxSize();
558 : 90608 : m_total_fee -= it->GetFee();
559 : 90608 : cachedInnerUsage -= it->DynamicMemoryUsage();
560 : 90608 : cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
561 : 90608 : mapTx.erase(it);
562 : 90608 : nTransactionsUpdated++;
563 : 90608 : }
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 : 2771203 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
572 : : {
573 : 2771203 : setEntries stage;
574 [ + + ]: 2771203 : if (setDescendants.count(entryit) == 0) {
575 [ + - ]: 2515609 : 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 [ + + ]: 48504183 : while (!stage.empty()) {
581 [ + - ]: 45732980 : txiter it = *stage.begin();
582 [ + - ]: 45732980 : setDescendants.insert(it);
583 : 45732980 : stage.erase(it);
584 : :
585 : 45732980 : const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
586 [ + + ]: 109268429 : for (const CTxMemPoolEntry& child : children) {
587 : 63535449 : txiter childiter = mapTx.iterator_to(child);
588 [ + + ]: 63535449 : if (!setDescendants.count(childiter)) {
589 [ + - ]: 50056743 : stage.insert(childiter);
590 : : }
591 : : }
592 : : }
593 : 2771203 : }
594 : :
595 : 3829 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
596 : : {
597 : : // Remove transaction from memory pool
598 : 3829 : AssertLockHeld(cs);
599 : 3829 : Assume(!m_have_changeset);
600 [ + - ]: 3829 : setEntries txToRemove;
601 [ + - ]: 3829 : txiter origit = mapTx.find(origTx.GetHash());
602 [ + - ]: 3829 : if (origit != mapTx.end()) {
603 [ + - ]: 3829 : 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 [ # # ]: 0 : for (unsigned int i = 0; i < origTx.vout.size(); i++) {
610 : 0 : auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
611 [ # # ]: 0 : if (it == mapNextTx.end())
612 : 0 : continue;
613 [ # # ]: 0 : txiter nextit = mapTx.find(it->second->GetHash());
614 [ # # ]: 0 : assert(nextit != mapTx.end());
615 [ # # ]: 0 : txToRemove.insert(nextit);
616 : : }
617 : : }
618 : 3829 : setEntries setAllRemoves;
619 [ + + ]: 7658 : for (txiter it : txToRemove) {
620 [ + - ]: 3829 : CalculateDescendants(it, setAllRemoves);
621 : : }
622 : :
623 [ + - ]: 3829 : RemoveStaged(setAllRemoves, false, reason);
624 : 3829 : }
625 : :
626 : 0 : 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 : 0 : AssertLockHeld(cs);
630 : 0 : AssertLockHeld(::cs_main);
631 : 0 : Assume(!m_have_changeset);
632 : :
633 : 0 : setEntries txToRemove;
634 [ # # ]: 0 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
635 [ # # # # : 0 : if (check_final_and_mature(it)) txToRemove.insert(it);
# # ]
636 : : }
637 : 0 : setEntries setAllRemoves;
638 [ # # ]: 0 : for (txiter it : txToRemove) {
639 [ # # ]: 0 : CalculateDescendants(it, setAllRemoves);
640 : : }
641 [ # # ]: 0 : RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
642 [ # # ]: 0 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
643 [ # # # # ]: 0 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
644 : : }
645 : 0 : }
646 : :
647 : 0 : void CTxMemPool::removeConflicts(const CTransaction &tx)
648 : : {
649 : : // Remove transactions which depend on inputs of tx, recursively
650 : 0 : AssertLockHeld(cs);
651 [ # # ]: 0 : for (const CTxIn &txin : tx.vin) {
652 : 0 : auto it = mapNextTx.find(txin.prevout);
653 [ # # ]: 0 : if (it != mapNextTx.end()) {
654 : 0 : const CTransaction &txConflict = *it->second;
655 [ # # ]: 0 : if (Assume(txConflict.GetHash() != tx.GetHash()))
656 : : {
657 : 0 : ClearPrioritisation(txConflict.GetHash());
658 : 0 : removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
659 : : }
660 : : }
661 : : }
662 : 0 : }
663 : :
664 : 139264 : 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 : 139264 : AssertLockHeld(cs);
668 : 139264 : Assume(!m_have_changeset);
669 : 139264 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
670 [ + - + - : 139264 : if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
- + ]
671 [ # # ]: 0 : txs_removed_for_block.reserve(vtx.size());
672 [ # # ]: 0 : for (const auto& tx : vtx) {
673 [ # # ]: 0 : txiter it = mapTx.find(tx->GetHash());
674 [ # # ]: 0 : if (it != mapTx.end()) {
675 [ # # ]: 0 : setEntries stage;
676 [ # # ]: 0 : stage.insert(it);
677 [ # # ]: 0 : txs_removed_for_block.emplace_back(*it);
678 [ # # ]: 0 : RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
679 : 0 : }
680 [ # # ]: 0 : removeConflicts(*tx);
681 [ # # ]: 0 : ClearPrioritisation(tx->GetHash());
682 : : }
683 : : }
684 [ + + ]: 139264 : if (m_opts.signals) {
685 [ + - ]: 138614 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
686 : : }
687 [ + - ]: 139264 : lastRollingFeeUpdate = GetTime();
688 : 139264 : blockSinceLastRollingFeeBump = true;
689 : 139264 : }
690 : :
691 : 174840 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
692 : : {
693 [ + - ]: 174840 : if (m_opts.check_ratio == 0) return;
694 : :
695 [ + - ]: 174840 : if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
696 : :
697 : 174840 : AssertLockHeld(::cs_main);
698 : 174840 : LOCK(cs);
699 [ + - + + : 174840 : LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - ]
700 : :
701 : 174840 : uint64_t checkTotal = 0;
702 : 174840 : CAmount check_total_fee{0};
703 : 174840 : uint64_t innerUsage = 0;
704 : 174840 : uint64_t prev_ancestor_count{0};
705 : :
706 [ + - ]: 174840 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
707 : :
708 [ + - + + ]: 304194 : for (const auto& it : GetSortedDepthAndScore()) {
709 [ + - ]: 129354 : checkTotal += it->GetTxSize();
710 : 129354 : check_total_fee += it->GetFee();
711 : 129354 : innerUsage += it->DynamicMemoryUsage();
712 : 129354 : const CTransaction& tx = it->GetTx();
713 : 129354 : innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
714 : 129354 : CTxMemPoolEntry::Parents setParentCheck;
715 [ + + ]: 340005 : for (const CTxIn &txin : tx.vin) {
716 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
717 [ + - ]: 210651 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
718 [ + + ]: 210651 : if (it2 != mapTx.end()) {
719 [ + - ]: 68128 : const CTransaction& tx2 = it2->GetTx();
720 [ + - - + ]: 68128 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
721 [ + - ]: 68128 : 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 [ + - - + ]: 210651 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
727 : : // Check whether its inputs are marked in mapNextTx.
728 : 210651 : auto it3 = mapNextTx.find(txin.prevout);
729 [ - + ]: 210651 : assert(it3 != mapNextTx.end());
730 [ - + ]: 210651 : assert(it3->first == &txin.prevout);
731 [ - + ]: 210651 : assert(it3->second == &tx);
732 : : }
733 : 229466 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
734 [ + - ]: 100112 : return a.GetTx().GetHash() == b.GetTx().GetHash();
735 : : };
736 [ - + ]: 129354 : assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
737 [ - + ]: 129354 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
738 : : // Verify ancestor state is correct.
739 [ + - ]: 129354 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
740 [ + - ]: 129354 : uint64_t nCountCheck = ancestors.size() + 1;
741 [ + - ]: 129354 : int32_t nSizeCheck = it->GetTxSize();
742 : 129354 : CAmount nFeesCheck = it->GetModifiedFee();
743 : 129354 : int64_t nSigOpCheck = it->GetSigOpCost();
744 : :
745 [ + + ]: 220964 : for (txiter ancestorIt : ancestors) {
746 [ + - ]: 91610 : nSizeCheck += ancestorIt->GetTxSize();
747 : 91610 : nFeesCheck += ancestorIt->GetModifiedFee();
748 : 91610 : nSigOpCheck += ancestorIt->GetSigOpCost();
749 : : }
750 : :
751 [ - + ]: 129354 : assert(it->GetCountWithAncestors() == nCountCheck);
752 [ - + ]: 129354 : assert(it->GetSizeWithAncestors() == nSizeCheck);
753 [ - + ]: 129354 : assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
754 [ - + ]: 129354 : assert(it->GetModFeesWithAncestors() == nFeesCheck);
755 : : // Sanity check: we are walking in ascending ancestor count order.
756 [ - + ]: 129354 : assert(prev_ancestor_count <= it->GetCountWithAncestors());
757 : 129354 : prev_ancestor_count = it->GetCountWithAncestors();
758 : :
759 : : // Check children against mapNextTx
760 : 129354 : CTxMemPoolEntry::Children setChildrenCheck;
761 : 129354 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
762 : 129354 : int32_t child_sizes{0};
763 [ + + + + ]: 197482 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
764 [ + - ]: 68128 : txiter childit = mapTx.find(iter->second->GetHash());
765 [ - + ]: 68128 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
766 [ + - + + ]: 68128 : if (setChildrenCheck.insert(*childit).second) {
767 [ + - ]: 50056 : child_sizes += childit->GetTxSize();
768 : : }
769 : : }
770 [ - + ]: 129354 : assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
771 [ - + ]: 129354 : 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 [ + - - + ]: 129354 : assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
775 : :
776 [ - + ]: 129354 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
777 : 129354 : CAmount txfee = 0;
778 [ - + ]: 129354 : assert(!tx.IsCoinBase());
779 [ + - - + ]: 129354 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
780 [ + - + + ]: 340005 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
781 [ + - ]: 129354 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
782 : 129354 : }
783 [ + + ]: 385491 : for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
784 [ + - ]: 210651 : uint256 hash = it->second->GetHash();
785 [ + - ]: 210651 : indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
786 [ - + ]: 210651 : const CTransaction& tx = it2->GetTx();
787 [ - + ]: 210651 : assert(it2 != mapTx.end());
788 [ - + ]: 210651 : assert(&tx == it->second);
789 : : }
790 : :
791 [ - + ]: 174840 : assert(totalTxSize == checkTotal);
792 [ - + ]: 174840 : assert(m_total_fee == check_total_fee);
793 [ - + ]: 174840 : assert(innerUsage == cachedInnerUsage);
794 [ + - ]: 349680 : }
795 : :
796 : 0 : bool CTxMemPool::CompareDepthAndScore(const Wtxid& hasha, const Wtxid& hashb) const
797 : : {
798 : : /* Return `true` if hasha should be considered sooner than hashb. Namely when:
799 : : * a is not in the mempool, but b is
800 : : * both are in the mempool and a has fewer ancestors than b
801 : : * both are in the mempool and a has a higher score than b
802 : : */
803 : 0 : LOCK(cs);
804 [ # # ]: 0 : auto j{GetIter(hashb)};
805 [ # # ]: 0 : if (!j.has_value()) return false;
806 [ # # ]: 0 : auto i{GetIter(hasha)};
807 [ # # ]: 0 : if (!i.has_value()) return true;
808 [ # # ]: 0 : uint64_t counta = i.value()->GetCountWithAncestors();
809 : 0 : uint64_t countb = j.value()->GetCountWithAncestors();
810 [ # # ]: 0 : if (counta == countb) {
811 [ # # ]: 0 : return CompareTxMemPoolEntryByScore()(*i.value(), *j.value());
812 : : }
813 : 0 : return counta < countb;
814 : 0 : }
815 : :
816 : : namespace {
817 : : class DepthAndScoreComparator
818 : : {
819 : : public:
820 : 87039777 : bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
821 : : {
822 [ + + ]: 87039777 : uint64_t counta = a->GetCountWithAncestors();
823 : 87039777 : uint64_t countb = b->GetCountWithAncestors();
824 [ + + ]: 87039777 : if (counta == countb) {
825 : 57725147 : return CompareTxMemPoolEntryByScore()(*a, *b);
826 : : }
827 : 29314630 : return counta < countb;
828 : : }
829 : : };
830 : : } // namespace
831 : :
832 : 1073858 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
833 : : {
834 : 1073858 : std::vector<indexed_transaction_set::const_iterator> iters;
835 : 1073858 : AssertLockHeld(cs);
836 : :
837 [ + - ]: 1073858 : iters.reserve(mapTx.size());
838 : :
839 [ + + + + ]: 30737070 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
840 [ + - ]: 14831606 : iters.push_back(mi);
841 : : }
842 [ + - ]: 1073858 : std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
843 : 1073858 : return iters;
844 : 0 : }
845 : :
846 : 47 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
847 : : {
848 : 47 : AssertLockHeld(cs);
849 : :
850 : 47 : std::vector<CTxMemPoolEntryRef> ret;
851 [ + - ]: 47 : ret.reserve(mapTx.size());
852 [ + - - + ]: 47 : for (const auto& it : GetSortedDepthAndScore()) {
853 [ # # ]: 0 : ret.emplace_back(*it);
854 : 0 : }
855 : 47 : return ret;
856 : 0 : }
857 : :
858 : 898971 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
859 : : {
860 : 898971 : LOCK(cs);
861 [ + - ]: 898971 : auto iters = GetSortedDepthAndScore();
862 : :
863 : 898971 : std::vector<TxMempoolInfo> ret;
864 [ + - ]: 898971 : ret.reserve(mapTx.size());
865 [ + + ]: 15601223 : for (auto it : iters) {
866 [ + - - + ]: 29404504 : ret.push_back(GetInfo(it));
867 : : }
868 : :
869 : 898971 : return ret;
870 [ + - ]: 1797942 : }
871 : :
872 : 14715846 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
873 : : {
874 : 14715846 : AssertLockHeld(cs);
875 : 14715846 : const auto i = mapTx.find(txid);
876 [ + + ]: 14715846 : return i == mapTx.end() ? nullptr : &(*i);
877 : : }
878 : :
879 : 33163613 : CTransactionRef CTxMemPool::get(const uint256& hash) const
880 : : {
881 : 33163613 : LOCK(cs);
882 [ + - ]: 33163613 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
883 [ + + ]: 33163613 : if (i == mapTx.end())
884 : 16248833 : return nullptr;
885 [ + - + - ]: 50078393 : return i->GetSharedTx();
886 : 33163613 : }
887 : :
888 : 1921242 : void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
889 : : {
890 : 1921242 : {
891 : 1921242 : LOCK(cs);
892 [ + - ]: 1921242 : CAmount &delta = mapDeltas[hash];
893 : 1921242 : delta = SaturatingAdd(delta, nFeeDelta);
894 [ + - ]: 1921242 : txiter it = mapTx.find(hash);
895 [ + + ]: 1921242 : if (it != mapTx.end()) {
896 [ + - ]: 1882634 : mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
897 : : // Now update all ancestors' modified fees with descendants
898 [ + - ]: 941317 : auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
899 [ + + ]: 1883725 : for (txiter ancestorIt : ancestors) {
900 [ + - + - ]: 2827224 : mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
901 : : }
902 : : // Now update all descendants' modified fees with ancestors
903 [ + - ]: 941317 : setEntries setDescendants;
904 [ + - ]: 941317 : CalculateDescendants(it, setDescendants);
905 : 941317 : setDescendants.erase(it);
906 [ + + ]: 1009114 : for (txiter descendantIt : setDescendants) {
907 [ + - ]: 203391 : mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
908 : : }
909 : 941317 : ++nTransactionsUpdated;
910 : 941317 : }
911 [ + + ]: 1921242 : if (delta == 0) {
912 : 9993 : mapDeltas.erase(hash);
913 [ + + + - : 20705 : LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
+ - ]
914 : : } else {
915 [ + - + - : 4763096 : LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
+ + + - +
- ]
916 : : hash.ToString(),
917 : : it == mapTx.end() ? "not " : "",
918 : : FormatMoney(nFeeDelta),
919 : : FormatMoney(delta));
920 : : }
921 : 1921242 : }
922 : 1921242 : }
923 : :
924 : 3077911 : void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
925 : : {
926 : 3077911 : AssertLockHeld(cs);
927 : 3077911 : std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
928 [ + + ]: 3077911 : if (pos == mapDeltas.end())
929 : : return;
930 : 157302 : const CAmount &delta = pos->second;
931 : 157302 : nFeeDelta += delta;
932 : : }
933 : :
934 : 0 : void CTxMemPool::ClearPrioritisation(const uint256& hash)
935 : : {
936 : 0 : AssertLockHeld(cs);
937 : 0 : mapDeltas.erase(hash);
938 : 0 : }
939 : :
940 : 19 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
941 : : {
942 : 19 : AssertLockNotHeld(cs);
943 : 19 : LOCK(cs);
944 : 19 : std::vector<delta_info> result;
945 [ + - ]: 19 : result.reserve(mapDeltas.size());
946 [ + - + + ]: 283 : for (const auto& [txid, delta] : mapDeltas) {
947 [ + - ]: 264 : const auto iter{mapTx.find(txid)};
948 [ - + ]: 264 : const bool in_mempool{iter != mapTx.end()};
949 : 264 : std::optional<CAmount> modified_fee;
950 [ - + ]: 264 : if (in_mempool) modified_fee = iter->GetModifiedFee();
951 [ + - ]: 264 : result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
952 : : }
953 [ + - ]: 19 : return result;
954 : 19 : }
955 : :
956 : 9737939 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
957 : : {
958 : 9737939 : const auto it = mapNextTx.find(prevout);
959 [ + + ]: 9737939 : return it == mapNextTx.end() ? nullptr : it->second;
960 : : }
961 : :
962 : 14517103 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
963 : : {
964 : 14517103 : AssertLockHeld(cs);
965 : 14517103 : auto it = mapTx.find(txid.ToUint256());
966 [ + + ]: 14517103 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
967 : : }
968 : :
969 : 11802 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
970 : : {
971 : 11802 : AssertLockHeld(cs);
972 [ - + ]: 11802 : auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
973 [ - + ]: 11802 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
974 : : }
975 : :
976 : 3016772 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
977 : : {
978 : 3016772 : CTxMemPool::setEntries ret;
979 [ + + ]: 6207792 : for (const auto& h : hashes) {
980 [ + - ]: 3191020 : const auto mi = GetIter(h);
981 [ + + + - ]: 3191020 : if (mi) ret.insert(*mi);
982 : : }
983 : 3016772 : return ret;
984 : 0 : }
985 : :
986 : 3630 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<uint256>& txids) const
987 : : {
988 : 3630 : AssertLockHeld(cs);
989 : 3630 : std::vector<txiter> ret;
990 [ + - ]: 3630 : ret.reserve(txids.size());
991 [ + + ]: 267093 : for (const auto& txid : txids) {
992 [ + - ]: 263463 : const auto it{GetIter(Txid::FromUint256(txid))};
993 [ - + ]: 263463 : if (!it) return {};
994 [ + - ]: 263463 : ret.push_back(*it);
995 : : }
996 : 3630 : return ret;
997 : 3630 : }
998 : :
999 : 175730 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
1000 : : {
1001 [ + + ]: 351398 : for (unsigned int i = 0; i < tx.vin.size(); i++)
1002 [ + + ]: 235918 : if (exists(tx.vin[i].prevout.hash))
1003 : : return false;
1004 : : return true;
1005 : : }
1006 : :
1007 [ + - + - ]: 2002488 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1008 : :
1009 : 32350534 : std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
1010 : : {
1011 : : // Check to see if the inputs are made available by another tx in the package.
1012 : : // These Coins would not be available in the underlying CoinsView.
1013 [ + + ]: 32350534 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
1014 : 179494 : return it->second;
1015 : : }
1016 : :
1017 : : // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1018 : : // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1019 : : // transactions. First checking the underlying cache risks returning a pruned entry instead.
1020 : 32171040 : CTransactionRef ptx = mempool.get(outpoint.hash);
1021 [ + + ]: 32171040 : if (ptx) {
1022 [ + + ]: 16626472 : if (outpoint.n < ptx->vout.size()) {
1023 : 16624933 : Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
1024 [ + - ]: 16624933 : m_non_base_coins.emplace(outpoint);
1025 : 16624933 : return coin;
1026 : 16624933 : }
1027 : 1539 : return std::nullopt;
1028 : : }
1029 [ + - ]: 15544568 : return base->GetCoin(outpoint);
1030 : 32171040 : }
1031 : :
1032 : 154934 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
1033 : : {
1034 [ + + ]: 1659532 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
1035 [ + - ]: 1504598 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
1036 : 1504598 : m_non_base_coins.emplace(tx->GetHash(), n);
1037 : : }
1038 : 154934 : }
1039 : 976221 : void CCoinsViewMemPool::Reset()
1040 : : {
1041 : 976221 : m_temp_added.clear();
1042 : 976221 : m_non_base_coins.clear();
1043 : 976221 : }
1044 : :
1045 : 2890108 : size_t CTxMemPool::DynamicMemoryUsage() const {
1046 : 2890108 : LOCK(cs);
1047 : : // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1048 [ + + + - ]: 4669703 : return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
1049 : 2890108 : }
1050 : :
1051 : 90608 : void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) {
1052 : 90608 : LOCK(cs);
1053 : :
1054 [ - + ]: 90608 : if (m_unbroadcast_txids.erase(txid))
1055 : : {
1056 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
# # # # #
# ]
1057 : : }
1058 : 90608 : }
1059 : :
1060 : 2707027 : void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1061 : 2707027 : AssertLockHeld(cs);
1062 : 2707027 : UpdateForRemoveFromMempool(stage, updateDescendants);
1063 [ + + ]: 2797635 : for (txiter it : stage) {
1064 : 90608 : removeUnchecked(it, reason);
1065 : : }
1066 : 2707027 : }
1067 : :
1068 : 343794 : int CTxMemPool::Expire(std::chrono::seconds time)
1069 : : {
1070 : 343794 : AssertLockHeld(cs);
1071 : 343794 : Assume(!m_have_changeset);
1072 : 343794 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1073 : 343794 : setEntries toremove;
1074 [ + + + + ]: 377002 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1075 [ + - ]: 33208 : toremove.insert(mapTx.project<0>(it));
1076 : 33208 : it++;
1077 : : }
1078 : 343794 : setEntries stage;
1079 [ + + ]: 377002 : for (txiter removeit : toremove) {
1080 [ + - ]: 33208 : CalculateDescendants(removeit, stage);
1081 : : }
1082 [ + - ]: 343794 : RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
1083 : 343794 : return stage.size();
1084 : 343794 : }
1085 : :
1086 : 1252971 : void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1087 : : {
1088 : 1252971 : AssertLockHeld(cs);
1089 [ + + ]: 1252971 : CTxMemPoolEntry::Children s;
1090 [ + + + - : 1252971 : if (add && entry->GetMemPoolChildren().insert(*child).second) {
+ - ]
1091 : 1221851 : cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1092 [ + - + - ]: 31120 : } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
1093 : 31120 : cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1094 : : }
1095 : 1252971 : }
1096 : :
1097 : 1221851 : void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1098 : : {
1099 : 1221851 : AssertLockHeld(cs);
1100 [ + - ]: 1221851 : CTxMemPoolEntry::Parents s;
1101 [ + - + - : 1221851 : if (add && entry->GetMemPoolParents().insert(*parent).second) {
+ - ]
1102 : 1221851 : cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1103 [ # # # # ]: 0 : } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
1104 : 0 : cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1105 : : }
1106 : 1221851 : }
1107 : :
1108 : 472368 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1109 : 472368 : LOCK(cs);
1110 [ + + + + ]: 472368 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1111 : 446274 : return CFeeRate(llround(rollingMinimumFeeRate));
1112 : :
1113 [ + - ]: 26094 : int64_t time = GetTime();
1114 [ + + ]: 26094 : if (time > lastRollingFeeUpdate + 10) {
1115 : 3328 : double halflife = ROLLING_FEE_HALFLIFE;
1116 [ + - + - ]: 3328 : if (DynamicMemoryUsage() < sizelimit / 4)
1117 : : halflife /= 4;
1118 [ + - - + ]: 3328 : else if (DynamicMemoryUsage() < sizelimit / 2)
1119 : 0 : halflife /= 2;
1120 : :
1121 : 3328 : rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1122 : 3328 : lastRollingFeeUpdate = time;
1123 : :
1124 [ + + ]: 3328 : if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
1125 : 2935 : rollingMinimumFeeRate = 0;
1126 : 2935 : return CFeeRate(0);
1127 : : }
1128 : : }
1129 [ + + + - ]: 494845 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
1130 : 472368 : }
1131 : :
1132 : 20370 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1133 : 20370 : AssertLockHeld(cs);
1134 [ + + ]: 20370 : if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1135 : 13074 : rollingMinimumFeeRate = rate.GetFeePerK();
1136 : 13074 : blockSinceLastRollingFeeBump = false;
1137 : : }
1138 : 20370 : }
1139 : :
1140 : 343794 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1141 : 343794 : AssertLockHeld(cs);
1142 : 343794 : Assume(!m_have_changeset);
1143 : :
1144 : 343794 : unsigned nTxnRemoved = 0;
1145 : 343794 : CFeeRate maxFeeRateRemoved(0);
1146 [ + + + + ]: 364164 : while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1147 : 20370 : indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1148 : :
1149 : : // We set the new mempool min fee to the feerate of the removed set, plus the
1150 : : // "minimum reasonable fee rate" (ie some value under which we consider txn
1151 : : // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1152 : : // equal to txn which were removed with no block in between.
1153 : 20370 : CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1154 : 20370 : removed += m_opts.incremental_relay_feerate;
1155 : 20370 : trackPackageRemoved(removed);
1156 [ + + ]: 20370 : maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1157 : :
1158 [ + - ]: 20370 : setEntries stage;
1159 [ + - ]: 20370 : CalculateDescendants(mapTx.project<0>(it), stage);
1160 [ + - ]: 20370 : nTxnRemoved += stage.size();
1161 : :
1162 : 20370 : std::vector<CTransaction> txn;
1163 [ + - ]: 20370 : if (pvNoSpendsRemaining) {
1164 [ + - ]: 20370 : txn.reserve(stage.size());
1165 [ + + ]: 41992 : for (txiter iter : stage)
1166 [ + - ]: 21622 : txn.push_back(iter->GetTx());
1167 : : }
1168 [ + - ]: 20370 : RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1169 [ + - ]: 20370 : if (pvNoSpendsRemaining) {
1170 [ + + ]: 41992 : for (const CTransaction& tx : txn) {
1171 [ + + ]: 54371 : for (const CTxIn& txin : tx.vin) {
1172 [ + - + + ]: 32749 : if (exists(txin.prevout.hash)) continue;
1173 [ + - ]: 30734 : pvNoSpendsRemaining->push_back(txin.prevout);
1174 : : }
1175 : : }
1176 : : }
1177 : 20370 : }
1178 : :
1179 [ + + ]: 343794 : if (maxFeeRateRemoved > CFeeRate(0)) {
1180 [ - + - - ]: 10223 : LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1181 : : }
1182 : 343794 : }
1183 : :
1184 : 0 : uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const {
1185 : : // find parent with highest descendant count
1186 : 0 : std::vector<txiter> candidates;
1187 [ # # ]: 0 : setEntries counted;
1188 [ # # ]: 0 : candidates.push_back(entry);
1189 : 0 : uint64_t maximum = 0;
1190 [ # # ]: 0 : while (candidates.size()) {
1191 : 0 : txiter candidate = candidates.back();
1192 [ # # ]: 0 : candidates.pop_back();
1193 [ # # # # ]: 0 : if (!counted.insert(candidate).second) continue;
1194 [ # # ]: 0 : const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst();
1195 [ # # ]: 0 : if (parents.size() == 0) {
1196 [ # # ]: 0 : maximum = std::max(maximum, candidate->GetCountWithDescendants());
1197 : : } else {
1198 [ # # # # ]: 0 : for (const CTxMemPoolEntry& i : parents) {
1199 [ # # ]: 0 : candidates.push_back(mapTx.iterator_to(i));
1200 : : }
1201 : : }
1202 : : }
1203 : 0 : return maximum;
1204 : 0 : }
1205 : :
1206 : 0 : void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
1207 : 0 : LOCK(cs);
1208 [ # # ]: 0 : auto it = mapTx.find(txid);
1209 : 0 : ancestors = descendants = 0;
1210 [ # # ]: 0 : if (it != mapTx.end()) {
1211 [ # # ]: 0 : ancestors = it->GetCountWithAncestors();
1212 [ # # ]: 0 : if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
1213 [ # # ]: 0 : if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
1214 [ # # ]: 0 : descendants = CalculateDescendantMaximum(it);
1215 : : }
1216 : 0 : }
1217 : :
1218 : 1 : bool CTxMemPool::GetLoadTried() const
1219 : : {
1220 : 1 : LOCK(cs);
1221 [ + - ]: 1 : return m_load_tried;
1222 : 1 : }
1223 : :
1224 : 1657 : void CTxMemPool::SetLoadTried(bool load_tried)
1225 : : {
1226 : 1657 : LOCK(cs);
1227 [ + - ]: 1657 : m_load_tried = load_tried;
1228 : 1657 : }
1229 : :
1230 : 3630 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<uint256>& txids) const
1231 : : {
1232 : 3630 : AssertLockHeld(cs);
1233 : 3630 : std::vector<txiter> clustered_txs{GetIterVec(txids)};
1234 : : // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not
1235 : : // necessarily mean the entry has been processed.
1236 : 3630 : WITH_FRESH_EPOCH(m_epoch);
1237 [ + + ]: 267093 : for (const auto& it : clustered_txs) {
1238 : 263463 : visited(it);
1239 : : }
1240 : : // i = index of where the list of entries to process starts
1241 [ + + ]: 394547 : for (size_t i{0}; i < clustered_txs.size(); ++i) {
1242 : : // DoS protection: if there are 500 or more entries to process, just quit.
1243 [ - + ]: 390917 : if (clustered_txs.size() > 500) return {};
1244 [ + - ]: 390917 : const txiter& tx_iter = clustered_txs.at(i);
1245 [ + - + - : 1954585 : for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
+ + - - ]
1246 [ + + ]: 1778132 : for (const CTxMemPoolEntry& entry : entries) {
1247 : 996298 : const auto entry_it = mapTx.iterator_to(entry);
1248 [ + + ]: 996298 : if (!visited(entry_it)) {
1249 [ - + ]: 127454 : clustered_txs.push_back(entry_it);
1250 : : }
1251 : : }
1252 [ + + - - ]: 1172751 : }
1253 : : }
1254 : 3630 : return clustered_txs;
1255 : 3630 : }
1256 : :
1257 : 10812 : std::optional<std::string> CTxMemPool::CheckConflictTopology(const setEntries& direct_conflicts)
1258 : : {
1259 [ + + ]: 2452536 : for (const auto& direct_conflict : direct_conflicts) {
1260 : : // Ancestor and descendant counts are inclusive of the tx itself.
1261 [ + - ]: 2443263 : const auto ancestor_count{direct_conflict->GetCountWithAncestors()};
1262 [ + - ]: 2443263 : const auto descendant_count{direct_conflict->GetCountWithDescendants()};
1263 : 2443263 : const bool has_ancestor{ancestor_count > 1};
1264 : 2443263 : const bool has_descendant{descendant_count > 1};
1265 [ + - + - : 4886526 : const auto& txid_string{direct_conflict->GetSharedTx()->GetHash().ToString()};
+ - ]
1266 : : // The only allowed configurations are:
1267 : : // 1 ancestor and 0 descendant
1268 : : // 0 ancestor and 1 descendant
1269 : : // 0 ancestor and 0 descendant
1270 [ + + ]: 2443263 : if (ancestor_count > 2) {
1271 [ + - ]: 900 : return strprintf("%s has %u ancestors, max 1 allowed", txid_string, ancestor_count - 1);
1272 [ + + ]: 2442813 : } else if (descendant_count > 2) {
1273 [ + - ]: 312 : return strprintf("%s has %u descendants, max 1 allowed", txid_string, descendant_count - 1);
1274 [ + + ]: 2442657 : } else if (has_ancestor && has_descendant) {
1275 [ + - ]: 614 : return strprintf("%s has both ancestor and descendant, exceeding cluster limit of 2", txid_string);
1276 : : }
1277 : : // Additionally enforce that:
1278 : : // If we have a child, we are its only parent.
1279 : : // If we have a parent, we are its only child.
1280 [ + + ]: 2442350 : if (has_descendant) {
1281 [ + + ]: 1085456 : const auto& our_child = direct_conflict->GetMemPoolChildrenConst().begin();
1282 [ + + ]: 1085456 : if (our_child->get().GetCountWithAncestors() > 2) {
1283 [ + - ]: 624 : return strprintf("%s is not the only parent of child %s",
1284 [ + - + - : 1560 : txid_string, our_child->get().GetSharedTx()->GetHash().ToString());
+ - + - ]
1285 : : }
1286 [ + + ]: 1356894 : } else if (has_ancestor) {
1287 [ + + ]: 1259889 : const auto& our_parent = direct_conflict->GetMemPoolParentsConst().begin();
1288 [ + + ]: 1259889 : if (our_parent->get().GetCountWithDescendants() > 2) {
1289 [ + - ]: 628 : return strprintf("%s is not the only child of parent %s",
1290 [ + - + - : 1570 : txid_string, our_parent->get().GetSharedTx()->GetHash().ToString());
+ - + - ]
1291 : : }
1292 : : }
1293 : 2443263 : }
1294 : 9273 : return std::nullopt;
1295 : : }
1296 : :
1297 : 10812 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1298 : : {
1299 : 10812 : LOCK(m_pool->cs);
1300 : 10812 : FeeFrac replacement_feerate{0, 0};
1301 [ + + ]: 30550 : for (auto it : m_entry_vec) {
1302 [ + - ]: 19738 : replacement_feerate += {it->GetModifiedFee(), it->GetTxSize()};
1303 : : }
1304 : :
1305 [ + - ]: 10812 : auto err_string{m_pool->CheckConflictTopology(m_to_remove)};
1306 [ + + ]: 10812 : if (err_string.has_value()) {
1307 : : // Unsupported topology for calculating a feerate diagram
1308 [ + - + - ]: 4617 : return util::Error{Untranslated(err_string.value())};
1309 : : }
1310 : :
1311 : : // new diagram will have chunks that consist of each ancestor of
1312 : : // direct_conflicts that is at its own fee/size, along with the replacement
1313 : : // tx/package at its own fee/size
1314 : :
1315 : : // old diagram will consist of the ancestors and descendants of each element of
1316 : : // all_conflicts. every such transaction will either be at its own feerate (followed
1317 : : // by any descendant at its own feerate), or as a single chunk at the descendant's
1318 : : // ancestor feerate.
1319 : :
1320 : 9273 : std::vector<FeeFrac> old_chunks;
1321 : : // Step 1: build the old diagram.
1322 : :
1323 : : // The above clusters are all trivially linearized;
1324 : : // they have a strict topology of 1 or two connected transactions.
1325 : :
1326 : : // OLD: Compute existing chunks from all affected clusters
1327 [ + + ]: 2450820 : for (auto txiter : m_to_remove) {
1328 : : // Does this transaction have descendants?
1329 [ + + ]: 2441547 : if (txiter->GetCountWithDescendants() > 1) {
1330 : : // Consider this tx when we consider the descendant.
1331 : 1085072 : continue;
1332 : : }
1333 : : // Does this transaction have ancestors?
1334 [ + - + + ]: 1356475 : FeeFrac individual{txiter->GetModifiedFee(), txiter->GetTxSize()};
1335 [ + + ]: 1356475 : if (txiter->GetCountWithAncestors() > 1) {
1336 : : // We'll add chunks for either the ancestor by itself and this tx
1337 : : // by itself, or for a combined package.
1338 [ + + ]: 1259512 : FeeFrac package{txiter->GetModFeesWithAncestors(), static_cast<int32_t>(txiter->GetSizeWithAncestors())};
1339 [ + + ]: 1259512 : if (individual >> package) {
1340 : : // The individual feerate is higher than the package, and
1341 : : // therefore higher than the parent's fee. Chunk these
1342 : : // together.
1343 [ + - ]: 633091 : old_chunks.emplace_back(package);
1344 : : } else {
1345 : : // Add two points, one for the parent and one for this child.
1346 [ + - ]: 626421 : old_chunks.emplace_back(package - individual);
1347 [ + - ]: 626421 : old_chunks.emplace_back(individual);
1348 : : }
1349 : : } else {
1350 [ + - ]: 96963 : old_chunks.emplace_back(individual);
1351 : : }
1352 : : }
1353 : :
1354 : : // No topology restrictions post-chunking; sort
1355 : 9273 : std::sort(old_chunks.begin(), old_chunks.end(), std::greater());
1356 : :
1357 : 9273 : std::vector<FeeFrac> new_chunks;
1358 : :
1359 : : /* Step 2: build the NEW diagram
1360 : : * CON = Conflicts of proposed chunk
1361 : : * CNK = Proposed chunk
1362 : : * NEW = OLD - CON + CNK: New diagram includes all chunks in OLD, minus
1363 : : * the conflicts, plus the proposed chunk
1364 : : */
1365 : :
1366 : : // OLD - CON: Add any parents of direct conflicts that are not conflicted themselves
1367 [ + + ]: 2450820 : for (auto direct_conflict : m_to_remove) {
1368 : : // If a direct conflict has an ancestor that is not in all_conflicts,
1369 : : // it can be affected by the replacement of the child.
1370 [ + + ]: 2441547 : if (direct_conflict->GetMemPoolParentsConst().size() > 0) {
1371 : : // Grab the parent.
1372 : 1259512 : const CTxMemPoolEntry& parent = direct_conflict->GetMemPoolParentsConst().begin()->get();
1373 [ + + ]: 1259512 : if (!m_to_remove.contains(m_pool->mapTx.iterator_to(parent))) {
1374 : : // This transaction would be left over, so add to the NEW
1375 : : // diagram.
1376 [ + - + - ]: 174440 : new_chunks.emplace_back(parent.GetModifiedFee(), parent.GetTxSize());
1377 : : }
1378 : : }
1379 : : }
1380 : : // + CNK: Add the proposed chunk itself
1381 [ + - ]: 9273 : new_chunks.emplace_back(replacement_feerate);
1382 : :
1383 : : // No topology restrictions post-chunking; sort
1384 : 9273 : std::sort(new_chunks.begin(), new_chunks.end(), std::greater());
1385 [ + - ]: 18546 : return std::make_pair(old_chunks, new_chunks);
1386 [ + - ]: 30897 : }
1387 : :
1388 : 3077911 : 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)
1389 : : {
1390 : 3077911 : LOCK(m_pool->cs);
1391 [ + - + - ]: 3077911 : Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1392 [ + - ]: 3077911 : auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1393 : 3077911 : CAmount delta{0};
1394 [ + - ]: 3077911 : m_pool->ApplyDelta(tx->GetHash(), delta);
1395 [ + + + - ]: 3235213 : if (delta) m_to_add.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
1396 : :
1397 [ + - ]: 3077911 : m_entry_vec.push_back(newit);
1398 [ + - ]: 3077911 : return newit;
1399 : 3077911 : }
1400 : :
1401 : 2339034 : void CTxMemPool::ChangeSet::Apply()
1402 : : {
1403 : 2339034 : LOCK(m_pool->cs);
1404 [ + - ]: 2339034 : m_pool->Apply(this);
1405 : 2339034 : m_to_add.clear();
1406 : 2339034 : m_to_remove.clear();
1407 [ + - ]: 2339034 : m_entry_vec.clear();
1408 [ + - ]: 2339034 : m_ancestors.clear();
1409 : 2339034 : }
|