Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #include <txmempool.h>
7 : :
8 : : #include <chain.h>
9 : : #include <coins.h>
10 : : #include <common/system.h>
11 : : #include <consensus/consensus.h>
12 : : #include <consensus/tx_verify.h>
13 : : #include <consensus/validation.h>
14 : : #include <policy/policy.h>
15 : : #include <policy/settings.h>
16 : : #include <random.h>
17 : : #include <tinyformat.h>
18 : : #include <util/check.h>
19 : : #include <util/feefrac.h>
20 : : #include <util/log.h>
21 : : #include <util/moneystr.h>
22 : : #include <util/overflow.h>
23 : : #include <util/result.h>
24 : : #include <util/time.h>
25 : : #include <util/trace.h>
26 : : #include <util/translation.h>
27 : : #include <validationinterface.h>
28 : :
29 : : #include <algorithm>
30 : : #include <cmath>
31 : : #include <numeric>
32 : : #include <optional>
33 : : #include <ranges>
34 : : #include <string_view>
35 : : #include <utility>
36 : :
37 : : TRACEPOINT_SEMAPHORE(mempool, added);
38 : : TRACEPOINT_SEMAPHORE(mempool, removed);
39 : :
40 : 0 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41 : : {
42 : 0 : AssertLockHeld(cs_main);
43 : : // If there are relative lock times then the maxInputBlock will be set
44 : : // If there are no relative lock times, the LockPoints don't depend on the chain
45 [ # # ]: 0 : if (lp.maxInputBlock) {
46 : : // Check whether active_chain is an extension of the block at which the LockPoints
47 : : // calculation was valid. If not LockPoints are no longer valid
48 [ # # ]: 0 : if (!active_chain.Contains(lp.maxInputBlock)) {
49 : 0 : return false;
50 : : }
51 : : }
52 : :
53 : : // LockPoints still valid
54 : : return true;
55 : : }
56 : :
57 : 377053 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58 : : {
59 : 377053 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60 [ + - ]: 377053 : const auto& hash = entry.GetTx().GetHash();
61 : 377053 : {
62 [ + - ]: 377053 : LOCK(cs);
63 : 377053 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64 [ + + + + ]: 748684 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65 [ + - ]: 371631 : ret.emplace_back(*(iter->second));
66 : : }
67 : 0 : }
68 : 377053 : std::ranges::sort(ret, CompareIteratorByHash{});
69 [ + + + + ]: 571773 : auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70 : 377053 : ret.erase(removed.begin(), removed.end());
71 : 377053 : return ret;
72 : 0 : }
73 : :
74 : 1837929 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75 : : {
76 : 1837929 : LOCK(cs);
77 : 1837929 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78 : 1837929 : std::set<Txid> inputs;
79 [ + + ]: 5548333 : for (const auto& txin : entry.GetTx().vin) {
80 [ + - ]: 3710404 : inputs.insert(txin.prevout.hash);
81 : : }
82 [ + + ]: 5164720 : for (const auto& hash : inputs) {
83 [ + - ]: 3326791 : std::optional<txiter> piter = GetIter(hash);
84 [ + + ]: 3326791 : if (piter) {
85 [ + - ]: 1502716 : ret.emplace_back(**piter);
86 : : }
87 : : }
88 : 1837929 : return ret;
89 [ + - ]: 3675858 : }
90 : :
91 : 11876 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
92 : : {
93 : 11876 : 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 [ + + ]: 47881 : for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
98 : : // calculate children from mapNextTx
99 : 36005 : txiter it = mapTx.find(hash);
100 [ - + ]: 36005 : if (it == mapTx.end()) {
101 : 0 : continue;
102 : : }
103 : 36005 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104 : 36005 : {
105 [ + + + + ]: 46099 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
106 [ - + ]: 10094 : txiter childIter = iter->second;
107 [ - + ]: 10094 : 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 : 10094 : m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
111 : : }
112 : : }
113 : : }
114 : :
115 : 11876 : auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
116 [ - + ]: 11876 : 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 : 11876 : }
121 : :
122 : 0 : bool CTxMemPool::HasDescendants(const Txid& txid) const
123 : : {
124 : 0 : LOCK(cs);
125 [ # # ]: 0 : auto entry = GetEntry(txid);
126 [ # # ]: 0 : if (!entry) return false;
127 [ # # ]: 0 : return m_txgraph->GetDescendants(*entry, TxGraph::Level::MAIN).size() > 1;
128 : 0 : }
129 : :
130 : 56527 : CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const
131 : : {
132 : 56527 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
133 [ - + ]: 56527 : setEntries ret;
134 [ - + + + ]: 56527 : if (ancestors.size() > 0) {
135 [ + + ]: 508 : for (auto ancestor : ancestors) {
136 [ + + ]: 284 : if (ancestor != &entry) {
137 [ + - ]: 60 : ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
138 : : }
139 : : }
140 : : return ret;
141 : : }
142 : :
143 : : // If we didn't get anything back, the transaction is not in the graph.
144 : : // Find each parent and call GetAncestors on each.
145 : 56303 : setEntries staged_parents;
146 : 56303 : const CTransaction &tx = entry.GetTx();
147 : :
148 : : // Get parents of this transaction that are in the mempool
149 [ - + + + ]: 261273 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
150 [ + - ]: 204970 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151 [ + + ]: 204970 : if (piter) {
152 [ + - ]: 79693 : staged_parents.insert(*piter);
153 : : }
154 : : }
155 : :
156 [ + + ]: 124052 : for (const auto& parent : staged_parents) {
157 : 67749 : auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN);
158 [ + + ]: 194837 : for (auto ancestor : parent_ancestors) {
159 [ + - ]: 127088 : ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
160 : : }
161 : 67749 : }
162 : :
163 : 56303 : return ret;
164 : 112830 : }
165 : :
166 : 30489 : static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
167 : : {
168 [ + - ]: 30489 : opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169 : 30489 : int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170 [ + - + + : 30489 : if (opts.max_size_bytes < 0 || (opts.max_size_bytes > 0 && opts.max_size_bytes < cluster_limit_bytes)) {
+ + ]
171 : 1274 : error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(cluster_limit_bytes / 1'000'000.0));
172 : : }
173 : 30489 : return std::move(opts);
174 : : }
175 : :
176 : 30489 : CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
177 [ + - + - ]: 30489 : : m_opts{Flatten(std::move(opts), error)}
178 : : {
179 : 60978 : m_txgraph = MakeTxGraph(
180 : 30489 : /*max_cluster_count=*/m_opts.limits.cluster_count,
181 : 30489 : /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,
182 : : /*acceptable_cost=*/ACCEPTABLE_COST,
183 : 30489 : /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184 : 48930504 : const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185 : 48930504 : const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186 : 48930504 : return txid_a <=> txid_b;
187 : 30489 : });
188 : 30489 : }
189 : :
190 : 7 : bool CTxMemPool::isSpent(const COutPoint& outpoint) const
191 : : {
192 : 7 : LOCK(cs);
193 [ + - ]: 7 : return mapNextTx.count(outpoint);
194 : : }
195 : :
196 : 0 : unsigned int CTxMemPool::GetTransactionsUpdated() const
197 : : {
198 : 0 : return nTransactionsUpdated;
199 : : }
200 : :
201 : 87877 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
202 : : {
203 : 87877 : nTransactionsUpdated += n;
204 : 87877 : }
205 : :
206 : 1384938 : void CTxMemPool::Apply(ChangeSet* changeset)
207 : : {
208 : 1384938 : AssertLockHeld(cs);
209 : 1384938 : m_txgraph->CommitStaging();
210 : :
211 : 1384938 : RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED);
212 : :
213 [ - + + + ]: 2774299 : for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214 : 1389361 : auto tx_entry = changeset->m_entry_vec[i];
215 : : // First splice this entry into mapTx.
216 : 1389361 : auto node_handle = changeset->m_to_add.extract(tx_entry);
217 [ + - ]: 1389361 : auto result = mapTx.insert(std::move(node_handle));
218 : :
219 [ - + ]: 1389361 : Assume(result.inserted);
220 : 1389361 : txiter it = result.position;
221 : :
222 [ + - ]: 1389361 : addNewTransaction(it);
223 [ - + ]: 1389361 : }
224 [ - + ]: 1384938 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
225 [ # # ]: 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after addition(s).");
226 : : }
227 : 1384938 : }
228 : :
229 : 1389361 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit)
230 : : {
231 : 1389361 : 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 : 1389361 : cachedInnerUsage += entry.DynamicMemoryUsage();
237 : :
238 : 1389361 : const CTransaction& tx = newit->GetTx();
239 [ - + + + ]: 3644397 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
240 : 2255036 : 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 : 1389361 : nTransactionsUpdated++;
250 : 1389361 : totalTxSize += entry.GetTxSize();
251 : 1389361 : m_total_fee += entry.GetFee();
252 : :
253 : 1389361 : txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
254 [ - + ]: 1389361 : newit->idx_randomized = txns_randomized.size() - 1;
255 : :
256 : : TRACEPOINT(mempool, added,
257 : : entry.GetTx().GetHash().data(),
258 : : entry.GetTxSize(),
259 : : entry.GetFee()
260 : 1389361 : );
261 : 1389361 : }
262 : :
263 : 164528 : 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 [ + + ]: 164528 : uint64_t mempool_sequence = GetAndIncrementSequence();
268 : :
269 [ + + + + ]: 164528 : 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 [ + - + - ]: 367605 : 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 : 164528 : );
283 : :
284 [ + + ]: 457663 : for (const CTxIn& txin : it->GetTx().vin)
285 : 293135 : mapNextTx.erase(txin.prevout);
286 : :
287 : 164528 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
288 : :
289 [ - + + + ]: 164528 : if (txns_randomized.size() > 1) {
290 : : // Remove entry from txns_randomized by replacing it with the back and deleting the back.
291 [ - + ]: 147502 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
292 [ - + ]: 147502 : txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
293 [ - + ]: 147502 : txns_randomized.pop_back();
294 [ - + - + : 147502 : if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
+ + ]
295 : 16316 : txns_randomized.shrink_to_fit();
296 : : }
297 : : } else {
298 [ + - ]: 17026 : txns_randomized.clear();
299 : : }
300 : :
301 : 164528 : totalTxSize -= it->GetTxSize();
302 : 164528 : m_total_fee -= it->GetFee();
303 : 164528 : cachedInnerUsage -= it->DynamicMemoryUsage();
304 : 164528 : mapTx.erase(it);
305 : 164528 : nTransactionsUpdated++;
306 : 164528 : }
307 : :
308 : : // Calculates descendants of given entry and adds to setDescendants.
309 : 1457254 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
310 : : {
311 : 1457254 : (void)CalculateDescendants(*entryit, setDescendants);
312 : 1457254 : return;
313 : : }
314 : :
315 : 1471938 : CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const
316 : : {
317 [ + + ]: 5677179 : for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
318 [ + - ]: 4205241 : setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
319 : : }
320 : 1471938 : return mapTx.iterator_to(entry);
321 : : }
322 : :
323 : 4320 : void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason)
324 : : {
325 : 4320 : AssertLockHeld(cs);
326 [ - + ]: 4320 : Assume(!m_have_changeset);
327 : 4320 : auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
328 [ + + ]: 10261 : for (auto tx: descendants) {
329 [ + - ]: 5941 : removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
330 : : }
331 : 4320 : }
332 : :
333 : 16196 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
334 : : {
335 : : // Remove transaction from memory pool
336 : 16196 : AssertLockHeld(cs);
337 [ - + ]: 16196 : Assume(!m_have_changeset);
338 : 16196 : txiter origit = mapTx.find(origTx.GetHash());
339 [ + + ]: 16196 : if (origit != mapTx.end()) {
340 : 4320 : 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 : 11876 : auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
347 : 11876 : std::vector<const TxGraph::Ref*> to_remove;
348 [ + + - + ]: 11876 : while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
349 [ # # ]: 0 : to_remove.emplace_back(&*(iter->second));
350 : 0 : ++iter;
351 : : }
352 [ - + ]: 11876 : auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
353 [ - + ]: 11876 : for (auto ref : all_removes) {
354 : 0 : auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
355 [ # # ]: 0 : removeUnchecked(tx, reason);
356 : : }
357 : 11876 : }
358 : 16196 : }
359 : :
360 : 0 : void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
361 : : {
362 : : // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
363 : 0 : AssertLockHeld(cs);
364 : 0 : AssertLockHeld(::cs_main);
365 [ # # ]: 0 : Assume(!m_have_changeset);
366 : :
367 : 0 : std::vector<const TxGraph::Ref*> to_remove;
368 [ # # ]: 0 : for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
369 [ # # # # ]: 0 : if (check_final_and_mature(it)) {
370 [ # # ]: 0 : to_remove.emplace_back(&*it);
371 : : }
372 : : }
373 : :
374 [ # # ]: 0 : auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
375 : :
376 [ # # ]: 0 : for (auto ref : all_to_remove) {
377 : 0 : auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
378 [ # # ]: 0 : removeUnchecked(it, MemPoolRemovalReason::REORG);
379 : : }
380 [ # # ]: 0 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
381 [ # # # # ]: 0 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
382 : : }
383 [ # # ]: 0 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
384 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after reorg.");
# # ]
385 : : }
386 : 0 : }
387 : :
388 : 42204 : void CTxMemPool::removeConflicts(const CTransaction &tx)
389 : : {
390 : : // Remove transactions which depend on inputs of tx, recursively
391 : 42204 : AssertLockHeld(cs);
392 [ + + ]: 98001 : for (const CTxIn &txin : tx.vin) {
393 : 55797 : auto it = mapNextTx.find(txin.prevout);
394 [ - + ]: 55797 : if (it != mapNextTx.end()) {
395 [ # # ]: 0 : const CTransaction &txConflict = it->second->GetTx();
396 [ # # ]: 0 : if (Assume(txConflict.GetHash() != tx.GetHash()))
397 : : {
398 : 0 : ClearPrioritisation(txConflict.GetHash());
399 : 0 : removeRecursive(it->second, MemPoolRemovalReason::CONFLICT);
400 : : }
401 : : }
402 : : }
403 : 42204 : }
404 : :
405 : 99753 : 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 : 99753 : AssertLockHeld(cs);
409 [ - + ]: 99753 : Assume(!m_have_changeset);
410 : 99753 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
411 [ + + + - : 99753 : if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
+ + ]
412 [ - + + - ]: 6199 : txs_removed_for_block.reserve(vtx.size());
413 [ + + ]: 48403 : for (const auto& tx : vtx) {
414 : 42204 : txiter it = mapTx.find(tx->GetHash());
415 [ + + ]: 42204 : if (it != mapTx.end()) {
416 [ + - ]: 36005 : txs_removed_for_block.emplace_back(*it);
417 [ + - ]: 36005 : removeUnchecked(it, MemPoolRemovalReason::BLOCK);
418 : : }
419 [ + - ]: 42204 : removeConflicts(*tx);
420 [ + - ]: 42204 : ClearPrioritisation(tx->GetHash());
421 : : }
422 : : }
423 [ + + ]: 99753 : if (m_opts.signals) {
424 [ + - ]: 98987 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
425 : : }
426 [ + - ]: 99753 : lastRollingFeeUpdate = GetTime();
427 : 99753 : blockSinceLastRollingFeeBump = true;
428 [ - + ]: 99753 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
429 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after block.");
# # ]
430 : : }
431 : 99753 : }
432 : :
433 : 125056 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
434 : : {
435 [ + - ]: 125056 : if (m_opts.check_ratio == 0) return;
436 : :
437 [ + - ]: 125056 : if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
438 : :
439 : 125056 : AssertLockHeld(::cs_main);
440 : 125056 : LOCK(cs);
441 [ + - + + : 125056 : LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - ]
442 : :
443 : 125056 : uint64_t checkTotal = 0;
444 : 125056 : CAmount check_total_fee{0};
445 : 125056 : CAmount check_total_modified_fee{0};
446 : 125056 : int64_t check_total_adjusted_weight{0};
447 : 125056 : uint64_t innerUsage = 0;
448 : :
449 [ - + ]: 125056 : assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
450 [ + - ]: 125056 : m_txgraph->SanityCheck();
451 : :
452 [ + - ]: 125056 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
453 : :
454 [ + - ]: 125056 : const auto score_with_topo{GetSortedScoreWithTopology()};
455 : :
456 : : // Number of chunks is bounded by number of transactions.
457 [ + - ]: 125056 : const auto diagram{GetFeerateDiagram()};
458 [ - + - + : 125056 : assert(diagram.size() <= score_with_topo.size() + 1);
- + ]
459 [ - + ]: 125056 : assert(diagram.size() >= 1);
460 : :
461 : 125056 : std::optional<Wtxid> last_wtxid = std::nullopt;
462 : 125056 : auto diagram_iter = diagram.cbegin();
463 : :
464 [ + + ]: 365867 : 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 [ - + ]: 240811 : assert(diagram_iter->size >= check_total_adjusted_weight);
472 [ + + ]: 240811 : if (diagram_iter->fee == check_total_modified_fee &&
473 [ + + ]: 190438 : diagram_iter->size == check_total_adjusted_weight) {
474 : 190323 : ++diagram_iter;
475 : : }
476 [ + - ]: 240811 : checkTotal += it->GetTxSize();
477 [ + - ]: 240811 : check_total_adjusted_weight += it->GetAdjustedWeight();
478 [ + + ]: 240811 : check_total_fee += it->GetFee();
479 [ + + ]: 240811 : check_total_modified_fee += it->GetModifiedFee();
480 [ + + ]: 240811 : innerUsage += it->DynamicMemoryUsage();
481 [ + + ]: 240811 : const CTransaction& tx = it->GetTx();
482 : :
483 : : // CompareMiningScoreWithTopology should agree with GetSortedScoreWithTopology()
484 [ + + ]: 240811 : if (last_wtxid) {
485 [ + - - + ]: 229682 : assert(CompareMiningScoreWithTopology(*last_wtxid, tx.GetWitnessHash()));
486 : : }
487 [ + + ]: 240811 : last_wtxid = tx.GetWitnessHash();
488 : :
489 : 240811 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
490 : 240811 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
491 [ + + ]: 619358 : for (const CTxIn &txin : tx.vin) {
492 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
493 : 378547 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
494 [ + + ]: 378547 : if (it2 != mapTx.end()) {
495 [ - + ]: 147038 : const CTransaction& tx2 = it2->GetTx();
496 [ - + + - : 147038 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
- + ]
497 [ + - ]: 147038 : 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 [ + - - + ]: 378547 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
504 : : // Check whether its inputs are marked in mapNextTx.
505 : 378547 : auto it3 = mapNextTx.find(txin.prevout);
506 [ - + ]: 378547 : assert(it3 != mapNextTx.end());
507 [ - + ]: 378547 : assert(it3->first == &txin.prevout);
508 [ - + ]: 378547 : assert(&it3->second->GetTx() == &tx);
509 : : }
510 : 478221 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
511 [ + - ]: 237410 : return a.GetTx().GetHash() == b.GetTx().GetHash();
512 : : };
513 [ + - + + ]: 359516 : for (auto &txentry : GetParents(*it)) {
514 [ + - ]: 118705 : setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
515 : 0 : }
516 [ - + ]: 240811 : assert(setParentCheck.size() == setParentsStored.size());
517 [ - + ]: 240811 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
518 : :
519 : : // Check children against mapNextTx
520 : 240811 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
521 : 240811 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
522 : 240811 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
523 [ + + + + ]: 387849 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
524 [ - + ]: 147038 : txiter childit = iter->second;
525 [ - + ]: 147038 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
526 [ + - ]: 147038 : setChildrenCheck.insert(*childit);
527 : : }
528 [ + - + + ]: 359516 : for (auto &txentry : GetChildren(*it)) {
529 [ + - ]: 118705 : setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
530 : 0 : }
531 [ - + ]: 240811 : assert(setChildrenCheck.size() == setChildrenStored.size());
532 [ - + ]: 240811 : assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
533 : :
534 [ - + ]: 240811 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
535 : 240811 : CAmount txfee = 0;
536 [ - + ]: 240811 : assert(!tx.IsCoinBase());
537 [ + - - + ]: 240811 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
538 [ + - + + ]: 619358 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
539 [ + - ]: 240811 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
540 : 240811 : }
541 [ + + ]: 503603 : for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
542 [ - + ]: 378547 : indexed_transaction_set::const_iterator it2 = it->second;
543 [ - + ]: 378547 : assert(it2 != mapTx.end());
544 : : }
545 : :
546 [ - + ]: 125056 : ++diagram_iter;
547 [ - + ]: 125056 : assert(diagram_iter == diagram.cend());
548 : :
549 [ - + ]: 125056 : assert(totalTxSize == checkTotal);
550 [ - + ]: 125056 : assert(m_total_fee == check_total_fee);
551 [ - + ]: 125056 : assert(diagram.back().fee == check_total_modified_fee);
552 [ - + ]: 125056 : assert(diagram.back().size == check_total_adjusted_weight);
553 [ - + ]: 125056 : assert(innerUsage == cachedInnerUsage);
554 [ + - ]: 250112 : }
555 : :
556 : 229682 : 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 : 229682 : LOCK(cs);
564 [ + - ]: 229682 : auto j{GetIter(hashb)};
565 [ + - ]: 229682 : if (!j.has_value()) return false;
566 [ + - ]: 229682 : auto i{GetIter(hasha)};
567 [ + - ]: 229682 : if (!i.has_value()) return true;
568 : :
569 : 229682 : return m_txgraph->CompareMainOrder(*i.value(), *j.value()) < 0;
570 : 229682 : }
571 : :
572 : 1439505 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
573 : : {
574 : 1439505 : std::vector<indexed_transaction_set::const_iterator> iters;
575 : 1439505 : AssertLockHeld(cs);
576 : :
577 [ + - ]: 1439505 : iters.reserve(mapTx.size());
578 : :
579 [ + + + + ]: 71412117 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
580 [ + - ]: 34986306 : iters.push_back(mi);
581 : : }
582 : 1439505 : std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
583 : 230671496 : return m_txgraph->CompareMainOrder(*a, *b) < 0;
584 : : });
585 : 1439505 : return iters;
586 : 0 : }
587 : :
588 : 56 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
589 : : {
590 : 56 : AssertLockHeld(cs);
591 : :
592 : 56 : std::vector<CTxMemPoolEntryRef> ret;
593 [ + - ]: 56 : ret.reserve(mapTx.size());
594 [ + - - + ]: 56 : for (const auto& it : GetSortedScoreWithTopology()) {
595 [ # # ]: 0 : ret.emplace_back(*it);
596 : : }
597 : 56 : return ret;
598 : 0 : }
599 : :
600 : 1314393 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
601 : : {
602 : 1314393 : LOCK(cs);
603 [ + - ]: 1314393 : auto iters = GetSortedScoreWithTopology();
604 : :
605 : 1314393 : std::vector<TxMempoolInfo> ret;
606 [ + - ]: 1314393 : ret.reserve(mapTx.size());
607 [ + + ]: 36059888 : for (auto it : iters) {
608 [ + - - + ]: 69490990 : ret.push_back(GetInfo(it));
609 : : }
610 : :
611 : 1314393 : return ret;
612 [ + - ]: 2628786 : }
613 : :
614 : 34655474 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
615 : : {
616 : 34655474 : AssertLockHeld(cs);
617 : 34655474 : const auto i = mapTx.find(txid);
618 [ + + ]: 34655474 : return i == mapTx.end() ? nullptr : &(*i);
619 : : }
620 : :
621 : 12712590 : CTransactionRef CTxMemPool::get(const Txid& hash) const
622 : : {
623 : 12712590 : LOCK(cs);
624 : 12712590 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
625 [ + + ]: 12712590 : if (i == mapTx.end())
626 : 8737322 : return nullptr;
627 [ + - + - ]: 16687858 : return i->GetSharedTx();
628 : 12712590 : }
629 : :
630 : 1511949 : void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
631 : : {
632 : 1511949 : {
633 : 1511949 : LOCK(cs);
634 [ + - ]: 1511949 : CAmount &delta = mapDeltas[hash];
635 : 1511949 : delta = SaturatingAdd(delta, nFeeDelta);
636 : 1511949 : txiter it = mapTx.find(hash);
637 [ + + ]: 1511949 : if (it != mapTx.end()) {
638 : : // PrioritiseTransaction calls stack on previous ones. Set the new
639 : : // transaction fee to be current modified fee + feedelta.
640 : 388573 : it->UpdateModifiedFee(nFeeDelta);
641 : 388573 : m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
642 : 388573 : ++nTransactionsUpdated;
643 : : }
644 [ + + ]: 1511949 : if (delta == 0) {
645 : 11625 : mapDeltas.erase(hash);
646 [ + + + - : 24845 : LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
+ - ]
647 : : } else {
648 [ + - + - : 3387626 : LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
+ + + - +
- ]
649 : : hash.ToString(),
650 : : it == mapTx.end() ? "not " : "",
651 : : FormatMoney(nFeeDelta),
652 : : FormatMoney(delta));
653 : : }
654 : 1511949 : }
655 : 1511949 : }
656 : :
657 : 3678135 : void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
658 : : {
659 : 3678135 : AssertLockHeld(cs);
660 : 3678135 : std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
661 [ + + ]: 3678135 : if (pos == mapDeltas.end())
662 : : return;
663 : 128180 : const CAmount &delta = pos->second;
664 : 128180 : nFeeDelta += delta;
665 : : }
666 : :
667 : 42204 : void CTxMemPool::ClearPrioritisation(const Txid& hash)
668 : : {
669 : 42204 : AssertLockHeld(cs);
670 : 42204 : mapDeltas.erase(hash);
671 : 42204 : }
672 : :
673 : 49 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
674 : : {
675 : 49 : AssertLockNotHeld(cs);
676 : 49 : LOCK(cs);
677 : 49 : std::vector<delta_info> result;
678 [ + - ]: 49 : result.reserve(mapDeltas.size());
679 [ + + ]: 773 : for (const auto& [txid, delta] : mapDeltas) {
680 : 724 : const auto iter{mapTx.find(txid)};
681 [ - + ]: 724 : const bool in_mempool{iter != mapTx.end()};
682 : 724 : std::optional<CAmount> modified_fee;
683 [ - + ]: 724 : if (in_mempool) modified_fee = iter->GetModifiedFee();
684 [ + - ]: 724 : result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
685 : : }
686 [ + - ]: 49 : return result;
687 : 49 : }
688 : :
689 : 10639534 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
690 : : {
691 : 10639534 : const auto it = mapNextTx.find(prevout);
692 [ + + ]: 10639534 : return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
693 : : }
694 : :
695 : 13968191 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
696 : : {
697 : 13968191 : AssertLockHeld(cs);
698 : 13968191 : auto it = mapTx.find(txid);
699 [ + + ]: 13968191 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
700 : : }
701 : :
702 : 465306 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
703 : : {
704 : 465306 : AssertLockHeld(cs);
705 [ + + ]: 465306 : auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
706 [ + + ]: 465306 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
707 : : }
708 : :
709 : 1051397 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
710 : : {
711 : 1051397 : CTxMemPool::setEntries ret;
712 [ + + ]: 1789895 : for (const auto& h : hashes) {
713 [ + - ]: 738498 : const auto mi = GetIter(h);
714 [ + - + - ]: 738498 : if (mi) ret.insert(*mi);
715 : : }
716 : 1051397 : return ret;
717 : 0 : }
718 : :
719 : 0 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
720 : : {
721 : 0 : AssertLockHeld(cs);
722 : 0 : std::vector<txiter> ret;
723 [ # # # # ]: 0 : ret.reserve(txids.size());
724 [ # # ]: 0 : for (const auto& txid : txids) {
725 [ # # ]: 0 : const auto it{GetIter(txid)};
726 [ # # ]: 0 : if (!it) return {};
727 [ # # ]: 0 : ret.push_back(*it);
728 : : }
729 : 0 : return ret;
730 : 0 : }
731 : :
732 : 345842 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
733 : : {
734 [ - + + + ]: 655090 : for (unsigned int i = 0; i < tx.vin.size(); i++)
735 [ + + ]: 445855 : if (exists(tx.vin[i].prevout.hash))
736 : : return false;
737 : : return true;
738 : : }
739 : :
740 [ + - + - ]: 2758571 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
741 : :
742 : 11897258 : std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
743 : : {
744 : : // Check to see if the inputs are made available by another tx in the package.
745 : : // These Coins would not be available in the underlying CoinsView.
746 [ + + ]: 11897258 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
747 : 277160 : return it->second;
748 : : }
749 : :
750 : : // If an entry in the mempool exists, always return that one, as it's guaranteed to never
751 : : // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
752 : : // transactions. First checking the underlying cache risks returning a pruned entry instead.
753 : 11620098 : CTransactionRef ptx = mempool.get(outpoint.hash);
754 [ + + ]: 11620098 : if (ptx) {
755 [ - + + + ]: 3560170 : if (outpoint.n < ptx->vout.size()) {
756 : 3553850 : Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
757 [ + - ]: 3553850 : m_non_base_coins.emplace(outpoint);
758 : 3553850 : return coin;
759 : 3553850 : }
760 : 6320 : return std::nullopt;
761 : : }
762 [ + - ]: 8059928 : return base->GetCoin(outpoint);
763 : 11620098 : }
764 : :
765 : 261274 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
766 : : {
767 [ - + + + ]: 1355792 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
768 [ + - ]: 1094518 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
769 : 1094518 : m_non_base_coins.emplace(tx->GetHash(), n);
770 : : }
771 : 261274 : }
772 : 3841767 : void CCoinsViewMemPool::Reset()
773 : : {
774 : 3841767 : m_temp_added.clear();
775 : 3841767 : m_non_base_coins.clear();
776 : 3841767 : }
777 : :
778 : 3661190 : size_t CTxMemPool::DynamicMemoryUsage() const {
779 : 3661190 : LOCK(cs);
780 : : // 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.
781 [ - + + - ]: 7322380 : return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
782 : 3661190 : }
783 : :
784 : 164528 : void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
785 : 164528 : LOCK(cs);
786 : :
787 [ - + ]: 164528 : if (m_unbroadcast_txids.erase(txid))
788 : : {
789 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
# # # # #
# ]
790 : : }
791 : 164528 : }
792 : :
793 : 1978912 : void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) {
794 : 1978912 : AssertLockHeld(cs);
795 [ + + ]: 2081873 : for (txiter it : stage) {
796 : 102961 : removeUnchecked(it, reason);
797 : : }
798 : 1978912 : }
799 : :
800 : 0 : bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx)
801 : : {
802 : 0 : LOCK(cs);
803 : : // Use ChangeSet interface to check whether the cluster count
804 : : // limits would be violated. Note that the changeset will be destroyed
805 : : // when it goes out of scope.
806 [ # # ]: 0 : auto changeset = GetChangeSet();
807 [ # # ]: 0 : (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
808 [ # # ]: 0 : return changeset->CheckMemPoolPolicyLimits();
809 [ # # ]: 0 : }
810 : :
811 : 593974 : int CTxMemPool::Expire(std::chrono::seconds time)
812 : : {
813 : 593974 : AssertLockHeld(cs);
814 [ - + ]: 593974 : Assume(!m_have_changeset);
815 : 593974 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
816 : 593974 : setEntries toremove;
817 [ + + + + ]: 642094 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
818 [ + - ]: 48120 : toremove.insert(mapTx.project<0>(it));
819 : 48120 : it++;
820 : : }
821 : 593974 : setEntries stage;
822 [ + + ]: 642094 : for (txiter removeit : toremove) {
823 [ + - ]: 48120 : CalculateDescendants(removeit, stage);
824 : : }
825 [ + - ]: 593974 : RemoveStaged(stage, MemPoolRemovalReason::EXPIRY);
826 : 593974 : return stage.size();
827 : 593974 : }
828 : :
829 : 1946774 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
830 : 1946774 : LOCK(cs);
831 [ + + + + ]: 1946774 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
832 : 1914577 : return CFeeRate(llround(rollingMinimumFeeRate));
833 : :
834 [ + - ]: 32197 : int64_t time = GetTime();
835 [ + + ]: 32197 : if (time > lastRollingFeeUpdate + 10) {
836 : 1778 : double halflife = ROLLING_FEE_HALFLIFE;
837 [ + - + - ]: 1778 : if (DynamicMemoryUsage() < sizelimit / 4)
838 : : halflife /= 4;
839 [ + - - + ]: 1778 : else if (DynamicMemoryUsage() < sizelimit / 2)
840 : 0 : halflife /= 2;
841 : :
842 : 1778 : rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
843 : 1778 : lastRollingFeeUpdate = time;
844 : :
845 [ + + ]: 1778 : if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
846 : 1252 : rollingMinimumFeeRate = 0;
847 : 1252 : return CFeeRate(0);
848 : : }
849 : : }
850 : 30945 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
851 : 1946774 : }
852 : :
853 : 15813 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
854 : 15813 : AssertLockHeld(cs);
855 [ + + ]: 15813 : if (rate.GetFeePerK() > rollingMinimumFeeRate) {
856 : 10544 : rollingMinimumFeeRate = rate.GetFeePerK();
857 : 10544 : blockSinceLastRollingFeeBump = false;
858 : : }
859 : 15813 : }
860 : :
861 : 592699 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
862 : 592699 : AssertLockHeld(cs);
863 [ - + ]: 592699 : Assume(!m_have_changeset);
864 : :
865 : 592699 : unsigned nTxnRemoved = 0;
866 : 592699 : CFeeRate maxFeeRateRemoved(0);
867 : :
868 [ + + + + ]: 608512 : while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
869 [ + - ]: 15813 : const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
870 [ + - ]: 15813 : FeePerVSize feerate = ToFeePerVSize(feeperweight);
871 [ + - ]: 15813 : CFeeRate removed{feerate.fee, feerate.size};
872 : :
873 : : // We set the new mempool min fee to the feerate of the removed set, plus the
874 : : // "minimum reasonable fee rate" (ie some value under which we consider txn
875 : : // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
876 : : // equal to txn which were removed with no block in between.
877 : 15813 : removed += m_opts.incremental_relay_feerate;
878 [ + - ]: 15813 : trackPackageRemoved(removed);
879 : 15813 : maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
880 : :
881 [ - + ]: 15813 : nTxnRemoved += worst_chunk.size();
882 : :
883 : 15813 : std::vector<CTransaction> txn;
884 [ + + ]: 15813 : if (pvNoSpendsRemaining) {
885 [ + - ]: 8687 : txn.reserve(worst_chunk.size());
886 [ + + ]: 20575 : for (auto ref : worst_chunk) {
887 [ + - ]: 11888 : txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
888 : : }
889 : : }
890 : :
891 : 15813 : setEntries stage;
892 [ + + ]: 35434 : for (auto ref : worst_chunk) {
893 [ + - ]: 19621 : stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
894 : : }
895 [ + + ]: 35434 : for (auto e : stage) {
896 [ + - ]: 19621 : removeUnchecked(e, MemPoolRemovalReason::SIZELIMIT);
897 : : }
898 [ + + ]: 15813 : if (pvNoSpendsRemaining) {
899 [ + + ]: 20575 : for (const CTransaction& tx : txn) {
900 [ + + ]: 55964 : for (const CTxIn& txin : tx.vin) {
901 [ + - + + ]: 44076 : if (exists(txin.prevout.hash)) continue;
902 [ + - ]: 43277 : pvNoSpendsRemaining->push_back(txin.prevout);
903 : : }
904 : : }
905 : : }
906 : 31626 : }
907 : :
908 [ + + ]: 592699 : if (maxFeeRateRemoved > CFeeRate(0)) {
909 [ - + - - ]: 8541 : LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
910 : : }
911 : 592699 : }
912 : :
913 : 2376504 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
914 : : {
915 : 2376504 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
916 : :
917 [ - + ]: 2376504 : size_t ancestor_count = ancestors.size();
918 : 2376504 : size_t ancestor_size = 0;
919 : 2376504 : CAmount ancestor_fees = 0;
920 [ + + ]: 6228420 : for (auto tx: ancestors) {
921 : 3851916 : const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
922 [ + - ]: 3851916 : ancestor_size += anc.GetTxSize();
923 : 3851916 : ancestor_fees += anc.GetModifiedFee();
924 : : }
925 : 2376504 : return {ancestor_count, ancestor_size, ancestor_fees};
926 : 2376504 : }
927 : :
928 : 2256976 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
929 : : {
930 : 2256976 : auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
931 [ - + ]: 2256976 : size_t descendant_count = descendants.size();
932 : 2256976 : size_t descendant_size = 0;
933 : 2256976 : CAmount descendant_fees = 0;
934 : :
935 [ + + ]: 5179108 : for (auto tx: descendants) {
936 : 2922132 : const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
937 [ + - ]: 2922132 : descendant_size += desc.GetTxSize();
938 : 2922132 : descendant_fees += desc.GetModifiedFee();
939 : : }
940 : 2256976 : return {descendant_count, descendant_size, descendant_fees};
941 : 2256976 : }
942 : :
943 : 0 : void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
944 : 0 : LOCK(cs);
945 : 0 : auto it = mapTx.find(txid);
946 : 0 : ancestors = cluster_count = 0;
947 [ # # ]: 0 : if (it != mapTx.end()) {
948 [ # # # # ]: 0 : auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
949 : 0 : ancestors = ancestor_count;
950 [ # # ]: 0 : if (ancestorsize) *ancestorsize = ancestor_size;
951 [ # # ]: 0 : if (ancestorfees) *ancestorfees = ancestor_fees;
952 [ # # ]: 0 : cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
953 : : }
954 : 0 : }
955 : :
956 : 1 : bool CTxMemPool::GetLoadTried() const
957 : : {
958 : 1 : LOCK(cs);
959 [ + - ]: 1 : return m_load_tried;
960 : 1 : }
961 : :
962 : 2214 : void CTxMemPool::SetLoadTried(bool load_tried)
963 : : {
964 : 2214 : LOCK(cs);
965 [ + - ]: 2214 : m_load_tried = load_tried;
966 : 2214 : }
967 : :
968 : 3826 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
969 : : {
970 : 3826 : AssertLockHeld(cs);
971 : :
972 : 3826 : std::vector<CTxMemPool::txiter> ret;
973 : 3826 : std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
974 [ + + ]: 110118 : for (auto txid : txids) {
975 : 106292 : auto it = mapTx.find(txid);
976 [ + - ]: 106292 : if (it != mapTx.end()) {
977 : : // Note that TxGraph::GetCluster will return results in graph
978 : : // order, which is deterministic (as long as we are not modifying
979 : : // the graph).
980 : 106292 : auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
981 [ + - + + ]: 106292 : if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
982 [ + + ]: 180176 : for (auto tx : cluster) {
983 [ + - ]: 164946 : ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
984 : : }
985 : : }
986 : 106292 : }
987 : : }
988 [ - + - + ]: 3826 : if (ret.size() > 500) {
989 : 0 : return {};
990 : : }
991 : 3826 : return ret;
992 : 3826 : }
993 : :
994 : 102432 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
995 : : {
996 : 102432 : LOCK(m_pool->cs);
997 : :
998 [ + - + + ]: 102432 : if (!CheckMemPoolPolicyLimits()) {
999 [ + - + - ]: 3828 : return util::Error{Untranslated("cluster size limit exceeded")};
1000 : : }
1001 : :
1002 : 202312 : return m_pool->m_txgraph->GetMainStagingDiagrams();
1003 : 102432 : }
1004 : :
1005 : 3678135 : 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)
1006 : : {
1007 : 3678135 : LOCK(m_pool->cs);
1008 [ - + ]: 3678135 : Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1009 [ - + ]: 3678135 : Assume(!m_dependencies_processed);
1010 : :
1011 : : // We need to process dependencies after adding a new transaction.
1012 : 3678135 : m_dependencies_processed = false;
1013 : :
1014 : 3678135 : CAmount delta{0};
1015 [ + - ]: 3678135 : m_pool->ApplyDelta(tx->GetHash(), delta);
1016 : :
1017 [ + - + - ]: 3678135 : FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp));
1018 [ + - ]: 3678135 : auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1019 : 3678135 : m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1020 [ + + ]: 3678135 : if (delta) {
1021 : 128180 : newit->UpdateModifiedFee(delta);
1022 : 128180 : m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1023 : : }
1024 : :
1025 [ + - ]: 3678135 : m_entry_vec.push_back(newit);
1026 : :
1027 [ + - ]: 3678135 : return newit;
1028 : 3678135 : }
1029 : :
1030 : 962327 : void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it)
1031 : : {
1032 : 962327 : LOCK(m_pool->cs);
1033 : 962327 : m_pool->m_txgraph->RemoveTransaction(*it);
1034 [ + - ]: 962327 : m_to_remove.insert(it);
1035 : 962327 : }
1036 : :
1037 : 1384938 : void CTxMemPool::ChangeSet::Apply()
1038 : : {
1039 : 1384938 : LOCK(m_pool->cs);
1040 [ + + ]: 1384938 : if (!m_dependencies_processed) {
1041 [ + - ]: 47 : ProcessDependencies();
1042 : : }
1043 [ + - ]: 1384938 : m_pool->Apply(this);
1044 : 1384938 : m_to_add.clear();
1045 : 1384938 : m_to_remove.clear();
1046 [ + - ]: 1384938 : m_entry_vec.clear();
1047 [ + - ]: 1384938 : m_ancestors.clear();
1048 : 1384938 : }
1049 : :
1050 : 2763701 : void CTxMemPool::ChangeSet::ProcessDependencies()
1051 : : {
1052 : 2763701 : LOCK(m_pool->cs);
1053 [ - + ]: 2763701 : Assume(!m_dependencies_processed); // should only call this once.
1054 [ + + ]: 5533839 : for (const auto& entryptr : m_entry_vec) {
1055 [ + - + - : 12806368 : for (const auto &txin : entryptr->GetSharedTx()->vin) {
+ + ]
1056 [ + - ]: 4495954 : std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1057 [ + + ]: 4495954 : if (!piter) {
1058 : 2936340 : auto it = m_to_add.find(txin.prevout.hash);
1059 [ + + ]: 2936340 : if (it != m_to_add.end()) {
1060 : 10008 : piter = std::make_optional(it);
1061 : : }
1062 : : }
1063 [ + + ]: 4495954 : if (piter) {
1064 : 1569622 : m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1065 : : }
1066 : : }
1067 : : }
1068 : 2763701 : m_dependencies_processed = true;
1069 [ + - ]: 2763701 : return;
1070 : 2763701 : }
1071 : :
1072 : 2922111 : bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits()
1073 : : {
1074 : 2922111 : LOCK(m_pool->cs);
1075 [ + + ]: 2922111 : if (!m_dependencies_processed) {
1076 [ + - ]: 2763654 : ProcessDependencies();
1077 : : }
1078 : :
1079 [ + - ]: 2922111 : return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1080 : 2922111 : }
1081 : :
1082 : 125057 : std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1083 : : {
1084 : 125057 : FeePerWeight zero{};
1085 : 125057 : std::vector<FeePerWeight> ret;
1086 : :
1087 [ + - ]: 125057 : ret.emplace_back(zero);
1088 : :
1089 : 125057 : StartBlockBuilding();
1090 : :
1091 : 125057 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1092 : :
1093 [ + - ]: 125057 : FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1094 [ + + ]: 315380 : while (last_selection != FeePerWeight{}) {
1095 [ + - ]: 190323 : last_selection += ret.back();
1096 [ + - ]: 190323 : ret.emplace_back(last_selection);
1097 : 190323 : IncludeBuilderChunk();
1098 [ + - ]: 190323 : last_selection = GetBlockBuilderChunk(dummy);
1099 : : }
1100 : 125057 : StopBlockBuilding();
1101 : 125057 : return ret;
1102 : 125057 : }
|