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