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