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 : 4627 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41 : : {
42 : 4627 : 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 [ + - ]: 4627 : 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 [ + + ]: 4627 : if (!active_chain.Contains(lp.maxInputBlock)) {
49 : 229 : return false;
50 : : }
51 : : }
52 : :
53 : : // LockPoints still valid
54 : : return true;
55 : : }
56 : :
57 : 11262065 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58 : : {
59 : 11262065 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60 [ + - ]: 11262065 : const auto& hash = entry.GetTx().GetHash();
61 : 11262065 : {
62 [ + - ]: 11262065 : LOCK(cs);
63 : 11262065 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64 [ + + + + ]: 11478484 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65 [ + - ]: 216419 : ret.emplace_back(*(iter->second));
66 : : }
67 : 0 : }
68 : 11262065 : std::ranges::sort(ret, CompareIteratorByHash{});
69 [ + + - - ]: 11283528 : auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70 : 11262065 : ret.erase(removed.begin(), removed.end());
71 : 11262065 : return ret;
72 : 0 : }
73 : :
74 : 11287524 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75 : : {
76 : 11287524 : LOCK(cs);
77 : 11287524 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78 : 11287524 : std::set<Txid> inputs;
79 [ + + ]: 26023017 : for (const auto& txin : entry.GetTx().vin) {
80 [ + - ]: 14735493 : inputs.insert(txin.prevout.hash);
81 : : }
82 [ + + ]: 26013089 : for (const auto& hash : inputs) {
83 [ + - ]: 14725565 : std::optional<txiter> piter = GetIter(hash);
84 [ + + ]: 14725565 : if (piter) {
85 [ + - ]: 215958 : ret.emplace_back(**piter);
86 : : }
87 : : }
88 : 11287524 : return ret;
89 [ + - ]: 22575048 : }
90 : :
91 : 3346 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
92 : : {
93 : 3346 : 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 [ + + ]: 4153 : for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
98 : : // calculate children from mapNextTx
99 : 807 : txiter it = mapTx.find(hash);
100 [ - + ]: 807 : if (it == mapTx.end()) {
101 : 0 : continue;
102 : : }
103 : 807 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104 : 807 : {
105 [ + + + + ]: 3270 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
106 [ - + ]: 2463 : txiter childIter = iter->second;
107 [ - + ]: 2463 : 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 : 2463 : m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
111 : : }
112 : : }
113 : : }
114 : :
115 : 3346 : auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
116 [ - + ]: 3346 : 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 : 3346 : }
121 : :
122 : 219 : bool CTxMemPool::HasDescendants(const Txid& txid) const
123 : : {
124 : 219 : LOCK(cs);
125 [ + - ]: 219 : auto entry = GetEntry(txid);
126 [ + + ]: 219 : if (!entry) return false;
127 [ - + ]: 218 : return m_txgraph->GetDescendants(*entry, TxGraph::Level::MAIN).size() > 1;
128 : 219 : }
129 : :
130 : 2650 : CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const
131 : : {
132 : 2650 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
133 [ - + ]: 2650 : setEntries ret;
134 [ - + + + ]: 2650 : if (ancestors.size() > 0) {
135 [ + + ]: 16357 : for (auto ancestor : ancestors) {
136 [ + + ]: 14969 : if (ancestor != &entry) {
137 [ + - ]: 13581 : 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 : 1262 : setEntries staged_parents;
146 : 1262 : const CTransaction &tx = entry.GetTx();
147 : :
148 : : // Get parents of this transaction that are in the mempool
149 [ - + + + ]: 2858 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
150 [ + - ]: 1596 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151 [ + + ]: 1596 : if (piter) {
152 [ + - ]: 235 : staged_parents.insert(*piter);
153 : : }
154 : : }
155 : :
156 [ + + ]: 1471 : 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 : 1262 : return ret;
164 : 3912 : }
165 : :
166 : 1274 : static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
167 : : {
168 [ + - ]: 1274 : opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169 : 1274 : int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170 [ + - + - : 1274 : 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 : 1274 : return std::move(opts);
174 : : }
175 : :
176 : 1274 : CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
177 [ + - + - ]: 1274 : : m_opts{Flatten(std::move(opts), error)}
178 : : {
179 : 2548 : m_txgraph = MakeTxGraph(
180 : 1274 : /*max_cluster_count=*/m_opts.limits.cluster_count,
181 : 1274 : /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,
182 : : /*acceptable_iters=*/ACCEPTABLE_ITERS,
183 : 1274 : /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184 : 77996303 : const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185 : 77996303 : const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186 : 77996303 : return txid_a <=> txid_b;
187 : 1274 : });
188 : 1274 : }
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 : 147885 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
202 : : {
203 : 147885 : nTransactionsUpdated += n;
204 : 147885 : }
205 : :
206 : 52410 : void CTxMemPool::Apply(ChangeSet* changeset)
207 : : {
208 : 52410 : AssertLockHeld(cs);
209 : 52410 : m_txgraph->CommitStaging();
210 : :
211 : 52410 : RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED);
212 : :
213 [ - + + + ]: 104888 : for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214 : 52478 : auto tx_entry = changeset->m_entry_vec[i];
215 : : // First splice this entry into mapTx.
216 : 52478 : auto node_handle = changeset->m_to_add.extract(tx_entry);
217 [ + - ]: 52478 : auto result = mapTx.insert(std::move(node_handle));
218 : :
219 [ + - ]: 52478 : Assume(result.inserted);
220 : 52478 : txiter it = result.position;
221 : :
222 [ + - ]: 52478 : addNewTransaction(it);
223 [ - + ]: 52478 : }
224 : 52410 : m_txgraph->DoWork(POST_CHANGE_WORK);
225 : 52410 : }
226 : :
227 : 52478 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit)
228 : : {
229 : 52478 : 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 : 52478 : cachedInnerUsage += entry.DynamicMemoryUsage();
235 : :
236 : 52478 : const CTransaction& tx = newit->GetTx();
237 [ - + + + ]: 117993 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
238 : 65515 : 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 : 52478 : nTransactionsUpdated++;
248 : 52478 : totalTxSize += entry.GetTxSize();
249 : 52478 : m_total_fee += entry.GetFee();
250 : :
251 : 52478 : txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
252 [ - + ]: 52478 : newit->idx_randomized = txns_randomized.size() - 1;
253 : :
254 : : TRACEPOINT(mempool, added,
255 : : entry.GetTx().GetHash().data(),
256 : : entry.GetTxSize(),
257 : : entry.GetFee()
258 : 52478 : );
259 : 52478 : }
260 : :
261 : 49032 : 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 [ + + ]: 49032 : uint64_t mempool_sequence = GetAndIncrementSequence();
266 : :
267 [ + + + - ]: 49032 : 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 [ + - + - ]: 6246 : 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 : 49032 : );
281 : :
282 [ + + ]: 110083 : for (const CTxIn& txin : it->GetTx().vin)
283 : 61051 : mapNextTx.erase(txin.prevout);
284 : :
285 : 49032 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
286 : :
287 [ - + + + ]: 49032 : if (txns_randomized.size() > 1) {
288 : : // Remove entry from txns_randomized by replacing it with the back and deleting the back.
289 [ - + ]: 46864 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
290 [ - + ]: 46864 : txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
291 [ - + ]: 46864 : txns_randomized.pop_back();
292 [ - + - + : 46864 : if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
+ + ]
293 : 3309 : txns_randomized.shrink_to_fit();
294 : : }
295 : : } else {
296 [ + - ]: 2168 : txns_randomized.clear();
297 : : }
298 : :
299 : 49032 : totalTxSize -= it->GetTxSize();
300 : 49032 : m_total_fee -= it->GetFee();
301 : 49032 : cachedInnerUsage -= it->DynamicMemoryUsage();
302 : 49032 : mapTx.erase(it);
303 : 49032 : nTransactionsUpdated++;
304 : 49032 : }
305 : :
306 : : // Calculates descendants of given entry and adds to setDescendants.
307 : 79951 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
308 : : {
309 : 79951 : (void)CalculateDescendants(*entryit, setDescendants);
310 : 79951 : return;
311 : : }
312 : :
313 : 80013 : CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const
314 : : {
315 [ + + ]: 362294 : for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
316 [ + - ]: 282281 : setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
317 : : }
318 : 80013 : return mapTx.iterator_to(entry);
319 : : }
320 : :
321 : 163 : void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason)
322 : : {
323 : 163 : AssertLockHeld(cs);
324 : 163 : Assume(!m_have_changeset);
325 : 163 : auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
326 [ + + ]: 542 : for (auto tx: descendants) {
327 [ + - ]: 379 : removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
328 : : }
329 : 163 : }
330 : :
331 : 19237 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
332 : : {
333 : : // Remove transaction from memory pool
334 : 19237 : AssertLockHeld(cs);
335 : 19237 : Assume(!m_have_changeset);
336 : 19237 : txiter origit = mapTx.find(origTx.GetHash());
337 [ + + ]: 19237 : 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 : 19230 : auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
345 : 19230 : std::vector<const TxGraph::Ref*> to_remove;
346 [ + + + + ]: 19304 : while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
347 [ + - ]: 74 : to_remove.emplace_back(&*(iter->second));
348 : 74 : ++iter;
349 : : }
350 [ - + ]: 19230 : auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
351 [ + + ]: 19307 : for (auto ref : all_removes) {
352 : 77 : auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
353 [ + - ]: 77 : removeUnchecked(tx, reason);
354 : : }
355 : 19230 : }
356 : 19237 : }
357 : :
358 : 3346 : 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 : 3346 : AssertLockHeld(cs);
362 : 3346 : AssertLockHeld(::cs_main);
363 : 3346 : Assume(!m_have_changeset);
364 : :
365 : 3346 : std::vector<const TxGraph::Ref*> to_remove;
366 [ + + ]: 5679 : for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
367 [ + - + + ]: 2333 : if (check_final_and_mature(it)) {
368 [ + - ]: 15 : to_remove.emplace_back(&*it);
369 : : }
370 : : }
371 : :
372 [ - + ]: 3346 : auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
373 : :
374 [ + + ]: 3383 : 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 [ + + ]: 5642 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
379 [ + - - + ]: 2296 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
380 : : }
381 : 3346 : m_txgraph->DoWork(POST_CHANGE_WORK);
382 : 3346 : }
383 : :
384 : 59273 : void CTxMemPool::removeConflicts(const CTransaction &tx)
385 : : {
386 : : // Remove transactions which depend on inputs of tx, recursively
387 : 59273 : AssertLockHeld(cs);
388 [ + + ]: 130598 : for (const CTxIn &txin : tx.vin) {
389 : 71325 : auto it = mapNextTx.find(txin.prevout);
390 [ + + ]: 71325 : if (it != mapNextTx.end()) {
391 [ + - ]: 156 : const CTransaction &txConflict = it->second->GetTx();
392 [ + - ]: 156 : if (Assume(txConflict.GetHash() != tx.GetHash()))
393 : : {
394 : 156 : ClearPrioritisation(txConflict.GetHash());
395 : 156 : removeRecursive(it->second, MemPoolRemovalReason::CONFLICT);
396 : : }
397 : : }
398 : : }
399 : 59273 : }
400 : :
401 : 133231 : 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 : 133231 : AssertLockHeld(cs);
405 [ + + ]: 133231 : Assume(!m_have_changeset);
406 : 133231 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
407 [ + + + - : 133231 : if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
+ + ]
408 [ - + + - ]: 7945 : txs_removed_for_block.reserve(vtx.size());
409 [ + + ]: 67218 : for (const auto& tx : vtx) {
410 : 59273 : txiter it = mapTx.find(tx->GetHash());
411 [ + + ]: 59273 : if (it != mapTx.end()) {
412 [ + - ]: 46950 : txs_removed_for_block.emplace_back(*it);
413 [ + - ]: 46950 : removeUnchecked(it, MemPoolRemovalReason::BLOCK);
414 : : }
415 [ + - ]: 59273 : removeConflicts(*tx);
416 [ + - ]: 59273 : ClearPrioritisation(tx->GetHash());
417 : : }
418 : : }
419 [ + - ]: 133231 : if (m_opts.signals) {
420 [ + - ]: 133231 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
421 : : }
422 [ + - ]: 133231 : lastRollingFeeUpdate = GetTime();
423 : 133231 : blockSinceLastRollingFeeBump = true;
424 : 133231 : m_txgraph->DoWork(POST_CHANGE_WORK);
425 : 133231 : }
426 : :
427 : 159243 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
428 : : {
429 [ + + ]: 159243 : if (m_opts.check_ratio == 0) return;
430 : :
431 [ + - ]: 157196 : if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
432 : :
433 : 157196 : AssertLockHeld(::cs_main);
434 : 157196 : LOCK(cs);
435 [ + - + - : 157196 : LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - ]
436 : :
437 : 157196 : uint64_t checkTotal = 0;
438 : 157196 : CAmount check_total_fee{0};
439 : 157196 : CAmount check_total_modified_fee{0};
440 : 157196 : int64_t check_total_adjusted_weight{0};
441 : 157196 : uint64_t innerUsage = 0;
442 : :
443 [ - + ]: 157196 : assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
444 [ + - ]: 157196 : m_txgraph->SanityCheck();
445 : :
446 [ + - ]: 157196 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
447 : :
448 [ + - ]: 157196 : const auto score_with_topo{GetSortedScoreWithTopology()};
449 : :
450 : : // Number of chunks is bounded by number of transactions.
451 [ + - ]: 157196 : const auto diagram{GetFeerateDiagram()};
452 [ - + - + : 157196 : assert(diagram.size() <= score_with_topo.size() + 1);
- + ]
453 [ - + ]: 157196 : assert(diagram.size() >= 1);
454 : :
455 : 157196 : std::optional<Wtxid> last_wtxid = std::nullopt;
456 : 157196 : auto diagram_iter = diagram.cbegin();
457 : :
458 [ + + ]: 11411196 : 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 [ - + ]: 11254000 : assert(diagram_iter->size >= check_total_adjusted_weight);
466 [ + + ]: 11254000 : if (diagram_iter->fee == check_total_modified_fee &&
467 [ + - ]: 11237134 : diagram_iter->size == check_total_adjusted_weight) {
468 : 11237134 : ++diagram_iter;
469 : : }
470 [ + - ]: 11254000 : checkTotal += it->GetTxSize();
471 [ + - ]: 11254000 : check_total_adjusted_weight += it->GetAdjustedWeight();
472 [ + + ]: 11254000 : check_total_fee += it->GetFee();
473 [ + + ]: 11254000 : check_total_modified_fee += it->GetModifiedFee();
474 [ + + ]: 11254000 : innerUsage += it->DynamicMemoryUsage();
475 [ + + ]: 11254000 : const CTransaction& tx = it->GetTx();
476 : :
477 : : // CompareMiningScoreWithTopology should agree with GetSortedScoreWithTopology()
478 [ + + ]: 11254000 : if (last_wtxid) {
479 [ + - - + ]: 11221911 : assert(CompareMiningScoreWithTopology(*last_wtxid, tx.GetWitnessHash()));
480 : : }
481 [ + + ]: 11254000 : last_wtxid = tx.GetWitnessHash();
482 : :
483 : 11254000 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
484 : 11254000 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
485 [ + + ]: 25936811 : for (const CTxIn &txin : tx.vin) {
486 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
487 : 14682811 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
488 [ + + ]: 14682811 : if (it2 != mapTx.end()) {
489 [ - + ]: 209236 : const CTransaction& tx2 = it2->GetTx();
490 [ - + + - : 209236 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
- + ]
491 [ + - ]: 209236 : 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 [ + - - + ]: 14682811 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
498 : : // Check whether its inputs are marked in mapNextTx.
499 : 14682811 : auto it3 = mapNextTx.find(txin.prevout);
500 [ - + ]: 14682811 : assert(it3 != mapNextTx.end());
501 [ - + ]: 14682811 : assert(it3->first == &txin.prevout);
502 [ - + ]: 14682811 : assert(&it3->second->GetTx() == &tx);
503 : : }
504 : 11672262 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
505 [ + - ]: 418262 : return a.GetTx().GetHash() == b.GetTx().GetHash();
506 : : };
507 [ + - + + ]: 11463131 : for (auto &txentry : GetParents(*it)) {
508 [ + - ]: 209131 : setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
509 : 0 : }
510 [ - + ]: 11254000 : assert(setParentCheck.size() == setParentsStored.size());
511 [ - + ]: 11254000 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
512 : :
513 : : // Check children against mapNextTx
514 : 11254000 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
515 : 11254000 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
516 : 11254000 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
517 [ + + + + ]: 11463236 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
518 [ - + ]: 209236 : txiter childit = iter->second;
519 [ - + ]: 209236 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
520 [ + - ]: 209236 : setChildrenCheck.insert(*childit);
521 : : }
522 [ + - + + ]: 11463131 : for (auto &txentry : GetChildren(*it)) {
523 [ + - ]: 209131 : setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
524 : 0 : }
525 [ - + ]: 11254000 : assert(setChildrenCheck.size() == setChildrenStored.size());
526 [ - + ]: 11254000 : assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
527 : :
528 [ - + ]: 11254000 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
529 : 11254000 : CAmount txfee = 0;
530 [ - + ]: 11254000 : assert(!tx.IsCoinBase());
531 [ + - - + ]: 11254000 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
532 [ + - + + ]: 25936811 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
533 [ + - ]: 11254000 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
534 : 11254000 : }
535 [ + + ]: 14840007 : for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
536 [ - + ]: 14682811 : indexed_transaction_set::const_iterator it2 = it->second;
537 [ - + ]: 14682811 : assert(it2 != mapTx.end());
538 : : }
539 : :
540 [ - + ]: 157196 : ++diagram_iter;
541 [ - + ]: 157196 : assert(diagram_iter == diagram.cend());
542 : :
543 [ - + ]: 157196 : assert(totalTxSize == checkTotal);
544 [ - + ]: 157196 : assert(m_total_fee == check_total_fee);
545 [ - + ]: 157196 : assert(diagram.back().fee == check_total_modified_fee);
546 [ - + ]: 157196 : assert(diagram.back().size == check_total_adjusted_weight);
547 [ - + ]: 157196 : assert(innerUsage == cachedInnerUsage);
548 [ + - ]: 314392 : }
549 : :
550 : 11242865 : 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 : 11242865 : LOCK(cs);
558 [ + - ]: 11242865 : auto j{GetIter(hashb)};
559 [ + + ]: 11242865 : if (!j.has_value()) return false;
560 [ + - ]: 11240504 : auto i{GetIter(hasha)};
561 [ + + ]: 11240504 : if (!i.has_value()) return true;
562 : :
563 : 11240275 : return m_txgraph->CompareMainOrder(*i.value(), *j.value()) < 0;
564 : 11242865 : }
565 : :
566 : 167407 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
567 : : {
568 : 167407 : std::vector<indexed_transaction_set::const_iterator> iters;
569 : 167407 : AssertLockHeld(cs);
570 : :
571 [ + - ]: 167407 : iters.reserve(mapTx.size());
572 : :
573 [ + + + + ]: 23301271 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
574 [ + - ]: 11566932 : iters.push_back(mi);
575 : : }
576 : 167407 : std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
577 : 134683669 : return m_txgraph->CompareMainOrder(*a, *b) < 0;
578 : : });
579 : 167407 : return iters;
580 : 0 : }
581 : :
582 : 9251 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
583 : : {
584 : 9251 : AssertLockHeld(cs);
585 : :
586 : 9251 : std::vector<CTxMemPoolEntryRef> ret;
587 [ + - ]: 9251 : ret.reserve(mapTx.size());
588 [ + - + + ]: 321033 : for (const auto& it : GetSortedScoreWithTopology()) {
589 [ + - ]: 311782 : ret.emplace_back(*it);
590 : : }
591 : 9251 : return ret;
592 : 0 : }
593 : :
594 : 960 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
595 : : {
596 : 960 : LOCK(cs);
597 [ + - ]: 960 : auto iters = GetSortedScoreWithTopology();
598 : :
599 : 960 : std::vector<TxMempoolInfo> ret;
600 [ + - ]: 960 : ret.reserve(mapTx.size());
601 [ + + ]: 2110 : for (auto it : iters) {
602 [ + - - + ]: 2300 : ret.push_back(GetInfo(it));
603 : : }
604 : :
605 : 960 : return ret;
606 [ + - ]: 1920 : }
607 : :
608 : 3645 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
609 : : {
610 : 3645 : AssertLockHeld(cs);
611 : 3645 : const auto i = mapTx.find(txid);
612 [ + + ]: 3645 : return i == mapTx.end() ? nullptr : &(*i);
613 : : }
614 : :
615 : 214375 : CTransactionRef CTxMemPool::get(const Txid& hash) const
616 : : {
617 : 214375 : LOCK(cs);
618 : 214375 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
619 [ + + ]: 214375 : if (i == mapTx.end())
620 : 155225 : return nullptr;
621 [ + - + - ]: 273525 : return i->GetSharedTx();
622 : 214375 : }
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 : 63785 : void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
652 : : {
653 : 63785 : AssertLockHeld(cs);
654 : 63785 : std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
655 [ + + ]: 63785 : if (pos == mapDeltas.end())
656 : : return;
657 : 41 : const CAmount &delta = pos->second;
658 : 41 : nFeeDelta += delta;
659 : : }
660 : :
661 : 59430 : void CTxMemPool::ClearPrioritisation(const Txid& hash)
662 : : {
663 : 59430 : AssertLockHeld(cs);
664 : 59430 : mapDeltas.erase(hash);
665 : 59430 : }
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 : 113855 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
684 : : {
685 : 113855 : const auto it = mapNextTx.find(prevout);
686 [ + + ]: 113855 : return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
687 : : }
688 : :
689 : 14857908 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
690 : : {
691 : 14857908 : AssertLockHeld(cs);
692 : 14857908 : auto it = mapTx.find(txid);
693 [ + + ]: 14857908 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
694 : : }
695 : :
696 : 22518117 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
697 : : {
698 : 22518117 : AssertLockHeld(cs);
699 [ + + ]: 22518117 : auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
700 [ + + ]: 22518117 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
701 : : }
702 : :
703 : 33510 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
704 : : {
705 : 33510 : CTxMemPool::setEntries ret;
706 [ + + ]: 35787 : for (const auto& h : hashes) {
707 [ + - ]: 2277 : const auto mi = GetIter(h);
708 [ + - + - ]: 2277 : if (mi) ret.insert(*mi);
709 : : }
710 : 33510 : 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 : 25895 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
727 : : {
728 [ - + + + ]: 59198 : for (unsigned int i = 0; i < tx.vin.size(); i++)
729 [ + + ]: 36462 : if (exists(tx.vin[i].prevout.hash))
730 : : return false;
731 : : return true;
732 : : }
733 : :
734 [ + - + - ]: 41645 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
735 : :
736 : 65435 : 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 [ + + ]: 65435 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
741 : 617 : 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 : 64818 : CTransactionRef ptx = mempool.get(outpoint.hash);
748 [ + + ]: 64818 : if (ptx) {
749 [ - + + - ]: 8346 : if (outpoint.n < ptx->vout.size()) {
750 : 8346 : Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
751 [ + - ]: 8346 : m_non_base_coins.emplace(outpoint);
752 : 8346 : return coin;
753 : 8346 : }
754 : 0 : return std::nullopt;
755 : : }
756 [ + - ]: 56472 : return base->GetCoin(outpoint);
757 : 64818 : }
758 : :
759 : 781 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
760 : : {
761 [ - + + + ]: 1599 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
762 [ + - ]: 818 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
763 : 818 : m_non_base_coins.emplace(tx->GetHash(), n);
764 : : }
765 : 781 : }
766 : 65436 : void CCoinsViewMemPool::Reset()
767 : : {
768 : 65436 : m_temp_added.clear();
769 : 65436 : m_non_base_coins.clear();
770 : 65436 : }
771 : :
772 : 545789 : size_t CTxMemPool::DynamicMemoryUsage() const {
773 : 545789 : 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 [ - + + - ]: 1091578 : 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 : 545789 : }
777 : :
778 : 62619 : void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
779 : 62619 : LOCK(cs);
780 : :
781 [ + + ]: 62619 : if (m_unbroadcast_txids.erase(txid))
782 : : {
783 [ + - + - : 29814 : LogDebug(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
+ + + - +
- ]
784 : : }
785 : 62619 : }
786 : :
787 : 80736 : void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) {
788 : 80736 : AssertLockHeld(cs);
789 [ + + ]: 82280 : for (txiter it : stage) {
790 : 1544 : removeUnchecked(it, reason);
791 : : }
792 : 80736 : }
793 : :
794 : 3443 : bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx)
795 : : {
796 : 3443 : 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 [ + - ]: 3443 : auto changeset = GetChangeSet();
801 [ + - ]: 3443 : (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
802 [ + - ]: 3443 : return changeset->CheckMemPoolPolicyLimits();
803 [ + - ]: 6886 : }
804 : :
805 : 28326 : int CTxMemPool::Expire(std::chrono::seconds time)
806 : : {
807 : 28326 : AssertLockHeld(cs);
808 : 28326 : Assume(!m_have_changeset);
809 : 28326 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
810 : 28326 : setEntries toremove;
811 [ + + + + ]: 28330 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
812 [ + - ]: 4 : toremove.insert(mapTx.project<0>(it));
813 : 4 : it++;
814 : : }
815 : 28326 : setEntries stage;
816 [ + + ]: 28330 : for (txiter removeit : toremove) {
817 [ + - ]: 4 : CalculateDescendants(removeit, stage);
818 : : }
819 [ + - ]: 28326 : RemoveStaged(stage, MemPoolRemovalReason::EXPIRY);
820 : 28326 : return stage.size();
821 : 28326 : }
822 : :
823 : 487929 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
824 : 487929 : LOCK(cs);
825 [ + + + + ]: 487929 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
826 : 487874 : return CFeeRate(llround(rollingMinimumFeeRate));
827 : :
828 [ + - ]: 55 : int64_t time = GetTime();
829 [ + + ]: 55 : 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 : 54 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
845 : 487929 : }
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 : 28335 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
856 : 28335 : AssertLockHeld(cs);
857 : 28335 : Assume(!m_have_changeset);
858 : :
859 : 28335 : unsigned nTxnRemoved = 0;
860 : 28335 : CFeeRate maxFeeRateRemoved(0);
861 : :
862 [ + + + + ]: 28374 : 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 [ + + ]: 28335 : if (maxFeeRateRemoved > CFeeRate(0)) {
903 [ + - + - ]: 64 : LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
904 : : }
905 : 28335 : }
906 : :
907 : 123814 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
908 : : {
909 : 123814 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
910 : :
911 [ - + ]: 123814 : size_t ancestor_count = ancestors.size();
912 : 123814 : size_t ancestor_size = 0;
913 : 123814 : CAmount ancestor_fees = 0;
914 [ + + ]: 442817 : for (auto tx: ancestors) {
915 : 319003 : const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
916 [ + - ]: 319003 : ancestor_size += anc.GetTxSize();
917 : 319003 : ancestor_fees += anc.GetModifiedFee();
918 : : }
919 : 123814 : return {ancestor_count, ancestor_size, ancestor_fees};
920 : 123814 : }
921 : :
922 : 8065 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
923 : : {
924 : 8065 : auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
925 [ - + ]: 8065 : size_t descendant_count = descendants.size();
926 : 8065 : size_t descendant_size = 0;
927 : 8065 : CAmount descendant_fees = 0;
928 : :
929 [ + + ]: 161989 : for (auto tx: descendants) {
930 : 153924 : const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
931 [ + - ]: 153924 : descendant_size += desc.GetTxSize();
932 : 153924 : descendant_fees += desc.GetModifiedFee();
933 : : }
934 : 8065 : return {descendant_count, descendant_size, descendant_fees};
935 : 8065 : }
936 : :
937 : 583482 : void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
938 : 583482 : LOCK(cs);
939 : 583482 : auto it = mapTx.find(txid);
940 : 583482 : ancestors = cluster_count = 0;
941 [ + + ]: 583482 : if (it != mapTx.end()) {
942 [ + - + + ]: 47630 : auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
943 : 47630 : ancestors = ancestor_count;
944 [ + + ]: 47630 : if (ancestorsize) *ancestorsize = ancestor_size;
945 [ + + ]: 47630 : if (ancestorfees) *ancestorfees = ancestor_fees;
946 [ - + ]: 47630 : cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
947 : : }
948 : 583482 : }
949 : :
950 : 2365 : bool CTxMemPool::GetLoadTried() const
951 : : {
952 : 2365 : LOCK(cs);
953 [ + - ]: 2365 : return m_load_tried;
954 : 2365 : }
955 : :
956 : 1040 : void CTxMemPool::SetLoadTried(bool load_tried)
957 : : {
958 : 1040 : LOCK(cs);
959 [ + - ]: 1040 : m_load_tried = load_tried;
960 : 1040 : }
961 : :
962 : 3058 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
963 : : {
964 : 3058 : AssertLockHeld(cs);
965 : :
966 : 3058 : std::vector<CTxMemPool::txiter> ret;
967 : 3058 : std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
968 [ + + ]: 52542 : for (auto txid : txids) {
969 : 49484 : auto it = mapTx.find(txid);
970 [ + - ]: 49484 : 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 : 49484 : auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
975 [ + - + + ]: 49484 : if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
976 [ + + ]: 118812 : for (auto tx : cluster) {
977 [ + - ]: 69485 : ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
978 : : }
979 : : }
980 : 49484 : }
981 : : }
982 [ - + + + ]: 3058 : if (ret.size() > 500) {
983 : 1 : return {};
984 : : }
985 : 3057 : return ret;
986 : 3058 : }
987 : :
988 : 1289 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
989 : : {
990 : 1289 : LOCK(m_pool->cs);
991 : :
992 [ + - - + ]: 1289 : if (!CheckMemPoolPolicyLimits()) {
993 [ # # # # ]: 0 : return util::Error{Untranslated("cluster size limit exceeded")};
994 : : }
995 : :
996 : 2578 : return m_pool->m_txgraph->GetMainStagingDiagrams();
997 : 1289 : }
998 : :
999 : 63785 : 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 : 63785 : LOCK(m_pool->cs);
1002 [ + - ]: 63785 : Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1003 : 63785 : Assume(!m_dependencies_processed);
1004 : :
1005 : : // We need to process dependencies after adding a new transaction.
1006 : 63785 : m_dependencies_processed = false;
1007 : :
1008 : 63785 : CAmount delta{0};
1009 [ + - ]: 63785 : m_pool->ApplyDelta(tx->GetHash(), delta);
1010 : :
1011 [ + - + - ]: 63785 : FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp));
1012 [ + - ]: 63785 : auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1013 : 63785 : m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1014 [ + + ]: 63785 : if (delta) {
1015 : 41 : newit->UpdateModifiedFee(delta);
1016 : 41 : m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1017 : : }
1018 : :
1019 [ + - ]: 63785 : m_entry_vec.push_back(newit);
1020 : :
1021 [ + - ]: 63785 : return newit;
1022 : 63785 : }
1023 : :
1024 : 2132 : void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it)
1025 : : {
1026 : 2132 : LOCK(m_pool->cs);
1027 : 2132 : m_pool->m_txgraph->RemoveTransaction(*it);
1028 [ + - ]: 2132 : m_to_remove.insert(it);
1029 : 2132 : }
1030 : :
1031 : 52410 : void CTxMemPool::ChangeSet::Apply()
1032 : : {
1033 : 52410 : LOCK(m_pool->cs);
1034 [ + + ]: 52410 : if (!m_dependencies_processed) {
1035 [ + - ]: 3 : ProcessDependencies();
1036 : : }
1037 [ + - ]: 52410 : m_pool->Apply(this);
1038 : 52410 : m_to_add.clear();
1039 : 52410 : m_to_remove.clear();
1040 [ + - ]: 52410 : m_entry_vec.clear();
1041 [ + - ]: 52410 : m_ancestors.clear();
1042 : 52410 : }
1043 : :
1044 : 62838 : void CTxMemPool::ChangeSet::ProcessDependencies()
1045 : : {
1046 : 62838 : LOCK(m_pool->cs);
1047 : 62838 : Assume(!m_dependencies_processed); // should only call this once.
1048 [ + + ]: 126264 : for (const auto& entryptr : m_entry_vec) {
1049 [ + - + - : 280016 : for (const auto &txin : entryptr->GetSharedTx()->vin) {
+ + ]
1050 [ + - ]: 89738 : std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1051 [ + + ]: 89738 : if (!piter) {
1052 : 80107 : auto it = m_to_add.find(txin.prevout.hash);
1053 [ + + ]: 80107 : if (it != m_to_add.end()) {
1054 : 587 : piter = std::make_optional(it);
1055 : : }
1056 : : }
1057 [ + + ]: 89738 : if (piter) {
1058 : 10218 : m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1059 : : }
1060 : : }
1061 : : }
1062 : 62838 : m_dependencies_processed = true;
1063 [ + - ]: 62838 : return;
1064 : 62838 : }
1065 : :
1066 : 65384 : bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits()
1067 : : {
1068 : 65384 : LOCK(m_pool->cs);
1069 [ + + ]: 65384 : if (!m_dependencies_processed) {
1070 [ + - ]: 62835 : ProcessDependencies();
1071 : : }
1072 : :
1073 [ + - ]: 65384 : return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1074 : 65384 : }
1075 : :
1076 : 157201 : std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1077 : : {
1078 : 157201 : FeePerWeight zero{};
1079 : 157201 : std::vector<FeePerWeight> ret;
1080 : :
1081 [ + - ]: 157201 : ret.emplace_back(zero);
1082 : :
1083 : 157201 : StartBlockBuilding();
1084 : :
1085 : 157201 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1086 : :
1087 [ + - ]: 157201 : FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1088 [ + + ]: 11394461 : while (last_selection != FeePerWeight{}) {
1089 [ + - ]: 11237260 : last_selection += ret.back();
1090 [ + - ]: 11237260 : ret.emplace_back(last_selection);
1091 : 11237260 : IncludeBuilderChunk();
1092 [ + - ]: 11237260 : last_selection = GetBlockBuilderChunk(dummy);
1093 : : }
1094 : 157201 : StopBlockBuilding();
1095 : 157201 : return ret;
1096 : 157201 : }
|