Bitcoin Core 30.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 <logging.h>
15#include <policy/policy.h>
16#include <policy/settings.h>
17#include <random.h>
18#include <tinyformat.h>
19#include <util/check.h>
20#include <util/feefrac.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{
180}
181
182bool CTxMemPool::isSpent(const COutPoint& outpoint) const
183{
184 LOCK(cs);
185 return mapNextTx.count(outpoint);
186}
187
189{
191}
192
194{
196}
197
199{
201 m_txgraph->CommitStaging();
202
204
205 for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
206 auto tx_entry = changeset->m_entry_vec[i];
207 // First splice this entry into mapTx.
208 auto node_handle = changeset->m_to_add.extract(tx_entry);
209 auto result = mapTx.insert(std::move(node_handle));
210
211 Assume(result.inserted);
212 txiter it = result.position;
213
215 }
216 m_txgraph->DoWork(POST_CHANGE_WORK);
217}
218
220{
221 const CTxMemPoolEntry& entry = *newit;
222
223 // Update cachedInnerUsage to include contained transaction's usage.
224 // (When we update the entry for in-mempool parents, memory usage will be
225 // further updated.)
226 cachedInnerUsage += entry.DynamicMemoryUsage();
227
228 const CTransaction& tx = newit->GetTx();
229 for (unsigned int i = 0; i < tx.vin.size(); i++) {
230 mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit));
231 }
232 // Don't bother worrying about child transactions of this one.
233 // Normal case of a new transaction arriving is that there can't be any
234 // children, because such children would be orphans.
235 // An exception to that is if a transaction enters that used to be in a block.
236 // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
237 // to clean up the mess we're leaving here.
238
240 totalTxSize += entry.GetTxSize();
241 m_total_fee += entry.GetFee();
242
243 txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
244 newit->idx_randomized = txns_randomized.size() - 1;
245
246 TRACEPOINT(mempool, added,
247 entry.GetTx().GetHash().data(),
248 entry.GetTxSize(),
249 entry.GetFee()
250 );
251}
252
254{
255 // We increment mempool sequence value no matter removal reason
256 // even if not directly reported below.
257 uint64_t mempool_sequence = GetAndIncrementSequence();
258
259 if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
260 // Notify clients that a transaction has been removed from the mempool
261 // for any reason except being included in a block. Clients interested
262 // in transactions included in blocks can subscribe to the BlockConnected
263 // notification.
264 m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
265 }
266 TRACEPOINT(mempool, removed,
267 it->GetTx().GetHash().data(),
268 RemovalReasonToString(reason).c_str(),
269 it->GetTxSize(),
270 it->GetFee(),
271 std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
272 );
273
274 for (const CTxIn& txin : it->GetTx().vin)
275 mapNextTx.erase(txin.prevout);
276
277 RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
278
279 if (txns_randomized.size() > 1) {
280 // Remove entry from txns_randomized by replacing it with the back and deleting the back.
281 txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
282 txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
283 txns_randomized.pop_back();
284 if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
285 txns_randomized.shrink_to_fit();
286 }
287 } else {
288 txns_randomized.clear();
289 }
290
291 totalTxSize -= it->GetTxSize();
292 m_total_fee -= it->GetFee();
293 cachedInnerUsage -= it->DynamicMemoryUsage();
294 mapTx.erase(it);
296}
297
298// Calculates descendants of given entry and adds to setDescendants.
299void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
300{
301 (void)CalculateDescendants(*entryit, setDescendants);
302 return;
303}
304
306{
307 for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
308 setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
309 }
310 return mapTx.iterator_to(entry);
311}
312
314{
316 Assume(!m_have_changeset);
317 auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
318 for (auto tx: descendants) {
319 removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
320 }
321}
322
324{
325 // Remove transaction from memory pool
327 Assume(!m_have_changeset);
328 txiter origit = mapTx.find(origTx.GetHash());
329 if (origit != mapTx.end()) {
330 removeRecursive(origit, reason);
331 } else {
332 // When recursively removing but origTx isn't in the mempool
333 // be sure to remove any descendants that are in the pool. This can
334 // happen during chain re-orgs if origTx isn't re-accepted into
335 // the mempool for any reason.
336 auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
337 std::vector<const TxGraph::Ref*> to_remove;
338 while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
339 to_remove.emplace_back(&*(iter->second));
340 ++iter;
341 }
342 auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
343 for (auto ref : all_removes) {
344 auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
345 removeUnchecked(tx, reason);
346 }
347 }
348}
349
350void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
351{
352 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
355 Assume(!m_have_changeset);
356
357 std::vector<const TxGraph::Ref*> to_remove;
358 for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
359 if (check_final_and_mature(it)) {
360 to_remove.emplace_back(&*it);
361 }
362 }
363
364 auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
365
366 for (auto ref : all_to_remove) {
367 auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
369 }
370 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
371 assert(TestLockPointValidity(chain, it->GetLockPoints()));
372 }
373 m_txgraph->DoWork(POST_CHANGE_WORK);
374}
375
377{
378 // Remove transactions which depend on inputs of tx, recursively
380 for (const CTxIn &txin : tx.vin) {
381 auto it = mapNextTx.find(txin.prevout);
382 if (it != mapNextTx.end()) {
383 const CTransaction &txConflict = it->second->GetTx();
384 if (Assume(txConflict.GetHash() != tx.GetHash()))
385 {
386 ClearPrioritisation(txConflict.GetHash());
388 }
389 }
390 }
391}
392
393void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
394{
395 // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
397 Assume(!m_have_changeset);
398 std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
399 if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
400 txs_removed_for_block.reserve(vtx.size());
401 for (const auto& tx : vtx) {
402 txiter it = mapTx.find(tx->GetHash());
403 if (it != mapTx.end()) {
404 txs_removed_for_block.emplace_back(*it);
406 }
407 removeConflicts(*tx);
408 ClearPrioritisation(tx->GetHash());
409 }
410 }
411 if (m_opts.signals) {
412 m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
413 }
414 lastRollingFeeUpdate = GetTime();
415 blockSinceLastRollingFeeBump = true;
416 m_txgraph->DoWork(POST_CHANGE_WORK);
417}
418
419void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
420{
421 if (m_opts.check_ratio == 0) return;
422
423 if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
424
426 LOCK(cs);
427 LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
428
429 uint64_t checkTotal = 0;
430 CAmount check_total_fee{0};
431 CAmount check_total_modified_fee{0};
432 int64_t check_total_adjusted_weight{0};
433 uint64_t innerUsage = 0;
434
435 assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
436 m_txgraph->SanityCheck();
437
438 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
439
440 const auto score_with_topo{GetSortedScoreWithTopology()};
441
442 // Number of chunks is bounded by number of transactions.
443 const auto diagram{GetFeerateDiagram()};
444 assert(diagram.size() <= score_with_topo.size() + 1);
445 assert(diagram.size() >= 1);
446
447 std::optional<Wtxid> last_wtxid = std::nullopt;
448 auto diagram_iter = diagram.cbegin();
449
450 for (const auto& it : score_with_topo) {
451 // GetSortedScoreWithTopology() contains the same chunks as the feerate
452 // diagram. We do not know where the chunk boundaries are, but we can
453 // check that there are points at which they match the cumulative fee
454 // and weight.
455 // The feerate diagram should never get behind the current transaction
456 // size totals.
457 assert(diagram_iter->size >= check_total_adjusted_weight);
458 if (diagram_iter->fee == check_total_modified_fee &&
459 diagram_iter->size == check_total_adjusted_weight) {
460 ++diagram_iter;
461 }
462 checkTotal += it->GetTxSize();
463 check_total_adjusted_weight += it->GetAdjustedWeight();
464 check_total_fee += it->GetFee();
465 check_total_modified_fee += it->GetModifiedFee();
466 innerUsage += it->DynamicMemoryUsage();
467 const CTransaction& tx = it->GetTx();
468
469 // CompareMiningScoreWithTopology should agree with GetSortedScoreWithTopology()
470 if (last_wtxid) {
472 }
473 last_wtxid = tx.GetWitnessHash();
474
475 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
476 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
477 for (const CTxIn &txin : tx.vin) {
478 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
479 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
480 if (it2 != mapTx.end()) {
481 const CTransaction& tx2 = it2->GetTx();
482 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
483 setParentCheck.insert(*it2);
484 }
485 // We are iterating through the mempool entries sorted
486 // topologically and by mining score. All parents must have been
487 // checked before their children and their coins added to the
488 // mempoolDuplicate coins cache.
489 assert(mempoolDuplicate.HaveCoin(txin.prevout));
490 // Check whether its inputs are marked in mapNextTx.
491 auto it3 = mapNextTx.find(txin.prevout);
492 assert(it3 != mapNextTx.end());
493 assert(it3->first == &txin.prevout);
494 assert(&it3->second->GetTx() == &tx);
495 }
496 auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
497 return a.GetTx().GetHash() == b.GetTx().GetHash();
498 };
499 for (auto &txentry : GetParents(*it)) {
500 setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
501 }
502 assert(setParentCheck.size() == setParentsStored.size());
503 assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
504
505 // Check children against mapNextTx
506 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
507 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
508 auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
509 for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
510 txiter childit = iter->second;
511 assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
512 setChildrenCheck.insert(*childit);
513 }
514 for (auto &txentry : GetChildren(*it)) {
515 setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
516 }
517 assert(setChildrenCheck.size() == setChildrenStored.size());
518 assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
519
520 TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
521 CAmount txfee = 0;
522 assert(!tx.IsCoinBase());
523 assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
524 for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
525 AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
526 }
527 for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
528 indexed_transaction_set::const_iterator it2 = it->second;
529 assert(it2 != mapTx.end());
530 }
531
532 ++diagram_iter;
533 assert(diagram_iter == diagram.cend());
534
535 assert(totalTxSize == checkTotal);
536 assert(m_total_fee == check_total_fee);
537 assert(diagram.back().fee == check_total_modified_fee);
538 assert(diagram.back().size == check_total_adjusted_weight);
539 assert(innerUsage == cachedInnerUsage);
540}
541
542bool CTxMemPool::CompareMiningScoreWithTopology(const Wtxid& hasha, const Wtxid& hashb) const
543{
544 /* Return `true` if hasha should be considered sooner than hashb, namely when:
545 * a is not in the mempool but b is, or
546 * both are in the mempool but a is sorted before b in the total mempool ordering
547 * (which takes dependencies and (chunk) feerates into account).
548 */
549 LOCK(cs);
550 auto j{GetIter(hashb)};
551 if (!j.has_value()) return false;
552 auto i{GetIter(hasha)};
553 if (!i.has_value()) return true;
554
555 return m_txgraph->CompareMainOrder(*i.value(), *j.value()) < 0;
556}
557
558std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
559{
560 std::vector<indexed_transaction_set::const_iterator> iters;
562
563 iters.reserve(mapTx.size());
564
565 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
566 iters.push_back(mi);
567 }
568 std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
569 return m_txgraph->CompareMainOrder(*a, *b) < 0;
570 });
571 return iters;
572}
573
574std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
575{
577
578 std::vector<CTxMemPoolEntryRef> ret;
579 ret.reserve(mapTx.size());
580 for (const auto& it : GetSortedScoreWithTopology()) {
581 ret.emplace_back(*it);
582 }
583 return ret;
584}
585
586std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
587{
588 LOCK(cs);
589 auto iters = GetSortedScoreWithTopology();
590
591 std::vector<TxMempoolInfo> ret;
592 ret.reserve(mapTx.size());
593 for (auto it : iters) {
594 ret.push_back(GetInfo(it));
595 }
596
597 return ret;
598}
599
601{
603 const auto i = mapTx.find(txid);
604 return i == mapTx.end() ? nullptr : &(*i);
605}
606
608{
609 LOCK(cs);
610 indexed_transaction_set::const_iterator i = mapTx.find(hash);
611 if (i == mapTx.end())
612 return nullptr;
613 return i->GetSharedTx();
614}
615
616void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
617{
618 {
619 LOCK(cs);
620 CAmount &delta = mapDeltas[hash];
621 delta = SaturatingAdd(delta, nFeeDelta);
622 txiter it = mapTx.find(hash);
623 if (it != mapTx.end()) {
624 // PrioritiseTransaction calls stack on previous ones. Set the new
625 // transaction fee to be current modified fee + feedelta.
626 it->UpdateModifiedFee(nFeeDelta);
627 m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
629 }
630 if (delta == 0) {
631 mapDeltas.erase(hash);
632 LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
633 } else {
634 LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
635 hash.ToString(),
636 it == mapTx.end() ? "not " : "",
637 FormatMoney(nFeeDelta),
638 FormatMoney(delta));
639 }
640 }
641}
642
643void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
644{
646 std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
647 if (pos == mapDeltas.end())
648 return;
649 const CAmount &delta = pos->second;
650 nFeeDelta += delta;
651}
652
654{
656 mapDeltas.erase(hash);
657}
658
659std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
660{
662 LOCK(cs);
663 std::vector<delta_info> result;
664 result.reserve(mapDeltas.size());
665 for (const auto& [txid, delta] : mapDeltas) {
666 const auto iter{mapTx.find(txid)};
667 const bool in_mempool{iter != mapTx.end()};
668 std::optional<CAmount> modified_fee;
669 if (in_mempool) modified_fee = iter->GetModifiedFee();
670 result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
671 }
672 return result;
673}
674
676{
677 const auto it = mapNextTx.find(prevout);
678 return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
679}
680
681std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
682{
684 auto it = mapTx.find(txid);
685 return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
686}
687
688std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
689{
691 auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
692 return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
693}
694
695CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
696{
698 for (const auto& h : hashes) {
699 const auto mi = GetIter(h);
700 if (mi) ret.insert(*mi);
701 }
702 return ret;
703}
704
705std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
706{
708 std::vector<txiter> ret;
709 ret.reserve(txids.size());
710 for (const auto& txid : txids) {
711 const auto it{GetIter(txid)};
712 if (!it) return {};
713 ret.push_back(*it);
714 }
715 return ret;
716}
717
719{
720 for (unsigned int i = 0; i < tx.vin.size(); i++)
721 if (exists(tx.vin[i].prevout.hash))
722 return false;
723 return true;
724}
725
726CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
727
728std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
729{
730 // Check to see if the inputs are made available by another tx in the package.
731 // These Coins would not be available in the underlying CoinsView.
732 if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
733 return it->second;
734 }
735
736 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
737 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
738 // transactions. First checking the underlying cache risks returning a pruned entry instead.
739 CTransactionRef ptx = mempool.get(outpoint.hash);
740 if (ptx) {
741 if (outpoint.n < ptx->vout.size()) {
742 Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
743 m_non_base_coins.emplace(outpoint);
744 return coin;
745 }
746 return std::nullopt;
747 }
748 return base->GetCoin(outpoint);
749}
750
752{
753 for (unsigned int n = 0; n < tx->vout.size(); ++n) {
754 m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
755 m_non_base_coins.emplace(tx->GetHash(), n);
756 }
757}
759{
760 m_temp_added.clear();
761 m_non_base_coins.clear();
762}
763
765 LOCK(cs);
766 // 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.
767 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
768}
769
770void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
771 LOCK(cs);
772
773 if (m_unbroadcast_txids.erase(txid))
774 {
775 LogDebug(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
776 }
777}
778
781 for (txiter it : stage) {
782 removeUnchecked(it, reason);
783 }
784}
785
787{
788 LOCK(cs);
789 // Use ChangeSet interface to check whether the cluster count
790 // limits would be violated. Note that the changeset will be destroyed
791 // when it goes out of scope.
792 auto changeset = GetChangeSet();
793 (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
794 return changeset->CheckMemPoolPolicyLimits();
795}
796
797int CTxMemPool::Expire(std::chrono::seconds time)
798{
800 Assume(!m_have_changeset);
801 indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
802 setEntries toremove;
803 while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
804 toremove.insert(mapTx.project<0>(it));
805 it++;
806 }
807 setEntries stage;
808 for (txiter removeit : toremove) {
809 CalculateDescendants(removeit, stage);
810 }
812 return stage.size();
813}
814
815CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
816 LOCK(cs);
817 if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
818 return CFeeRate(llround(rollingMinimumFeeRate));
819
820 int64_t time = GetTime();
821 if (time > lastRollingFeeUpdate + 10) {
822 double halflife = ROLLING_FEE_HALFLIFE;
823 if (DynamicMemoryUsage() < sizelimit / 4)
824 halflife /= 4;
825 else if (DynamicMemoryUsage() < sizelimit / 2)
826 halflife /= 2;
827
828 rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
829 lastRollingFeeUpdate = time;
830
831 if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
832 rollingMinimumFeeRate = 0;
833 return CFeeRate(0);
834 }
835 }
836 return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
837}
838
841 if (rate.GetFeePerK() > rollingMinimumFeeRate) {
842 rollingMinimumFeeRate = rate.GetFeePerK();
843 blockSinceLastRollingFeeBump = false;
844 }
845}
846
847void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
849 Assume(!m_have_changeset);
850
851 unsigned nTxnRemoved = 0;
852 CFeeRate maxFeeRateRemoved(0);
853
854 while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
855 const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
856 FeePerVSize feerate = ToFeePerVSize(feeperweight);
857 CFeeRate removed{feerate.fee, feerate.size};
858
859 // We set the new mempool min fee to the feerate of the removed set, plus the
860 // "minimum reasonable fee rate" (ie some value under which we consider txn
861 // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
862 // equal to txn which were removed with no block in between.
864 trackPackageRemoved(removed);
865 maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
866
867 nTxnRemoved += worst_chunk.size();
868
869 std::vector<CTransaction> txn;
870 if (pvNoSpendsRemaining) {
871 txn.reserve(worst_chunk.size());
872 for (auto ref : worst_chunk) {
873 txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
874 }
875 }
876
877 setEntries stage;
878 for (auto ref : worst_chunk) {
879 stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
880 }
881 for (auto e : stage) {
883 }
884 if (pvNoSpendsRemaining) {
885 for (const CTransaction& tx : txn) {
886 for (const CTxIn& txin : tx.vin) {
887 if (exists(txin.prevout.hash)) continue;
888 pvNoSpendsRemaining->push_back(txin.prevout);
889 }
890 }
891 }
892 }
893
894 if (maxFeeRateRemoved > CFeeRate(0)) {
895 LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
896 }
897}
898
899std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
900{
901 auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
902
903 size_t ancestor_count = ancestors.size();
904 size_t ancestor_size = 0;
905 CAmount ancestor_fees = 0;
906 for (auto tx: ancestors) {
907 const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
908 ancestor_size += anc.GetTxSize();
909 ancestor_fees += anc.GetModifiedFee();
910 }
911 return {ancestor_count, ancestor_size, ancestor_fees};
912}
913
914std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
915{
916 auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
917 size_t descendant_count = descendants.size();
918 size_t descendant_size = 0;
919 CAmount descendant_fees = 0;
920
921 for (auto tx: descendants) {
922 const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
923 descendant_size += desc.GetTxSize();
924 descendant_fees += desc.GetModifiedFee();
925 }
926 return {descendant_count, descendant_size, descendant_fees};
927}
928
929void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
930 LOCK(cs);
931 auto it = mapTx.find(txid);
932 ancestors = cluster_count = 0;
933 if (it != mapTx.end()) {
934 auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
935 ancestors = ancestor_count;
936 if (ancestorsize) *ancestorsize = ancestor_size;
937 if (ancestorfees) *ancestorfees = ancestor_fees;
938 cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
939 }
940}
941
943{
944 LOCK(cs);
945 return m_load_tried;
946}
947
948void CTxMemPool::SetLoadTried(bool load_tried)
949{
950 LOCK(cs);
951 m_load_tried = load_tried;
952}
953
954std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
955{
957
958 std::vector<CTxMemPool::txiter> ret;
959 std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
960 for (auto txid : txids) {
961 auto it = mapTx.find(txid);
962 if (it != mapTx.end()) {
963 // Note that TxGraph::GetCluster will return results in graph
964 // order, which is deterministic (as long as we are not modifying
965 // the graph).
966 auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
967 if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
968 for (auto tx : cluster) {
969 ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
970 }
971 }
972 }
973 }
974 if (ret.size() > 500) {
975 return {};
976 }
977 return ret;
978}
979
981{
982 LOCK(m_pool->cs);
983
985 return util::Error{Untranslated("cluster size limit exceeded")};
986 }
987
988 return m_pool->m_txgraph->GetMainStagingDiagrams();
989}
990
991CTxMemPool::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)
992{
993 LOCK(m_pool->cs);
994 Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
995 Assume(!m_dependencies_processed);
996
997 // We need to process dependencies after adding a new transaction.
998 m_dependencies_processed = false;
999
1000 CAmount delta{0};
1001 m_pool->ApplyDelta(tx->GetHash(), delta);
1002
1003 TxGraph::Ref ref(m_pool->m_txgraph->AddTransaction(FeePerWeight(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp))));
1004 auto newit = m_to_add.emplace(std::move(ref), tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1005 if (delta) {
1006 newit->UpdateModifiedFee(delta);
1007 m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1008 }
1009
1010 m_entry_vec.push_back(newit);
1011
1012 return newit;
1013}
1014
1016{
1017 LOCK(m_pool->cs);
1018 m_pool->m_txgraph->RemoveTransaction(*it);
1019 m_to_remove.insert(it);
1020}
1021
1023{
1024 LOCK(m_pool->cs);
1025 if (!m_dependencies_processed) {
1026 ProcessDependencies();
1027 }
1028 m_pool->Apply(this);
1029 m_to_add.clear();
1030 m_to_remove.clear();
1031 m_entry_vec.clear();
1032 m_ancestors.clear();
1033}
1034
1036{
1037 LOCK(m_pool->cs);
1038 Assume(!m_dependencies_processed); // should only call this once.
1039 for (const auto& entryptr : m_entry_vec) {
1040 for (const auto &txin : entryptr->GetSharedTx()->vin) {
1041 std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1042 if (!piter) {
1043 auto it = m_to_add.find(txin.prevout.hash);
1044 if (it != m_to_add.end()) {
1045 piter = std::make_optional(it);
1046 }
1047 }
1048 if (piter) {
1049 m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1050 }
1051 }
1052 }
1053 m_dependencies_processed = true;
1054 return;
1055 }
1056
1058{
1059 LOCK(m_pool->cs);
1060 if (!m_dependencies_processed) {
1061 ProcessDependencies();
1062 }
1063
1064 return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1065}
1066
1067std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1068{
1069 FeePerWeight zero{};
1070 std::vector<FeePerWeight> ret;
1071
1072 ret.emplace_back(zero);
1073
1075
1076 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1077
1078 FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1079 while (last_selection != FeePerWeight{}) {
1080 last_selection += ret.back();
1081 ret.emplace_back(last_selection);
1083 last_selection = GetBlockBuilderChunk(dummy);
1084 }
1086 return ret;
1087}
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int ret
#define Assume(val)
Assume is the identity function.
Definition: check.h:125
An in-memory indexed chain of blocks.
Definition: chain.h:381
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:411
CCoinsView backed by another CCoinsView.
Definition: coins.h:336
CCoinsView * base
Definition: coins.h:338
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:355
Abstract view on the open txout dataset.
Definition: coins.h:302
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:17
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
GetCoin, returning whether it exists and is not spent.
Definition: txmempool.cpp:728
void Reset()
Clear m_temp_added and m_non_base_coins.
Definition: txmempool.cpp:758
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
Definition: txmempool.h:759
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:726
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:765
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
Definition: txmempool.cpp:751
const CTxMemPool & mempool
Definition: txmempool.h:767
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:35
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:29
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
Definition: feerate.h:65
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:690
void Apply() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: txmempool.cpp:1022
CTxMemPool * m_pool
Definition: txmempool.h:685
void StageRemoval(CTxMemPool::txiter it)
Definition: txmempool.cpp:1015
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:980
CTxMemPool::txiter TxHandle
Definition: txmempool.h:635
CTxMemPool::indexed_transaction_set m_to_add
Definition: txmempool.h:686
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:991
bool CheckMemPoolPolicyLimits()
Check if any cluster limits are exceeded.
Definition: txmempool.cpp:1057
std::vector< CTxMemPool::txiter > m_entry_vec
Definition: txmempool.h:687
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:188
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:376
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:190
void Apply(CTxMemPool::ChangeSet *changeset) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:198
void PrioritiseTransaction(const Txid &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:616
std::unique_ptr< ChangeSet > GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:696
bool CompareMiningScoreWithTopology(const Wtxid &hasha, const Wtxid &hashb) const
Definition: txmempool.cpp:542
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.h:289
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:718
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:695
void ClearPrioritisation(const Txid &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:653
std::optional< txiter > GetIter(const Txid &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:681
bool GetLoadTried() const
Definition: txmempool.cpp:942
void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:737
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.h:453
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:261
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:839
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:326
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:847
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:929
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:193
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:558
void StartBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:721
CTransactionRef get(const Txid &hash) const
Definition: txmempool.cpp:607
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:764
const Options m_opts
Definition: txmempool.h:304
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:586
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:219
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:253
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:797
void IncludeBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:735
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:350
std::vector< FeePerWeight > GetFeerateDiagram() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1067
std::tuple< size_t, size_t, CAmount > CalculateDescendantData(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:914
bool exists(const Txid &txid) const
Definition: txmempool.h:504
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:705
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:213
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:269
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:643
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:393
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:659
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:954
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:266
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
Definition: txmempool.h:571
bool CheckPolicyLimits(const CTransactionRef &tx)
Definition: txmempool.cpp:786
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:675
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of given transaction.
Definition: txmempool.cpp:299
std::tuple< size_t, size_t, CAmount > CalculateAncestorData(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:899
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:770
void cs_main
Definition: txmempool.h:334
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:948
void RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:779
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:574
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:182
FeePerWeight GetBlockBuilderChunk(std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &entries) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:722
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:600
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:188
A UTXO entry.
Definition: coins.h:34
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:124
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: logging.h:392
#define LogDebug(category,...)
Definition: logging.h:412
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: logging.h:89
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:35
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:376
static FeePerVSize ToFeePerVSize(FeePerWeight feerate)
Definition: policy.h:194
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
int64_t fee
Definition: feefrac.h:107
int32_t size
Definition: feefrac.h:108
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:142
#define LOCK(cs)
Definition: sync.h:259
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
#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_iters) noexcept
Construct a new TxGraph with the specified limit on the number of transactions within a cluster,...
Definition: txgraph.cpp:3441
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_ITERS
How many linearization iterations required for TxGraph clusters to have "acceptable" quality,...
Definition: txmempool.h:55
static constexpr uint64_t POST_CHANGE_WORK
How much work we ask TxGraph to do after a mempool change occurs (either due to a changeset being app...
Definition: txmempool.h:59
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:81
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())