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