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 : 4068 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41 : : {
42 : 4068 : 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 [ + - ]: 4068 : 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 [ + + ]: 4068 : if (!active_chain.Contains(*lp.maxInputBlock)) {
49 : 230 : return false;
50 : : }
51 : : }
52 : :
53 : : // LockPoints still valid
54 : : return true;
55 : : }
56 : :
57 : 10221338 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58 : : {
59 : 10221338 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60 [ + - ]: 10221338 : const auto& hash = entry.GetTx().GetHash();
61 : 10221338 : {
62 [ + - ]: 10221338 : LOCK(cs);
63 : 10221338 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64 [ + + + + ]: 10420303 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65 [ + - ]: 198965 : ret.emplace_back(*(iter->second));
66 : : }
67 : 0 : }
68 : 10221338 : std::ranges::sort(ret, CompareIteratorByHash{});
69 [ + + - - ]: 10242997 : auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70 : 10221338 : ret.erase(removed.begin(), removed.end());
71 : 10221338 : return ret;
72 : 0 : }
73 : :
74 : 10254987 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75 : : {
76 : 10254987 : LOCK(cs);
77 : 10254987 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78 : 10254987 : std::set<Txid> inputs;
79 [ + + ]: 23127040 : for (const auto& txin : entry.GetTx().vin) {
80 [ + - ]: 12872053 : inputs.insert(txin.prevout.hash);
81 : : }
82 [ + + ]: 23111258 : for (const auto& hash : inputs) {
83 [ + - ]: 12856271 : std::optional<txiter> piter = GetIter(hash);
84 [ + + ]: 12856271 : if (piter) {
85 [ + - ]: 198103 : ret.emplace_back(**piter);
86 : : }
87 : : }
88 : 10254987 : return ret;
89 [ + - ]: 20509974 : }
90 : :
91 : 3007 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
92 : : {
93 : 3007 : 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 [ + + ]: 3810 : for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
98 : : // calculate children from mapNextTx
99 : 803 : txiter it = mapTx.find(hash);
100 [ - + ]: 803 : if (it == mapTx.end()) {
101 : 0 : continue;
102 : : }
103 : 803 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104 : 803 : {
105 [ + + + + ]: 3277 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
106 [ - + ]: 2474 : txiter childIter = iter->second;
107 [ - + ]: 2474 : assert(childIter != mapTx.end());
108 : : // Add dependencies that are discovered between transactions in the
109 : : // block and transactions that were in the mempool to txgraph.
110 : 2474 : m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
111 : : }
112 : : }
113 : : }
114 : :
115 : 3007 : auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
116 [ - + ]: 3007 : 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 : 3007 : }
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 : 1901 : CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const
131 : : {
132 : 1901 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
133 [ - + ]: 1901 : setEntries ret;
134 [ - + + + ]: 1901 : if (ancestors.size() > 0) {
135 [ + + ]: 14715 : for (auto ancestor : ancestors) {
136 [ + + ]: 14100 : if (ancestor != &entry) {
137 [ + - ]: 13485 : 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 : 1286 : setEntries staged_parents;
146 : 1286 : const CTransaction &tx = entry.GetTx();
147 : :
148 : : // Get parents of this transaction that are in the mempool
149 [ - + + + ]: 2910 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
150 [ + - ]: 1624 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151 [ + + ]: 1624 : if (piter) {
152 [ + - ]: 239 : staged_parents.insert(*piter);
153 : : }
154 : : }
155 : :
156 [ + + ]: 1499 : for (const auto& parent : staged_parents) {
157 : 213 : auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN);
158 [ + + ]: 812 : for (auto ancestor : parent_ancestors) {
159 [ + - ]: 599 : ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
160 : : }
161 : 213 : }
162 : :
163 : 1286 : return ret;
164 : 3187 : }
165 : :
166 : 1274 : static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
167 : : {
168 [ + - ]: 1274 : opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169 : 1274 : int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170 [ + - + - : 1274 : if (opts.max_size_bytes < 0 || (opts.max_size_bytes > 0 && opts.max_size_bytes < cluster_limit_bytes)) {
+ + ]
171 : 2 : error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(cluster_limit_bytes / 1'000'000.0));
172 : : }
173 : 1274 : return std::move(opts);
174 : : }
175 : :
176 : 1274 : CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
177 [ + - + - ]: 1274 : : m_opts{Flatten(std::move(opts), error)}
178 : : {
179 : 2548 : m_txgraph = MakeTxGraph(
180 : 1274 : /*max_cluster_count=*/m_opts.limits.cluster_count,
181 : 1274 : /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,
182 : : /*acceptable_cost=*/ACCEPTABLE_COST,
183 : 1274 : /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184 : 72209766 : const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185 : 72209766 : const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186 : 72209766 : return txid_a <=> txid_b;
187 : 1274 : });
188 : 1274 : }
189 : :
190 : 54 : bool CTxMemPool::isSpent(const COutPoint& outpoint) const
191 : : {
192 : 54 : LOCK(cs);
193 [ + - ]: 54 : return mapNextTx.count(outpoint);
194 : 54 : }
195 : :
196 : 2093 : unsigned int CTxMemPool::GetTransactionsUpdated() const
197 : : {
198 : 2093 : return nTransactionsUpdated;
199 : : }
200 : :
201 : 147991 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
202 : : {
203 : 147991 : nTransactionsUpdated += n;
204 : 147991 : }
205 : :
206 : 51464 : void CTxMemPool::Apply(ChangeSet* changeset)
207 : : {
208 : 51464 : AssertLockHeld(cs);
209 : 51464 : m_txgraph->CommitStaging();
210 : :
211 : 51464 : RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED);
212 : :
213 [ - + + + ]: 102996 : for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214 : 51532 : auto tx_entry = changeset->m_entry_vec[i];
215 : : // First splice this entry into mapTx.
216 : 51532 : auto node_handle = changeset->m_to_add.extract(tx_entry);
217 [ + - ]: 51532 : auto result = mapTx.insert(std::move(node_handle));
218 : :
219 [ + - ]: 51532 : Assume(result.inserted);
220 : 51532 : txiter it = result.position;
221 : :
222 [ + - ]: 51532 : addNewTransaction(it);
223 [ - + ]: 51532 : }
224 [ - + ]: 51464 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
225 [ # # ]: 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after addition(s).");
226 : : }
227 : 51464 : }
228 : :
229 : 51532 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit)
230 : : {
231 : 51532 : 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 : 51532 : cachedInnerUsage += entry.DynamicMemoryUsage();
237 : :
238 : 51532 : const CTransaction& tx = newit->GetTx();
239 [ - + + + ]: 116159 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
240 : 64627 : 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 : 51532 : nTransactionsUpdated++;
250 : 51532 : totalTxSize += entry.GetTxSize();
251 : 51532 : m_total_fee += entry.GetFee();
252 : :
253 : 51532 : txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
254 [ - + ]: 51532 : newit->idx_randomized = txns_randomized.size() - 1;
255 : :
256 : : TRACEPOINT(mempool, added,
257 : : entry.GetTx().GetHash().data(),
258 : : entry.GetTxSize(),
259 : : entry.GetFee()
260 : 51532 : );
261 : 51532 : }
262 : :
263 : 48011 : 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 [ + + ]: 48011 : uint64_t mempool_sequence = GetAndIncrementSequence();
268 : :
269 [ + + + - ]: 48011 : 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 [ + - + - ]: 5520 : 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 : 48011 : );
283 : :
284 [ + + ]: 107869 : for (const CTxIn& txin : it->GetTx().vin)
285 : 59858 : mapNextTx.erase(txin.prevout);
286 : :
287 : 48011 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
288 : :
289 [ - + + + ]: 48011 : if (txns_randomized.size() > 1) {
290 : : // Remove entry from txns_randomized by replacing it with the back and deleting the back.
291 [ - + ]: 45805 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
292 [ - + ]: 45805 : txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
293 [ - + ]: 45805 : txns_randomized.pop_back();
294 [ - + - + : 45805 : if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
+ + ]
295 : 3280 : txns_randomized.shrink_to_fit();
296 : : }
297 : : } else {
298 [ + - ]: 2206 : txns_randomized.clear();
299 : : }
300 : :
301 : 48011 : totalTxSize -= it->GetTxSize();
302 : 48011 : m_total_fee -= it->GetFee();
303 : 48011 : cachedInnerUsage -= it->DynamicMemoryUsage();
304 : 48011 : mapTx.erase(it);
305 : 48011 : nTransactionsUpdated++;
306 : 48011 : }
307 : :
308 : : // Calculates descendants of given entry and adds to setDescendants.
309 : 80159 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
310 : : {
311 : 80159 : (void)CalculateDescendants(*entryit, setDescendants);
312 : 80159 : return;
313 : : }
314 : :
315 : 80221 : CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const
316 : : {
317 [ + + ]: 362450 : for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
318 [ + - ]: 282229 : setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
319 : : }
320 : 80221 : return mapTx.iterator_to(entry);
321 : : }
322 : :
323 : 77 : void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason)
324 : : {
325 : 77 : AssertLockHeld(cs);
326 : 77 : Assume(!m_have_changeset);
327 : 77 : auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
328 [ + + ]: 197 : for (auto tx: descendants) {
329 [ + - ]: 120 : removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
330 : : }
331 : 77 : }
332 : :
333 : 19090 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
334 : : {
335 : : // Remove transaction from memory pool
336 : 19090 : AssertLockHeld(cs);
337 : 19090 : Assume(!m_have_changeset);
338 : 19090 : txiter origit = mapTx.find(origTx.GetHash());
339 [ + + ]: 19090 : if (origit != mapTx.end()) {
340 : 7 : 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 : 19083 : auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
347 : 19083 : std::vector<const TxGraph::Ref*> to_remove;
348 [ + + + + ]: 19157 : while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
349 [ + - ]: 74 : to_remove.emplace_back(&*(iter->second));
350 : 74 : ++iter;
351 : : }
352 [ - + ]: 19083 : auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
353 [ + + ]: 19160 : for (auto ref : all_removes) {
354 : 77 : auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
355 [ + - ]: 77 : removeUnchecked(tx, reason);
356 : : }
357 : 19083 : }
358 : 19090 : }
359 : :
360 : 3007 : 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 : 3007 : AssertLockHeld(cs);
364 : 3007 : AssertLockHeld(::cs_main);
365 : 3007 : Assume(!m_have_changeset);
366 : :
367 : 3007 : std::vector<const TxGraph::Ref*> to_remove;
368 [ + + ]: 5056 : for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
369 [ + - + + ]: 2049 : if (check_final_and_mature(it)) {
370 [ + - ]: 15 : to_remove.emplace_back(&*it);
371 : : }
372 : : }
373 : :
374 [ - + ]: 3007 : auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
375 : :
376 [ + + ]: 3034 : for (auto ref : all_to_remove) {
377 : 27 : auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
378 [ + - ]: 27 : removeUnchecked(it, MemPoolRemovalReason::REORG);
379 : : }
380 [ + + ]: 5029 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
381 [ + - - + ]: 2022 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
382 : : }
383 [ - + ]: 3007 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
384 [ - - - - : 3007 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after reorg.");
- - ]
385 : : }
386 : 3007 : }
387 : :
388 : 58638 : void CTxMemPool::removeConflicts(const CTransaction &tx)
389 : : {
390 : : // Remove transactions which depend on inputs of tx, recursively
391 : 58638 : AssertLockHeld(cs);
392 [ + + ]: 129055 : for (const CTxIn &txin : tx.vin) {
393 : 70417 : auto it = mapNextTx.find(txin.prevout);
394 [ + + ]: 70417 : if (it != mapNextTx.end()) {
395 [ + - ]: 70 : const CTransaction &txConflict = it->second->GetTx();
396 [ + - ]: 70 : if (Assume(txConflict.GetHash() != tx.GetHash()))
397 : : {
398 : 70 : ClearPrioritisation(txConflict.GetHash());
399 : 70 : removeRecursive(it->second, MemPoolRemovalReason::CONFLICT);
400 : : }
401 : : }
402 : : }
403 : 58638 : }
404 : :
405 : 133396 : 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 : 133396 : AssertLockHeld(cs);
409 [ + + ]: 133396 : Assume(!m_have_changeset);
410 : 133396 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
411 [ + + + - : 133396 : if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
+ + ]
412 [ - + + - ]: 8040 : txs_removed_for_block.reserve(vtx.size());
413 [ + + ]: 66678 : for (const auto& tx : vtx) {
414 : 58638 : txiter it = mapTx.find(tx->GetHash());
415 [ + + ]: 58638 : if (it != mapTx.end()) {
416 [ + - ]: 46171 : txs_removed_for_block.emplace_back(*it);
417 [ + - ]: 46171 : removeUnchecked(it, MemPoolRemovalReason::BLOCK);
418 : : }
419 [ + - ]: 58638 : removeConflicts(*tx);
420 [ + - ]: 58638 : ClearPrioritisation(tx->GetHash());
421 : : }
422 : : }
423 [ + - ]: 133396 : if (m_opts.signals) {
424 [ + - ]: 133396 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
425 : : }
426 [ + - ]: 133396 : lastRollingFeeUpdate = GetTime();
427 : 133396 : blockSinceLastRollingFeeBump = true;
428 [ - + ]: 133396 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
429 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after block.");
# # ]
430 : : }
431 : 133396 : }
432 : :
433 : 168186 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
434 : : {
435 [ + + ]: 168186 : if (m_opts.check_ratio == 0) return;
436 : :
437 [ + - ]: 166139 : if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
438 : :
439 : 166139 : AssertLockHeld(::cs_main);
440 : 166139 : LOCK(cs);
441 [ + - + - : 166139 : LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - ]
442 : :
443 : 166139 : uint64_t checkTotal = 0;
444 : 166139 : CAmount check_total_fee{0};
445 : 166139 : CAmount check_total_modified_fee{0};
446 : 166139 : int64_t check_total_adjusted_weight{0};
447 : 166139 : uint64_t innerUsage = 0;
448 : :
449 [ - + ]: 166139 : assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
450 [ + - ]: 166139 : m_txgraph->SanityCheck();
451 : :
452 [ + - ]: 166139 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
453 : :
454 [ + - ]: 166139 : const auto score_with_topo{GetSortedScoreWithTopology()};
455 : :
456 : : // Number of chunks is bounded by number of transactions.
457 [ + - ]: 166139 : const auto diagram{GetFeerateDiagram()};
458 [ - + - + : 166139 : assert(diagram.size() <= score_with_topo.size() + 1);
- + ]
459 [ - + ]: 166139 : assert(diagram.size() >= 1);
460 : :
461 : 166139 : std::optional<Wtxid> last_wtxid = std::nullopt;
462 : 166139 : auto diagram_iter = diagram.cbegin();
463 : :
464 [ + + ]: 10378523 : 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 [ - + ]: 10212384 : assert(diagram_iter->size >= check_total_adjusted_weight);
472 [ + + ]: 10212384 : if (diagram_iter->fee == check_total_modified_fee &&
473 [ + - ]: 10191517 : diagram_iter->size == check_total_adjusted_weight) {
474 : 10191517 : ++diagram_iter;
475 : : }
476 [ + - ]: 10212384 : checkTotal += it->GetTxSize();
477 [ + - ]: 10212384 : check_total_adjusted_weight += it->GetAdjustedWeight();
478 [ + + ]: 10212384 : check_total_fee += it->GetFee();
479 [ + + ]: 10212384 : check_total_modified_fee += it->GetModifiedFee();
480 [ + + ]: 10212384 : innerUsage += it->DynamicMemoryUsage();
481 [ + + ]: 10212384 : const CTransaction& tx = it->GetTx();
482 : :
483 : : // CompareMiningScoreWithTopology should agree with GetSortedScoreWithTopology()
484 [ + + ]: 10212384 : if (last_wtxid) {
485 [ + - - + ]: 10181203 : assert(CompareMiningScoreWithTopology(*last_wtxid, tx.GetWitnessHash()));
486 : : }
487 [ + + ]: 10212384 : last_wtxid = tx.GetWitnessHash();
488 : :
489 : 10212384 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
490 : 10212384 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
491 [ + + ]: 23022543 : for (const CTxIn &txin : tx.vin) {
492 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
493 : 12810159 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
494 [ + + ]: 12810159 : if (it2 != mapTx.end()) {
495 [ - + ]: 191485 : const CTransaction& tx2 = it2->GetTx();
496 [ - + + - : 191485 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
- + ]
497 [ + - ]: 191485 : setParentCheck.insert(*it2);
498 : : }
499 : : // We are iterating through the mempool entries sorted
500 : : // topologically and by mining score. All parents must have been
501 : : // checked before their children and their coins added to the
502 : : // mempoolDuplicate coins cache.
503 [ + - - + ]: 12810159 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
504 : : // Check whether its inputs are marked in mapNextTx.
505 : 12810159 : auto it3 = mapNextTx.find(txin.prevout);
506 [ - + ]: 12810159 : assert(it3 != mapNextTx.end());
507 [ - + ]: 12810159 : assert(it3->first == &txin.prevout);
508 [ - + ]: 12810159 : assert(&it3->second->GetTx() == &tx);
509 : : }
510 : 10595164 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
511 [ + - ]: 382780 : return a.GetTx().GetHash() == b.GetTx().GetHash();
512 : : };
513 [ + - + + ]: 10403774 : for (auto &txentry : GetParents(*it)) {
514 [ + - ]: 191390 : setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
515 : 0 : }
516 [ - + ]: 10212384 : assert(setParentCheck.size() == setParentsStored.size());
517 [ - + ]: 10212384 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
518 : :
519 : : // Check children against mapNextTx
520 : 10212384 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
521 : 10212384 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
522 : 10212384 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
523 [ + + + + ]: 10403869 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
524 [ - + ]: 191485 : txiter childit = iter->second;
525 [ - + ]: 191485 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
526 [ + - ]: 191485 : setChildrenCheck.insert(*childit);
527 : : }
528 [ + - + + ]: 10403774 : for (auto &txentry : GetChildren(*it)) {
529 [ + - ]: 191390 : setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
530 : 0 : }
531 [ - + ]: 10212384 : assert(setChildrenCheck.size() == setChildrenStored.size());
532 [ - + ]: 10212384 : assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
533 : :
534 [ - + ]: 10212384 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
535 : 10212384 : CAmount txfee = 0;
536 [ - + ]: 10212384 : assert(!tx.IsCoinBase());
537 [ + - - + ]: 10212384 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
538 [ + - + + ]: 23022543 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
539 [ + - ]: 10212384 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
540 : 10212384 : }
541 [ + + ]: 12976298 : for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
542 [ - + ]: 12810159 : indexed_transaction_set::const_iterator it2 = it->second;
543 [ - + ]: 12810159 : assert(it2 != mapTx.end());
544 : : }
545 : :
546 [ - + ]: 166139 : ++diagram_iter;
547 [ - + ]: 166139 : assert(diagram_iter == diagram.cend());
548 : :
549 [ - + ]: 166139 : assert(totalTxSize == checkTotal);
550 [ - + ]: 166139 : assert(m_total_fee == check_total_fee);
551 [ - + ]: 166139 : assert(diagram.back().fee == check_total_modified_fee);
552 [ - + ]: 166139 : assert(diagram.back().size == check_total_adjusted_weight);
553 [ - + ]: 166139 : assert(innerUsage == cachedInnerUsage);
554 [ + - ]: 332278 : }
555 : :
556 : 10209565 : bool CTxMemPool::CompareMiningScoreWithTopology(const Wtxid& hasha, const Wtxid& hashb) const
557 : : {
558 : : /* Return `true` if hasha should be considered sooner than hashb, namely when:
559 : : * a is not in the mempool but b is, or
560 : : * both are in the mempool but a is sorted before b in the total mempool ordering
561 : : * (which takes dependencies and (chunk) feerates into account).
562 : : */
563 : 10209565 : LOCK(cs);
564 [ + - ]: 10209565 : auto j{GetIter(hashb)};
565 [ + + ]: 10209565 : if (!j.has_value()) return false;
566 [ + - ]: 10203839 : auto i{GetIter(hasha)};
567 [ + + ]: 10203839 : if (!i.has_value()) return true;
568 : :
569 : 10203627 : return m_txgraph->CompareMainOrder(*i.value(), *j.value()) < 0;
570 : 10209565 : }
571 : :
572 : 176366 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
573 : : {
574 : 176366 : std::vector<indexed_transaction_set::const_iterator> iters;
575 : 176366 : AssertLockHeld(cs);
576 : :
577 [ + - ]: 176366 : iters.reserve(mapTx.size());
578 : :
579 [ + + + + ]: 21202932 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
580 [ + - ]: 10513283 : iters.push_back(mi);
581 : : }
582 : 176366 : std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
583 : 120867362 : return m_txgraph->CompareMainOrder(*a, *b) < 0;
584 : : });
585 : 176366 : return iters;
586 : 0 : }
587 : :
588 : 9244 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
589 : : {
590 : 9244 : AssertLockHeld(cs);
591 : :
592 : 9244 : std::vector<CTxMemPoolEntryRef> ret;
593 [ + - ]: 9244 : ret.reserve(mapTx.size());
594 [ + - + + ]: 308919 : for (const auto& it : GetSortedScoreWithTopology()) {
595 [ + - ]: 299675 : ret.emplace_back(*it);
596 : : }
597 : 9244 : return ret;
598 : 0 : }
599 : :
600 : 983 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
601 : : {
602 : 983 : LOCK(cs);
603 [ + - ]: 983 : auto iters = GetSortedScoreWithTopology();
604 : :
605 : 983 : std::vector<TxMempoolInfo> ret;
606 [ + - ]: 983 : ret.reserve(mapTx.size());
607 [ + + ]: 2207 : for (auto it : iters) {
608 [ + - - + ]: 2448 : ret.push_back(GetInfo(it));
609 : : }
610 : :
611 : 983 : return ret;
612 [ + - ]: 1966 : }
613 : :
614 : 2862 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
615 : : {
616 : 2862 : AssertLockHeld(cs);
617 : 2862 : const auto i = mapTx.find(txid);
618 [ + + ]: 2862 : return i == mapTx.end() ? nullptr : &(*i);
619 : : }
620 : :
621 : 246082 : CTransactionRef CTxMemPool::get(const Txid& hash) const
622 : : {
623 : 246082 : LOCK(cs);
624 : 246082 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
625 [ + + ]: 246082 : if (i == mapTx.end())
626 : 188441 : return nullptr;
627 [ + - + - ]: 303723 : return i->GetSharedTx();
628 : 246082 : }
629 : :
630 : 4 : CTransactionRef CTxMemPool::get(const Wtxid& hash) const
631 : : {
632 : 4 : LOCK(cs);
633 : 4 : const auto& wtxid_map{mapTx.get<index_by_wtxid>()};
634 : 4 : const auto it{wtxid_map.find(hash)};
635 [ + + ]: 4 : if (it == wtxid_map.end()) return nullptr;
636 [ + - + - ]: 6 : return it->GetSharedTx();
637 : 4 : }
638 : :
639 : 769 : void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
640 : : {
641 : 769 : {
642 : 769 : LOCK(cs);
643 [ + - ]: 769 : CAmount &delta = mapDeltas[hash];
644 : 769 : delta = SaturatingAdd(delta, nFeeDelta);
645 : 769 : txiter it = mapTx.find(hash);
646 [ + + ]: 769 : if (it != mapTx.end()) {
647 : : // PrioritiseTransaction calls stack on previous ones. Set the new
648 : : // transaction fee to be current modified fee + feedelta.
649 : 262 : it->UpdateModifiedFee(nFeeDelta);
650 : 262 : m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
651 : 262 : ++nTransactionsUpdated;
652 : : }
653 [ + + ]: 769 : if (delta == 0) {
654 : 9 : mapDeltas.erase(hash);
655 [ + + + - : 16 : LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
+ - ]
656 : : } else {
657 [ + - + - : 1015 : LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
+ + + - +
- ]
658 : : hash.ToString(),
659 : : it == mapTx.end() ? "not " : "",
660 : : FormatMoney(nFeeDelta),
661 : : FormatMoney(delta));
662 : : }
663 : 769 : }
664 : 769 : }
665 : :
666 : 72906 : void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
667 : : {
668 : 72906 : AssertLockHeld(cs);
669 : 72906 : std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
670 [ + + ]: 72906 : if (pos == mapDeltas.end())
671 : : return;
672 : 41 : const CAmount &delta = pos->second;
673 : 41 : nFeeDelta += delta;
674 : : }
675 : :
676 : 58709 : void CTxMemPool::ClearPrioritisation(const Txid& hash)
677 : : {
678 : 58709 : AssertLockHeld(cs);
679 : 58709 : mapDeltas.erase(hash);
680 : 58709 : }
681 : :
682 : 31 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
683 : : {
684 : 31 : AssertLockNotHeld(cs);
685 : 31 : LOCK(cs);
686 : 31 : std::vector<delta_info> result;
687 [ + - ]: 31 : result.reserve(mapDeltas.size());
688 [ + + ]: 61 : for (const auto& [txid, delta] : mapDeltas) {
689 : 30 : const auto iter{mapTx.find(txid)};
690 [ + + ]: 30 : const bool in_mempool{iter != mapTx.end()};
691 : 30 : std::optional<CAmount> modified_fee;
692 [ + + ]: 30 : if (in_mempool) modified_fee = iter->GetModifiedFee();
693 [ + - ]: 30 : result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
694 : : }
695 [ + - ]: 31 : return result;
696 : 31 : }
697 : :
698 : 116267 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
699 : : {
700 : 116267 : const auto it = mapNextTx.find(prevout);
701 [ + + ]: 116267 : return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
702 : : }
703 : :
704 : 12997049 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
705 : : {
706 : 12997049 : AssertLockHeld(cs);
707 : 12997049 : auto it = mapTx.find(txid);
708 [ + + ]: 12997049 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
709 : : }
710 : :
711 : 20446620 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
712 : : {
713 : 20446620 : AssertLockHeld(cs);
714 [ + + ]: 20446620 : auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
715 [ + + ]: 20446620 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
716 : : }
717 : :
718 : 42589 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
719 : : {
720 : 42589 : CTxMemPool::setEntries ret;
721 [ + + ]: 44889 : for (const auto& h : hashes) {
722 [ + - ]: 2300 : const auto mi = GetIter(h);
723 [ + - + - ]: 2300 : if (mi) ret.insert(*mi);
724 : : }
725 : 42589 : return ret;
726 : 0 : }
727 : :
728 : 2 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
729 : : {
730 : 2 : AssertLockHeld(cs);
731 : 2 : std::vector<txiter> ret;
732 [ - + + - ]: 2 : ret.reserve(txids.size());
733 [ + + ]: 565 : for (const auto& txid : txids) {
734 [ + - ]: 563 : const auto it{GetIter(txid)};
735 [ - + ]: 563 : if (!it) return {};
736 [ + - ]: 563 : ret.push_back(*it);
737 : : }
738 : 2 : return ret;
739 : 2 : }
740 : :
741 : 24948 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
742 : : {
743 [ - + + + ]: 57432 : for (unsigned int i = 0; i < tx.vin.size(); i++)
744 [ + + ]: 35536 : if (exists(tx.vin[i].prevout.hash))
745 : : return false;
746 : : return true;
747 : : }
748 : :
749 [ + - + - ]: 50724 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
750 : :
751 : 70949 : std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
752 : : {
753 : : // Check to see if the inputs are made available by another tx in the package.
754 : : // These Coins would not be available in the underlying CoinsView.
755 [ + + ]: 70949 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
756 : 615 : return it->second;
757 : : }
758 : :
759 : : // If an entry in the mempool exists, always return that one, as it's guaranteed to never
760 : : // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
761 : : // transactions. First checking the underlying cache risks returning a pruned entry instead.
762 : 70334 : CTransactionRef ptx = mempool.get(outpoint.hash);
763 [ + + ]: 70334 : if (ptx) {
764 [ - + + - ]: 8291 : if (outpoint.n < ptx->vout.size()) {
765 : 8291 : Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
766 [ + - ]: 8291 : m_non_base_coins.emplace(outpoint);
767 : 8291 : return coin;
768 : 8291 : }
769 : 0 : return std::nullopt;
770 : : }
771 [ + - ]: 62043 : return base->GetCoin(outpoint);
772 : 70334 : }
773 : :
774 : 779 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
775 : : {
776 [ - + + + ]: 1595 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
777 [ + - ]: 816 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
778 : 816 : m_non_base_coins.emplace(tx->GetHash(), n);
779 : : }
780 : 779 : }
781 : 73552 : void CCoinsViewMemPool::Reset()
782 : : {
783 : 73552 : m_temp_added.clear();
784 : 73552 : m_non_base_coins.clear();
785 : 73552 : }
786 : :
787 : 552389 : size_t CTxMemPool::DynamicMemoryUsage() const {
788 : 552389 : LOCK(cs);
789 : : // 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.
790 [ - + + - ]: 1104778 : return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
791 : 552389 : }
792 : :
793 : 60894 : void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
794 : 60894 : LOCK(cs);
795 : :
796 [ + + ]: 60894 : if (m_unbroadcast_txids.erase(txid))
797 : : {
798 [ + - + - : 17792 : LogDebug(BCLog::MEMPOOL, "Removed %s from set of unbroadcast txns%s", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
+ + + - +
- ]
799 : : }
800 : 60894 : }
801 : :
802 : 78495 : void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) {
803 : 78495 : AssertLockHeld(cs);
804 [ + + ]: 80062 : for (txiter it : stage) {
805 : 1567 : removeUnchecked(it, reason);
806 : : }
807 : 78495 : }
808 : :
809 : 3487 : bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx)
810 : : {
811 : 3487 : LOCK(cs);
812 : : // Use ChangeSet interface to check whether the cluster count
813 : : // limits would be violated. Note that the changeset will be destroyed
814 : : // when it goes out of scope.
815 [ + - ]: 3487 : auto changeset = GetChangeSet();
816 [ + - ]: 3487 : (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
817 [ + - ]: 3487 : return changeset->CheckMemPoolPolicyLimits();
818 [ + - ]: 6974 : }
819 : :
820 : 27031 : int CTxMemPool::Expire(std::chrono::seconds time)
821 : : {
822 : 27031 : AssertLockHeld(cs);
823 : 27031 : Assume(!m_have_changeset);
824 : 27031 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
825 : 27031 : setEntries toremove;
826 [ + + + + ]: 27035 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
827 [ + - ]: 4 : toremove.insert(mapTx.project<0>(it));
828 : 4 : it++;
829 : : }
830 : 27031 : setEntries stage;
831 [ + + ]: 27035 : for (txiter removeit : toremove) {
832 [ + - ]: 4 : CalculateDescendants(removeit, stage);
833 : : }
834 [ + - ]: 27031 : RemoveStaged(stage, MemPoolRemovalReason::EXPIRY);
835 : 27031 : return stage.size();
836 : 27031 : }
837 : :
838 : 469176 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
839 : 469176 : LOCK(cs);
840 [ + + + + ]: 469176 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
841 : 469083 : return CFeeRate(llround(rollingMinimumFeeRate));
842 : :
843 [ + - ]: 93 : int64_t time = GetTime();
844 [ + + ]: 93 : if (time > lastRollingFeeUpdate + 10) {
845 : 6 : double halflife = ROLLING_FEE_HALFLIFE;
846 [ + - + + ]: 6 : if (DynamicMemoryUsage() < sizelimit / 4)
847 : : halflife /= 4;
848 [ + - + + ]: 5 : else if (DynamicMemoryUsage() < sizelimit / 2)
849 : 1 : halflife /= 2;
850 : :
851 : 6 : rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
852 : 6 : lastRollingFeeUpdate = time;
853 : :
854 [ + + ]: 6 : if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
855 : 1 : rollingMinimumFeeRate = 0;
856 : 1 : return CFeeRate(0);
857 : : }
858 : : }
859 : 92 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
860 : 469176 : }
861 : :
862 : 43 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
863 : 43 : AssertLockHeld(cs);
864 [ + + ]: 43 : if (rate.GetFeePerK() > rollingMinimumFeeRate) {
865 : 41 : rollingMinimumFeeRate = rate.GetFeePerK();
866 : 41 : blockSinceLastRollingFeeBump = false;
867 : : }
868 : 43 : }
869 : :
870 : 27040 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
871 : 27040 : AssertLockHeld(cs);
872 : 27040 : Assume(!m_have_changeset);
873 : :
874 : 27040 : unsigned nTxnRemoved = 0;
875 : 27040 : CFeeRate maxFeeRateRemoved(0);
876 : :
877 [ + + + + ]: 27083 : while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
878 [ + - ]: 43 : const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
879 [ + - ]: 43 : FeePerVSize feerate = ToFeePerVSize(feeperweight);
880 [ + - ]: 43 : CFeeRate removed{feerate.fee, feerate.size};
881 : :
882 : : // We set the new mempool min fee to the feerate of the removed set, plus the
883 : : // "minimum reasonable fee rate" (ie some value under which we consider txn
884 : : // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
885 : : // equal to txn which were removed with no block in between.
886 : 43 : removed += m_opts.incremental_relay_feerate;
887 [ + - ]: 43 : trackPackageRemoved(removed);
888 : 43 : maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
889 : :
890 [ - + ]: 43 : nTxnRemoved += worst_chunk.size();
891 : :
892 : 43 : std::vector<CTransaction> txn;
893 [ + + ]: 43 : if (pvNoSpendsRemaining) {
894 [ + - ]: 35 : txn.reserve(worst_chunk.size());
895 [ + + ]: 71 : for (auto ref : worst_chunk) {
896 [ + - ]: 36 : txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
897 : : }
898 : : }
899 : :
900 : 43 : setEntries stage;
901 [ + + ]: 92 : for (auto ref : worst_chunk) {
902 [ + - ]: 49 : stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
903 : : }
904 [ + + ]: 92 : for (auto e : stage) {
905 [ + - ]: 49 : removeUnchecked(e, MemPoolRemovalReason::SIZELIMIT);
906 : : }
907 [ + + ]: 43 : if (pvNoSpendsRemaining) {
908 [ + + ]: 71 : for (const CTransaction& tx : txn) {
909 [ + + ]: 72 : for (const CTxIn& txin : tx.vin) {
910 [ + - + + ]: 36 : if (exists(txin.prevout.hash)) continue;
911 [ + - ]: 35 : pvNoSpendsRemaining->push_back(txin.prevout);
912 : : }
913 : : }
914 : : }
915 : 86 : }
916 : :
917 [ + + ]: 27040 : if (maxFeeRateRemoved > CFeeRate(0)) {
918 [ + - + - ]: 35 : LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
919 : : }
920 : 27040 : }
921 : :
922 : 125039 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
923 : : {
924 : 125039 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
925 : :
926 [ - + ]: 125039 : size_t ancestor_count = ancestors.size();
927 : 125039 : size_t ancestor_size = 0;
928 : 125039 : CAmount ancestor_fees = 0;
929 [ + + ]: 445323 : for (auto tx: ancestors) {
930 : 320284 : const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
931 [ + - ]: 320284 : ancestor_size += anc.GetTxSize();
932 : 320284 : ancestor_fees += anc.GetModifiedFee();
933 : : }
934 : 125039 : return {ancestor_count, ancestor_size, ancestor_fees};
935 : 125039 : }
936 : :
937 : 8954 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
938 : : {
939 : 8954 : auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
940 [ - + ]: 8954 : size_t descendant_count = descendants.size();
941 : 8954 : size_t descendant_size = 0;
942 : 8954 : CAmount descendant_fees = 0;
943 : :
944 [ + + ]: 164128 : for (auto tx: descendants) {
945 : 155174 : const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
946 [ + - ]: 155174 : descendant_size += desc.GetTxSize();
947 : 155174 : descendant_fees += desc.GetModifiedFee();
948 : : }
949 : 8954 : return {descendant_count, descendant_size, descendant_fees};
950 : 8954 : }
951 : :
952 : 582789 : void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
953 : 582789 : LOCK(cs);
954 : 582789 : auto it = mapTx.find(txid);
955 : 582789 : ancestors = cluster_count = 0;
956 [ + + ]: 582789 : if (it != mapTx.end()) {
957 [ + - + + ]: 47781 : auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
958 : 47781 : ancestors = ancestor_count;
959 [ + + ]: 47781 : if (ancestorsize) *ancestorsize = ancestor_size;
960 [ + + ]: 47781 : if (ancestorfees) *ancestorfees = ancestor_fees;
961 [ - + ]: 47781 : cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
962 : : }
963 : 582789 : }
964 : :
965 : 2415 : bool CTxMemPool::GetLoadTried() const
966 : : {
967 : 2415 : LOCK(cs);
968 [ + - ]: 2415 : return m_load_tried;
969 : 2415 : }
970 : :
971 : 1063 : void CTxMemPool::SetLoadTried(bool load_tried)
972 : : {
973 : 1063 : LOCK(cs);
974 [ + - ]: 1063 : m_load_tried = load_tried;
975 : 1063 : }
976 : :
977 : 3140 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
978 : : {
979 : 3140 : AssertLockHeld(cs);
980 : :
981 : 3140 : std::vector<CTxMemPool::txiter> ret;
982 : 3140 : std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
983 [ + + ]: 52860 : for (auto txid : txids) {
984 : 49720 : auto it = mapTx.find(txid);
985 [ + - ]: 49720 : if (it != mapTx.end()) {
986 : : // Note that TxGraph::GetCluster will return results in graph
987 : : // order, which is deterministic (as long as we are not modifying
988 : : // the graph).
989 : 49720 : auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
990 [ + - + + ]: 49720 : if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
991 [ + + ]: 119208 : for (auto tx : cluster) {
992 [ + - ]: 69670 : ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
993 : : }
994 : : }
995 : 49720 : }
996 : : }
997 [ - + + + ]: 3140 : if (ret.size() > 500) {
998 : 1 : return {};
999 : : }
1000 : 3139 : return ret;
1001 : 3140 : }
1002 : :
1003 : 1313 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1004 : : {
1005 : 1313 : LOCK(m_pool->cs);
1006 : :
1007 [ + - - + ]: 1313 : if (!CheckMemPoolPolicyLimits()) {
1008 [ # # # # ]: 0 : return util::Error{Untranslated("cluster size limit exceeded")};
1009 : : }
1010 : :
1011 : 2626 : return m_pool->m_txgraph->GetMainStagingDiagrams();
1012 : 1313 : }
1013 : :
1014 : 72906 : 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)
1015 : : {
1016 : 72906 : LOCK(m_pool->cs);
1017 [ + - ]: 72906 : Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1018 : 72906 : Assume(!m_dependencies_processed);
1019 : :
1020 : : // We need to process dependencies after adding a new transaction.
1021 : 72906 : m_dependencies_processed = false;
1022 : :
1023 : 72906 : CAmount delta{0};
1024 [ + - ]: 72906 : m_pool->ApplyDelta(tx->GetHash(), delta);
1025 : :
1026 [ + - + - ]: 72906 : FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp));
1027 [ + - ]: 72906 : auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1028 : 72906 : m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1029 [ + + ]: 72906 : if (delta) {
1030 : 41 : newit->UpdateModifiedFee(delta);
1031 : 41 : m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1032 : : }
1033 : :
1034 [ + - ]: 72906 : m_entry_vec.push_back(newit);
1035 : :
1036 [ + - ]: 72906 : return newit;
1037 : 72906 : }
1038 : :
1039 : 2158 : void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it)
1040 : : {
1041 : 2158 : LOCK(m_pool->cs);
1042 : 2158 : m_pool->m_txgraph->RemoveTransaction(*it);
1043 [ + - ]: 2158 : m_to_remove.insert(it);
1044 : 2158 : }
1045 : :
1046 : 51464 : void CTxMemPool::ChangeSet::Apply()
1047 : : {
1048 : 51464 : LOCK(m_pool->cs);
1049 [ + + ]: 51464 : if (!m_dependencies_processed) {
1050 [ + - ]: 3 : ProcessDependencies();
1051 : : }
1052 [ + - ]: 51464 : m_pool->Apply(this);
1053 : 51464 : m_to_add.clear();
1054 : 51464 : m_to_remove.clear();
1055 [ + - ]: 51464 : m_entry_vec.clear();
1056 [ + - ]: 51464 : m_ancestors.clear();
1057 : 51464 : }
1058 : :
1059 : 71966 : void CTxMemPool::ChangeSet::ProcessDependencies()
1060 : : {
1061 : 71966 : LOCK(m_pool->cs);
1062 : 71966 : Assume(!m_dependencies_processed); // should only call this once.
1063 [ + + ]: 144518 : for (const auto& entryptr : m_entry_vec) {
1064 [ + - + - : 316725 : for (const auto &txin : entryptr->GetSharedTx()->vin) {
+ + ]
1065 [ + - ]: 99069 : std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1066 [ + + ]: 99069 : if (!piter) {
1067 : 89530 : auto it = m_to_add.find(txin.prevout.hash);
1068 [ + + ]: 89530 : if (it != m_to_add.end()) {
1069 : 585 : piter = std::make_optional(it);
1070 : : }
1071 : : }
1072 [ + + ]: 99069 : if (piter) {
1073 : 10124 : m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1074 : : }
1075 : : }
1076 : : }
1077 : 71966 : m_dependencies_processed = true;
1078 [ + - ]: 71966 : return;
1079 : 71966 : }
1080 : :
1081 : 74560 : bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits()
1082 : : {
1083 : 74560 : LOCK(m_pool->cs);
1084 [ + + ]: 74560 : if (!m_dependencies_processed) {
1085 [ + - ]: 71963 : ProcessDependencies();
1086 : : }
1087 : :
1088 [ + - ]: 74560 : return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1089 : 74560 : }
1090 : :
1091 : 166144 : std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1092 : : {
1093 : 166144 : FeePerWeight zero{};
1094 : 166144 : std::vector<FeePerWeight> ret;
1095 : :
1096 [ + - ]: 166144 : ret.emplace_back(zero);
1097 : :
1098 : 166144 : StartBlockBuilding();
1099 : :
1100 : 166144 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1101 : :
1102 [ + - ]: 166144 : FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1103 [ + + ]: 10357787 : while (last_selection != FeePerWeight{}) {
1104 [ + - ]: 10191643 : last_selection += ret.back();
1105 [ + - ]: 10191643 : ret.emplace_back(last_selection);
1106 : 10191643 : IncludeBuilderChunk();
1107 [ + - ]: 10191643 : last_selection = GetBlockBuilderChunk(dummy);
1108 : : }
1109 : 166144 : StopBlockBuilding();
1110 : 166144 : return ret;
1111 : 166144 : }
|