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 : 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 : 305840 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58 : : {
59 : 305840 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60 [ + - ]: 305840 : const auto& hash = entry.GetTx().GetHash();
61 : 305840 : {
62 [ + - ]: 305840 : LOCK(cs);
63 : 305840 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64 [ + + + + ]: 534759 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65 [ + - ]: 228919 : ret.emplace_back(*(iter->second));
66 : : }
67 : 0 : }
68 : 305840 : std::ranges::sort(ret, CompareIteratorByHash{});
69 [ + + + + ]: 429563 : auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70 : 305840 : ret.erase(removed.begin(), removed.end());
71 : 305840 : return ret;
72 : 0 : }
73 : :
74 : 2061461 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75 : : {
76 : 2061461 : LOCK(cs);
77 : 2061461 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78 : 2061461 : std::set<Txid> inputs;
79 [ + + ]: 6068980 : for (const auto& txin : entry.GetTx().vin) {
80 [ + - ]: 4007519 : inputs.insert(txin.prevout.hash);
81 : : }
82 [ + + ]: 5625954 : for (const auto& hash : inputs) {
83 [ + - ]: 3564493 : std::optional<txiter> piter = GetIter(hash);
84 [ + + ]: 3564493 : if (piter) {
85 [ + - ]: 1598138 : ret.emplace_back(**piter);
86 : : }
87 : : }
88 : 2061461 : return ret;
89 [ + - ]: 4122922 : }
90 : :
91 : 10175 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
92 : : {
93 : 10175 : 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 [ + + ]: 58590 : for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
98 : : // calculate children from mapNextTx
99 : 48415 : txiter it = mapTx.find(hash);
100 [ - + ]: 48415 : if (it == mapTx.end()) {
101 : 0 : continue;
102 : : }
103 : 48415 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104 : 48415 : {
105 [ + + + + ]: 72912 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
106 [ - + ]: 24497 : txiter childIter = iter->second;
107 [ - + ]: 24497 : 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 : 24497 : m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
111 : : }
112 : : }
113 : : }
114 : :
115 : 10175 : auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
116 [ - + ]: 10175 : 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 : 10175 : }
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 : 58289 : CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const
131 : : {
132 : 58289 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
133 [ - + ]: 58289 : setEntries ret;
134 [ - + + + ]: 58289 : if (ancestors.size() > 0) {
135 [ + + ]: 802 : for (auto ancestor : ancestors) {
136 [ + + ]: 536 : if (ancestor != &entry) {
137 [ + - ]: 270 : 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 : 58023 : setEntries staged_parents;
146 : 58023 : const CTransaction &tx = entry.GetTx();
147 : :
148 : : // Get parents of this transaction that are in the mempool
149 [ - + + + ]: 285620 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
150 [ + - ]: 227597 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151 [ + + ]: 227597 : if (piter) {
152 [ + - ]: 80804 : staged_parents.insert(*piter);
153 : : }
154 : : }
155 : :
156 [ + + ]: 121739 : for (const auto& parent : staged_parents) {
157 : 63716 : auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN);
158 [ + + ]: 170298 : for (auto ancestor : parent_ancestors) {
159 [ + - ]: 106582 : ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
160 : : }
161 : 63716 : }
162 : :
163 : 58023 : return ret;
164 : 116312 : }
165 : :
166 : 26068 : static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
167 : : {
168 [ + - ]: 26068 : opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169 : 26068 : int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170 [ + - + + : 26068 : if (opts.max_size_bytes < 0 || (opts.max_size_bytes > 0 && opts.max_size_bytes < cluster_limit_bytes)) {
+ + ]
171 : 1522 : error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(cluster_limit_bytes / 1'000'000.0));
172 : : }
173 : 26068 : return std::move(opts);
174 : : }
175 : :
176 : 26068 : CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
177 [ + - + - ]: 26068 : : m_opts{Flatten(std::move(opts), error)}
178 : : {
179 : 52136 : m_txgraph = MakeTxGraph(
180 : 26068 : /*max_cluster_count=*/m_opts.limits.cluster_count,
181 : 26068 : /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,
182 : : /*acceptable_cost=*/ACCEPTABLE_COST,
183 : 26068 : /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184 : 57954710 : const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185 : 57954710 : const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186 : 57954710 : return txid_a <=> txid_b;
187 : 26068 : });
188 : 26068 : }
189 : :
190 : 4 : bool CTxMemPool::isSpent(const COutPoint& outpoint) const
191 : : {
192 : 4 : LOCK(cs);
193 [ + - ]: 4 : return mapNextTx.count(outpoint);
194 : 4 : }
195 : :
196 : 0 : unsigned int CTxMemPool::GetTransactionsUpdated() const
197 : : {
198 : 0 : return nTransactionsUpdated;
199 : : }
200 : :
201 : 203416 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
202 : : {
203 : 203416 : nTransactionsUpdated += n;
204 : 203416 : }
205 : :
206 : 1890988 : void CTxMemPool::Apply(ChangeSet* changeset)
207 : : {
208 : 1890988 : AssertLockHeld(cs);
209 : 1890988 : m_txgraph->CommitStaging();
210 : :
211 : 1890988 : RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED);
212 : :
213 [ - + + + ]: 3787014 : for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214 : 1896026 : auto tx_entry = changeset->m_entry_vec[i];
215 : : // First splice this entry into mapTx.
216 : 1896026 : auto node_handle = changeset->m_to_add.extract(tx_entry);
217 [ + - ]: 1896026 : auto result = mapTx.insert(std::move(node_handle));
218 : :
219 [ - + ]: 1896026 : Assume(result.inserted);
220 : 1896026 : txiter it = result.position;
221 : :
222 [ + - ]: 1896026 : addNewTransaction(it);
223 [ - + ]: 1896026 : }
224 [ - + ]: 1890988 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
225 [ # # ]: 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after addition(s).");
226 : : }
227 : 1890988 : }
228 : :
229 : 1896026 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit)
230 : : {
231 : 1896026 : const CTxMemPoolEntry& entry = *newit;
232 : :
233 : : // Update cachedInnerUsage to include contained transaction's usage.
234 : : // (When we update the entry for in-mempool parents, memory usage will be
235 : : // further updated.)
236 : 1896026 : cachedInnerUsage += entry.DynamicMemoryUsage();
237 : :
238 : 1896026 : const CTransaction& tx = newit->GetTx();
239 [ - + + + ]: 4598173 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
240 : 2702147 : mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit));
241 : : }
242 : : // Don't bother worrying about child transactions of this one.
243 : : // Normal case of a new transaction arriving is that there can't be any
244 : : // children, because such children would be orphans.
245 : : // An exception to that is if a transaction enters that used to be in a block.
246 : : // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
247 : : // to clean up the mess we're leaving here.
248 : :
249 : 1896026 : nTransactionsUpdated++;
250 : 1896026 : totalTxSize += entry.GetTxSize();
251 : 1896026 : m_total_fee += entry.GetFee();
252 : :
253 : 1896026 : txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
254 [ - + ]: 1896026 : newit->idx_randomized = txns_randomized.size() - 1;
255 : :
256 : : TRACEPOINT(mempool, added,
257 : : entry.GetTx().GetHash().data(),
258 : : entry.GetTxSize(),
259 : : entry.GetFee()
260 : 1896026 : );
261 : 1896026 : }
262 : :
263 : 198376 : void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
264 : : {
265 : : // We increment mempool sequence value no matter removal reason
266 : : // even if not directly reported below.
267 [ + + ]: 198376 : uint64_t mempool_sequence = GetAndIncrementSequence();
268 : :
269 [ + + + + ]: 198376 : if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
270 : : // Notify clients that a transaction has been removed from the mempool
271 : : // for any reason except being included in a block. Clients interested
272 : : // in transactions included in blocks can subscribe to the BlockConnected
273 : : // notification.
274 [ + - + - ]: 410442 : m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
275 : : }
276 : : TRACEPOINT(mempool, removed,
277 : : it->GetTx().GetHash().data(),
278 : : RemovalReasonToString(reason).c_str(),
279 : : it->GetTxSize(),
280 : : it->GetFee(),
281 : : std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
282 : 198376 : );
283 : :
284 [ + + ]: 581079 : for (const CTxIn& txin : it->GetTx().vin)
285 : 382703 : mapNextTx.erase(txin.prevout);
286 : :
287 : 198376 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
288 : :
289 [ - + + + ]: 198376 : if (txns_randomized.size() > 1) {
290 : : // Remove entry from txns_randomized by replacing it with the back and deleting the back.
291 [ - + ]: 175921 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
292 [ - + ]: 175921 : txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
293 [ - + ]: 175921 : txns_randomized.pop_back();
294 [ - + - + : 175921 : if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
+ + ]
295 : 21030 : txns_randomized.shrink_to_fit();
296 : : }
297 : : } else {
298 [ + - ]: 22455 : txns_randomized.clear();
299 : : }
300 : :
301 : 198376 : totalTxSize -= it->GetTxSize();
302 : 198376 : m_total_fee -= it->GetFee();
303 : 198376 : cachedInnerUsage -= it->DynamicMemoryUsage();
304 : 198376 : mapTx.erase(it);
305 : 198376 : nTransactionsUpdated++;
306 : 198376 : }
307 : :
308 : : // Calculates descendants of given entry and adds to setDescendants.
309 : 1676485 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
310 : : {
311 : 1676485 : (void)CalculateDescendants(*entryit, setDescendants);
312 : 1676485 : return;
313 : : }
314 : :
315 : 1691347 : CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const
316 : : {
317 [ + + ]: 5742057 : for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
318 [ + - ]: 4050710 : setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
319 : : }
320 : 1691347 : return mapTx.iterator_to(entry);
321 : : }
322 : :
323 : 7375 : void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason)
324 : : {
325 : 7375 : AssertLockHeld(cs);
326 [ - + ]: 7375 : Assume(!m_have_changeset);
327 : 7375 : auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
328 [ + + ]: 20490 : for (auto tx: descendants) {
329 [ + - ]: 13115 : removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
330 : : }
331 : 7375 : }
332 : :
333 : 17550 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
334 : : {
335 : : // Remove transaction from memory pool
336 : 17550 : AssertLockHeld(cs);
337 [ - + ]: 17550 : Assume(!m_have_changeset);
338 : 17550 : txiter origit = mapTx.find(origTx.GetHash());
339 [ + + ]: 17550 : if (origit != mapTx.end()) {
340 : 7375 : removeRecursive(origit, reason);
341 : : } else {
342 : : // When recursively removing but origTx isn't in the mempool
343 : : // be sure to remove any descendants that are in the pool. This can
344 : : // happen during chain re-orgs if origTx isn't re-accepted into
345 : : // the mempool for any reason.
346 : 10175 : auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
347 : 10175 : std::vector<const TxGraph::Ref*> to_remove;
348 [ + + - + ]: 10175 : while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
349 [ # # ]: 0 : to_remove.emplace_back(&*(iter->second));
350 : 0 : ++iter;
351 : : }
352 [ - + ]: 10175 : auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
353 [ - + ]: 10175 : for (auto ref : all_removes) {
354 : 0 : auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
355 [ # # ]: 0 : removeUnchecked(tx, reason);
356 : : }
357 : 10175 : }
358 : 17550 : }
359 : :
360 : 0 : void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
361 : : {
362 : : // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
363 : 0 : AssertLockHeld(cs);
364 : 0 : AssertLockHeld(::cs_main);
365 [ # # ]: 0 : Assume(!m_have_changeset);
366 : :
367 : 0 : std::vector<const TxGraph::Ref*> to_remove;
368 [ # # ]: 0 : for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
369 [ # # # # ]: 0 : if (check_final_and_mature(it)) {
370 [ # # ]: 0 : to_remove.emplace_back(&*it);
371 : : }
372 : : }
373 : :
374 [ # # ]: 0 : auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
375 : :
376 [ # # ]: 0 : for (auto ref : all_to_remove) {
377 : 0 : auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
378 [ # # ]: 0 : removeUnchecked(it, MemPoolRemovalReason::REORG);
379 : : }
380 [ # # ]: 0 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
381 [ # # # # ]: 0 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
382 : : }
383 [ # # ]: 0 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
384 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after reorg.");
# # ]
385 : : }
386 : 0 : }
387 : :
388 : 57073 : void CTxMemPool::removeConflicts(const CTransaction &tx)
389 : : {
390 : : // Remove transactions which depend on inputs of tx, recursively
391 : 57073 : AssertLockHeld(cs);
392 [ + + ]: 138235 : for (const CTxIn &txin : tx.vin) {
393 : 81162 : auto it = mapNextTx.find(txin.prevout);
394 [ - + ]: 81162 : if (it != mapNextTx.end()) {
395 [ # # ]: 0 : const CTransaction &txConflict = it->second->GetTx();
396 [ # # ]: 0 : if (Assume(txConflict.GetHash() != tx.GetHash()))
397 : : {
398 : 0 : ClearPrioritisation(txConflict.GetHash());
399 : 0 : removeRecursive(it->second, MemPoolRemovalReason::CONFLICT);
400 : : }
401 : : }
402 : : }
403 : 57073 : }
404 : :
405 : 213591 : void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
406 : : {
407 : : // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
408 : 213591 : AssertLockHeld(cs);
409 [ - + ]: 213591 : Assume(!m_have_changeset);
410 : 213591 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
411 [ + + + - : 213591 : if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
+ + ]
412 [ - + + - ]: 8658 : txs_removed_for_block.reserve(vtx.size());
413 [ + + ]: 65731 : for (const auto& tx : vtx) {
414 : 57073 : txiter it = mapTx.find(tx->GetHash());
415 [ + + ]: 57073 : if (it != mapTx.end()) {
416 [ + - ]: 48415 : txs_removed_for_block.emplace_back(*it);
417 [ + - ]: 48415 : removeUnchecked(it, MemPoolRemovalReason::BLOCK);
418 : : }
419 [ + - ]: 57073 : removeConflicts(*tx);
420 [ + - ]: 57073 : ClearPrioritisation(tx->GetHash());
421 : : }
422 : : }
423 [ + + ]: 213591 : if (m_opts.signals) {
424 [ + - ]: 212952 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
425 : : }
426 [ + - ]: 213591 : lastRollingFeeUpdate = GetTime();
427 : 213591 : blockSinceLastRollingFeeBump = true;
428 [ - + ]: 213591 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
429 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after block.");
# # ]
430 : : }
431 : 213591 : }
432 : :
433 : 238035 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
434 : : {
435 [ + - ]: 238035 : if (m_opts.check_ratio == 0) return;
436 : :
437 [ + - ]: 238035 : if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
438 : :
439 : 238035 : AssertLockHeld(::cs_main);
440 : 238035 : LOCK(cs);
441 [ + - + + : 238035 : LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - ]
442 : :
443 : 238035 : uint64_t checkTotal = 0;
444 : 238035 : CAmount check_total_fee{0};
445 : 238035 : CAmount check_total_modified_fee{0};
446 : 238035 : int64_t check_total_adjusted_weight{0};
447 : 238035 : uint64_t innerUsage = 0;
448 : :
449 [ - + ]: 238035 : assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
450 [ + - ]: 238035 : m_txgraph->SanityCheck();
451 : :
452 [ + - ]: 238035 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
453 : :
454 [ + - ]: 238035 : const auto score_with_topo{GetSortedScoreWithTopology()};
455 : :
456 : : // Number of chunks is bounded by number of transactions.
457 [ + - ]: 238035 : const auto diagram{GetFeerateDiagram()};
458 [ - + - + : 238035 : assert(diagram.size() <= score_with_topo.size() + 1);
- + ]
459 [ - + ]: 238035 : assert(diagram.size() >= 1);
460 : :
461 : 238035 : std::optional<txiter> last_iter = std::nullopt;
462 : 238035 : auto diagram_iter = diagram.cbegin();
463 : :
464 [ + + ]: 499400 : for (const auto& it : score_with_topo) {
465 : : // GetSortedScoreWithTopology() contains the same chunks as the feerate
466 : : // diagram. We do not know where the chunk boundaries are, but we can
467 : : // check that there are points at which they match the cumulative fee
468 : : // and weight.
469 : : // The feerate diagram should never get behind the current transaction
470 : : // size totals.
471 [ - + ]: 261365 : assert(diagram_iter->size >= check_total_adjusted_weight);
472 [ + + ]: 261365 : if (diagram_iter->fee == check_total_modified_fee &&
473 [ + + ]: 216039 : diagram_iter->size == check_total_adjusted_weight) {
474 : 215949 : ++diagram_iter;
475 : : }
476 [ + - ]: 261365 : checkTotal += it->GetTxSize();
477 [ + - ]: 261365 : check_total_adjusted_weight += it->GetAdjustedWeight();
478 [ + + ]: 261365 : check_total_fee += it->GetFee();
479 [ + + ]: 261365 : check_total_modified_fee += it->GetModifiedFee();
480 [ + + ]: 261365 : innerUsage += it->DynamicMemoryUsage();
481 [ + + ]: 261365 : const CTransaction& tx = it->GetTx();
482 : :
483 [ + + ]: 261365 : if (last_iter) {
484 [ - + ]: 246056 : assert(m_txgraph->CompareMainOrder(**last_iter, *it) < 0);
485 : : }
486 [ + + ]: 261365 : last_iter = it;
487 : :
488 : 261365 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
489 : 261365 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
490 [ + + ]: 663818 : for (const CTxIn &txin : tx.vin) {
491 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
492 : 402453 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
493 [ + + ]: 402453 : if (it2 != mapTx.end()) {
494 [ - + ]: 153609 : const CTransaction& tx2 = it2->GetTx();
495 [ - + + - : 153609 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
- + ]
496 [ + - ]: 153609 : setParentCheck.insert(*it2);
497 : : }
498 : : // We are iterating through the mempool entries sorted
499 : : // topologically and by mining score. All parents must have been
500 : : // checked before their children and their coins added to the
501 : : // mempoolDuplicate coins cache.
502 [ + - - + ]: 402453 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
503 : : // Check whether its inputs are marked in mapNextTx.
504 : 402453 : auto it3 = mapNextTx.find(txin.prevout);
505 [ - + ]: 402453 : assert(it3 != mapNextTx.end());
506 [ - + ]: 402453 : assert(it3->first == &txin.prevout);
507 [ - + ]: 402453 : assert(&it3->second->GetTx() == &tx);
508 : : }
509 : 497619 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
510 [ + - ]: 236254 : return a.GetTx().GetHash() == b.GetTx().GetHash();
511 : : };
512 [ + - + + ]: 379492 : for (auto &txentry : GetParents(*it)) {
513 [ + - ]: 118127 : setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
514 : 0 : }
515 [ - + ]: 261365 : assert(setParentCheck.size() == setParentsStored.size());
516 [ - + ]: 261365 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
517 : :
518 : : // Check children against mapNextTx
519 : 261365 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
520 : 261365 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
521 : 261365 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
522 [ + + + + ]: 414974 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
523 [ - + ]: 153609 : txiter childit = iter->second;
524 [ - + ]: 153609 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
525 [ + - ]: 153609 : setChildrenCheck.insert(*childit);
526 : : }
527 [ + - + + ]: 379492 : for (auto &txentry : GetChildren(*it)) {
528 [ + - ]: 118127 : setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
529 : 0 : }
530 [ - + ]: 261365 : assert(setChildrenCheck.size() == setChildrenStored.size());
531 [ - + ]: 261365 : assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
532 : :
533 [ - + ]: 261365 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
534 : 261365 : CAmount txfee = 0;
535 [ - + ]: 261365 : assert(!tx.IsCoinBase());
536 [ + - - + ]: 261365 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
537 [ + - + + ]: 663818 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
538 [ + - ]: 261365 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
539 : 261365 : }
540 [ + + ]: 640488 : for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
541 [ - + ]: 402453 : indexed_transaction_set::const_iterator it2 = it->second;
542 [ - + ]: 402453 : assert(it2 != mapTx.end());
543 : : }
544 : :
545 [ - + ]: 238035 : ++diagram_iter;
546 [ - + ]: 238035 : assert(diagram_iter == diagram.cend());
547 : :
548 [ - + ]: 238035 : assert(totalTxSize == checkTotal);
549 [ - + ]: 238035 : assert(m_total_fee == check_total_fee);
550 [ - + ]: 238035 : assert(diagram.back().fee == check_total_modified_fee);
551 [ - + ]: 238035 : assert(diagram.back().size == check_total_adjusted_weight);
552 [ - + ]: 238035 : assert(innerUsage == cachedInnerUsage);
553 [ + - ]: 476070 : }
554 : :
555 : 0 : std::vector<CTxMemPool::txiter> CTxMemPool::ExtractBestByMiningScoreWithTopology(std::vector<Wtxid>& wtxids, size_t n_to_sort) const
556 : : {
557 : : /* This function takes a vector of `wtxids`, and returns the
558 : : * best mempool entries corresponding to those `wtxids` (by mining
559 : : * score/topology). It updates the input `wtxids` so that multiple
560 : : * calls with the same vector will drain that vector to empty.
561 : : *
562 : : * It operates under the following constraints:
563 : : * - wtxids that do not correspond to a mempool entry are dropped
564 : : * - the return vector contains no duplicates, either with itself
565 : : * or with the updated `wtxids` input.
566 : : * - the return vector will have `n_to_sort` entries (or `wtxids`
567 : : will become empty).
568 : : * - the `wtxids` vector will be reduced by at least `n_to_sort`
569 : : * entries (or will become empty).
570 : : */
571 : :
572 : 0 : auto cmp = [&](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept { return m_txgraph->CompareMainOrder(*a, *b) < 0; };
573 : :
574 : 0 : std::vector<txiter> res;
575 : :
576 [ # # # # ]: 0 : n_to_sort = std::min(wtxids.size(), n_to_sort);
577 [ # # ]: 0 : if (n_to_sort > 0) {
578 [ # # # # ]: 0 : res.reserve(wtxids.size());
579 : 0 : std::sort(wtxids.begin(), wtxids.end());
580 [ # # ]: 0 : for (auto it = wtxids.begin(); it != wtxids.end(); ++it) {
581 : : // skip duplicates
582 [ # # ]: 0 : auto itnext = it + 1;
583 [ # # # # ]: 0 : if (itnext != wtxids.end() && *it == *itnext) continue;
584 : :
585 [ # # # # ]: 0 : if (auto i{GetIter(*it)}; i.has_value()) {
586 [ # # ]: 0 : res.push_back(i.value());
587 : : }
588 : : }
589 [ # # ]: 0 : wtxids.clear();
590 : :
591 [ # # ]: 0 : if (!res.empty()) {
592 [ # # ]: 0 : auto begin = res.begin();
593 [ # # ]: 0 : auto end = res.end();
594 : 0 : auto middle = end;
595 [ # # # # ]: 0 : if (n_to_sort >= res.size()) {
596 : : // use regular sort when sorting everything
597 : 0 : std::sort(begin, end, cmp);
598 : : } else {
599 : 0 : middle = begin + n_to_sort;
600 : 0 : std::partial_sort(begin, middle, end, cmp);
601 : : }
602 : 0 : auto it = middle;
603 [ # # ]: 0 : while (it != end) {
604 [ # # ]: 0 : wtxids.push_back((*it)->GetTx().GetWitnessHash());
605 : 0 : ++it;
606 : : }
607 : 0 : res.erase(middle, end);
608 : : }
609 : : }
610 : 0 : return res;
611 : 0 : }
612 : :
613 : 1334767 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
614 : : {
615 : 1334767 : std::vector<indexed_transaction_set::const_iterator> iters;
616 : 1334767 : AssertLockHeld(cs);
617 : :
618 [ + - ]: 1334767 : iters.reserve(mapTx.size());
619 : :
620 [ + + + + ]: 54129357 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
621 [ + - ]: 26397295 : iters.push_back(mi);
622 : : }
623 : 1334767 : std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
624 : 169159495 : return m_txgraph->CompareMainOrder(*a, *b) < 0;
625 : : });
626 : 1334767 : return iters;
627 : 0 : }
628 : :
629 : 52 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
630 : : {
631 : 52 : AssertLockHeld(cs);
632 : :
633 : 52 : std::vector<CTxMemPoolEntryRef> ret;
634 [ + - ]: 52 : ret.reserve(mapTx.size());
635 [ + - - + ]: 52 : for (const auto& it : GetSortedScoreWithTopology()) {
636 [ # # ]: 0 : ret.emplace_back(*it);
637 : : }
638 : 52 : return ret;
639 : 0 : }
640 : :
641 : 1096680 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
642 : : {
643 : 1096680 : LOCK(cs);
644 [ + - ]: 1096680 : auto iters = GetSortedScoreWithTopology();
645 : :
646 : 1096680 : std::vector<TxMempoolInfo> ret;
647 [ + - ]: 1096680 : ret.reserve(mapTx.size());
648 [ + + ]: 27232610 : for (auto it : iters) {
649 [ + - - + ]: 52271860 : ret.push_back(GetInfo(it));
650 : : }
651 : :
652 : 1096680 : return ret;
653 [ + - ]: 2193360 : }
654 : :
655 : 26052495 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
656 : : {
657 : 26052495 : AssertLockHeld(cs);
658 : 26052495 : const auto i = mapTx.find(txid);
659 [ + + ]: 26052495 : return i == mapTx.end() ? nullptr : &(*i);
660 : : }
661 : :
662 : 21836565 : CTransactionRef CTxMemPool::get(const Txid& hash) const
663 : : {
664 : 21836565 : LOCK(cs);
665 : 21836565 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
666 [ + + ]: 21836565 : if (i == mapTx.end())
667 : 13073786 : return nullptr;
668 [ + - + - ]: 30599344 : return i->GetSharedTx();
669 : 21836565 : }
670 : :
671 : 0 : CTransactionRef CTxMemPool::get(const Wtxid& hash) const
672 : : {
673 : 0 : LOCK(cs);
674 : 0 : const auto& wtxid_map{mapTx.get<index_by_wtxid>()};
675 : 0 : const auto it{wtxid_map.find(hash)};
676 [ # # ]: 0 : if (it == wtxid_map.end()) return nullptr;
677 [ # # # # ]: 0 : return it->GetSharedTx();
678 : 0 : }
679 : :
680 : 1640813 : void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
681 : : {
682 : 1640813 : {
683 : 1640813 : LOCK(cs);
684 [ + - ]: 1640813 : CAmount &delta = mapDeltas[hash];
685 : 1640813 : delta = SaturatingAdd(delta, nFeeDelta);
686 : 1640813 : txiter it = mapTx.find(hash);
687 [ + + ]: 1640813 : if (it != mapTx.end()) {
688 : : // PrioritiseTransaction calls stack on previous ones. Set the new
689 : : // transaction fee to be current modified fee + feedelta.
690 : 564177 : it->UpdateModifiedFee(nFeeDelta);
691 : 564177 : m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
692 : 564177 : ++nTransactionsUpdated;
693 : : }
694 [ + + ]: 1640813 : if (delta == 0) {
695 : 11620 : mapDeltas.erase(hash);
696 [ + + + - : 13055 : LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
+ - ]
697 : : } else {
698 [ + - + - : 2191935 : LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
+ + + - +
- ]
699 : : hash.ToString(),
700 : : it == mapTx.end() ? "not " : "",
701 : : FormatMoney(nFeeDelta),
702 : : FormatMoney(delta));
703 : : }
704 : 1640813 : }
705 : 1640813 : }
706 : :
707 : 3839560 : void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
708 : : {
709 : 3839560 : AssertLockHeld(cs);
710 : 3839560 : std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
711 [ + + ]: 3839560 : if (pos == mapDeltas.end())
712 : : return;
713 : 157522 : const CAmount &delta = pos->second;
714 : 157522 : nFeeDelta += delta;
715 : : }
716 : :
717 : 57073 : void CTxMemPool::ClearPrioritisation(const Txid& hash)
718 : : {
719 : 57073 : AssertLockHeld(cs);
720 : 57073 : mapDeltas.erase(hash);
721 : 57073 : }
722 : :
723 : 31 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
724 : : {
725 : 31 : AssertLockNotHeld(cs);
726 : 31 : LOCK(cs);
727 : 31 : std::vector<delta_info> result;
728 [ + - ]: 31 : result.reserve(mapDeltas.size());
729 [ + + ]: 259 : for (const auto& [txid, delta] : mapDeltas) {
730 : 228 : const auto iter{mapTx.find(txid)};
731 [ - + ]: 228 : const bool in_mempool{iter != mapTx.end()};
732 : 228 : std::optional<CAmount> modified_fee;
733 [ - + ]: 228 : if (in_mempool) modified_fee = iter->GetModifiedFee();
734 [ + - ]: 228 : result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
735 : : }
736 [ + - ]: 31 : return result;
737 : 31 : }
738 : :
739 : 10201120 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
740 : : {
741 : 10201120 : const auto it = mapNextTx.find(prevout);
742 [ + + ]: 10201120 : return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
743 : : }
744 : :
745 : 15807413 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
746 : : {
747 : 15807413 : AssertLockHeld(cs);
748 : 15807413 : auto it = mapTx.find(txid);
749 [ + + ]: 15807413 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
750 : : }
751 : :
752 : 16663 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
753 : : {
754 : 16663 : AssertLockHeld(cs);
755 [ - + ]: 16663 : auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
756 [ - + ]: 16663 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
757 : : }
758 : :
759 : 1012307 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
760 : : {
761 : 1012307 : CTxMemPool::setEntries ret;
762 [ + + ]: 1633668 : for (const auto& h : hashes) {
763 [ + - ]: 621361 : const auto mi = GetIter(h);
764 [ + - + - ]: 621361 : if (mi) ret.insert(*mi);
765 : : }
766 : 1012307 : return ret;
767 : 0 : }
768 : :
769 : 0 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
770 : : {
771 : 0 : AssertLockHeld(cs);
772 : 0 : std::vector<txiter> ret;
773 [ # # # # ]: 0 : ret.reserve(txids.size());
774 [ # # ]: 0 : for (const auto& txid : txids) {
775 [ # # ]: 0 : const auto it{GetIter(txid)};
776 [ # # ]: 0 : if (!it) return {};
777 [ # # ]: 0 : ret.push_back(*it);
778 : : }
779 : 0 : return ret;
780 : 0 : }
781 : :
782 : 363334 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
783 : : {
784 [ - + + + ]: 702904 : for (unsigned int i = 0; i < tx.vin.size(); i++)
785 [ + + ]: 479793 : if (exists(tx.vin[i].prevout.hash))
786 : : return false;
787 : : return true;
788 : : }
789 : :
790 [ + - + - ]: 2539133 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
791 : :
792 : 20905129 : std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
793 : : {
794 : : // Check to see if the inputs are made available by another tx in the package.
795 : : // These Coins would not be available in the underlying CoinsView.
796 [ + + ]: 20905129 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
797 : 213044 : return it->second;
798 : : }
799 : :
800 : : // If an entry in the mempool exists, always return that one, as it's guaranteed to never
801 : : // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
802 : : // transactions. First checking the underlying cache risks returning a pruned entry instead.
803 : 20692085 : CTransactionRef ptx = mempool.get(outpoint.hash);
804 [ + + ]: 20692085 : if (ptx) {
805 [ - + + + ]: 8392168 : if (outpoint.n < ptx->vout.size()) {
806 : 8384517 : Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
807 [ + - ]: 8384517 : m_non_base_coins.emplace(outpoint);
808 : 8384517 : return coin;
809 : 8384517 : }
810 : 7651 : return std::nullopt;
811 : : }
812 [ + - ]: 12299917 : return base->GetCoin(outpoint);
813 : 20692085 : }
814 : :
815 : 225499 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
816 : : {
817 [ - + + + ]: 1862960 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
818 [ + - ]: 1637461 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
819 : 1637461 : m_non_base_coins.emplace(tx->GetHash(), n);
820 : : }
821 : 225499 : }
822 : 3412939 : void CCoinsViewMemPool::Reset()
823 : : {
824 : 3412939 : m_temp_added.clear();
825 : 3412939 : m_non_base_coins.clear();
826 : 3412939 : }
827 : :
828 : 3778009 : size_t CTxMemPool::DynamicMemoryUsage() const {
829 : 3778009 : LOCK(cs);
830 : : // 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.
831 [ - + + - ]: 7556018 : return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
832 : 3778009 : }
833 : :
834 : 198376 : void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
835 : 198376 : LOCK(cs);
836 : :
837 [ - + ]: 198376 : if (m_unbroadcast_txids.erase(txid))
838 : : {
839 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Removed %s from set of unbroadcast txns%s", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
# # # # #
# ]
840 : : }
841 : 198376 : }
842 : :
843 : 2411226 : void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) {
844 : 2411226 : AssertLockHeld(cs);
845 [ + + ]: 2515920 : for (txiter it : stage) {
846 : 104694 : removeUnchecked(it, reason);
847 : : }
848 : 2411226 : }
849 : :
850 : 0 : bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx)
851 : : {
852 : 0 : LOCK(cs);
853 : : // Use ChangeSet interface to check whether the cluster count
854 : : // limits would be violated. Note that the changeset will be destroyed
855 : : // when it goes out of scope.
856 [ # # ]: 0 : auto changeset = GetChangeSet();
857 [ # # ]: 0 : (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
858 [ # # ]: 0 : return changeset->CheckMemPoolPolicyLimits();
859 [ # # ]: 0 : }
860 : :
861 : 520238 : int CTxMemPool::Expire(std::chrono::seconds time)
862 : : {
863 : 520238 : AssertLockHeld(cs);
864 [ - + ]: 520238 : Assume(!m_have_changeset);
865 : 520238 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
866 : 520238 : setEntries toremove;
867 [ + + + + ]: 574179 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
868 [ + - ]: 53941 : toremove.insert(mapTx.project<0>(it));
869 : 53941 : it++;
870 : : }
871 : 520238 : setEntries stage;
872 [ + + ]: 574179 : for (txiter removeit : toremove) {
873 [ + - ]: 53941 : CalculateDescendants(removeit, stage);
874 : : }
875 [ + - ]: 520238 : RemoveStaged(stage, MemPoolRemovalReason::EXPIRY);
876 : 520238 : return stage.size();
877 : 520238 : }
878 : :
879 : 2257675 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
880 : 2257675 : LOCK(cs);
881 [ + + + + ]: 2257675 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
882 : 2225002 : return CFeeRate(llround(rollingMinimumFeeRate));
883 : :
884 [ + - ]: 32673 : int64_t time = GetTime();
885 [ + + ]: 32673 : if (time > lastRollingFeeUpdate + 10) {
886 : 2304 : double halflife = ROLLING_FEE_HALFLIFE;
887 [ + - + - ]: 2304 : if (DynamicMemoryUsage() < sizelimit / 4)
888 : : halflife /= 4;
889 [ + - - + ]: 2304 : else if (DynamicMemoryUsage() < sizelimit / 2)
890 : 0 : halflife /= 2;
891 : :
892 : 2304 : rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
893 : 2304 : lastRollingFeeUpdate = time;
894 : :
895 [ + + ]: 2304 : if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
896 : 1761 : rollingMinimumFeeRate = 0;
897 : 1761 : return CFeeRate(0);
898 : : }
899 : : }
900 : 30912 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
901 : 2257675 : }
902 : :
903 : 26274 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
904 : 26274 : AssertLockHeld(cs);
905 [ + + ]: 26274 : if (rate.GetFeePerK() > rollingMinimumFeeRate) {
906 : 16232 : rollingMinimumFeeRate = rate.GetFeePerK();
907 : 16232 : blockSinceLastRollingFeeBump = false;
908 : : }
909 : 26274 : }
910 : :
911 : 520492 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
912 : 520492 : AssertLockHeld(cs);
913 [ - + ]: 520492 : Assume(!m_have_changeset);
914 : :
915 : 520492 : unsigned nTxnRemoved = 0;
916 : 520492 : CFeeRate maxFeeRateRemoved(0);
917 : :
918 [ + + + + ]: 546766 : while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
919 [ + - ]: 26274 : const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
920 [ + - ]: 26274 : FeePerVSize feerate = ToFeePerVSize(feeperweight);
921 [ + - ]: 26274 : CFeeRate removed{feerate.fee, feerate.size};
922 : :
923 : : // We set the new mempool min fee to the feerate of the removed set, plus the
924 : : // "minimum reasonable fee rate" (ie some value under which we consider txn
925 : : // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
926 : : // equal to txn which were removed with no block in between.
927 : 26274 : removed += m_opts.incremental_relay_feerate;
928 [ + - ]: 26274 : trackPackageRemoved(removed);
929 : 26274 : maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
930 : :
931 [ - + ]: 26274 : nTxnRemoved += worst_chunk.size();
932 : :
933 : 26274 : std::vector<CTransaction> txn;
934 [ + + ]: 26274 : if (pvNoSpendsRemaining) {
935 [ + - ]: 12233 : txn.reserve(worst_chunk.size());
936 [ + + ]: 28376 : for (auto ref : worst_chunk) {
937 [ + - ]: 16143 : txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
938 : : }
939 : : }
940 : :
941 : 26274 : setEntries stage;
942 [ + + ]: 58426 : for (auto ref : worst_chunk) {
943 [ + - ]: 32152 : stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
944 : : }
945 [ + + ]: 58426 : for (auto e : stage) {
946 [ + - ]: 32152 : removeUnchecked(e, MemPoolRemovalReason::SIZELIMIT);
947 : : }
948 [ + + ]: 26274 : if (pvNoSpendsRemaining) {
949 [ + + ]: 28376 : for (const CTransaction& tx : txn) {
950 [ + + ]: 94529 : for (const CTxIn& txin : tx.vin) {
951 [ + - + + ]: 78386 : if (exists(txin.prevout.hash)) continue;
952 [ + - ]: 77397 : pvNoSpendsRemaining->push_back(txin.prevout);
953 : : }
954 : : }
955 : : }
956 : 52548 : }
957 : :
958 [ + + ]: 520492 : if (maxFeeRateRemoved > CFeeRate(0)) {
959 [ - + - - ]: 12177 : LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
960 : : }
961 : 520492 : }
962 : :
963 : 2888755 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
964 : : {
965 : 2888755 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
966 : :
967 [ - + ]: 2888755 : size_t ancestor_count = ancestors.size();
968 : 2888755 : size_t ancestor_size = 0;
969 : 2888755 : CAmount ancestor_fees = 0;
970 [ + + ]: 7239256 : for (auto tx: ancestors) {
971 : 4350501 : const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
972 [ + - ]: 4350501 : ancestor_size += anc.GetTxSize();
973 : 4350501 : ancestor_fees += anc.GetModifiedFee();
974 : : }
975 : 2888755 : return {ancestor_count, ancestor_size, ancestor_fees};
976 : 2888755 : }
977 : :
978 : 2791261 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
979 : : {
980 : 2791261 : auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
981 [ - + ]: 2791261 : size_t descendant_count = descendants.size();
982 : 2791261 : size_t descendant_size = 0;
983 : 2791261 : CAmount descendant_fees = 0;
984 : :
985 [ + + ]: 6463628 : for (auto tx: descendants) {
986 : 3672367 : const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
987 [ + - ]: 3672367 : descendant_size += desc.GetTxSize();
988 : 3672367 : descendant_fees += desc.GetModifiedFee();
989 : : }
990 : 2791261 : return {descendant_count, descendant_size, descendant_fees};
991 : 2791261 : }
992 : :
993 : 0 : void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
994 : 0 : LOCK(cs);
995 : 0 : auto it = mapTx.find(txid);
996 : 0 : ancestors = cluster_count = 0;
997 [ # # ]: 0 : if (it != mapTx.end()) {
998 [ # # # # ]: 0 : auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
999 : 0 : ancestors = ancestor_count;
1000 [ # # ]: 0 : if (ancestorsize) *ancestorsize = ancestor_size;
1001 [ # # ]: 0 : if (ancestorfees) *ancestorfees = ancestor_fees;
1002 [ # # ]: 0 : cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
1003 : : }
1004 : 0 : }
1005 : :
1006 : 1 : bool CTxMemPool::GetLoadTried() const
1007 : : {
1008 : 1 : LOCK(cs);
1009 [ + - ]: 1 : return m_load_tried;
1010 : 1 : }
1011 : :
1012 : 1674 : void CTxMemPool::SetLoadTried(bool load_tried)
1013 : : {
1014 : 1674 : LOCK(cs);
1015 [ + - ]: 1674 : m_load_tried = load_tried;
1016 : 1674 : }
1017 : :
1018 : 3240 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
1019 : : {
1020 : 3240 : AssertLockHeld(cs);
1021 : :
1022 : 3240 : std::vector<CTxMemPool::txiter> ret;
1023 : 3240 : std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
1024 [ + + ]: 88058 : for (auto txid : txids) {
1025 : 84818 : auto it = mapTx.find(txid);
1026 [ + - ]: 84818 : if (it != mapTx.end()) {
1027 : : // Note that TxGraph::GetCluster will return results in graph
1028 : : // order, which is deterministic (as long as we are not modifying
1029 : : // the graph).
1030 : 84818 : auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
1031 [ + - + + ]: 84818 : if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
1032 [ + + ]: 150278 : for (auto tx : cluster) {
1033 [ + - ]: 139722 : ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
1034 : : }
1035 : : }
1036 : 84818 : }
1037 : : }
1038 [ - + - + ]: 3240 : if (ret.size() > 500) {
1039 : 0 : return {};
1040 : : }
1041 : 3240 : return ret;
1042 : 3240 : }
1043 : :
1044 : 85663 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1045 : : {
1046 : 85663 : LOCK(m_pool->cs);
1047 : :
1048 [ + - + + ]: 85663 : if (!CheckMemPoolPolicyLimits()) {
1049 [ + - + - ]: 1164 : return util::Error{Untranslated("cluster size limit exceeded")};
1050 : : }
1051 : :
1052 : 170550 : return m_pool->m_txgraph->GetMainStagingDiagrams();
1053 : 85663 : }
1054 : :
1055 : 3839560 : 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)
1056 : : {
1057 : 3839560 : LOCK(m_pool->cs);
1058 [ - + ]: 3839560 : Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1059 [ - + ]: 3839560 : Assume(!m_dependencies_processed);
1060 : :
1061 : : // We need to process dependencies after adding a new transaction.
1062 : 3839560 : m_dependencies_processed = false;
1063 : :
1064 : 3839560 : CAmount delta{0};
1065 [ + - ]: 3839560 : m_pool->ApplyDelta(tx->GetHash(), delta);
1066 : :
1067 [ + - + - ]: 3839560 : FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp));
1068 [ + - ]: 3839560 : auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1069 : 3839560 : m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1070 [ + + ]: 3839560 : if (delta) {
1071 : 157522 : newit->UpdateModifiedFee(delta);
1072 : 157522 : m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1073 : : }
1074 : :
1075 [ + - ]: 3839560 : m_entry_vec.push_back(newit);
1076 : :
1077 [ + - ]: 3839560 : return newit;
1078 : 3839560 : }
1079 : :
1080 : 1221969 : void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it)
1081 : : {
1082 : 1221969 : LOCK(m_pool->cs);
1083 : 1221969 : m_pool->m_txgraph->RemoveTransaction(*it);
1084 [ + - ]: 1221969 : m_to_remove.insert(it);
1085 : 1221969 : }
1086 : :
1087 : 1890988 : void CTxMemPool::ChangeSet::Apply()
1088 : : {
1089 : 1890988 : LOCK(m_pool->cs);
1090 [ + + ]: 1890988 : if (!m_dependencies_processed) {
1091 [ + - ]: 32 : ProcessDependencies();
1092 : : }
1093 [ + - ]: 1890988 : m_pool->Apply(this);
1094 : 1890988 : m_to_add.clear();
1095 : 1890988 : m_to_remove.clear();
1096 [ + - ]: 1890988 : m_entry_vec.clear();
1097 [ + - ]: 1890988 : m_ancestors.clear();
1098 : 1890988 : }
1099 : :
1100 : 3108129 : void CTxMemPool::ChangeSet::ProcessDependencies()
1101 : : {
1102 : 3108129 : LOCK(m_pool->cs);
1103 [ - + ]: 3108129 : Assume(!m_dependencies_processed); // should only call this once.
1104 [ + + ]: 6222145 : for (const auto& entryptr : m_entry_vec) {
1105 [ + - + - : 14161322 : for (const auto &txin : entryptr->GetSharedTx()->vin) {
+ + ]
1106 [ + - ]: 4819274 : std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1107 [ + + ]: 4819274 : if (!piter) {
1108 : 3048137 : auto it = m_to_add.find(txin.prevout.hash);
1109 [ + + ]: 3048137 : if (it != m_to_add.end()) {
1110 : 9493 : piter = std::make_optional(it);
1111 : : }
1112 : : }
1113 [ + + ]: 4819274 : if (piter) {
1114 : 1780630 : m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1115 : : }
1116 : : }
1117 : : }
1118 : 3108129 : m_dependencies_processed = true;
1119 [ + - ]: 3108129 : return;
1120 : 3108129 : }
1121 : :
1122 : 3251727 : bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits()
1123 : : {
1124 : 3251727 : LOCK(m_pool->cs);
1125 [ + + ]: 3251727 : if (!m_dependencies_processed) {
1126 [ + - ]: 3108097 : ProcessDependencies();
1127 : : }
1128 : :
1129 [ + - ]: 3251727 : return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1130 : 3251727 : }
1131 : :
1132 : 238037 : std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1133 : : {
1134 : 238037 : FeePerWeight zero{};
1135 : 238037 : std::vector<FeePerWeight> ret;
1136 : :
1137 [ + - ]: 238037 : ret.emplace_back(zero);
1138 : :
1139 : 238037 : StartBlockBuilding();
1140 : :
1141 : 238037 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1142 : :
1143 [ + - ]: 238037 : FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1144 [ + + ]: 453986 : while (last_selection != FeePerWeight{}) {
1145 [ + - ]: 215949 : last_selection += ret.back();
1146 [ + - ]: 215949 : ret.emplace_back(last_selection);
1147 : 215949 : IncludeBuilderChunk();
1148 [ + - ]: 215949 : last_selection = GetBlockBuilderChunk(dummy);
1149 : : }
1150 : 238037 : StopBlockBuilding();
1151 : 238037 : return ret;
1152 : 238037 : }
|