Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present 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 <policy/policy.h>
15 : : #include <policy/settings.h>
16 : : #include <random.h>
17 : : #include <tinyformat.h>
18 : : #include <util/check.h>
19 : : #include <util/feefrac.h>
20 : : #include <util/log.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 : 4546 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41 : : {
42 : 4546 : 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 [ + - ]: 4546 : 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 [ + + ]: 4546 : if (!active_chain.Contains(lp.maxInputBlock)) {
49 : 229 : return false;
50 : : }
51 : : }
52 : :
53 : : // LockPoints still valid
54 : : return true;
55 : : }
56 : :
57 : 11616688 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58 : : {
59 : 11616688 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60 [ + - ]: 11616688 : const auto& hash = entry.GetTx().GetHash();
61 : 11616688 : {
62 [ + - ]: 11616688 : LOCK(cs);
63 : 11616688 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64 [ + + + + ]: 11822793 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65 [ + - ]: 206105 : ret.emplace_back(*(iter->second));
66 : : }
67 : 0 : }
68 : 11616688 : std::ranges::sort(ret, CompareIteratorByHash{});
69 [ + + - - ]: 11638010 : auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70 : 11616688 : ret.erase(removed.begin(), removed.end());
71 : 11616688 : return ret;
72 : 0 : }
73 : :
74 : 11639867 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75 : : {
76 : 11639867 : LOCK(cs);
77 : 11639867 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78 : 11639867 : std::set<Txid> inputs;
79 [ + + ]: 26276056 : for (const auto& txin : entry.GetTx().vin) {
80 [ + - ]: 14636189 : inputs.insert(txin.prevout.hash);
81 : : }
82 [ + + ]: 26264534 : for (const auto& hash : inputs) {
83 [ + - ]: 14624667 : std::optional<txiter> piter = GetIter(hash);
84 [ + + ]: 14624667 : if (piter) {
85 [ + - ]: 205452 : ret.emplace_back(**piter);
86 : : }
87 : : }
88 : 11639867 : return ret;
89 [ + - ]: 23279734 : }
90 : :
91 : 3342 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
92 : : {
93 : 3342 : AssertLockHeld(cs);
94 : :
95 : : // Iterate in reverse, so that whenever we are looking at a transaction
96 : : // we are sure that all in-mempool descendants have already been processed.
97 [ + + ]: 4160 : for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
98 : : // calculate children from mapNextTx
99 : 818 : txiter it = mapTx.find(hash);
100 [ - + ]: 818 : if (it == mapTx.end()) {
101 : 0 : continue;
102 : : }
103 : 818 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104 : 818 : {
105 [ + + + + ]: 3292 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
106 [ - + ]: 2474 : txiter childIter = iter->second;
107 [ - + ]: 2474 : assert(childIter != mapTx.end());
108 : : // Add dependencies that are discovered between transactions in the
109 : : // block and transactions that were in the mempool to txgraph.
110 : 2474 : m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
111 : : }
112 : : }
113 : : }
114 : :
115 : 3342 : auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
116 [ - + ]: 3342 : for (auto txptr : txs_to_remove) {
117 : 0 : const CTxMemPoolEntry& entry = *(static_cast<const CTxMemPoolEntry*>(txptr));
118 [ # # ]: 0 : removeUnchecked(mapTx.iterator_to(entry), MemPoolRemovalReason::SIZELIMIT);
119 : : }
120 : 3342 : }
121 : :
122 : 223 : bool CTxMemPool::HasDescendants(const Txid& txid) const
123 : : {
124 : 223 : LOCK(cs);
125 [ + - ]: 223 : auto entry = GetEntry(txid);
126 [ + + ]: 223 : if (!entry) return false;
127 [ - + ]: 222 : return m_txgraph->GetDescendants(*entry, TxGraph::Level::MAIN).size() > 1;
128 : 223 : }
129 : :
130 : 3618 : CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const
131 : : {
132 : 3618 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
133 [ - + ]: 3618 : setEntries ret;
134 [ - + + + ]: 3618 : if (ancestors.size() > 0) {
135 [ + + ]: 18750 : for (auto ancestor : ancestors) {
136 [ + + ]: 16389 : if (ancestor != &entry) {
137 [ + - ]: 14028 : ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
138 : : }
139 : : }
140 : : return ret;
141 : : }
142 : :
143 : : // If we didn't get anything back, the transaction is not in the graph.
144 : : // Find each parent and call GetAncestors on each.
145 : 1257 : setEntries staged_parents;
146 : 1257 : const CTransaction &tx = entry.GetTx();
147 : :
148 : : // Get parents of this transaction that are in the mempool
149 [ - + + + ]: 2848 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
150 [ + - ]: 1591 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151 [ + + ]: 1591 : if (piter) {
152 [ + - ]: 235 : staged_parents.insert(*piter);
153 : : }
154 : : }
155 : :
156 [ + + ]: 1466 : for (const auto& parent : staged_parents) {
157 : 209 : auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN);
158 [ + + ]: 696 : for (auto ancestor : parent_ancestors) {
159 [ + - ]: 487 : ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
160 : : }
161 : 209 : }
162 : :
163 : 1257 : return ret;
164 : 4875 : }
165 : :
166 : 1259 : static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
167 : : {
168 [ + - ]: 1259 : opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169 : 1259 : int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170 [ + - + - : 1259 : if (opts.max_size_bytes < 0 || (opts.max_size_bytes > 0 && opts.max_size_bytes < cluster_limit_bytes)) {
+ + ]
171 : 2 : error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(cluster_limit_bytes / 1'000'000.0));
172 : : }
173 : 1259 : return std::move(opts);
174 : : }
175 : :
176 : 1259 : CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
177 [ + - + - ]: 1259 : : m_opts{Flatten(std::move(opts), error)}
178 : : {
179 : 2518 : m_txgraph = MakeTxGraph(
180 : 1259 : /*max_cluster_count=*/m_opts.limits.cluster_count,
181 : 1259 : /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,
182 : : /*acceptable_iters=*/ACCEPTABLE_ITERS,
183 : 1259 : /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184 : 84225673 : const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185 : 84225673 : const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186 : 84225673 : return txid_a <=> txid_b;
187 : 1259 : });
188 : 1259 : }
189 : :
190 : 54 : bool CTxMemPool::isSpent(const COutPoint& outpoint) const
191 : : {
192 : 54 : LOCK(cs);
193 [ + - ]: 54 : return mapNextTx.count(outpoint);
194 : : }
195 : :
196 : 2082 : unsigned int CTxMemPool::GetTransactionsUpdated() const
197 : : {
198 : 2082 : return nTransactionsUpdated;
199 : : }
200 : :
201 : 147493 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
202 : : {
203 : 147493 : nTransactionsUpdated += n;
204 : 147493 : }
205 : :
206 : 51255 : void CTxMemPool::Apply(ChangeSet* changeset)
207 : : {
208 : 51255 : AssertLockHeld(cs);
209 : 51255 : m_txgraph->CommitStaging();
210 : :
211 : 51255 : RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED);
212 : :
213 [ - + + + ]: 102578 : for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214 : 51323 : auto tx_entry = changeset->m_entry_vec[i];
215 : : // First splice this entry into mapTx.
216 : 51323 : auto node_handle = changeset->m_to_add.extract(tx_entry);
217 [ + - ]: 51323 : auto result = mapTx.insert(std::move(node_handle));
218 : :
219 [ + - ]: 51323 : Assume(result.inserted);
220 : 51323 : txiter it = result.position;
221 : :
222 [ + - ]: 51323 : addNewTransaction(it);
223 [ - + ]: 51323 : }
224 : 51255 : m_txgraph->DoWork(POST_CHANGE_WORK);
225 : 51255 : }
226 : :
227 : 51323 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit)
228 : : {
229 : 51323 : const CTxMemPoolEntry& entry = *newit;
230 : :
231 : : // Update cachedInnerUsage to include contained transaction's usage.
232 : : // (When we update the entry for in-mempool parents, memory usage will be
233 : : // further updated.)
234 : 51323 : cachedInnerUsage += entry.DynamicMemoryUsage();
235 : :
236 : 51323 : const CTransaction& tx = newit->GetTx();
237 [ - + + + ]: 115487 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
238 : 64164 : mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit));
239 : : }
240 : : // Don't bother worrying about child transactions of this one.
241 : : // Normal case of a new transaction arriving is that there can't be any
242 : : // children, because such children would be orphans.
243 : : // An exception to that is if a transaction enters that used to be in a block.
244 : : // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
245 : : // to clean up the mess we're leaving here.
246 : :
247 : 51323 : nTransactionsUpdated++;
248 : 51323 : totalTxSize += entry.GetTxSize();
249 : 51323 : m_total_fee += entry.GetFee();
250 : :
251 : 51323 : txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
252 [ - + ]: 51323 : newit->idx_randomized = txns_randomized.size() - 1;
253 : :
254 : : TRACEPOINT(mempool, added,
255 : : entry.GetTx().GetHash().data(),
256 : : entry.GetTxSize(),
257 : : entry.GetFee()
258 : 51323 : );
259 : 51323 : }
260 : :
261 : 47807 : void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
262 : : {
263 : : // We increment mempool sequence value no matter removal reason
264 : : // even if not directly reported below.
265 [ + + ]: 47807 : uint64_t mempool_sequence = GetAndIncrementSequence();
266 : :
267 [ + + + - ]: 47807 : if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
268 : : // Notify clients that a transaction has been removed from the mempool
269 : : // for any reason except being included in a block. Clients interested
270 : : // in transactions included in blocks can subscribe to the BlockConnected
271 : : // notification.
272 [ + - + - ]: 5988 : m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
273 : : }
274 : : TRACEPOINT(mempool, removed,
275 : : it->GetTx().GetHash().data(),
276 : : RemovalReasonToString(reason).c_str(),
277 : : it->GetTxSize(),
278 : : it->GetFee(),
279 : : std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
280 : 47807 : );
281 : :
282 [ + + ]: 107418 : for (const CTxIn& txin : it->GetTx().vin)
283 : 59611 : mapNextTx.erase(txin.prevout);
284 : :
285 : 47807 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
286 : :
287 [ - + + + ]: 47807 : if (txns_randomized.size() > 1) {
288 : : // Remove entry from txns_randomized by replacing it with the back and deleting the back.
289 [ - + ]: 45671 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
290 [ - + ]: 45671 : txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
291 [ - + ]: 45671 : txns_randomized.pop_back();
292 [ - + - + : 45671 : if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
+ + ]
293 : 3224 : txns_randomized.shrink_to_fit();
294 : : }
295 : : } else {
296 [ + - ]: 2136 : txns_randomized.clear();
297 : : }
298 : :
299 : 47807 : totalTxSize -= it->GetTxSize();
300 : 47807 : m_total_fee -= it->GetFee();
301 : 47807 : cachedInnerUsage -= it->DynamicMemoryUsage();
302 : 47807 : mapTx.erase(it);
303 : 47807 : nTransactionsUpdated++;
304 : 47807 : }
305 : :
306 : : // Calculates descendants of given entry and adds to setDescendants.
307 : 79880 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
308 : : {
309 : 79880 : (void)CalculateDescendants(*entryit, setDescendants);
310 : 79880 : return;
311 : : }
312 : :
313 : 79942 : CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const
314 : : {
315 [ + + ]: 365121 : for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
316 [ + - ]: 285179 : setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
317 : : }
318 : 79942 : return mapTx.iterator_to(entry);
319 : : }
320 : :
321 : 255 : void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason)
322 : : {
323 : 255 : AssertLockHeld(cs);
324 : 255 : Assume(!m_have_changeset);
325 : 255 : auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
326 [ + + ]: 556 : for (auto tx: descendants) {
327 [ + - ]: 301 : removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
328 : : }
329 : 255 : }
330 : :
331 : 19176 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
332 : : {
333 : : // Remove transaction from memory pool
334 : 19176 : AssertLockHeld(cs);
335 : 19176 : Assume(!m_have_changeset);
336 : 19176 : txiter origit = mapTx.find(origTx.GetHash());
337 [ + + ]: 19176 : if (origit != mapTx.end()) {
338 : 7 : removeRecursive(origit, reason);
339 : : } else {
340 : : // When recursively removing but origTx isn't in the mempool
341 : : // be sure to remove any descendants that are in the pool. This can
342 : : // happen during chain re-orgs if origTx isn't re-accepted into
343 : : // the mempool for any reason.
344 : 19169 : auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
345 : 19169 : std::vector<const TxGraph::Ref*> to_remove;
346 [ + + + + ]: 19243 : while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
347 [ + - ]: 74 : to_remove.emplace_back(&*(iter->second));
348 : 74 : ++iter;
349 : : }
350 [ - + ]: 19169 : auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
351 [ + + ]: 19246 : for (auto ref : all_removes) {
352 : 77 : auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
353 [ + - ]: 77 : removeUnchecked(tx, reason);
354 : : }
355 : 19169 : }
356 : 19176 : }
357 : :
358 : 3342 : void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
359 : : {
360 : : // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
361 : 3342 : AssertLockHeld(cs);
362 : 3342 : AssertLockHeld(::cs_main);
363 : 3342 : Assume(!m_have_changeset);
364 : :
365 : 3342 : std::vector<const TxGraph::Ref*> to_remove;
366 [ + + ]: 5635 : for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
367 [ + - + + ]: 2293 : if (check_final_and_mature(it)) {
368 [ + - ]: 15 : to_remove.emplace_back(&*it);
369 : : }
370 : : }
371 : :
372 [ - + ]: 3342 : auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
373 : :
374 [ + + ]: 3379 : for (auto ref : all_to_remove) {
375 : 37 : auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
376 [ + - ]: 37 : removeUnchecked(it, MemPoolRemovalReason::REORG);
377 : : }
378 [ + + ]: 5598 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
379 [ + - - + ]: 2256 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
380 : : }
381 : 3342 : m_txgraph->DoWork(POST_CHANGE_WORK);
382 : 3342 : }
383 : :
384 : 58140 : void CTxMemPool::removeConflicts(const CTransaction &tx)
385 : : {
386 : : // Remove transactions which depend on inputs of tx, recursively
387 : 58140 : AssertLockHeld(cs);
388 [ + + ]: 128223 : for (const CTxIn &txin : tx.vin) {
389 : 70083 : auto it = mapNextTx.find(txin.prevout);
390 [ + + ]: 70083 : if (it != mapNextTx.end()) {
391 [ + - ]: 248 : const CTransaction &txConflict = it->second->GetTx();
392 [ + - ]: 248 : if (Assume(txConflict.GetHash() != tx.GetHash()))
393 : : {
394 : 248 : ClearPrioritisation(txConflict.GetHash());
395 : 248 : removeRecursive(it->second, MemPoolRemovalReason::CONFLICT);
396 : : }
397 : : }
398 : : }
399 : 58140 : }
400 : :
401 : 132835 : void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
402 : : {
403 : : // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
404 : 132835 : AssertLockHeld(cs);
405 [ + + ]: 132835 : Assume(!m_have_changeset);
406 : 132835 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
407 [ + + + - : 132835 : if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
+ + ]
408 [ - + + - ]: 7907 : txs_removed_for_block.reserve(vtx.size());
409 [ + + ]: 66047 : for (const auto& tx : vtx) {
410 : 58140 : txiter it = mapTx.find(tx->GetHash());
411 [ + + ]: 58140 : if (it != mapTx.end()) {
412 [ + - ]: 45811 : txs_removed_for_block.emplace_back(*it);
413 [ + - ]: 45811 : removeUnchecked(it, MemPoolRemovalReason::BLOCK);
414 : : }
415 [ + - ]: 58140 : removeConflicts(*tx);
416 [ + - ]: 58140 : ClearPrioritisation(tx->GetHash());
417 : : }
418 : : }
419 [ + - ]: 132835 : if (m_opts.signals) {
420 [ + - ]: 132835 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
421 : : }
422 [ + - ]: 132835 : lastRollingFeeUpdate = GetTime();
423 : 132835 : blockSinceLastRollingFeeBump = true;
424 : 132835 : m_txgraph->DoWork(POST_CHANGE_WORK);
425 : 132835 : }
426 : :
427 : 157597 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
428 : : {
429 [ + + ]: 157597 : if (m_opts.check_ratio == 0) return;
430 : :
431 [ + - ]: 155550 : if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
432 : :
433 : 155550 : AssertLockHeld(::cs_main);
434 : 155550 : LOCK(cs);
435 [ + - + - : 155550 : LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - ]
436 : :
437 : 155550 : uint64_t checkTotal = 0;
438 : 155550 : CAmount check_total_fee{0};
439 : 155550 : CAmount check_total_modified_fee{0};
440 : 155550 : int64_t check_total_adjusted_weight{0};
441 : 155550 : uint64_t innerUsage = 0;
442 : :
443 [ - + ]: 155550 : assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
444 [ + - ]: 155550 : m_txgraph->SanityCheck();
445 : :
446 [ + - ]: 155550 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
447 : :
448 [ + - ]: 155550 : const auto score_with_topo{GetSortedScoreWithTopology()};
449 : :
450 : : // Number of chunks is bounded by number of transactions.
451 [ + - ]: 155550 : const auto diagram{GetFeerateDiagram()};
452 [ - + - + : 155550 : assert(diagram.size() <= score_with_topo.size() + 1);
- + ]
453 [ - + ]: 155550 : assert(diagram.size() >= 1);
454 : :
455 : 155550 : std::optional<Wtxid> last_wtxid = std::nullopt;
456 : 155550 : auto diagram_iter = diagram.cbegin();
457 : :
458 [ + + ]: 11763100 : for (const auto& it : score_with_topo) {
459 : : // GetSortedScoreWithTopology() contains the same chunks as the feerate
460 : : // diagram. We do not know where the chunk boundaries are, but we can
461 : : // check that there are points at which they match the cumulative fee
462 : : // and weight.
463 : : // The feerate diagram should never get behind the current transaction
464 : : // size totals.
465 [ - + ]: 11607550 : assert(diagram_iter->size >= check_total_adjusted_weight);
466 [ + + ]: 11607550 : if (diagram_iter->fee == check_total_modified_fee &&
467 [ + - ]: 11586109 : diagram_iter->size == check_total_adjusted_weight) {
468 : 11586109 : ++diagram_iter;
469 : : }
470 [ + - ]: 11607550 : checkTotal += it->GetTxSize();
471 [ + - ]: 11607550 : check_total_adjusted_weight += it->GetAdjustedWeight();
472 [ + + ]: 11607550 : check_total_fee += it->GetFee();
473 [ + + ]: 11607550 : check_total_modified_fee += it->GetModifiedFee();
474 [ + + ]: 11607550 : innerUsage += it->DynamicMemoryUsage();
475 [ + + ]: 11607550 : const CTransaction& tx = it->GetTx();
476 : :
477 : : // CompareMiningScoreWithTopology should agree with GetSortedScoreWithTopology()
478 [ + + ]: 11607550 : if (last_wtxid) {
479 [ + - - + ]: 11576714 : assert(CompareMiningScoreWithTopology(*last_wtxid, tx.GetWitnessHash()));
480 : : }
481 [ + + ]: 11607550 : last_wtxid = tx.GetWitnessHash();
482 : :
483 : 11607550 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
484 : 11607550 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
485 [ + + ]: 26192393 : for (const CTxIn &txin : tx.vin) {
486 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
487 : 14584843 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
488 [ + + ]: 14584843 : if (it2 != mapTx.end()) {
489 [ - + ]: 198483 : const CTransaction& tx2 = it2->GetTx();
490 [ - + + - : 198483 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
- + ]
491 [ + - ]: 198483 : setParentCheck.insert(*it2);
492 : : }
493 : : // We are iterating through the mempool entries sorted
494 : : // topologically and by mining score. All parents must have been
495 : : // checked before their children and their coins added to the
496 : : // mempoolDuplicate coins cache.
497 [ + - - + ]: 14584843 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
498 : : // Check whether its inputs are marked in mapNextTx.
499 : 14584843 : auto it3 = mapNextTx.find(txin.prevout);
500 [ - + ]: 14584843 : assert(it3 != mapNextTx.end());
501 [ - + ]: 14584843 : assert(it3->first == &txin.prevout);
502 [ - + ]: 14584843 : assert(&it3->second->GetTx() == &tx);
503 : : }
504 : 12004314 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
505 [ + - ]: 396764 : return a.GetTx().GetHash() == b.GetTx().GetHash();
506 : : };
507 [ + - + + ]: 11805932 : for (auto &txentry : GetParents(*it)) {
508 [ + - ]: 198382 : setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
509 : 0 : }
510 [ - + ]: 11607550 : assert(setParentCheck.size() == setParentsStored.size());
511 [ - + ]: 11607550 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
512 : :
513 : : // Check children against mapNextTx
514 : 11607550 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
515 : 11607550 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
516 : 11607550 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
517 [ + + + + ]: 11806033 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
518 [ - + ]: 198483 : txiter childit = iter->second;
519 [ - + ]: 198483 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
520 [ + - ]: 198483 : setChildrenCheck.insert(*childit);
521 : : }
522 [ + - + + ]: 11805932 : for (auto &txentry : GetChildren(*it)) {
523 [ + - ]: 198382 : setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
524 : 0 : }
525 [ - + ]: 11607550 : assert(setChildrenCheck.size() == setChildrenStored.size());
526 [ - + ]: 11607550 : assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
527 : :
528 [ - + ]: 11607550 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
529 : 11607550 : CAmount txfee = 0;
530 [ - + ]: 11607550 : assert(!tx.IsCoinBase());
531 [ + - - + ]: 11607550 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
532 [ + - + + ]: 26192393 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
533 [ + - ]: 11607550 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
534 : 11607550 : }
535 [ + + ]: 14740393 : for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
536 [ - + ]: 14584843 : indexed_transaction_set::const_iterator it2 = it->second;
537 [ - + ]: 14584843 : assert(it2 != mapTx.end());
538 : : }
539 : :
540 [ - + ]: 155550 : ++diagram_iter;
541 [ - + ]: 155550 : assert(diagram_iter == diagram.cend());
542 : :
543 [ - + ]: 155550 : assert(totalTxSize == checkTotal);
544 [ - + ]: 155550 : assert(m_total_fee == check_total_fee);
545 [ - + ]: 155550 : assert(diagram.back().fee == check_total_modified_fee);
546 [ - + ]: 155550 : assert(diagram.back().size == check_total_adjusted_weight);
547 [ - + ]: 155550 : assert(innerUsage == cachedInnerUsage);
548 [ + - ]: 311100 : }
549 : :
550 : 11600116 : bool CTxMemPool::CompareMiningScoreWithTopology(const Wtxid& hasha, const Wtxid& hashb) const
551 : : {
552 : : /* Return `true` if hasha should be considered sooner than hashb, namely when:
553 : : * a is not in the mempool but b is, or
554 : : * both are in the mempool but a is sorted before b in the total mempool ordering
555 : : * (which takes dependencies and (chunk) feerates into account).
556 : : */
557 : 11600116 : LOCK(cs);
558 [ + - ]: 11600116 : auto j{GetIter(hashb)};
559 [ + + ]: 11600116 : if (!j.has_value()) return false;
560 [ + - ]: 11596012 : auto i{GetIter(hasha)};
561 [ + + ]: 11596012 : if (!i.has_value()) return true;
562 : :
563 : 11595521 : return m_txgraph->CompareMainOrder(*i.value(), *j.value()) < 0;
564 : 11600116 : }
565 : :
566 : 165508 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
567 : : {
568 : 165508 : std::vector<indexed_transaction_set::const_iterator> iters;
569 : 165508 : AssertLockHeld(cs);
570 : :
571 [ + - ]: 165508 : iters.reserve(mapTx.size());
572 : :
573 [ + + + + ]: 24032922 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
574 [ + - ]: 11933707 : iters.push_back(mi);
575 : : }
576 : 165508 : std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
577 : 138951956 : return m_txgraph->CompareMainOrder(*a, *b) < 0;
578 : : });
579 : 165508 : return iters;
580 : 0 : }
581 : :
582 : 9002 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
583 : : {
584 : 9002 : AssertLockHeld(cs);
585 : :
586 : 9002 : std::vector<CTxMemPoolEntryRef> ret;
587 [ + - ]: 9002 : ret.reserve(mapTx.size());
588 [ + - + + ]: 333939 : for (const auto& it : GetSortedScoreWithTopology()) {
589 [ + - ]: 324937 : ret.emplace_back(*it);
590 : : }
591 : 9002 : return ret;
592 : 0 : }
593 : :
594 : 956 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
595 : : {
596 : 956 : LOCK(cs);
597 [ + - ]: 956 : auto iters = GetSortedScoreWithTopology();
598 : :
599 : 956 : std::vector<TxMempoolInfo> ret;
600 [ + - ]: 956 : ret.reserve(mapTx.size());
601 [ + + ]: 2176 : for (auto it : iters) {
602 [ + - - + ]: 2440 : ret.push_back(GetInfo(it));
603 : : }
604 : :
605 : 956 : return ret;
606 [ + - ]: 1912 : }
607 : :
608 : 4624 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
609 : : {
610 : 4624 : AssertLockHeld(cs);
611 : 4624 : const auto i = mapTx.find(txid);
612 [ + + ]: 4624 : return i == mapTx.end() ? nullptr : &(*i);
613 : : }
614 : :
615 : 210347 : CTransactionRef CTxMemPool::get(const Txid& hash) const
616 : : {
617 : 210347 : LOCK(cs);
618 : 210347 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
619 [ + + ]: 210347 : if (i == mapTx.end())
620 : 149392 : return nullptr;
621 [ + - + - ]: 271302 : return i->GetSharedTx();
622 : 210347 : }
623 : :
624 : 769 : void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
625 : : {
626 : 769 : {
627 : 769 : LOCK(cs);
628 [ + - ]: 769 : CAmount &delta = mapDeltas[hash];
629 : 769 : delta = SaturatingAdd(delta, nFeeDelta);
630 : 769 : txiter it = mapTx.find(hash);
631 [ + + ]: 769 : if (it != mapTx.end()) {
632 : : // PrioritiseTransaction calls stack on previous ones. Set the new
633 : : // transaction fee to be current modified fee + feedelta.
634 : 262 : it->UpdateModifiedFee(nFeeDelta);
635 : 262 : m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
636 : 262 : ++nTransactionsUpdated;
637 : : }
638 [ + + ]: 769 : if (delta == 0) {
639 : 9 : mapDeltas.erase(hash);
640 [ + + + - : 25 : LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
+ - ]
641 : : } else {
642 [ + - + - : 1775 : LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
+ + + - +
- ]
643 : : hash.ToString(),
644 : : it == mapTx.end() ? "not " : "",
645 : : FormatMoney(nFeeDelta),
646 : : FormatMoney(delta));
647 : : }
648 : 769 : }
649 : 769 : }
650 : :
651 : 62552 : void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
652 : : {
653 : 62552 : AssertLockHeld(cs);
654 : 62552 : std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
655 [ + + ]: 62552 : if (pos == mapDeltas.end())
656 : : return;
657 : 41 : const CAmount &delta = pos->second;
658 : 41 : nFeeDelta += delta;
659 : : }
660 : :
661 : 58389 : void CTxMemPool::ClearPrioritisation(const Txid& hash)
662 : : {
663 : 58389 : AssertLockHeld(cs);
664 : 58389 : mapDeltas.erase(hash);
665 : 58389 : }
666 : :
667 : 31 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
668 : : {
669 : 31 : AssertLockNotHeld(cs);
670 : 31 : LOCK(cs);
671 : 31 : std::vector<delta_info> result;
672 [ + - ]: 31 : result.reserve(mapDeltas.size());
673 [ + + ]: 61 : for (const auto& [txid, delta] : mapDeltas) {
674 : 30 : const auto iter{mapTx.find(txid)};
675 [ + + ]: 30 : const bool in_mempool{iter != mapTx.end()};
676 : 30 : std::optional<CAmount> modified_fee;
677 [ + + ]: 30 : if (in_mempool) modified_fee = iter->GetModifiedFee();
678 [ + - ]: 30 : result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
679 : : }
680 [ + - ]: 31 : return result;
681 : 31 : }
682 : :
683 : 111553 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
684 : : {
685 : 111553 : const auto it = mapNextTx.find(prevout);
686 [ + + ]: 111553 : return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
687 : : }
688 : :
689 : 14754634 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
690 : : {
691 : 14754634 : AssertLockHeld(cs);
692 : 14754634 : auto it = mapTx.find(txid);
693 [ + + ]: 14754634 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
694 : : }
695 : :
696 : 23229655 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
697 : : {
698 : 23229655 : AssertLockHeld(cs);
699 [ + + ]: 23229655 : auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
700 [ + + ]: 23229655 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
701 : : }
702 : :
703 : 32303 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
704 : : {
705 : 32303 : CTxMemPool::setEntries ret;
706 [ + + ]: 34677 : for (const auto& h : hashes) {
707 [ + - ]: 2374 : const auto mi = GetIter(h);
708 [ + - + - ]: 2374 : if (mi) ret.insert(*mi);
709 : : }
710 : 32303 : return ret;
711 : 0 : }
712 : :
713 : 2 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
714 : : {
715 : 2 : AssertLockHeld(cs);
716 : 2 : std::vector<txiter> ret;
717 [ - + + - ]: 2 : ret.reserve(txids.size());
718 [ + + ]: 565 : for (const auto& txid : txids) {
719 [ + - ]: 563 : const auto it{GetIter(txid)};
720 [ - + ]: 563 : if (!it) return {};
721 [ + - ]: 563 : ret.push_back(*it);
722 : : }
723 : 2 : return ret;
724 : 2 : }
725 : :
726 : 24740 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
727 : : {
728 [ - + + + ]: 56442 : for (unsigned int i = 0; i < tx.vin.size(); i++)
729 [ + + ]: 35096 : if (exists(tx.vin[i].prevout.hash))
730 : : return false;
731 : : return true;
732 : : }
733 : :
734 [ + - + - ]: 40433 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
735 : :
736 : 63917 : std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
737 : : {
738 : : // Check to see if the inputs are made available by another tx in the package.
739 : : // These Coins would not be available in the underlying CoinsView.
740 [ + + ]: 63917 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
741 : 615 : return it->second;
742 : : }
743 : :
744 : : // If an entry in the mempool exists, always return that one, as it's guaranteed to never
745 : : // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
746 : : // transactions. First checking the underlying cache risks returning a pruned entry instead.
747 : 63302 : CTransactionRef ptx = mempool.get(outpoint.hash);
748 [ + + ]: 63302 : if (ptx) {
749 [ - + + - ]: 8663 : if (outpoint.n < ptx->vout.size()) {
750 : 8663 : Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
751 [ + - ]: 8663 : m_non_base_coins.emplace(outpoint);
752 : 8663 : return coin;
753 : 8663 : }
754 : 0 : return std::nullopt;
755 : : }
756 [ + - ]: 54639 : return base->GetCoin(outpoint);
757 : 63302 : }
758 : :
759 : 778 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
760 : : {
761 [ - + + + ]: 1593 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
762 [ + - ]: 815 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
763 : 815 : m_non_base_coins.emplace(tx->GetHash(), n);
764 : : }
765 : 778 : }
766 : 63059 : void CCoinsViewMemPool::Reset()
767 : : {
768 : 63059 : m_temp_added.clear();
769 : 63059 : m_non_base_coins.clear();
770 : 63059 : }
771 : :
772 : 540763 : size_t CTxMemPool::DynamicMemoryUsage() const {
773 : 540763 : LOCK(cs);
774 : : // Estimate the overhead of mapTx to be 9 pointers (3 pointers per index) + an allocation, as no exact formula for boost::multi_index_contained is implemented.
775 [ - + + - ]: 1081526 : return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
776 : 540763 : }
777 : :
778 : 60605 : void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
779 : 60605 : LOCK(cs);
780 : :
781 [ + + ]: 60605 : if (m_unbroadcast_txids.erase(txid))
782 : : {
783 [ + - + - : 28386 : LogDebug(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
+ + + - +
- ]
784 : : }
785 : 60605 : }
786 : :
787 : 78409 : void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) {
788 : 78409 : AssertLockHeld(cs);
789 [ + + ]: 79945 : for (txiter it : stage) {
790 : 1536 : removeUnchecked(it, reason);
791 : : }
792 : 78409 : }
793 : :
794 : 3417 : bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx)
795 : : {
796 : 3417 : LOCK(cs);
797 : : // Use ChangeSet interface to check whether the cluster count
798 : : // limits would be violated. Note that the changeset will be destroyed
799 : : // when it goes out of scope.
800 [ + - ]: 3417 : auto changeset = GetChangeSet();
801 [ + - ]: 3417 : (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
802 [ + - ]: 3417 : return changeset->CheckMemPoolPolicyLimits();
803 [ + - ]: 6834 : }
804 : :
805 : 27154 : int CTxMemPool::Expire(std::chrono::seconds time)
806 : : {
807 : 27154 : AssertLockHeld(cs);
808 : 27154 : Assume(!m_have_changeset);
809 : 27154 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
810 : 27154 : setEntries toremove;
811 [ + + + + ]: 27158 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
812 [ + - ]: 4 : toremove.insert(mapTx.project<0>(it));
813 : 4 : it++;
814 : : }
815 : 27154 : setEntries stage;
816 [ + + ]: 27158 : for (txiter removeit : toremove) {
817 [ + - ]: 4 : CalculateDescendants(removeit, stage);
818 : : }
819 [ + - ]: 27154 : RemoveStaged(stage, MemPoolRemovalReason::EXPIRY);
820 : 27154 : return stage.size();
821 : 27154 : }
822 : :
823 : 481297 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
824 : 481297 : LOCK(cs);
825 [ + + + + ]: 481297 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
826 : 481248 : return CFeeRate(llround(rollingMinimumFeeRate));
827 : :
828 [ + - ]: 49 : int64_t time = GetTime();
829 [ + + ]: 49 : if (time > lastRollingFeeUpdate + 10) {
830 : 6 : double halflife = ROLLING_FEE_HALFLIFE;
831 [ + - + + ]: 6 : if (DynamicMemoryUsage() < sizelimit / 4)
832 : : halflife /= 4;
833 [ + - + + ]: 5 : else if (DynamicMemoryUsage() < sizelimit / 2)
834 : 1 : halflife /= 2;
835 : :
836 : 6 : rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
837 : 6 : lastRollingFeeUpdate = time;
838 : :
839 [ + + ]: 6 : if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
840 : 1 : rollingMinimumFeeRate = 0;
841 : 1 : return CFeeRate(0);
842 : : }
843 : : }
844 : 48 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
845 : 481297 : }
846 : :
847 : 39 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
848 : 39 : AssertLockHeld(cs);
849 [ + + ]: 39 : if (rate.GetFeePerK() > rollingMinimumFeeRate) {
850 : 37 : rollingMinimumFeeRate = rate.GetFeePerK();
851 : 37 : blockSinceLastRollingFeeBump = false;
852 : : }
853 : 39 : }
854 : :
855 : 27163 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
856 : 27163 : AssertLockHeld(cs);
857 : 27163 : Assume(!m_have_changeset);
858 : :
859 : 27163 : unsigned nTxnRemoved = 0;
860 : 27163 : CFeeRate maxFeeRateRemoved(0);
861 : :
862 [ + + + + ]: 27202 : while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
863 [ + - ]: 39 : const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
864 [ + - ]: 39 : FeePerVSize feerate = ToFeePerVSize(feeperweight);
865 [ + - ]: 39 : CFeeRate removed{feerate.fee, feerate.size};
866 : :
867 : : // We set the new mempool min fee to the feerate of the removed set, plus the
868 : : // "minimum reasonable fee rate" (ie some value under which we consider txn
869 : : // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
870 : : // equal to txn which were removed with no block in between.
871 : 39 : removed += m_opts.incremental_relay_feerate;
872 [ + - ]: 39 : trackPackageRemoved(removed);
873 : 39 : maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
874 : :
875 [ - + ]: 39 : nTxnRemoved += worst_chunk.size();
876 : :
877 : 39 : std::vector<CTransaction> txn;
878 [ + + ]: 39 : if (pvNoSpendsRemaining) {
879 [ + - ]: 31 : txn.reserve(worst_chunk.size());
880 [ + + ]: 63 : for (auto ref : worst_chunk) {
881 [ + - ]: 32 : txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
882 : : }
883 : : }
884 : :
885 : 39 : setEntries stage;
886 [ + + ]: 84 : for (auto ref : worst_chunk) {
887 [ + - ]: 45 : stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
888 : : }
889 [ + + ]: 84 : for (auto e : stage) {
890 [ + - ]: 45 : removeUnchecked(e, MemPoolRemovalReason::SIZELIMIT);
891 : : }
892 [ + + ]: 39 : if (pvNoSpendsRemaining) {
893 [ + + ]: 63 : for (const CTransaction& tx : txn) {
894 [ + + ]: 64 : for (const CTxIn& txin : tx.vin) {
895 [ + - + + ]: 32 : if (exists(txin.prevout.hash)) continue;
896 [ + - ]: 31 : pvNoSpendsRemaining->push_back(txin.prevout);
897 : : }
898 : : }
899 : : }
900 : 78 : }
901 : :
902 [ + + ]: 27163 : if (maxFeeRateRemoved > CFeeRate(0)) {
903 [ + - + - ]: 64 : LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
904 : : }
905 : 27163 : }
906 : :
907 : 124167 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
908 : : {
909 : 124167 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
910 : :
911 [ - + ]: 124167 : size_t ancestor_count = ancestors.size();
912 : 124167 : size_t ancestor_size = 0;
913 : 124167 : CAmount ancestor_fees = 0;
914 [ + + ]: 447561 : for (auto tx: ancestors) {
915 : 323394 : const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
916 [ + - ]: 323394 : ancestor_size += anc.GetTxSize();
917 : 323394 : ancestor_fees += anc.GetModifiedFee();
918 : : }
919 : 124167 : return {ancestor_count, ancestor_size, ancestor_fees};
920 : 124167 : }
921 : :
922 : 9138 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
923 : : {
924 : 9138 : auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
925 [ - + ]: 9138 : size_t descendant_count = descendants.size();
926 : 9138 : size_t descendant_size = 0;
927 : 9138 : CAmount descendant_fees = 0;
928 : :
929 [ + + ]: 164688 : for (auto tx: descendants) {
930 : 155550 : const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
931 [ + - ]: 155550 : descendant_size += desc.GetTxSize();
932 : 155550 : descendant_fees += desc.GetModifiedFee();
933 : : }
934 : 9138 : return {descendant_count, descendant_size, descendant_fees};
935 : 9138 : }
936 : :
937 : 582682 : void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
938 : 582682 : LOCK(cs);
939 : 582682 : auto it = mapTx.find(txid);
940 : 582682 : ancestors = cluster_count = 0;
941 [ + + ]: 582682 : if (it != mapTx.end()) {
942 [ + - + + ]: 47078 : auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
943 : 47078 : ancestors = ancestor_count;
944 [ + + ]: 47078 : if (ancestorsize) *ancestorsize = ancestor_size;
945 [ + + ]: 47078 : if (ancestorfees) *ancestorfees = ancestor_fees;
946 [ - + ]: 47078 : cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
947 : : }
948 : 582682 : }
949 : :
950 : 2391 : bool CTxMemPool::GetLoadTried() const
951 : : {
952 : 2391 : LOCK(cs);
953 [ + - ]: 2391 : return m_load_tried;
954 : 2391 : }
955 : :
956 : 1033 : void CTxMemPool::SetLoadTried(bool load_tried)
957 : : {
958 : 1033 : LOCK(cs);
959 [ + - ]: 1033 : m_load_tried = load_tried;
960 : 1033 : }
961 : :
962 : 3056 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
963 : : {
964 : 3056 : AssertLockHeld(cs);
965 : :
966 : 3056 : std::vector<CTxMemPool::txiter> ret;
967 : 3056 : std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
968 [ + + ]: 51775 : for (auto txid : txids) {
969 : 48719 : auto it = mapTx.find(txid);
970 [ + - ]: 48719 : if (it != mapTx.end()) {
971 : : // Note that TxGraph::GetCluster will return results in graph
972 : : // order, which is deterministic (as long as we are not modifying
973 : : // the graph).
974 : 48719 : auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
975 [ + - + + ]: 48719 : if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
976 [ + + ]: 117869 : for (auto tx : cluster) {
977 [ + - ]: 69317 : ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
978 : : }
979 : : }
980 : 48719 : }
981 : : }
982 [ - + + + ]: 3056 : if (ret.size() > 500) {
983 : 1 : return {};
984 : : }
985 : 3055 : return ret;
986 : 3056 : }
987 : :
988 : 1284 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
989 : : {
990 : 1284 : LOCK(m_pool->cs);
991 : :
992 [ + - - + ]: 1284 : if (!CheckMemPoolPolicyLimits()) {
993 [ # # # # ]: 0 : return util::Error{Untranslated("cluster size limit exceeded")};
994 : : }
995 : :
996 : 2568 : return m_pool->m_txgraph->GetMainStagingDiagrams();
997 : 1284 : }
998 : :
999 : 62552 : 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)
1000 : : {
1001 : 62552 : LOCK(m_pool->cs);
1002 [ + - ]: 62552 : Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1003 : 62552 : Assume(!m_dependencies_processed);
1004 : :
1005 : : // We need to process dependencies after adding a new transaction.
1006 : 62552 : m_dependencies_processed = false;
1007 : :
1008 : 62552 : CAmount delta{0};
1009 [ + - ]: 62552 : m_pool->ApplyDelta(tx->GetHash(), delta);
1010 : :
1011 [ + - + - ]: 62552 : FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp));
1012 [ + - ]: 62552 : auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1013 : 62552 : m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1014 [ + + ]: 62552 : if (delta) {
1015 : 41 : newit->UpdateModifiedFee(delta);
1016 : 41 : m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1017 : : }
1018 : :
1019 [ + - ]: 62552 : m_entry_vec.push_back(newit);
1020 : :
1021 [ + - ]: 62552 : return newit;
1022 : 62552 : }
1023 : :
1024 : 2126 : void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it)
1025 : : {
1026 : 2126 : LOCK(m_pool->cs);
1027 : 2126 : m_pool->m_txgraph->RemoveTransaction(*it);
1028 [ + - ]: 2126 : m_to_remove.insert(it);
1029 : 2126 : }
1030 : :
1031 : 51255 : void CTxMemPool::ChangeSet::Apply()
1032 : : {
1033 : 51255 : LOCK(m_pool->cs);
1034 [ + + ]: 51255 : if (!m_dependencies_processed) {
1035 [ + - ]: 3 : ProcessDependencies();
1036 : : }
1037 [ + - ]: 51255 : m_pool->Apply(this);
1038 : 51255 : m_to_add.clear();
1039 : 51255 : m_to_remove.clear();
1040 [ + - ]: 51255 : m_entry_vec.clear();
1041 [ + - ]: 51255 : m_ancestors.clear();
1042 : 51255 : }
1043 : :
1044 : 61605 : void CTxMemPool::ChangeSet::ProcessDependencies()
1045 : : {
1046 : 61605 : LOCK(m_pool->cs);
1047 : 61605 : Assume(!m_dependencies_processed); // should only call this once.
1048 [ + + ]: 123796 : for (const auto& entryptr : m_entry_vec) {
1049 [ + - + - : 274998 : for (const auto &txin : entryptr->GetSharedTx()->vin) {
+ + ]
1050 [ + - ]: 88425 : std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1051 [ + + ]: 88425 : if (!piter) {
1052 : 78562 : auto it = m_to_add.find(txin.prevout.hash);
1053 [ + + ]: 78562 : if (it != m_to_add.end()) {
1054 : 585 : piter = std::make_optional(it);
1055 : : }
1056 : : }
1057 [ + + ]: 88425 : if (piter) {
1058 : 10448 : m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1059 : : }
1060 : : }
1061 : : }
1062 : 61605 : m_dependencies_processed = true;
1063 [ + - ]: 61605 : return;
1064 : 61605 : }
1065 : :
1066 : 64141 : bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits()
1067 : : {
1068 : 64141 : LOCK(m_pool->cs);
1069 [ + + ]: 64141 : if (!m_dependencies_processed) {
1070 [ + - ]: 61602 : ProcessDependencies();
1071 : : }
1072 : :
1073 [ + - ]: 64141 : return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1074 : 64141 : }
1075 : :
1076 : 155555 : std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1077 : : {
1078 : 155555 : FeePerWeight zero{};
1079 : 155555 : std::vector<FeePerWeight> ret;
1080 : :
1081 [ + - ]: 155555 : ret.emplace_back(zero);
1082 : :
1083 : 155555 : StartBlockBuilding();
1084 : :
1085 : 155555 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1086 : :
1087 [ + - ]: 155555 : FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1088 [ + + ]: 11741790 : while (last_selection != FeePerWeight{}) {
1089 [ + - ]: 11586235 : last_selection += ret.back();
1090 [ + - ]: 11586235 : ret.emplace_back(last_selection);
1091 : 11586235 : IncludeBuilderChunk();
1092 [ + - ]: 11586235 : last_selection = GetBlockBuilderChunk(dummy);
1093 : : }
1094 : 155555 : StopBlockBuilding();
1095 : 155555 : return ret;
1096 : 155555 : }
|