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 : 4548 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41 : : {
42 : 4548 : 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 [ + - ]: 4548 : 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 [ + + ]: 4548 : if (!active_chain.Contains(*lp.maxInputBlock)) {
49 : 230 : return false;
50 : : }
51 : : }
52 : :
53 : : // LockPoints still valid
54 : : return true;
55 : : }
56 : :
57 : 9500628 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58 : : {
59 : 9500628 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60 [ + - ]: 9500628 : const auto& hash = entry.GetTx().GetHash();
61 : 9500628 : {
62 [ + - ]: 9500628 : LOCK(cs);
63 : 9500628 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64 [ + + + + ]: 9706233 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65 [ + - ]: 205605 : ret.emplace_back(*(iter->second));
66 : : }
67 : 0 : }
68 : 9500628 : std::ranges::sort(ret, CompareIteratorByHash{});
69 [ + + - - ]: 9521984 : auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70 : 9500628 : ret.erase(removed.begin(), removed.end());
71 : 9500628 : return ret;
72 : 0 : }
73 : :
74 : 9534114 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75 : : {
76 : 9534114 : LOCK(cs);
77 : 9534114 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78 : 9534114 : std::set<Txid> inputs;
79 [ + + ]: 21664712 : for (const auto& txin : entry.GetTx().vin) {
80 [ + - ]: 12130598 : inputs.insert(txin.prevout.hash);
81 : : }
82 [ + + ]: 21650452 : for (const auto& hash : inputs) {
83 [ + - ]: 12116338 : std::optional<txiter> piter = GetIter(hash);
84 [ + + ]: 12116338 : if (piter) {
85 [ + - ]: 204678 : ret.emplace_back(**piter);
86 : : }
87 : : }
88 : 9534114 : return ret;
89 [ + - ]: 19068228 : }
90 : :
91 : 3009 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
92 : : {
93 : 3009 : 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 [ + + ]: 3817 : for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
98 : : // calculate children from mapNextTx
99 : 808 : txiter it = mapTx.find(hash);
100 [ - + ]: 808 : if (it == mapTx.end()) {
101 : 0 : continue;
102 : : }
103 : 808 : auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104 : 808 : {
105 [ + + + + ]: 3285 : for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
106 [ - + ]: 2477 : txiter childIter = iter->second;
107 [ - + ]: 2477 : 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 : 2477 : m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
111 : : }
112 : : }
113 : : }
114 : :
115 : 3009 : auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
116 [ - + ]: 3009 : 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 : 3009 : }
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 : 1904 : CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const
131 : : {
132 : 1904 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
133 [ - + ]: 1904 : setEntries ret;
134 [ - + + + ]: 1904 : 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 : 1289 : setEntries staged_parents;
146 : 1289 : const CTransaction &tx = entry.GetTx();
147 : :
148 : : // Get parents of this transaction that are in the mempool
149 [ - + + + ]: 2918 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
150 [ + - ]: 1629 : std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151 [ + + ]: 1629 : if (piter) {
152 [ + - ]: 239 : staged_parents.insert(*piter);
153 : : }
154 : : }
155 : :
156 [ + + ]: 1502 : 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 : 1289 : return ret;
164 : 3193 : }
165 : :
166 : 1287 : static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
167 : : {
168 [ + - ]: 1287 : opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169 : 1287 : int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170 [ + - + - : 1287 : 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 : 1287 : return std::move(opts);
174 : : }
175 : :
176 : 1287 : CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
177 [ + - + - ]: 1287 : : m_opts{Flatten(std::move(opts), error)}
178 : : {
179 : 2574 : m_txgraph = MakeTxGraph(
180 : 1287 : /*max_cluster_count=*/m_opts.limits.cluster_count,
181 : 1287 : /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,
182 : : /*acceptable_cost=*/ACCEPTABLE_COST,
183 : 1287 : /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184 : 64667546 : const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185 : 64667546 : const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186 : 64667546 : return txid_a <=> txid_b;
187 : 1287 : });
188 : 1287 : }
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 : 152125 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
202 : : {
203 : 152125 : nTransactionsUpdated += n;
204 : 152125 : }
205 : :
206 : 51623 : void CTxMemPool::Apply(ChangeSet* changeset)
207 : : {
208 : 51623 : AssertLockHeld(cs);
209 : 51623 : m_txgraph->CommitStaging();
210 : :
211 : 51623 : RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED);
212 : :
213 [ - + + + ]: 103314 : for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214 : 51691 : auto tx_entry = changeset->m_entry_vec[i];
215 : : // First splice this entry into mapTx.
216 : 51691 : auto node_handle = changeset->m_to_add.extract(tx_entry);
217 [ + - ]: 51691 : auto result = mapTx.insert(std::move(node_handle));
218 : :
219 [ + - ]: 51691 : Assume(result.inserted);
220 : 51691 : txiter it = result.position;
221 : :
222 [ + - ]: 51691 : addNewTransaction(it);
223 [ - + ]: 51691 : }
224 [ - + ]: 51623 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
225 [ # # ]: 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after addition(s).");
226 : : }
227 : 51623 : }
228 : :
229 : 51691 : void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit)
230 : : {
231 : 51691 : 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 : 51691 : cachedInnerUsage += entry.DynamicMemoryUsage();
237 : :
238 : 51691 : const CTransaction& tx = newit->GetTx();
239 [ - + + + ]: 116230 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
240 : 64539 : 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 : 51691 : nTransactionsUpdated++;
250 : 51691 : totalTxSize += entry.GetTxSize();
251 : 51691 : m_total_fee += entry.GetFee();
252 : :
253 : 51691 : txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
254 [ - + ]: 51691 : newit->idx_randomized = txns_randomized.size() - 1;
255 : :
256 : : TRACEPOINT(mempool, added,
257 : : entry.GetTx().GetHash().data(),
258 : : entry.GetTxSize(),
259 : : entry.GetFee()
260 : 51691 : );
261 : 51691 : }
262 : :
263 : 48049 : 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 [ + + ]: 48049 : uint64_t mempool_sequence = GetAndIncrementSequence();
268 : :
269 [ + + + - ]: 48049 : 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 [ + - + - ]: 5757 : 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 : 48049 : );
283 : :
284 [ + + ]: 107675 : for (const CTxIn& txin : it->GetTx().vin)
285 : 59626 : mapNextTx.erase(txin.prevout);
286 : :
287 : 48049 : RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
288 : :
289 [ - + + + ]: 48049 : if (txns_randomized.size() > 1) {
290 : : // Remove entry from txns_randomized by replacing it with the back and deleting the back.
291 [ - + ]: 45835 : txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
292 [ - + ]: 45835 : txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
293 [ - + ]: 45835 : txns_randomized.pop_back();
294 [ - + - + : 45835 : if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
+ + ]
295 : 3293 : txns_randomized.shrink_to_fit();
296 : : }
297 : : } else {
298 [ + - ]: 2214 : txns_randomized.clear();
299 : : }
300 : :
301 : 48049 : totalTxSize -= it->GetTxSize();
302 : 48049 : m_total_fee -= it->GetFee();
303 : 48049 : cachedInnerUsage -= it->DynamicMemoryUsage();
304 : 48049 : mapTx.erase(it);
305 : 48049 : nTransactionsUpdated++;
306 : 48049 : }
307 : :
308 : : // Calculates descendants of given entry and adds to setDescendants.
309 : 80082 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
310 : : {
311 : 80082 : (void)CalculateDescendants(*entryit, setDescendants);
312 : 80082 : return;
313 : : }
314 : :
315 : 80144 : CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const
316 : : {
317 [ + + ]: 363752 : for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
318 [ + - ]: 283608 : setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
319 : : }
320 : 80144 : return mapTx.iterator_to(entry);
321 : : }
322 : :
323 : 110 : void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason)
324 : : {
325 : 110 : AssertLockHeld(cs);
326 : 110 : Assume(!m_have_changeset);
327 : 110 : auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
328 [ + + ]: 301 : for (auto tx: descendants) {
329 [ + - ]: 191 : removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
330 : : }
331 : 110 : }
332 : :
333 : 19004 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
334 : : {
335 : : // Remove transaction from memory pool
336 : 19004 : AssertLockHeld(cs);
337 : 19004 : Assume(!m_have_changeset);
338 : 19004 : txiter origit = mapTx.find(origTx.GetHash());
339 [ + + ]: 19004 : 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 : 18997 : auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
347 : 18997 : std::vector<const TxGraph::Ref*> to_remove;
348 [ + + + + ]: 19071 : while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
349 [ + - ]: 74 : to_remove.emplace_back(&*(iter->second));
350 : 74 : ++iter;
351 : : }
352 [ - + ]: 18997 : auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
353 [ + + ]: 19074 : for (auto ref : all_removes) {
354 : 77 : auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
355 [ + - ]: 77 : removeUnchecked(tx, reason);
356 : : }
357 : 18997 : }
358 : 19004 : }
359 : :
360 : 3009 : 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 : 3009 : AssertLockHeld(cs);
364 : 3009 : AssertLockHeld(::cs_main);
365 : 3009 : Assume(!m_have_changeset);
366 : :
367 : 3009 : std::vector<const TxGraph::Ref*> to_remove;
368 [ + + ]: 5303 : for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
369 [ + - + + ]: 2294 : if (check_final_and_mature(it)) {
370 [ + - ]: 15 : to_remove.emplace_back(&*it);
371 : : }
372 : : }
373 : :
374 [ - + ]: 3009 : auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
375 : :
376 [ + + ]: 3046 : for (auto ref : all_to_remove) {
377 : 37 : auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
378 [ + - ]: 37 : removeUnchecked(it, MemPoolRemovalReason::REORG);
379 : : }
380 [ + + ]: 5266 : for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
381 [ + - - + ]: 2257 : assert(TestLockPointValidity(chain, it->GetLockPoints()));
382 : : }
383 [ - + ]: 3009 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
384 [ - - - - : 3009 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after reorg.");
- - ]
385 : : }
386 : 3009 : }
387 : :
388 : 58725 : void CTxMemPool::removeConflicts(const CTransaction &tx)
389 : : {
390 : : // Remove transactions which depend on inputs of tx, recursively
391 : 58725 : AssertLockHeld(cs);
392 [ + + ]: 129057 : for (const CTxIn &txin : tx.vin) {
393 : 70332 : auto it = mapNextTx.find(txin.prevout);
394 [ + + ]: 70332 : if (it != mapNextTx.end()) {
395 [ + - ]: 103 : const CTransaction &txConflict = it->second->GetTx();
396 [ + - ]: 103 : if (Assume(txConflict.GetHash() != tx.GetHash()))
397 : : {
398 : 103 : ClearPrioritisation(txConflict.GetHash());
399 : 103 : removeRecursive(it->second, MemPoolRemovalReason::CONFLICT);
400 : : }
401 : : }
402 : : }
403 : 58725 : }
404 : :
405 : 137612 : 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 : 137612 : AssertLockHeld(cs);
409 [ + + ]: 137612 : Assume(!m_have_changeset);
410 : 137612 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
411 [ + + + - : 137612 : if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
+ + ]
412 [ - + + - ]: 8040 : txs_removed_for_block.reserve(vtx.size());
413 [ + + ]: 66765 : for (const auto& tx : vtx) {
414 : 58725 : txiter it = mapTx.find(tx->GetHash());
415 [ + + ]: 58725 : if (it != mapTx.end()) {
416 [ + - ]: 46130 : txs_removed_for_block.emplace_back(*it);
417 [ + - ]: 46130 : removeUnchecked(it, MemPoolRemovalReason::BLOCK);
418 : : }
419 [ + - ]: 58725 : removeConflicts(*tx);
420 [ + - ]: 58725 : ClearPrioritisation(tx->GetHash());
421 : : }
422 : : }
423 [ + - ]: 137612 : if (m_opts.signals) {
424 [ + - ]: 137612 : m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
425 : : }
426 [ + - ]: 137612 : lastRollingFeeUpdate = GetTime();
427 : 137612 : blockSinceLastRollingFeeBump = true;
428 [ - + ]: 137612 : if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
429 [ # # # # : 0 : LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after block.");
# # ]
430 : : }
431 : 137612 : }
432 : :
433 : 172686 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
434 : : {
435 [ + + ]: 172686 : if (m_opts.check_ratio == 0) return;
436 : :
437 [ + - ]: 170638 : if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
438 : :
439 : 170638 : AssertLockHeld(::cs_main);
440 : 170638 : LOCK(cs);
441 [ + - + - : 170638 : LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
+ - ]
442 : :
443 : 170638 : uint64_t checkTotal = 0;
444 : 170638 : CAmount check_total_fee{0};
445 : 170638 : CAmount check_total_modified_fee{0};
446 : 170638 : int64_t check_total_adjusted_weight{0};
447 : 170638 : uint64_t innerUsage = 0;
448 : :
449 [ - + ]: 170638 : assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
450 [ + - ]: 170638 : m_txgraph->SanityCheck();
451 : :
452 [ + - ]: 170638 : CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
453 : :
454 [ + - ]: 170638 : const auto score_with_topo{GetSortedScoreWithTopology()};
455 : :
456 : : // Number of chunks is bounded by number of transactions.
457 [ + - ]: 170638 : const auto diagram{GetFeerateDiagram()};
458 [ - + - + : 170638 : assert(diagram.size() <= score_with_topo.size() + 1);
- + ]
459 [ - + ]: 170638 : assert(diagram.size() >= 1);
460 : :
461 : 170638 : std::optional<txiter> last_iter = std::nullopt;
462 : 170638 : auto diagram_iter = diagram.cbegin();
463 : :
464 [ + + ]: 9662012 : 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 [ - + ]: 9491374 : assert(diagram_iter->size >= check_total_adjusted_weight);
472 [ + + ]: 9491374 : if (diagram_iter->fee == check_total_modified_fee &&
473 [ + - ]: 9470875 : diagram_iter->size == check_total_adjusted_weight) {
474 : 9470875 : ++diagram_iter;
475 : : }
476 [ + - ]: 9491374 : checkTotal += it->GetTxSize();
477 [ + - ]: 9491374 : check_total_adjusted_weight += it->GetAdjustedWeight();
478 [ + + ]: 9491374 : check_total_fee += it->GetFee();
479 [ + + ]: 9491374 : check_total_modified_fee += it->GetModifiedFee();
480 [ + + ]: 9491374 : innerUsage += it->DynamicMemoryUsage();
481 [ + + ]: 9491374 : const CTransaction& tx = it->GetTx();
482 : :
483 [ + + ]: 9491374 : if (last_iter) {
484 [ - + ]: 9460026 : assert(m_txgraph->CompareMainOrder(**last_iter, *it) < 0);
485 : : }
486 [ + + ]: 9491374 : last_iter = it;
487 : :
488 : 9491374 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
489 : 9491374 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
490 [ + + ]: 21560275 : for (const CTxIn &txin : tx.vin) {
491 : : // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
492 : 12068901 : indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
493 [ + + ]: 12068901 : if (it2 != mapTx.end()) {
494 [ - + ]: 197948 : const CTransaction& tx2 = it2->GetTx();
495 [ - + + - : 197948 : assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
- + ]
496 [ + - ]: 197948 : setParentCheck.insert(*it2);
497 : : }
498 : : // We are iterating through the mempool entries sorted
499 : : // topologically and by mining score. All parents must have been
500 : : // checked before their children and their coins added to the
501 : : // mempoolDuplicate coins cache.
502 [ + - - + ]: 12068901 : assert(mempoolDuplicate.HaveCoin(txin.prevout));
503 : : // Check whether its inputs are marked in mapNextTx.
504 : 12068901 : auto it3 = mapNextTx.find(txin.prevout);
505 [ - + ]: 12068901 : assert(it3 != mapNextTx.end());
506 [ - + ]: 12068901 : assert(it3->first == &txin.prevout);
507 [ - + ]: 12068901 : assert(&it3->second->GetTx() == &tx);
508 : : }
509 : 9887078 : auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
510 [ + - ]: 395704 : return a.GetTx().GetHash() == b.GetTx().GetHash();
511 : : };
512 [ + - + + ]: 9689226 : for (auto &txentry : GetParents(*it)) {
513 [ + - ]: 197852 : setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
514 : 0 : }
515 [ - + ]: 9491374 : assert(setParentCheck.size() == setParentsStored.size());
516 [ - + ]: 9491374 : assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
517 : :
518 : : // Check children against mapNextTx
519 : 9491374 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
520 : 9491374 : std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
521 : 9491374 : auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
522 [ + + + + ]: 9689322 : for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
523 [ - + ]: 197948 : txiter childit = iter->second;
524 [ - + ]: 197948 : assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
525 [ + - ]: 197948 : setChildrenCheck.insert(*childit);
526 : : }
527 [ + - + + ]: 9689226 : for (auto &txentry : GetChildren(*it)) {
528 [ + - ]: 197852 : setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
529 : 0 : }
530 [ - + ]: 9491374 : assert(setChildrenCheck.size() == setChildrenStored.size());
531 [ - + ]: 9491374 : assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
532 : :
533 [ - + ]: 9491374 : TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
534 : 9491374 : CAmount txfee = 0;
535 [ - + ]: 9491374 : assert(!tx.IsCoinBase());
536 [ + - - + ]: 9491374 : assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
537 [ + - + + ]: 21560275 : for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
538 [ + - ]: 9491374 : AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
539 : 9491374 : }
540 [ + + ]: 12239539 : for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
541 [ - + ]: 12068901 : indexed_transaction_set::const_iterator it2 = it->second;
542 [ - + ]: 12068901 : assert(it2 != mapTx.end());
543 : : }
544 : :
545 [ - + ]: 170638 : ++diagram_iter;
546 [ - + ]: 170638 : assert(diagram_iter == diagram.cend());
547 : :
548 [ - + ]: 170638 : assert(totalTxSize == checkTotal);
549 [ - + ]: 170638 : assert(m_total_fee == check_total_fee);
550 [ - + ]: 170638 : assert(diagram.back().fee == check_total_modified_fee);
551 [ - + ]: 170638 : assert(diagram.back().size == check_total_adjusted_weight);
552 [ - + ]: 170638 : assert(innerUsage == cachedInnerUsage);
553 [ + - ]: 341276 : }
554 : :
555 : 38931 : std::vector<CTxMemPool::txiter> CTxMemPool::ExtractBestByMiningScoreWithTopology(std::vector<Wtxid>& wtxids, size_t n_to_sort) const
556 : : {
557 : : /* This function takes a vector of `wtxids`, and returns the
558 : : * best mempool entries corresponding to those `wtxids` (by mining
559 : : * score/topology). It updates the input `wtxids` so that multiple
560 : : * calls with the same vector will drain that vector to empty.
561 : : *
562 : : * It operates under the following constraints:
563 : : * - wtxids that do not correspond to a mempool entry are dropped
564 : : * - the return vector contains no duplicates, either with itself
565 : : * or with the updated `wtxids` input.
566 : : * - the return vector will have `n_to_sort` entries (or `wtxids`
567 : : will become empty).
568 : : * - the `wtxids` vector will be reduced by at least `n_to_sort`
569 : : * entries (or will become empty).
570 : : */
571 : :
572 : 365374 : auto cmp = [&](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept { return m_txgraph->CompareMainOrder(*a, *b) < 0; };
573 : :
574 : 38931 : std::vector<txiter> res;
575 : :
576 [ - + + + ]: 38931 : n_to_sort = std::min(wtxids.size(), n_to_sort);
577 [ + - ]: 38931 : if (n_to_sort > 0) {
578 [ - + + - ]: 38931 : res.reserve(wtxids.size());
579 : 38931 : std::sort(wtxids.begin(), wtxids.end());
580 [ + + ]: 174930 : for (auto it = wtxids.begin(); it != wtxids.end(); ++it) {
581 : : // skip duplicates
582 [ + + ]: 135999 : auto itnext = it + 1;
583 [ + + + + ]: 135999 : if (itnext != wtxids.end() && *it == *itnext) continue;
584 : :
585 [ + - + + ]: 130456 : if (auto i{GetIter(*it)}; i.has_value()) {
586 [ + - ]: 121280 : res.push_back(i.value());
587 : : }
588 : : }
589 [ + - ]: 38931 : wtxids.clear();
590 : :
591 [ + + ]: 38931 : if (!res.empty()) {
592 [ - + ]: 38716 : auto begin = res.begin();
593 [ - + ]: 38716 : auto end = res.end();
594 : 38716 : auto middle = end;
595 [ - + + + ]: 38716 : if (n_to_sort >= res.size()) {
596 : : // use regular sort when sorting everything
597 : 38582 : std::sort(begin, end, cmp);
598 : : } else {
599 : 134 : middle = begin + n_to_sort;
600 : 134 : std::partial_sort(begin, middle, end, cmp);
601 : : }
602 : 38716 : auto it = middle;
603 [ + + ]: 84946 : while (it != end) {
604 [ + - ]: 46230 : wtxids.push_back((*it)->GetTx().GetWitnessHash());
605 : 46230 : ++it;
606 : : }
607 : 38716 : res.erase(middle, end);
608 : : }
609 : : }
610 : 38931 : return res;
611 : 0 : }
612 : :
613 : 181847 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
614 : : {
615 : 181847 : std::vector<indexed_transaction_set::const_iterator> iters;
616 : 181847 : AssertLockHeld(cs);
617 : :
618 [ + - ]: 181847 : iters.reserve(mapTx.size());
619 : :
620 [ + + + + ]: 19744639 : for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
621 [ + - ]: 9781396 : iters.push_back(mi);
622 : : }
623 : 181847 : std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
624 : 110459425 : return m_txgraph->CompareMainOrder(*a, *b) < 0;
625 : : });
626 : 181847 : return iters;
627 : 0 : }
628 : :
629 : 10216 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
630 : : {
631 : 10216 : AssertLockHeld(cs);
632 : :
633 : 10216 : std::vector<CTxMemPoolEntryRef> ret;
634 [ + - ]: 10216 : ret.reserve(mapTx.size());
635 [ + - + + ]: 298893 : for (const auto& it : GetSortedScoreWithTopology()) {
636 [ + - ]: 288677 : ret.emplace_back(*it);
637 : : }
638 : 10216 : return ret;
639 : 0 : }
640 : :
641 : 993 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
642 : : {
643 : 993 : LOCK(cs);
644 [ + - ]: 993 : auto iters = GetSortedScoreWithTopology();
645 : :
646 : 993 : std::vector<TxMempoolInfo> ret;
647 [ + - ]: 993 : ret.reserve(mapTx.size());
648 [ + + ]: 2338 : for (auto it : iters) {
649 [ + - - + ]: 2690 : ret.push_back(GetInfo(it));
650 : : }
651 : :
652 : 993 : return ret;
653 [ + - ]: 1986 : }
654 : :
655 : 2862 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
656 : : {
657 : 2862 : AssertLockHeld(cs);
658 : 2862 : const auto i = mapTx.find(txid);
659 [ + + ]: 2862 : return i == mapTx.end() ? nullptr : &(*i);
660 : : }
661 : :
662 : 246018 : CTransactionRef CTxMemPool::get(const Txid& hash) const
663 : : {
664 : 246018 : LOCK(cs);
665 : 246018 : indexed_transaction_set::const_iterator i = mapTx.find(hash);
666 [ + + ]: 246018 : if (i == mapTx.end())
667 : 190209 : return nullptr;
668 [ + - + - ]: 301827 : return i->GetSharedTx();
669 : 246018 : }
670 : :
671 : 4 : CTransactionRef CTxMemPool::get(const Wtxid& hash) const
672 : : {
673 : 4 : LOCK(cs);
674 : 4 : const auto& wtxid_map{mapTx.get<index_by_wtxid>()};
675 : 4 : const auto it{wtxid_map.find(hash)};
676 [ + + ]: 4 : if (it == wtxid_map.end()) return nullptr;
677 [ + - + - ]: 6 : return it->GetSharedTx();
678 : 4 : }
679 : :
680 : 769 : void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
681 : : {
682 : 769 : {
683 : 769 : LOCK(cs);
684 [ + - ]: 769 : CAmount &delta = mapDeltas[hash];
685 : 769 : delta = SaturatingAdd(delta, nFeeDelta);
686 : 769 : txiter it = mapTx.find(hash);
687 [ + + ]: 769 : if (it != mapTx.end()) {
688 : : // PrioritiseTransaction calls stack on previous ones. Set the new
689 : : // transaction fee to be current modified fee + feedelta.
690 : 262 : it->UpdateModifiedFee(nFeeDelta);
691 : 262 : m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
692 : 262 : ++nTransactionsUpdated;
693 : : }
694 [ + + ]: 769 : if (delta == 0) {
695 : 9 : mapDeltas.erase(hash);
696 [ + + + - : 16 : LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
+ - ]
697 : : } else {
698 [ + - + - : 1015 : LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
+ + + - +
- ]
699 : : hash.ToString(),
700 : : it == mapTx.end() ? "not " : "",
701 : : FormatMoney(nFeeDelta),
702 : : FormatMoney(delta));
703 : : }
704 : 769 : }
705 : 769 : }
706 : :
707 : 73047 : void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
708 : : {
709 : 73047 : AssertLockHeld(cs);
710 : 73047 : std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
711 [ + + ]: 73047 : if (pos == mapDeltas.end())
712 : : return;
713 : 41 : const CAmount &delta = pos->second;
714 : 41 : nFeeDelta += delta;
715 : : }
716 : :
717 : 58829 : void CTxMemPool::ClearPrioritisation(const Txid& hash)
718 : : {
719 : 58829 : AssertLockHeld(cs);
720 : 58829 : mapDeltas.erase(hash);
721 : 58829 : }
722 : :
723 : 31 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
724 : : {
725 : 31 : AssertLockNotHeld(cs);
726 : 31 : LOCK(cs);
727 : 31 : std::vector<delta_info> result;
728 [ + - ]: 31 : result.reserve(mapDeltas.size());
729 [ + + ]: 61 : for (const auto& [txid, delta] : mapDeltas) {
730 : 30 : const auto iter{mapTx.find(txid)};
731 [ + + ]: 30 : const bool in_mempool{iter != mapTx.end()};
732 : 30 : std::optional<CAmount> modified_fee;
733 [ + + ]: 30 : if (in_mempool) modified_fee = iter->GetModifiedFee();
734 [ + - ]: 30 : result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
735 : : }
736 [ + - ]: 31 : return result;
737 : 31 : }
738 : :
739 : 115789 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
740 : : {
741 : 115789 : const auto it = mapNextTx.find(prevout);
742 [ + + ]: 115789 : return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
743 : : }
744 : :
745 : 12261305 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
746 : : {
747 : 12261305 : AssertLockHeld(cs);
748 : 12261305 : auto it = mapTx.find(txid);
749 [ + + ]: 12261305 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
750 : : }
751 : :
752 : 141153 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
753 : : {
754 : 141153 : AssertLockHeld(cs);
755 [ + + ]: 141153 : auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
756 [ + + ]: 141153 : return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
757 : : }
758 : :
759 : 42726 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
760 : : {
761 : 42726 : CTxMemPool::setEntries ret;
762 [ + + ]: 45029 : for (const auto& h : hashes) {
763 [ + - ]: 2303 : const auto mi = GetIter(h);
764 [ + - + - ]: 2303 : if (mi) ret.insert(*mi);
765 : : }
766 : 42726 : return ret;
767 : 0 : }
768 : :
769 : 2 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
770 : : {
771 : 2 : AssertLockHeld(cs);
772 : 2 : std::vector<txiter> ret;
773 [ - + + - ]: 2 : ret.reserve(txids.size());
774 [ + + ]: 565 : for (const auto& txid : txids) {
775 [ + - ]: 563 : const auto it{GetIter(txid)};
776 [ - + ]: 563 : if (!it) return {};
777 [ + - ]: 563 : ret.push_back(*it);
778 : : }
779 : 2 : return ret;
780 : 2 : }
781 : :
782 : 25107 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
783 : : {
784 [ - + + + ]: 57380 : for (unsigned int i = 0; i < tx.vin.size(); i++)
785 [ + + ]: 35434 : if (exists(tx.vin[i].prevout.hash))
786 : : return false;
787 : : return true;
788 : : }
789 : :
790 [ + - + - ]: 50927 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
791 : :
792 : 70864 : std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
793 : : {
794 : : // Check to see if the inputs are made available by another tx in the package.
795 : : // These Coins would not be available in the underlying CoinsView.
796 [ + + ]: 70864 : if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
797 : 615 : return it->second;
798 : : }
799 : :
800 : : // If an entry in the mempool exists, always return that one, as it's guaranteed to never
801 : : // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
802 : : // transactions. First checking the underlying cache risks returning a pruned entry instead.
803 : 70249 : CTransactionRef ptx = mempool.get(outpoint.hash);
804 [ + + ]: 70249 : if (ptx) {
805 [ - + + - ]: 8403 : if (outpoint.n < ptx->vout.size()) {
806 : 8403 : Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
807 [ + - ]: 8403 : m_non_base_coins.emplace(outpoint);
808 : 8403 : return coin;
809 : 8403 : }
810 : 0 : return std::nullopt;
811 : : }
812 [ + - ]: 61846 : return base->GetCoin(outpoint);
813 : 70249 : }
814 : :
815 : 780 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
816 : : {
817 [ - + + + ]: 1597 : for (unsigned int n = 0; n < tx->vout.size(); ++n) {
818 [ + - ]: 817 : m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
819 : 817 : m_non_base_coins.emplace(tx->GetHash(), n);
820 : : }
821 : 780 : }
822 : 73903 : void CCoinsViewMemPool::Reset()
823 : : {
824 : 73903 : m_temp_added.clear();
825 : 73903 : m_non_base_coins.clear();
826 : 73903 : }
827 : :
828 : 562915 : size_t CTxMemPool::DynamicMemoryUsage() const {
829 : 562915 : LOCK(cs);
830 : : // Estimate the overhead of mapTx to be 9 pointers (3 pointers per index) + an allocation, as no exact formula for boost::multi_index_contained is implemented.
831 [ - + + - ]: 1125830 : return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
832 : 562915 : }
833 : :
834 : 58799 : void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
835 : 58799 : LOCK(cs);
836 : :
837 [ + + ]: 58799 : if (m_unbroadcast_txids.erase(txid))
838 : : {
839 [ + - + - : 20142 : LogDebug(BCLog::MEMPOOL, "Removed %s from set of unbroadcast txns%s", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
+ + + - +
- ]
840 : : }
841 : 58799 : }
842 : :
843 : 78815 : void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) {
844 : 78815 : AssertLockHeld(cs);
845 [ + + ]: 80384 : for (txiter it : stage) {
846 : 1569 : removeUnchecked(it, reason);
847 : : }
848 : 78815 : }
849 : :
850 : 3491 : bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx)
851 : : {
852 : 3491 : LOCK(cs);
853 : : // Use ChangeSet interface to check whether the cluster count
854 : : // limits would be violated. Note that the changeset will be destroyed
855 : : // when it goes out of scope.
856 [ + - ]: 3491 : auto changeset = GetChangeSet();
857 [ + - ]: 3491 : (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
858 [ + - ]: 3491 : return changeset->CheckMemPoolPolicyLimits();
859 [ + - ]: 6982 : }
860 : :
861 : 27192 : int CTxMemPool::Expire(std::chrono::seconds time)
862 : : {
863 : 27192 : AssertLockHeld(cs);
864 : 27192 : Assume(!m_have_changeset);
865 : 27192 : indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
866 : 27192 : setEntries toremove;
867 [ + + + + ]: 27196 : while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
868 [ + - ]: 4 : toremove.insert(mapTx.project<0>(it));
869 : 4 : it++;
870 : : }
871 : 27192 : setEntries stage;
872 [ + + ]: 27196 : for (txiter removeit : toremove) {
873 [ + - ]: 4 : CalculateDescendants(removeit, stage);
874 : : }
875 [ + - ]: 27192 : RemoveStaged(stage, MemPoolRemovalReason::EXPIRY);
876 : 27192 : return stage.size();
877 : 27192 : }
878 : :
879 : 468418 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
880 : 468418 : LOCK(cs);
881 [ + + + + ]: 468418 : if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
882 : 468353 : return CFeeRate(llround(rollingMinimumFeeRate));
883 : :
884 [ + - ]: 65 : int64_t time = GetTime();
885 [ + + ]: 65 : if (time > lastRollingFeeUpdate + 10) {
886 : 6 : double halflife = ROLLING_FEE_HALFLIFE;
887 [ + - + + ]: 6 : if (DynamicMemoryUsage() < sizelimit / 4)
888 : : halflife /= 4;
889 [ + - + + ]: 5 : else if (DynamicMemoryUsage() < sizelimit / 2)
890 : 1 : halflife /= 2;
891 : :
892 : 6 : rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
893 : 6 : lastRollingFeeUpdate = time;
894 : :
895 [ + + ]: 6 : if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
896 : 1 : rollingMinimumFeeRate = 0;
897 : 1 : return CFeeRate(0);
898 : : }
899 : : }
900 : 64 : return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
901 : 468418 : }
902 : :
903 : 39 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
904 : 39 : AssertLockHeld(cs);
905 [ + + ]: 39 : if (rate.GetFeePerK() > rollingMinimumFeeRate) {
906 : 37 : rollingMinimumFeeRate = rate.GetFeePerK();
907 : 37 : blockSinceLastRollingFeeBump = false;
908 : : }
909 : 39 : }
910 : :
911 : 27201 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
912 : 27201 : AssertLockHeld(cs);
913 : 27201 : Assume(!m_have_changeset);
914 : :
915 : 27201 : unsigned nTxnRemoved = 0;
916 : 27201 : CFeeRate maxFeeRateRemoved(0);
917 : :
918 [ + + + + ]: 27240 : while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
919 [ + - ]: 39 : const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
920 [ + - ]: 39 : FeePerVSize feerate = ToFeePerVSize(feeperweight);
921 [ + - ]: 39 : CFeeRate removed{feerate.fee, feerate.size};
922 : :
923 : : // We set the new mempool min fee to the feerate of the removed set, plus the
924 : : // "minimum reasonable fee rate" (ie some value under which we consider txn
925 : : // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
926 : : // equal to txn which were removed with no block in between.
927 : 39 : removed += m_opts.incremental_relay_feerate;
928 [ + - ]: 39 : trackPackageRemoved(removed);
929 : 39 : maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
930 : :
931 [ - + ]: 39 : nTxnRemoved += worst_chunk.size();
932 : :
933 : 39 : std::vector<CTransaction> txn;
934 [ + + ]: 39 : if (pvNoSpendsRemaining) {
935 [ + - ]: 31 : txn.reserve(worst_chunk.size());
936 [ + + ]: 63 : for (auto ref : worst_chunk) {
937 [ + - ]: 32 : txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
938 : : }
939 : : }
940 : :
941 : 39 : setEntries stage;
942 [ + + ]: 84 : for (auto ref : worst_chunk) {
943 [ + - ]: 45 : stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
944 : : }
945 [ + + ]: 84 : for (auto e : stage) {
946 [ + - ]: 45 : removeUnchecked(e, MemPoolRemovalReason::SIZELIMIT);
947 : : }
948 [ + + ]: 39 : if (pvNoSpendsRemaining) {
949 [ + + ]: 63 : for (const CTransaction& tx : txn) {
950 [ + + ]: 64 : for (const CTxIn& txin : tx.vin) {
951 [ + - + + ]: 32 : if (exists(txin.prevout.hash)) continue;
952 [ + - ]: 31 : pvNoSpendsRemaining->push_back(txin.prevout);
953 : : }
954 : : }
955 : : }
956 : 78 : }
957 : :
958 [ + + ]: 27201 : if (maxFeeRateRemoved > CFeeRate(0)) {
959 [ + - + - ]: 32 : LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
960 : : }
961 : 27201 : }
962 : :
963 : 124973 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
964 : : {
965 : 124973 : auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
966 : :
967 [ - + ]: 124973 : size_t ancestor_count = ancestors.size();
968 : 124973 : size_t ancestor_size = 0;
969 : 124973 : CAmount ancestor_fees = 0;
970 [ + + ]: 447230 : for (auto tx: ancestors) {
971 : 322257 : const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
972 [ + - ]: 322257 : ancestor_size += anc.GetTxSize();
973 : 322257 : ancestor_fees += anc.GetModifiedFee();
974 : : }
975 : 124973 : return {ancestor_count, ancestor_size, ancestor_fees};
976 : 124973 : }
977 : :
978 : 9254 : std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
979 : : {
980 : 9254 : auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
981 [ - + ]: 9254 : size_t descendant_count = descendants.size();
982 : 9254 : size_t descendant_size = 0;
983 : 9254 : CAmount descendant_fees = 0;
984 : :
985 [ + + ]: 165021 : for (auto tx: descendants) {
986 : 155767 : const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
987 [ + - ]: 155767 : descendant_size += desc.GetTxSize();
988 : 155767 : descendant_fees += desc.GetModifiedFee();
989 : : }
990 : 9254 : return {descendant_count, descendant_size, descendant_fees};
991 : 9254 : }
992 : :
993 : 584003 : void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
994 : 584003 : LOCK(cs);
995 : 584003 : auto it = mapTx.find(txid);
996 : 584003 : ancestors = cluster_count = 0;
997 [ + + ]: 584003 : if (it != mapTx.end()) {
998 [ + - + + ]: 47495 : auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
999 : 47495 : ancestors = ancestor_count;
1000 [ + + ]: 47495 : if (ancestorsize) *ancestorsize = ancestor_size;
1001 [ + + ]: 47495 : if (ancestorfees) *ancestorfees = ancestor_fees;
1002 [ - + ]: 47495 : cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
1003 : : }
1004 : 584003 : }
1005 : :
1006 : 2400 : bool CTxMemPool::GetLoadTried() const
1007 : : {
1008 : 2400 : LOCK(cs);
1009 [ + - ]: 2400 : return m_load_tried;
1010 : 2400 : }
1011 : :
1012 : 1073 : void CTxMemPool::SetLoadTried(bool load_tried)
1013 : : {
1014 : 1073 : LOCK(cs);
1015 [ + - ]: 1073 : m_load_tried = load_tried;
1016 : 1073 : }
1017 : :
1018 : 3160 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
1019 : : {
1020 : 3160 : AssertLockHeld(cs);
1021 : :
1022 : 3160 : std::vector<CTxMemPool::txiter> ret;
1023 : 3160 : std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
1024 [ + + ]: 52487 : for (auto txid : txids) {
1025 : 49327 : auto it = mapTx.find(txid);
1026 [ + - ]: 49327 : if (it != mapTx.end()) {
1027 : : // Note that TxGraph::GetCluster will return results in graph
1028 : : // order, which is deterministic (as long as we are not modifying
1029 : : // the graph).
1030 : 49327 : auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
1031 [ + - + + ]: 49327 : if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
1032 [ + + ]: 118745 : for (auto tx : cluster) {
1033 [ + - ]: 69590 : ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
1034 : : }
1035 : : }
1036 : 49327 : }
1037 : : }
1038 [ - + + + ]: 3160 : if (ret.size() > 500) {
1039 : 1 : return {};
1040 : : }
1041 : 3159 : return ret;
1042 : 3160 : }
1043 : :
1044 : 1316 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1045 : : {
1046 : 1316 : LOCK(m_pool->cs);
1047 : :
1048 [ + - - + ]: 1316 : if (!CheckMemPoolPolicyLimits()) {
1049 [ # # # # ]: 0 : return util::Error{Untranslated("cluster size limit exceeded")};
1050 : : }
1051 : :
1052 : 2632 : return m_pool->m_txgraph->GetMainStagingDiagrams();
1053 : 1316 : }
1054 : :
1055 : 73047 : CTxMemPool::ChangeSet::TxHandle CTxMemPool::ChangeSet::StageAddition(const CTransactionRef& tx, const CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp)
1056 : : {
1057 : 73047 : LOCK(m_pool->cs);
1058 [ + - ]: 73047 : Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1059 : 73047 : Assume(!m_dependencies_processed);
1060 : :
1061 : : // We need to process dependencies after adding a new transaction.
1062 : 73047 : m_dependencies_processed = false;
1063 : :
1064 : 73047 : CAmount delta{0};
1065 [ + - ]: 73047 : m_pool->ApplyDelta(tx->GetHash(), delta);
1066 : :
1067 [ + - + - ]: 73047 : FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp));
1068 [ + - ]: 73047 : auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1069 : 73047 : m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1070 [ + + ]: 73047 : if (delta) {
1071 : 41 : newit->UpdateModifiedFee(delta);
1072 : 41 : m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1073 : : }
1074 : :
1075 [ + - ]: 73047 : m_entry_vec.push_back(newit);
1076 : :
1077 [ + - ]: 73047 : return newit;
1078 : 73047 : }
1079 : :
1080 : 2161 : void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it)
1081 : : {
1082 : 2161 : LOCK(m_pool->cs);
1083 : 2161 : m_pool->m_txgraph->RemoveTransaction(*it);
1084 [ + - ]: 2161 : m_to_remove.insert(it);
1085 : 2161 : }
1086 : :
1087 : 51623 : void CTxMemPool::ChangeSet::Apply()
1088 : : {
1089 : 51623 : LOCK(m_pool->cs);
1090 [ + + ]: 51623 : if (!m_dependencies_processed) {
1091 [ + - ]: 3 : ProcessDependencies();
1092 : : }
1093 [ + - ]: 51623 : m_pool->Apply(this);
1094 : 51623 : m_to_add.clear();
1095 : 51623 : m_to_remove.clear();
1096 [ + - ]: 51623 : m_entry_vec.clear();
1097 [ + - ]: 51623 : m_ancestors.clear();
1098 : 51623 : }
1099 : :
1100 : 72104 : void CTxMemPool::ChangeSet::ProcessDependencies()
1101 : : {
1102 : 72104 : LOCK(m_pool->cs);
1103 : 72104 : Assume(!m_dependencies_processed); // should only call this once.
1104 [ + + ]: 144794 : for (const auto& entryptr : m_entry_vec) {
1105 [ + - + - : 316881 : for (const auto &txin : entryptr->GetSharedTx()->vin) {
+ + ]
1106 [ + - ]: 98811 : std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1107 [ + + ]: 98811 : if (!piter) {
1108 : 89163 : auto it = m_to_add.find(txin.prevout.hash);
1109 [ + + ]: 89163 : if (it != m_to_add.end()) {
1110 : 585 : piter = std::make_optional(it);
1111 : : }
1112 : : }
1113 [ + + ]: 98811 : if (piter) {
1114 : 10233 : m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1115 : : }
1116 : : }
1117 : : }
1118 : 72104 : m_dependencies_processed = true;
1119 [ + - ]: 72104 : return;
1120 : 72104 : }
1121 : :
1122 : 74704 : bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits()
1123 : : {
1124 : 74704 : LOCK(m_pool->cs);
1125 [ + + ]: 74704 : if (!m_dependencies_processed) {
1126 [ + - ]: 72101 : ProcessDependencies();
1127 : : }
1128 : :
1129 [ + - ]: 74704 : return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1130 : 74704 : }
1131 : :
1132 : 170643 : std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1133 : : {
1134 : 170643 : FeePerWeight zero{};
1135 : 170643 : std::vector<FeePerWeight> ret;
1136 : :
1137 [ + - ]: 170643 : ret.emplace_back(zero);
1138 : :
1139 : 170643 : StartBlockBuilding();
1140 : :
1141 : 170643 : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1142 : :
1143 [ + - ]: 170643 : FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1144 [ + + ]: 9641644 : while (last_selection != FeePerWeight{}) {
1145 [ + - ]: 9471001 : last_selection += ret.back();
1146 [ + - ]: 9471001 : ret.emplace_back(last_selection);
1147 : 9471001 : IncludeBuilderChunk();
1148 [ + - ]: 9471001 : last_selection = GetBlockBuilderChunk(dummy);
1149 : : }
1150 : 170643 : StopBlockBuilding();
1151 : 170643 : return ret;
1152 : 170643 : }
|