Bitcoin Core 31.99.0
P2P Digital Currency
txmempool.cpp
Go to the documentation of this file.
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>
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
37TRACEPOINT_SEMAPHORE(mempool, added);
38TRACEPOINT_SEMAPHORE(mempool, removed);
39
40bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41{
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 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 if (!active_chain.Contains(*lp.maxInputBlock)) {
49 return false;
50 }
51 }
52
53 // LockPoints still valid
54 return true;
55}
56
57std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58{
59 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60 const auto& hash = entry.GetTx().GetHash();
61 {
62 LOCK(cs);
63 auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64 for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65 ret.emplace_back(*(iter->second));
66 }
67 }
68 std::ranges::sort(ret, CompareIteratorByHash{});
69 auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70 ret.erase(removed.begin(), removed.end());
71 return ret;
72}
73
74std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75{
76 LOCK(cs);
77 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78 std::set<Txid> inputs;
79 for (const auto& txin : entry.GetTx().vin) {
80 inputs.insert(txin.prevout.hash);
81 }
82 for (const auto& hash : inputs) {
83 std::optional<txiter> piter = GetIter(hash);
84 if (piter) {
85 ret.emplace_back(**piter);
86 }
87 }
88 return ret;
89}
90
91void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
92{
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 for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
98 // calculate children from mapNextTx
99 txiter it = mapTx.find(hash);
100 if (it == mapTx.end()) {
101 continue;
102 }
103 auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104 {
105 for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
106 txiter childIter = iter->second;
107 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 m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
111 }
112 }
113 }
114
115 auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
116 for (auto txptr : txs_to_remove) {
117 const CTxMemPoolEntry& entry = *(static_cast<const CTxMemPoolEntry*>(txptr));
118 removeUnchecked(mapTx.iterator_to(entry), MemPoolRemovalReason::SIZELIMIT);
119 }
120}
121
122bool CTxMemPool::HasDescendants(const Txid& txid) const
123{
124 LOCK(cs);
125 auto entry = GetEntry(txid);
126 if (!entry) return false;
127 return m_txgraph->GetDescendants(*entry, TxGraph::Level::MAIN).size() > 1;
128}
129
131{
132 auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
134 if (ancestors.size() > 0) {
135 for (auto ancestor : ancestors) {
136 if (ancestor != &entry) {
137 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 setEntries staged_parents;
146 const CTransaction &tx = entry.GetTx();
147
148 // Get parents of this transaction that are in the mempool
149 for (unsigned int i = 0; i < tx.vin.size(); i++) {
150 std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151 if (piter) {
152 staged_parents.insert(*piter);
153 }
154 }
155
156 for (const auto& parent : staged_parents) {
157 auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN);
158 for (auto ancestor : parent_ancestors) {
159 ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
160 }
161 }
162
163 return ret;
164}
165
167{
168 opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169 int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170 if (opts.max_size_bytes < 0 || (opts.max_size_bytes > 0 && opts.max_size_bytes < cluster_limit_bytes)) {
171 error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(cluster_limit_bytes / 1'000'000.0));
172 }
173 return std::move(opts);
174}
175
177 : m_opts{Flatten(std::move(opts), error)}
178{
179 m_txgraph = MakeTxGraph(
180 /*max_cluster_count=*/m_opts.limits.cluster_count,
182 /*acceptable_cost=*/ACCEPTABLE_COST,
183 /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184 const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185 const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186 return txid_a <=> txid_b;
187 });
188}
189
190bool CTxMemPool::isSpent(const COutPoint& outpoint) const
191{
192 LOCK(cs);
193 return mapNextTx.count(outpoint);
194}
195
197{
199}
200
202{
204}
205
207{
209 m_txgraph->CommitStaging();
210
212
213 for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214 auto tx_entry = changeset->m_entry_vec[i];
215 // First splice this entry into mapTx.
216 auto node_handle = changeset->m_to_add.extract(tx_entry);
217 auto result = mapTx.insert(std::move(node_handle));
218
219 Assume(result.inserted);
220 txiter it = result.position;
221
223 }
224 if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
225 LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after addition(s).");
226 }
227}
228
230{
231 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 cachedInnerUsage += entry.DynamicMemoryUsage();
237
238 const CTransaction& tx = newit->GetTx();
239 for (unsigned int i = 0; i < tx.vin.size(); i++) {
240 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
250 totalTxSize += entry.GetTxSize();
251 m_total_fee += entry.GetFee();
252
253 txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
254 newit->idx_randomized = txns_randomized.size() - 1;
255
256 TRACEPOINT(mempool, added,
257 entry.GetTx().GetHash().data(),
258 entry.GetTxSize(),
259 entry.GetFee()
260 );
261}
262
264{
265 // We increment mempool sequence value no matter removal reason
266 // even if not directly reported below.
267 uint64_t mempool_sequence = GetAndIncrementSequence();
268
269 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 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 );
283
284 for (const CTxIn& txin : it->GetTx().vin)
285 mapNextTx.erase(txin.prevout);
286
287 RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
288
289 if (txns_randomized.size() > 1) {
290 // Remove entry from txns_randomized by replacing it with the back and deleting the back.
291 txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
292 txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
293 txns_randomized.pop_back();
294 if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
295 txns_randomized.shrink_to_fit();
296 }
297 } else {
298 txns_randomized.clear();
299 }
300
301 totalTxSize -= it->GetTxSize();
302 m_total_fee -= it->GetFee();
303 cachedInnerUsage -= it->DynamicMemoryUsage();
304 mapTx.erase(it);
306}
307
308// Calculates descendants of given entry and adds to setDescendants.
309void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
310{
311 (void)CalculateDescendants(*entryit, setDescendants);
312 return;
313}
314
316{
317 for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
318 setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
319 }
320 return mapTx.iterator_to(entry);
321}
322
324{
326 Assume(!m_have_changeset);
327 auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
328 for (auto tx: descendants) {
329 removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
330 }
331}
332
334{
335 // Remove transaction from memory pool
337 Assume(!m_have_changeset);
338 txiter origit = mapTx.find(origTx.GetHash());
339 if (origit != mapTx.end()) {
340 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 auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
347 std::vector<const TxGraph::Ref*> to_remove;
348 while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
349 to_remove.emplace_back(&*(iter->second));
350 ++iter;
351 }
352 auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
353 for (auto ref : all_removes) {
354 auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
355 removeUnchecked(tx, reason);
356 }
357 }
358}
359
360void 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
365 Assume(!m_have_changeset);
366
367 std::vector<const TxGraph::Ref*> to_remove;
368 for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
369 if (check_final_and_mature(it)) {
370 to_remove.emplace_back(&*it);
371 }
372 }
373
374 auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
375
376 for (auto ref : all_to_remove) {
377 auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
379 }
380 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
381 assert(TestLockPointValidity(chain, it->GetLockPoints()));
382 }
383 if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
384 LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after reorg.");
385 }
386}
387
389{
390 // Remove transactions which depend on inputs of tx, recursively
392 for (const CTxIn &txin : tx.vin) {
393 auto it = mapNextTx.find(txin.prevout);
394 if (it != mapNextTx.end()) {
395 const CTransaction &txConflict = it->second->GetTx();
396 if (Assume(txConflict.GetHash() != tx.GetHash()))
397 {
398 ClearPrioritisation(txConflict.GetHash());
400 }
401 }
402 }
403}
404
405void 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
409 Assume(!m_have_changeset);
410 std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
411 if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
412 txs_removed_for_block.reserve(vtx.size());
413 for (const auto& tx : vtx) {
414 txiter it = mapTx.find(tx->GetHash());
415 if (it != mapTx.end()) {
416 txs_removed_for_block.emplace_back(*it);
418 }
419 removeConflicts(*tx);
420 ClearPrioritisation(tx->GetHash());
421 }
422 }
423 if (m_opts.signals) {
424 m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
425 }
426 lastRollingFeeUpdate = GetTime();
427 blockSinceLastRollingFeeBump = true;
428 if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
429 LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after block.");
430 }
431}
432
433void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
434{
435 if (m_opts.check_ratio == 0) return;
436
437 if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
438
440 LOCK(cs);
441 LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
442
443 uint64_t checkTotal = 0;
444 CAmount check_total_fee{0};
445 CAmount check_total_modified_fee{0};
446 int64_t check_total_adjusted_weight{0};
447 uint64_t innerUsage = 0;
448
449 assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
450 m_txgraph->SanityCheck();
451
452 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
453
454 const auto score_with_topo{GetSortedScoreWithTopology()};
455
456 // Number of chunks is bounded by number of transactions.
457 const auto diagram{GetFeerateDiagram()};
458 assert(diagram.size() <= score_with_topo.size() + 1);
459 assert(diagram.size() >= 1);
460
461 std::optional<txiter> last_iter = std::nullopt;
462 auto diagram_iter = diagram.cbegin();
463
464 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 assert(diagram_iter->size >= check_total_adjusted_weight);
472 if (diagram_iter->fee == check_total_modified_fee &&
473 diagram_iter->size == check_total_adjusted_weight) {
474 ++diagram_iter;
475 }
476 checkTotal += it->GetTxSize();
477 check_total_adjusted_weight += it->GetAdjustedWeight();
478 check_total_fee += it->GetFee();
479 check_total_modified_fee += it->GetModifiedFee();
480 innerUsage += it->DynamicMemoryUsage();
481 const CTransaction& tx = it->GetTx();
482
483 if (last_iter) {
484 assert(m_txgraph->CompareMainOrder(**last_iter, *it) < 0);
485 }
486 last_iter = it;
487
488 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
489 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
490 for (const CTxIn &txin : tx.vin) {
491 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
492 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
493 if (it2 != mapTx.end()) {
494 const CTransaction& tx2 = it2->GetTx();
495 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
496 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 assert(mempoolDuplicate.HaveCoin(txin.prevout));
503 // Check whether its inputs are marked in mapNextTx.
504 auto it3 = mapNextTx.find(txin.prevout);
505 assert(it3 != mapNextTx.end());
506 assert(it3->first == &txin.prevout);
507 assert(&it3->second->GetTx() == &tx);
508 }
509 auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
510 return a.GetTx().GetHash() == b.GetTx().GetHash();
511 };
512 for (auto &txentry : GetParents(*it)) {
513 setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
514 }
515 assert(setParentCheck.size() == setParentsStored.size());
516 assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
517
518 // Check children against mapNextTx
519 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
520 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
521 auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
522 for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
523 txiter childit = iter->second;
524 assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
525 setChildrenCheck.insert(*childit);
526 }
527 for (auto &txentry : GetChildren(*it)) {
528 setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
529 }
530 assert(setChildrenCheck.size() == setChildrenStored.size());
531 assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
532
533 TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
534 CAmount txfee = 0;
535 assert(!tx.IsCoinBase());
536 assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
537 for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
538 AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
539 }
540 for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
541 indexed_transaction_set::const_iterator it2 = it->second;
542 assert(it2 != mapTx.end());
543 }
544
545 ++diagram_iter;
546 assert(diagram_iter == diagram.cend());
547
548 assert(totalTxSize == checkTotal);
549 assert(m_total_fee == check_total_fee);
550 assert(diagram.back().fee == check_total_modified_fee);
551 assert(diagram.back().size == check_total_adjusted_weight);
552 assert(innerUsage == cachedInnerUsage);
553}
554
555std::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 auto cmp = [&](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept { return m_txgraph->CompareMainOrder(*a, *b) < 0; };
573
574 std::vector<txiter> res;
575
576 n_to_sort = std::min(wtxids.size(), n_to_sort);
577 if (n_to_sort > 0) {
578 res.reserve(wtxids.size());
579 std::sort(wtxids.begin(), wtxids.end());
580 for (auto it = wtxids.begin(); it != wtxids.end(); ++it) {
581 // skip duplicates
582 auto itnext = it + 1;
583 if (itnext != wtxids.end() && *it == *itnext) continue;
584
585 if (auto i{GetIter(*it)}; i.has_value()) {
586 res.push_back(i.value());
587 }
588 }
589 wtxids.clear();
590
591 if (!res.empty()) {
592 auto begin = res.begin();
593 auto end = res.end();
594 auto middle = end;
595 if (n_to_sort >= res.size()) {
596 // use regular sort when sorting everything
597 std::sort(begin, end, cmp);
598 } else {
599 middle = begin + n_to_sort;
600 std::partial_sort(begin, middle, end, cmp);
601 }
602 auto it = middle;
603 while (it != end) {
604 wtxids.push_back((*it)->GetTx().GetWitnessHash());
605 ++it;
606 }
607 res.erase(middle, end);
608 }
609 }
610 return res;
611}
612
613std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
614{
615 std::vector<indexed_transaction_set::const_iterator> iters;
617
618 iters.reserve(mapTx.size());
619
620 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
621 iters.push_back(mi);
622 }
623 std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
624 return m_txgraph->CompareMainOrder(*a, *b) < 0;
625 });
626 return iters;
627}
628
629std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
630{
632
633 std::vector<CTxMemPoolEntryRef> ret;
634 ret.reserve(mapTx.size());
635 for (const auto& it : GetSortedScoreWithTopology()) {
636 ret.emplace_back(*it);
637 }
638 return ret;
639}
640
641std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
642{
643 LOCK(cs);
644 auto iters = GetSortedScoreWithTopology();
645
646 std::vector<TxMempoolInfo> ret;
647 ret.reserve(mapTx.size());
648 for (auto it : iters) {
649 ret.push_back(GetInfo(it));
650 }
651
652 return ret;
653}
654
656{
658 const auto i = mapTx.find(txid);
659 return i == mapTx.end() ? nullptr : &(*i);
660}
661
663{
664 LOCK(cs);
665 indexed_transaction_set::const_iterator i = mapTx.find(hash);
666 if (i == mapTx.end())
667 return nullptr;
668 return i->GetSharedTx();
669}
670
672{
673 LOCK(cs);
674 const auto& wtxid_map{mapTx.get<index_by_wtxid>()};
675 const auto it{wtxid_map.find(hash)};
676 if (it == wtxid_map.end()) return nullptr;
677 return it->GetSharedTx();
678}
679
680void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
681{
682 {
683 LOCK(cs);
684 CAmount &delta = mapDeltas[hash];
685 delta = SaturatingAdd(delta, nFeeDelta);
686 txiter it = mapTx.find(hash);
687 if (it != mapTx.end()) {
688 // PrioritiseTransaction calls stack on previous ones. Set the new
689 // transaction fee to be current modified fee + feedelta.
690 it->UpdateModifiedFee(nFeeDelta);
691 m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
693 }
694 if (delta == 0) {
695 mapDeltas.erase(hash);
696 LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
697 } else {
698 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 }
705}
706
707void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
708{
710 std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
711 if (pos == mapDeltas.end())
712 return;
713 const CAmount &delta = pos->second;
714 nFeeDelta += delta;
715}
716
718{
720 mapDeltas.erase(hash);
721}
722
723std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
724{
726 LOCK(cs);
727 std::vector<delta_info> result;
728 result.reserve(mapDeltas.size());
729 for (const auto& [txid, delta] : mapDeltas) {
730 const auto iter{mapTx.find(txid)};
731 const bool in_mempool{iter != mapTx.end()};
732 std::optional<CAmount> modified_fee;
733 if (in_mempool) modified_fee = iter->GetModifiedFee();
734 result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
735 }
736 return result;
737}
738
740{
741 const auto it = mapNextTx.find(prevout);
742 return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
743}
744
745std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
746{
748 auto it = mapTx.find(txid);
749 return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
750}
751
752std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
753{
755 auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
756 return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
757}
758
759CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
760{
762 for (const auto& h : hashes) {
763 const auto mi = GetIter(h);
764 if (mi) ret.insert(*mi);
765 }
766 return ret;
767}
768
769std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
770{
772 std::vector<txiter> ret;
773 ret.reserve(txids.size());
774 for (const auto& txid : txids) {
775 const auto it{GetIter(txid)};
776 if (!it) return {};
777 ret.push_back(*it);
778 }
779 return ret;
780}
781
783{
784 for (unsigned int i = 0; i < tx.vin.size(); i++)
785 if (exists(tx.vin[i].prevout.hash))
786 return false;
787 return true;
788}
789
790CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
791
792std::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 if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
797 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 CTransactionRef ptx = mempool.get(outpoint.hash);
804 if (ptx) {
805 if (outpoint.n < ptx->vout.size()) {
806 Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
807 m_non_base_coins.emplace(outpoint);
808 return coin;
809 }
810 return std::nullopt;
811 }
812 return base->GetCoin(outpoint);
813}
814
816{
817 for (unsigned int n = 0; n < tx->vout.size(); ++n) {
818 m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
819 m_non_base_coins.emplace(tx->GetHash(), n);
820 }
821}
823{
824 m_temp_added.clear();
825 m_non_base_coins.clear();
826}
827
829 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 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}
833
834void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
835 LOCK(cs);
836
837 if (m_unbroadcast_txids.erase(txid))
838 {
839 LogDebug(BCLog::MEMPOOL, "Removed %s from set of unbroadcast txns%s", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
840 }
841}
842
845 for (txiter it : stage) {
846 removeUnchecked(it, reason);
847 }
848}
849
851{
852 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 auto changeset = GetChangeSet();
857 (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
858 return changeset->CheckMemPoolPolicyLimits();
859}
860
861int CTxMemPool::Expire(std::chrono::seconds time)
862{
864 Assume(!m_have_changeset);
865 indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
866 setEntries toremove;
867 while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
868 toremove.insert(mapTx.project<0>(it));
869 it++;
870 }
871 setEntries stage;
872 for (txiter removeit : toremove) {
873 CalculateDescendants(removeit, stage);
874 }
876 return stage.size();
877}
878
879CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
880 LOCK(cs);
881 if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
882 return CFeeRate(llround(rollingMinimumFeeRate));
883
884 int64_t time = GetTime();
885 if (time > lastRollingFeeUpdate + 10) {
886 double halflife = ROLLING_FEE_HALFLIFE;
887 if (DynamicMemoryUsage() < sizelimit / 4)
888 halflife /= 4;
889 else if (DynamicMemoryUsage() < sizelimit / 2)
890 halflife /= 2;
891
892 rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
893 lastRollingFeeUpdate = time;
894
895 if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
896 rollingMinimumFeeRate = 0;
897 return CFeeRate(0);
898 }
899 }
900 return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
901}
902
905 if (rate.GetFeePerK() > rollingMinimumFeeRate) {
906 rollingMinimumFeeRate = rate.GetFeePerK();
907 blockSinceLastRollingFeeBump = false;
908 }
909}
910
911void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
913 Assume(!m_have_changeset);
914
915 unsigned nTxnRemoved = 0;
916 CFeeRate maxFeeRateRemoved(0);
917
918 while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
919 const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
920 FeePerVSize feerate = ToFeePerVSize(feeperweight);
921 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.
928 trackPackageRemoved(removed);
929 maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
930
931 nTxnRemoved += worst_chunk.size();
932
933 std::vector<CTransaction> txn;
934 if (pvNoSpendsRemaining) {
935 txn.reserve(worst_chunk.size());
936 for (auto ref : worst_chunk) {
937 txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
938 }
939 }
940
941 setEntries stage;
942 for (auto ref : worst_chunk) {
943 stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
944 }
945 for (auto e : stage) {
947 }
948 if (pvNoSpendsRemaining) {
949 for (const CTransaction& tx : txn) {
950 for (const CTxIn& txin : tx.vin) {
951 if (exists(txin.prevout.hash)) continue;
952 pvNoSpendsRemaining->push_back(txin.prevout);
953 }
954 }
955 }
956 }
957
958 if (maxFeeRateRemoved > CFeeRate(0)) {
959 LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
960 }
961}
962
963std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
964{
965 auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
966
967 size_t ancestor_count = ancestors.size();
968 size_t ancestor_size = 0;
969 CAmount ancestor_fees = 0;
970 for (auto tx: ancestors) {
971 const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
972 ancestor_size += anc.GetTxSize();
973 ancestor_fees += anc.GetModifiedFee();
974 }
975 return {ancestor_count, ancestor_size, ancestor_fees};
976}
977
978std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
979{
980 auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
981 size_t descendant_count = descendants.size();
982 size_t descendant_size = 0;
983 CAmount descendant_fees = 0;
984
985 for (auto tx: descendants) {
986 const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
987 descendant_size += desc.GetTxSize();
988 descendant_fees += desc.GetModifiedFee();
989 }
990 return {descendant_count, descendant_size, descendant_fees};
991}
992
993void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
994 LOCK(cs);
995 auto it = mapTx.find(txid);
996 ancestors = cluster_count = 0;
997 if (it != mapTx.end()) {
998 auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
999 ancestors = ancestor_count;
1000 if (ancestorsize) *ancestorsize = ancestor_size;
1001 if (ancestorfees) *ancestorfees = ancestor_fees;
1002 cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
1003 }
1004}
1005
1007{
1008 LOCK(cs);
1009 return m_load_tried;
1010}
1011
1012void CTxMemPool::SetLoadTried(bool load_tried)
1013{
1014 LOCK(cs);
1015 m_load_tried = load_tried;
1016}
1017
1018std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
1019{
1021
1022 std::vector<CTxMemPool::txiter> ret;
1023 std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
1024 for (auto txid : txids) {
1025 auto it = mapTx.find(txid);
1026 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 auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
1031 if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
1032 for (auto tx : cluster) {
1033 ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
1034 }
1035 }
1036 }
1037 }
1038 if (ret.size() > 500) {
1039 return {};
1040 }
1041 return ret;
1042}
1043
1045{
1046 LOCK(m_pool->cs);
1047
1048 if (!CheckMemPoolPolicyLimits()) {
1049 return util::Error{Untranslated("cluster size limit exceeded")};
1050 }
1051
1052 return m_pool->m_txgraph->GetMainStagingDiagrams();
1053}
1054
1055CTxMemPool::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 LOCK(m_pool->cs);
1058 Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1059 Assume(!m_dependencies_processed);
1060
1061 // We need to process dependencies after adding a new transaction.
1062 m_dependencies_processed = false;
1063
1064 CAmount delta{0};
1065 m_pool->ApplyDelta(tx->GetHash(), delta);
1066
1068 auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1069 m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1070 if (delta) {
1071 newit->UpdateModifiedFee(delta);
1072 m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1073 }
1074
1075 m_entry_vec.push_back(newit);
1076
1077 return newit;
1078}
1079
1081{
1082 LOCK(m_pool->cs);
1083 m_pool->m_txgraph->RemoveTransaction(*it);
1084 m_to_remove.insert(it);
1085}
1086
1088{
1089 LOCK(m_pool->cs);
1090 if (!m_dependencies_processed) {
1091 ProcessDependencies();
1092 }
1093 m_pool->Apply(this);
1094 m_to_add.clear();
1095 m_to_remove.clear();
1096 m_entry_vec.clear();
1097 m_ancestors.clear();
1098}
1099
1101{
1102 LOCK(m_pool->cs);
1103 Assume(!m_dependencies_processed); // should only call this once.
1104 for (const auto& entryptr : m_entry_vec) {
1105 for (const auto &txin : entryptr->GetSharedTx()->vin) {
1106 std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1107 if (!piter) {
1108 auto it = m_to_add.find(txin.prevout.hash);
1109 if (it != m_to_add.end()) {
1110 piter = std::make_optional(it);
1111 }
1112 }
1113 if (piter) {
1114 m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1115 }
1116 }
1117 }
1118 m_dependencies_processed = true;
1119 return;
1120 }
1121
1123{
1124 LOCK(m_pool->cs);
1125 if (!m_dependencies_processed) {
1126 ProcessDependencies();
1127 }
1128
1129 return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1130}
1131
1132std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1133{
1134 FeePerWeight zero{};
1135 std::vector<FeePerWeight> ret;
1136
1137 ret.emplace_back(zero);
1138
1140
1141 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1142
1143 FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1144 while (last_selection != FeePerWeight{}) {
1145 last_selection += ret.back();
1146 ret.emplace_back(last_selection);
1148 last_selection = GetBlockBuilderChunk(dummy);
1149 }
1151 return ret;
1152}
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static void pool cs
int ret
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
An in-memory indexed chain of blocks.
Definition: chain.h:380
bool Contains(const CBlockIndex &index) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:410
CCoinsView backed by another CCoinsView.
Definition: coins.h:416
CCoinsView * base
Definition: coins.h:418
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:437
Pure abstract view on the open txout dataset.
Definition: coins.h:356
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const =0
Retrieve the Coin (unspent transaction output) for a given outpoint.
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
GetCoin, returning whether it exists and is not spent.
Definition: txmempool.cpp:792
void Reset()
Clear m_temp_added and m_non_base_coins.
Definition: txmempool.cpp:822
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
Definition: txmempool.h:782
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:790
std::unordered_set< COutPoint, SaltedOutpointHasher > m_non_base_coins
Set of all coins that have been fetched from mempool or created using PackageAddTransaction (not base...
Definition: txmempool.h:788
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
Definition: txmempool.cpp:815
const CTxMemPool & mempool
Definition: txmempool.h:790
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
std::string ToString(FeeRateFormat fee_rate_format=FeeRateFormat::BTC_KVB) const
Definition: feerate.cpp:29
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
Definition: feerate.h:62
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
uint32_t n
Definition: transaction.h:32
Txid hash
Definition: transaction.h:31
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:281
const std::vector< CTxOut > vout
Definition: transaction.h:292
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:329
bool IsCoinBase() const
Definition: transaction.h:341
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:328
const std::vector< CTxIn > vin
Definition: transaction.h:291
An input of a transaction.
Definition: transaction.h:62
COutPoint prevout
Definition: transaction.h:64
CTxMemPool::setEntries m_to_remove
Definition: txmempool.h:713
void Apply() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: txmempool.cpp:1087
CTxMemPool * m_pool
Definition: txmempool.h:708
void StageRemoval(CTxMemPool::txiter it)
Definition: txmempool.cpp:1080
util::Result< std::pair< std::vector< FeeFrac >, std::vector< FeeFrac > > > CalculateChunksForRBF()
Calculate the sorted chunks for the old and new mempool relating to the clusters that would be affect...
Definition: txmempool.cpp:1044
CTxMemPool::txiter TxHandle
Definition: txmempool.h:658
CTxMemPool::indexed_transaction_set m_to_add
Definition: txmempool.h:709
TxHandle StageAddition(const CTransactionRef &tx, CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp)
Definition: txmempool.cpp:1055
bool CheckMemPoolPolicyLimits()
Check if any cluster limits are exceeded.
Definition: txmempool.cpp:1122
std::vector< CTxMemPool::txiter > m_entry_vec
Definition: txmempool.h:710
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:66
const CTransaction & GetTx() const
size_t DynamicMemoryUsage() const
int32_t GetTxSize() const
const CAmount & GetFee() const
CAmount GetModifiedFee() const
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:187
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:388
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:189
void Apply(CTxMemPool::ChangeSet *changeset) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:206
void PrioritiseTransaction(const Txid &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:680
std::unique_ptr< ChangeSet > GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:719
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.h:286
bool HasNoInputsOf(const CTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
Definition: txmempool.cpp:782
setEntries GetIterSet(const std::set< Txid > &hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of hashes into a set of pool iterators to avoid repeated lookups.
Definition: txmempool.cpp:759
void ClearPrioritisation(const Txid &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:717
std::optional< txiter > GetIter(const Txid &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:745
bool GetLoadTried() const
Definition: txmempool.cpp:1006
void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:760
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.h:462
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:903
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.h:323
void TrimToSize(size_t sizelimit, std::vector< COutPoint > *pvNoSpendsRemaining=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
Definition: txmempool.cpp:911
void GetTransactionAncestry(const Txid &txid, size_t &ancestors, size_t &cluster_count, size_t *ancestorsize=nullptr, CAmount *ancestorfees=nullptr) const
Calculate the ancestor and cluster count for the given transaction.
Definition: txmempool.cpp:993
void UpdateTransactionsFromBlock(const std::vector< Txid > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
UpdateTransactionsFromBlock is called when adding transactions from a disconnected block back to the ...
Definition: txmempool.cpp:91
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:201
bool HasDescendants(const Txid &txid) const
Definition: txmempool.cpp:122
std::vector< indexed_transaction_set::const_iterator > GetSortedScoreWithTopology() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:613
void StartBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:744
CTransactionRef get(const Txid &hash) const
Return a mempool transaction with a given hash.
Definition: txmempool.cpp:662
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:828
const Options m_opts
Definition: txmempool.h:301
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:641
static constexpr int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:212
CTxMemPool(Options opts, bilingual_str &error)
Create a new CTxMemPool.
Definition: txmempool.cpp:176
void addNewTransaction(CTxMemPool::txiter it) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:229
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:263
int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Expire all transaction (and their dependencies) in the mempool older than time.
Definition: txmempool.cpp:861
void IncludeBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:758
void removeForReorg(CChain &chain, std::function< bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs
After reorg, filter the entries that would no longer be valid in the next block, and update the entri...
Definition: txmempool.cpp:360
std::vector< FeePerWeight > GetFeerateDiagram() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1132
std::tuple< size_t, size_t, CAmount > CalculateDescendantData(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:978
bool exists(const Txid &txid) const
Definition: txmempool.h:513
std::vector< txiter > GetIterVec(const std::vector< Txid > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
Definition: txmempool.cpp:769
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:266
std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > GetParents(const CTxMemPoolEntry &entry) const
Definition: txmempool.cpp:74
void ApplyDelta(const Txid &hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:707
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:405
std::vector< delta_info > GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return a vector of all entries in mapDeltas with their corresponding delta_info.
Definition: txmempool.cpp:723
std::vector< txiter > GatherClusters(const std::vector< Txid > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Collect the entire cluster of connected transactions for each transaction in txids.
Definition: txmempool.cpp:1018
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:263
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:594
bool CheckPolicyLimits(const CTransactionRef &tx)
Definition: txmempool.cpp:850
const CTransaction * GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
Definition: txmempool.cpp:739
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of given transaction.
Definition: txmempool.cpp:309
std::tuple< size_t, size_t, CAmount > CalculateAncestorData(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:963
std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > GetChildren(const CTxMemPoolEntry &entry) const
Definition: txmempool.cpp:57
setEntries CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Calculate all in-mempool ancestors of entry (not including the tx itself)
Definition: txmempool.cpp:130
void RemoveUnbroadcastTx(const Txid &txid, bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:834
void cs_main
Definition: txmempool.h:331
std::vector< txiter > ExtractBestByMiningScoreWithTopology(std::vector< Wtxid > &wtxids, size_t n_to_sort) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Look up wtxids in the mempool and (partially) sort by mining score.
Definition: txmempool.cpp:555
void SetLoadTried(bool load_tried)
Set whether or not an initial attempt to load the persisted mempool was made (regardless of whether t...
Definition: txmempool.cpp:1012
void RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:843
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:629
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:190
FeePerWeight GetBlockBuilderChunk(std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &entries) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:745
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:655
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:196
A UTXO entry.
Definition: coins.h:46
Fast randomness source.
Definition: random.h:386
@ MAIN
Always refers to the main graph, whether staging is present or not.
@ TOP
Refers to staging if it exists, main otherwise.
void MempoolTransactionsRemovedForBlock(const std::vector< RemovedMempoolTransactionInfo > &, unsigned int nBlockHeight)
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)
std::string ToString() const
std::string GetHex() const
constexpr const std::byte * data() const
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
Definition: coins.cpp:133
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:132
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define LogInfo(...)
Definition: log.h:125
#define LogDebug(category,...)
Definition: log.h:143
uint64_t fee
LockPoints lp
std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
@ SIZELIMIT
Removed in size limiting.
@ BLOCK
Removed for block.
@ EXPIRY
Expired from mempool.
@ REPLACED
Removed for replacement.
@ CONFLICT
Removed for conflict with in-block transaction.
@ REORG
Removed for reorganization.
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:19
@ MEMPOOL
Definition: categories.h:18
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:164
T check(T ptr)
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:31
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
Definition: memusage.h:52
T SaturatingAdd(const T i, const T j) noexcept
Definition: overflow.h:44
unsigned int nBytesPerSigOp
Definition: settings.cpp:10
int64_t GetSigOpsAdjustedWeight(int64_t weight, int64_t sigop_cost, unsigned int bytes_per_sigop)
Definition: policy.cpp:390
static FeePerVSize ToFeePerVSize(FeePerWeight feerate)
Definition: policy.h:197
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
int64_t fee
Definition: feefrac.h:89
int32_t size
Definition: feefrac.h:90
CBlockIndex * maxInputBlock
Definition: mempool_entry.h:35
Bilingual messages:
Definition: translation.h:24
unsigned cluster_count
The maximum number of transactions in a cluster.
int64_t cluster_size_vbytes
The maximum allowed size in virtual bytes of a cluster.
Options struct containing options for constructing a CTxMemPool.
ValidationSignals * signals
CFeeRate incremental_relay_feerate
#define AssertLockNotHeld(cs)
Definition: sync.h:149
#define LOCK(cs)
Definition: sync.h:268
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
#define TRACEPOINT(context,...)
Definition: trace.h:56
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:82
std::unique_ptr< TxGraph > MakeTxGraph(unsigned max_cluster_count, uint64_t max_cluster_size, uint64_t acceptable_cost, const std::function< std::strong_ordering(const TxGraph::Ref &, const TxGraph::Ref &)> &fallback_order) noexcept
Construct a new TxGraph with the specified limit on the number of transactions within a cluster,...
Definition: txgraph.cpp:3583
static CTxMemPool::Options && Flatten(CTxMemPool::Options &&opts, bilingual_str &error)
Definition: txmempool.cpp:166
TRACEPOINT_SEMAPHORE(mempool, added)
bool TestLockPointValidity(CChain &active_chain, const LockPoints &lp)
Test whether the LockPoints height and time are still valid on the current chain.
Definition: txmempool.cpp:40
static constexpr uint64_t ACCEPTABLE_COST
How much linearization cost required for TxGraph clusters to have "acceptable" quality,...
Definition: txmempool.h:54
static constexpr uint64_t POST_CHANGE_COST
How much work we ask TxGraph to do after a mempool change occurs (either due to a changeset being app...
Definition: txmempool.h:58
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
Definition: txmempool.h:50
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:89
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())