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-2022 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 LOCK(cs);
60 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
61 setEntries children;
62 auto iter = mapNextTx.lower_bound(COutPoint(entry.GetTx().GetHash(), 0));
63 for (; iter != mapNextTx.end() && iter->first->hash == entry.GetTx().GetHash(); ++iter) {
64 children.insert(iter->second);
65 }
66 for (const auto& child : children) {
67 ret.emplace_back(*child);
68 }
69 return ret;
70}
71
72std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
73{
74 LOCK(cs);
75 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
76 std::set<Txid> inputs;
77 for (const auto& txin : entry.GetTx().vin) {
78 inputs.insert(txin.prevout.hash);
79 }
80 for (const auto& hash : inputs) {
81 std::optional<txiter> piter = GetIter(hash);
82 if (piter) {
83 ret.emplace_back(**piter);
84 }
85 }
86 return ret;
87}
88
89void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
90{
92
93 // Iterate in reverse, so that whenever we are looking at a transaction
94 // we are sure that all in-mempool descendants have already been processed.
95 for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
96 // calculate children from mapNextTx
97 txiter it = mapTx.find(hash);
98 if (it == mapTx.end()) {
99 continue;
100 }
101 auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
102 {
103 for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
104 txiter childIter = iter->second;
105 assert(childIter != mapTx.end());
106 // Add dependencies that are discovered between transactions in the
107 // block and transactions that were in the mempool to txgraph.
108 m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
109 }
110 }
111 }
112
113 auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
114 for (auto txptr : txs_to_remove) {
115 const CTxMemPoolEntry& entry = *(static_cast<const CTxMemPoolEntry*>(txptr));
116 removeUnchecked(mapTx.iterator_to(entry), MemPoolRemovalReason::SIZELIMIT);
117 }
118}
119
120bool CTxMemPool::HasDescendants(const Txid& txid) const
121{
122 LOCK(cs);
123 auto entry = GetEntry(txid);
124 if (!entry) return false;
125 return m_txgraph->GetDescendants(*entry, TxGraph::Level::MAIN).size() > 1;
126}
127
129{
130 auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
132 if (ancestors.size() > 0) {
133 for (auto ancestor : ancestors) {
134 if (ancestor != &entry) {
135 ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
136 }
137 }
138 return ret;
139 }
140
141 // If we didn't get anything back, the transaction is not in the graph.
142 // Find each parent and call GetAncestors on each.
143 setEntries staged_parents;
144 const CTransaction &tx = entry.GetTx();
145
146 // Get parents of this transaction that are in the mempool
147 for (unsigned int i = 0; i < tx.vin.size(); i++) {
148 std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
149 if (piter) {
150 staged_parents.insert(*piter);
151 }
152 }
153
154 for (const auto& parent : staged_parents) {
155 auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN);
156 for (auto ancestor : parent_ancestors) {
157 ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
158 }
159 }
160
161 return ret;
162}
163
165{
166 opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
167 int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
168 if (opts.max_size_bytes < 0 || (opts.max_size_bytes > 0 && opts.max_size_bytes < cluster_limit_bytes)) {
169 error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(cluster_limit_bytes / 1'000'000.0));
170 }
171 return std::move(opts);
172}
173
175 : m_opts{Flatten(std::move(opts), error)}
176{
178}
179
180bool CTxMemPool::isSpent(const COutPoint& outpoint) const
181{
182 LOCK(cs);
183 return mapNextTx.count(outpoint);
184}
185
187{
189}
190
192{
194}
195
197{
199 m_txgraph->CommitStaging();
200
202
203 for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
204 auto tx_entry = changeset->m_entry_vec[i];
205 // First splice this entry into mapTx.
206 auto node_handle = changeset->m_to_add.extract(tx_entry);
207 auto result = mapTx.insert(std::move(node_handle));
208
209 Assume(result.inserted);
210 txiter it = result.position;
213 }
214 m_txgraph->DoWork(POST_CHANGE_WORK);
215}
216
218{
219 const CTxMemPoolEntry& entry = *newit;
220
221 // Update cachedInnerUsage to include contained transaction's usage.
222 // (When we update the entry for in-mempool parents, memory usage will be
223 // further updated.)
224 cachedInnerUsage += entry.DynamicMemoryUsage();
225
226 const CTransaction& tx = newit->GetTx();
227 for (unsigned int i = 0; i < tx.vin.size(); i++) {
228 mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit));
229 }
230 // Don't bother worrying about child transactions of this one.
231 // Normal case of a new transaction arriving is that there can't be any
232 // children, because such children would be orphans.
233 // An exception to that is if a transaction enters that used to be in a block.
234 // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
235 // to clean up the mess we're leaving here.
236
238 totalTxSize += entry.GetTxSize();
239 m_total_fee += entry.GetFee();
240
241 txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
242 newit->idx_randomized = txns_randomized.size() - 1;
243
244 TRACEPOINT(mempool, added,
245 entry.GetTx().GetHash().data(),
246 entry.GetTxSize(),
247 entry.GetFee()
248 );
249}
250
252{
253 // We increment mempool sequence value no matter removal reason
254 // even if not directly reported below.
255 uint64_t mempool_sequence = GetAndIncrementSequence();
256
257 if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
258 // Notify clients that a transaction has been removed from the mempool
259 // for any reason except being included in a block. Clients interested
260 // in transactions included in blocks can subscribe to the BlockConnected
261 // notification.
262 m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
263 }
264 TRACEPOINT(mempool, removed,
265 it->GetTx().GetHash().data(),
266 RemovalReasonToString(reason).c_str(),
267 it->GetTxSize(),
268 it->GetFee(),
269 std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
270 );
271
272 for (const CTxIn& txin : it->GetTx().vin)
273 mapNextTx.erase(txin.prevout);
274
275 RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
276
277 if (txns_randomized.size() > 1) {
278 // Remove entry from txns_randomized by replacing it with the back and deleting the back.
279 txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
280 txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
281 txns_randomized.pop_back();
282 if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
283 txns_randomized.shrink_to_fit();
284 }
285 } else {
286 txns_randomized.clear();
287 }
288
289 totalTxSize -= it->GetTxSize();
290 m_total_fee -= it->GetFee();
291 cachedInnerUsage -= it->DynamicMemoryUsage();
292 mapTx.erase(it);
294}
295
296// Calculates descendants of given entry and adds to setDescendants.
297void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
298{
299 (void)CalculateDescendants(*entryit, setDescendants);
300 return;
301}
302
304{
305 for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
306 setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
307 }
308 return mapTx.iterator_to(entry);
309}
310
312{
313 // Remove transaction from memory pool
315 Assume(!m_have_changeset);
316 setEntries txToRemove;
317 txiter origit = mapTx.find(origTx.GetHash());
318 if (origit != mapTx.end()) {
319 txToRemove.insert(origit);
320 } else {
321 // When recursively removing but origTx isn't in the mempool
322 // be sure to remove any children that are in the pool. This can
323 // happen during chain re-orgs if origTx isn't re-accepted into
324 // the mempool for any reason.
325 for (unsigned int i = 0; i < origTx.vout.size(); i++) {
326 auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
327 if (it == mapNextTx.end())
328 continue;
329 txiter nextit = it->second;
330 assert(nextit != mapTx.end());
331 txToRemove.insert(nextit);
332 }
333 }
334 setEntries setAllRemoves;
335 for (txiter it : txToRemove) {
336 CalculateDescendants(it, setAllRemoves);
337 }
338
339 RemoveStaged(setAllRemoves, false, reason);
340}
341
342void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
343{
344 // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
347 Assume(!m_have_changeset);
348
349 setEntries txToRemove;
350 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
351 if (check_final_and_mature(it)) txToRemove.insert(it);
352 }
353 setEntries setAllRemoves;
354 for (txiter it : txToRemove) {
355 CalculateDescendants(it, setAllRemoves);
356 }
357 RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
358 for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
359 assert(TestLockPointValidity(chain, it->GetLockPoints()));
360 }
361 m_txgraph->DoWork(POST_CHANGE_WORK);
362}
363
365{
366 // Remove transactions which depend on inputs of tx, recursively
368 for (const CTxIn &txin : tx.vin) {
369 auto it = mapNextTx.find(txin.prevout);
370 if (it != mapNextTx.end()) {
371 const CTransaction &txConflict = it->second->GetTx();
372 if (Assume(txConflict.GetHash() != tx.GetHash()))
373 {
374 ClearPrioritisation(txConflict.GetHash());
376 }
377 }
378 }
379}
380
381void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
382{
383 // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
385 Assume(!m_have_changeset);
386 std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
387 if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
388 txs_removed_for_block.reserve(vtx.size());
389 for (const auto& tx : vtx) {
390 txiter it = mapTx.find(tx->GetHash());
391 if (it != mapTx.end()) {
392 setEntries stage;
393 stage.insert(it);
394 txs_removed_for_block.emplace_back(*it);
396 }
397 removeConflicts(*tx);
398 ClearPrioritisation(tx->GetHash());
399 }
400 }
401 if (m_opts.signals) {
402 m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
403 }
404 lastRollingFeeUpdate = GetTime();
405 blockSinceLastRollingFeeBump = true;
406 m_txgraph->DoWork(POST_CHANGE_WORK);
407}
408
409void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
410{
411 if (m_opts.check_ratio == 0) return;
412
413 if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
414
416 LOCK(cs);
417 LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
418
419 uint64_t checkTotal = 0;
420 CAmount check_total_fee{0};
421 uint64_t innerUsage = 0;
422
423 assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
424 m_txgraph->SanityCheck();
425
426 CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
427
428 const auto score_with_topo{GetSortedScoreWithTopology()};
429
430 // Number of chunks is bounded by number of transactions.
431 const auto diagram{GetFeerateDiagram()};
432 Assume(diagram.size() <= score_with_topo.size() + 1);
433
434 std::optional<Wtxid> last_wtxid = std::nullopt;
435
436 for (const auto& it : score_with_topo) {
437 checkTotal += it->GetTxSize();
438 check_total_fee += it->GetFee();
439 innerUsage += it->DynamicMemoryUsage();
440 const CTransaction& tx = it->GetTx();
441
442 // CompareMiningScoreWithTopology should agree with GetSortedScoreWithTopology()
443 if (last_wtxid) {
445 }
446 last_wtxid = tx.GetWitnessHash();
447
448 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
449 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
450 for (const CTxIn &txin : tx.vin) {
451 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
452 indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
453 if (it2 != mapTx.end()) {
454 const CTransaction& tx2 = it2->GetTx();
455 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
456 setParentCheck.insert(*it2);
457 }
458 // We are iterating through the mempool entries sorted
459 // topologically and by mining score. All parents must have been
460 // checked before their children and their coins added to the
461 // mempoolDuplicate coins cache.
462 assert(mempoolDuplicate.HaveCoin(txin.prevout));
463 // Check whether its inputs are marked in mapNextTx.
464 auto it3 = mapNextTx.find(txin.prevout);
465 assert(it3 != mapNextTx.end());
466 assert(it3->first == &txin.prevout);
467 assert(&it3->second->GetTx() == &tx);
468 }
469 auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
470 return a.GetTx().GetHash() == b.GetTx().GetHash();
471 };
472 for (auto &txentry : GetParents(*it)) {
473 setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
474 }
475 assert(setParentCheck.size() == setParentsStored.size());
476 assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
477
478 // Check children against mapNextTx
479 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
480 std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
481 auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
482 for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
483 txiter childit = iter->second;
484 assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
485 setChildrenCheck.insert(*childit);
486 }
487 for (auto &txentry : GetChildren(*it)) {
488 setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
489 }
490 assert(setChildrenCheck.size() == setChildrenStored.size());
491 assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
492
493 TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
494 CAmount txfee = 0;
495 assert(!tx.IsCoinBase());
496 assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
497 for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
498 AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
499 }
500 for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
501 indexed_transaction_set::const_iterator it2 = it->second;
502 assert(it2 != mapTx.end());
503 }
504
505 assert(totalTxSize == checkTotal);
506 assert(m_total_fee == check_total_fee);
507 assert(innerUsage == cachedInnerUsage);
508}
509
510bool CTxMemPool::CompareMiningScoreWithTopology(const Wtxid& hasha, const Wtxid& hashb) const
511{
512 /* Return `true` if hasha should be considered sooner than hashb, namely when:
513 * a is not in the mempool but b is, or
514 * both are in the mempool but a is sorted before b in the total mempool ordering
515 * (which takes dependencies and (chunk) feerates into account).
516 */
517 LOCK(cs);
518 auto j{GetIter(hashb)};
519 if (!j.has_value()) return false;
520 auto i{GetIter(hasha)};
521 if (!i.has_value()) return true;
522
523 return m_txgraph->CompareMainOrder(*i.value(), *j.value()) < 0;
524}
525
526std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
527{
528 std::vector<indexed_transaction_set::const_iterator> iters;
530
531 iters.reserve(mapTx.size());
532
533 for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
534 iters.push_back(mi);
535 }
536 std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
537 return m_txgraph->CompareMainOrder(*a, *b) < 0;
538 });
539 return iters;
540}
541
542std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
543{
545
546 std::vector<CTxMemPoolEntryRef> ret;
547 ret.reserve(mapTx.size());
548 for (const auto& it : GetSortedScoreWithTopology()) {
549 ret.emplace_back(*it);
550 }
551 return ret;
552}
553
554std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
555{
556 LOCK(cs);
557 auto iters = GetSortedScoreWithTopology();
558
559 std::vector<TxMempoolInfo> ret;
560 ret.reserve(mapTx.size());
561 for (auto it : iters) {
562 ret.push_back(GetInfo(it));
563 }
564
565 return ret;
566}
567
569{
571 const auto i = mapTx.find(txid);
572 return i == mapTx.end() ? nullptr : &(*i);
573}
574
576{
577 LOCK(cs);
578 indexed_transaction_set::const_iterator i = mapTx.find(hash);
579 if (i == mapTx.end())
580 return nullptr;
581 return i->GetSharedTx();
582}
583
584void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
585{
586 {
587 LOCK(cs);
588 CAmount &delta = mapDeltas[hash];
589 delta = SaturatingAdd(delta, nFeeDelta);
590 txiter it = mapTx.find(hash);
591 if (it != mapTx.end()) {
592 // PrioritiseTransaction calls stack on previous ones. Set the new
593 // transaction fee to be current modified fee + feedelta.
594 mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
595 m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
597 }
598 if (delta == 0) {
599 mapDeltas.erase(hash);
600 LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
601 } else {
602 LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
603 hash.ToString(),
604 it == mapTx.end() ? "not " : "",
605 FormatMoney(nFeeDelta),
606 FormatMoney(delta));
607 }
608 }
609}
610
611void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
612{
614 std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
615 if (pos == mapDeltas.end())
616 return;
617 const CAmount &delta = pos->second;
618 nFeeDelta += delta;
619}
620
622{
624 mapDeltas.erase(hash);
625}
626
627std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
628{
630 LOCK(cs);
631 std::vector<delta_info> result;
632 result.reserve(mapDeltas.size());
633 for (const auto& [txid, delta] : mapDeltas) {
634 const auto iter{mapTx.find(txid)};
635 const bool in_mempool{iter != mapTx.end()};
636 std::optional<CAmount> modified_fee;
637 if (in_mempool) modified_fee = iter->GetModifiedFee();
638 result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
639 }
640 return result;
641}
642
644{
645 const auto it = mapNextTx.find(prevout);
646 return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
647}
648
649std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
650{
652 auto it = mapTx.find(txid);
653 return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
654}
655
656std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
657{
659 auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
660 return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
661}
662
663CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
664{
666 for (const auto& h : hashes) {
667 const auto mi = GetIter(h);
668 if (mi) ret.insert(*mi);
669 }
670 return ret;
671}
672
673std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
674{
676 std::vector<txiter> ret;
677 ret.reserve(txids.size());
678 for (const auto& txid : txids) {
679 const auto it{GetIter(txid)};
680 if (!it) return {};
681 ret.push_back(*it);
682 }
683 return ret;
684}
685
687{
688 for (unsigned int i = 0; i < tx.vin.size(); i++)
689 if (exists(tx.vin[i].prevout.hash))
690 return false;
691 return true;
692}
693
694CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
695
696std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
697{
698 // Check to see if the inputs are made available by another tx in the package.
699 // These Coins would not be available in the underlying CoinsView.
700 if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
701 return it->second;
702 }
703
704 // If an entry in the mempool exists, always return that one, as it's guaranteed to never
705 // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
706 // transactions. First checking the underlying cache risks returning a pruned entry instead.
707 CTransactionRef ptx = mempool.get(outpoint.hash);
708 if (ptx) {
709 if (outpoint.n < ptx->vout.size()) {
710 Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
711 m_non_base_coins.emplace(outpoint);
712 return coin;
713 }
714 return std::nullopt;
715 }
716 return base->GetCoin(outpoint);
717}
718
720{
721 for (unsigned int n = 0; n < tx->vout.size(); ++n) {
722 m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
723 m_non_base_coins.emplace(tx->GetHash(), n);
724 }
725}
727{
728 m_temp_added.clear();
729 m_non_base_coins.clear();
730}
731
733 LOCK(cs);
734 // 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.
735 return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
736}
737
738void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
739 LOCK(cs);
740
741 if (m_unbroadcast_txids.erase(txid))
742 {
743 LogDebug(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
744 }
745}
746
747void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
749 for (txiter it : stage) {
750 removeUnchecked(it, reason);
751 }
752}
753
755{
756 LOCK(cs);
757 // Use ChangeSet interface to check whether the chain
758 // limits would be violated. Note that the changeset will be destroyed
759 // when it goes out of scope.
760 auto changeset = GetChangeSet();
761 (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
762 return changeset->CheckMemPoolPolicyLimits();
763}
764
765int CTxMemPool::Expire(std::chrono::seconds time)
766{
768 Assume(!m_have_changeset);
769 indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
770 setEntries toremove;
771 while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
772 toremove.insert(mapTx.project<0>(it));
773 it++;
774 }
775 setEntries stage;
776 for (txiter removeit : toremove) {
777 CalculateDescendants(removeit, stage);
778 }
780 return stage.size();
781}
782
783CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
784 LOCK(cs);
785 if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
786 return CFeeRate(llround(rollingMinimumFeeRate));
787
788 int64_t time = GetTime();
789 if (time > lastRollingFeeUpdate + 10) {
790 double halflife = ROLLING_FEE_HALFLIFE;
791 if (DynamicMemoryUsage() < sizelimit / 4)
792 halflife /= 4;
793 else if (DynamicMemoryUsage() < sizelimit / 2)
794 halflife /= 2;
795
796 rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
797 lastRollingFeeUpdate = time;
798
799 if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
800 rollingMinimumFeeRate = 0;
801 return CFeeRate(0);
802 }
803 }
804 return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
805}
806
809 if (rate.GetFeePerK() > rollingMinimumFeeRate) {
810 rollingMinimumFeeRate = rate.GetFeePerK();
811 blockSinceLastRollingFeeBump = false;
812 }
813}
814
815void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
817 Assume(!m_have_changeset);
818
819 unsigned nTxnRemoved = 0;
820 CFeeRate maxFeeRateRemoved(0);
821
822 while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
823 const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
824 FeePerVSize feerate = ToFeePerVSize(feeperweight);
825 CFeeRate removed{feerate.fee, feerate.size};
826
827 // We set the new mempool min fee to the feerate of the removed set, plus the
828 // "minimum reasonable fee rate" (ie some value under which we consider txn
829 // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
830 // equal to txn which were removed with no block in between.
832 trackPackageRemoved(removed);
833 maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
834
835 nTxnRemoved += worst_chunk.size();
836
837 std::vector<CTransaction> txn;
838 if (pvNoSpendsRemaining) {
839 txn.reserve(worst_chunk.size());
840 for (auto ref : worst_chunk) {
841 txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
842 }
843 }
844
845 setEntries stage;
846 for (auto ref : worst_chunk) {
847 stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
848 }
849 for (auto e : stage) {
851 }
852 if (pvNoSpendsRemaining) {
853 for (const CTransaction& tx : txn) {
854 for (const CTxIn& txin : tx.vin) {
855 if (exists(txin.prevout.hash)) continue;
856 pvNoSpendsRemaining->push_back(txin.prevout);
857 }
858 }
859 }
860 }
861
862 if (maxFeeRateRemoved > CFeeRate(0)) {
863 LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
864 }
865}
866
867std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
868{
869 auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
870
871 size_t ancestor_count = ancestors.size();
872 size_t ancestor_size = 0;
873 CAmount ancestor_fees = 0;
874 for (auto tx: ancestors) {
875 const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
876 ancestor_size += anc.GetTxSize();
877 ancestor_fees += anc.GetModifiedFee();
878 }
879 return {ancestor_count, ancestor_size, ancestor_fees};
880}
881
882std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
883{
884 auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
885 size_t descendant_count = descendants.size();
886 size_t descendant_size = 0;
887 CAmount descendant_fees = 0;
888
889 for (auto tx: descendants) {
890 const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
891 descendant_size += desc.GetTxSize();
892 descendant_fees += desc.GetModifiedFee();
893 }
894 return {descendant_count, descendant_size, descendant_fees};
895}
896
897void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
898 LOCK(cs);
899 auto it = mapTx.find(txid);
900 ancestors = cluster_count = 0;
901 if (it != mapTx.end()) {
902 auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
903 ancestors = ancestor_count;
904 if (ancestorsize) *ancestorsize = ancestor_size;
905 if (ancestorfees) *ancestorfees = ancestor_fees;
906 cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
907 }
908}
909
911{
912 LOCK(cs);
913 return m_load_tried;
914}
915
916void CTxMemPool::SetLoadTried(bool load_tried)
917{
918 LOCK(cs);
919 m_load_tried = load_tried;
920}
921
922std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
923{
925
926 std::vector<CTxMemPool::txiter> ret;
927 std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
928 for (auto txid : txids) {
929 auto it = mapTx.find(txid);
930 if (it != mapTx.end()) {
931 auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
932 if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
933 for (auto tx : cluster) {
934 ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
935 }
936 }
937 }
938 }
939 if (ret.size() > 500) {
940 return {};
941 }
942 return ret;
943}
944
946{
947 LOCK(m_pool->cs);
948
950 return util::Error{Untranslated("cluster size limit exceeded")};
951 }
952
953 return m_pool->m_txgraph->GetMainStagingDiagrams();
954}
955
956CTxMemPool::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)
957{
958 LOCK(m_pool->cs);
959 Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
960 Assume(!m_dependencies_processed);
961
962 // We need to process dependencies after adding a new transaction.
963 m_dependencies_processed = false;
964
965 CAmount delta{0};
966 m_pool->ApplyDelta(tx->GetHash(), delta);
967
968 TxGraph::Ref ref(m_pool->m_txgraph->AddTransaction(FeePerWeight(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp))));
969 auto newit = m_to_add.emplace(std::move(ref), tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
970 if (delta) {
971 m_to_add.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
972 m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
973 }
974
975 m_entry_vec.push_back(newit);
976
977 return newit;
978}
979
981{
982 LOCK(m_pool->cs);
983 m_pool->m_txgraph->RemoveTransaction(*it);
984 m_to_remove.insert(it);
985}
986
988{
989 LOCK(m_pool->cs);
990 if (!m_dependencies_processed) {
991 ProcessDependencies();
992 }
993 m_pool->Apply(this);
994 m_to_add.clear();
995 m_to_remove.clear();
996 m_entry_vec.clear();
997 m_ancestors.clear();
998}
999
1001{
1002 LOCK(m_pool->cs);
1003 Assume(!m_dependencies_processed); // should only call this once.
1004 for (const auto& entryptr : m_entry_vec) {
1005 for (const auto &txin : entryptr->GetSharedTx()->vin) {
1006 std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1007 if (!piter) {
1008 auto it = m_to_add.find(txin.prevout.hash);
1009 if (it != m_to_add.end()) {
1010 piter = std::make_optional(it);
1011 }
1012 }
1013 if (piter) {
1014 m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1015 }
1016 }
1017 }
1018 m_dependencies_processed = true;
1019 return;
1020 }
1021
1023{
1024 LOCK(m_pool->cs);
1025 if (!m_dependencies_processed) {
1026 ProcessDependencies();
1027 }
1028
1029 return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1030}
1031
1032std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1033{
1034 FeePerWeight zero{};
1035 std::vector<FeePerWeight> ret;
1036
1037 ret.emplace_back(zero);
1038
1040
1041 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1042
1043 FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1044 while (last_selection != FeePerWeight{}) {
1045 last_selection += ret.back();
1046 ret.emplace_back(last_selection);
1048 last_selection = GetBlockBuilderChunk(dummy);
1049 }
1051 return ret;
1052}
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:342
CCoinsView * base
Definition: coins.h:344
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:361
Abstract view on the open txout dataset.
Definition: coins.h:308
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:16
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
GetCoin, returning whether it exists and is not spent.
Definition: txmempool.cpp:696
void Reset()
Clear m_temp_added and m_non_base_coins.
Definition: txmempool.cpp:726
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
Definition: txmempool.h:784
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
Definition: txmempool.cpp:694
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:790
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
Definition: txmempool.cpp:719
const CTxMemPool & mempool
Definition: txmempool.h:792
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:63
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:296
const std::vector< CTxOut > vout
Definition: transaction.h:307
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:344
bool IsCoinBase() const
Definition: transaction.h:356
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
const std::vector< CTxIn > vin
Definition: transaction.h:306
An input of a transaction.
Definition: transaction.h:67
COutPoint prevout
Definition: transaction.h:69
CTxMemPool::setEntries m_to_remove
Definition: txmempool.h:715
void Apply() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: txmempool.cpp:987
CTxMemPool * m_pool
Definition: txmempool.h:710
void StageRemoval(CTxMemPool::txiter it)
Definition: txmempool.cpp:980
TxHandle 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)
Definition: txmempool.cpp:956
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:945
CTxMemPool::txiter TxHandle
Definition: txmempool.h:660
CTxMemPool::indexed_transaction_set m_to_add
Definition: txmempool.h:711
bool CheckMemPoolPolicyLimits()
Check if any cluster limits are exceeded.
Definition: txmempool.cpp:1022
std::vector< CTxMemPool::txiter > m_entry_vec
Definition: txmempool.h:712
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:67
const CTransaction & GetTx() const
void UpdateModifiedFee(CAmount fee_diff)
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:189
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:364
std::atomic< unsigned int > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
Definition: txmempool.h:191
void Apply(CTxMemPool::ChangeSet *changeset) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:196
void PrioritiseTransaction(const Txid &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:584
std::unique_ptr< ChangeSet > GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:721
bool CompareMiningScoreWithTopology(const Wtxid &hasha, const Wtxid &hashb) const
Definition: txmempool.cpp:510
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.h:294
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:686
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:663
void ClearPrioritisation(const Txid &hash) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:621
std::optional< txiter > GetIter(const Txid &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:649
bool GetLoadTried() const
Definition: txmempool.cpp:910
void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:762
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:263
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:807
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:815
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:897
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:89
return !it visited * it
Definition: txmempool.h:615
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:191
bool HasDescendants(const Txid &txid) const
Definition: txmempool.cpp:120
std::vector< indexed_transaction_set::const_iterator > GetSortedScoreWithTopology() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:526
void StartBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:746
CTransactionRef get(const Txid &hash) const
Definition: txmempool.cpp:575
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:732
const Options m_opts
Definition: txmempool.h:309
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:554
CTxMemPool(Options opts, bilingual_str &error)
Create a new CTxMemPool.
Definition: txmempool.cpp:174
void addNewTransaction(CTxMemPool::txiter it) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:217
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Before calling removeUnchecked for a given transaction, UpdateForRemoveFromMempool must be called on ...
Definition: txmempool.cpp:251
void RemoveUnbroadcastTx(const Txid &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
Definition: txmempool.cpp:738
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:765
void IncludeBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:760
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:342
std::vector< FeePerWeight > GetFeerateDiagram() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:1032
std::tuple< size_t, size_t, CAmount > CalculateDescendantData(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:882
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:673
static const int ROLLING_FEE_HALFLIFE
Definition: txmempool.h:215
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:271
std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > GetParents(const CTxMemPoolEntry &entry) const
Definition: txmempool.cpp:72
void ApplyDelta(const Txid &hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:611
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:747
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:381
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:627
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:922
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:268
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:754
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:643
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of given transaction.
Definition: txmempool.cpp:297
std::tuple< size_t, size_t, CAmount > CalculateAncestorData(const CTxMemPoolEntry &entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:867
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:128
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:916
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:542
bool isSpent(const COutPoint &outpoint) const
Definition: txmempool.cpp:180
FeePerWeight GetBlockBuilderChunk(std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &entries) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:747
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:568
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:186
A UTXO entry.
Definition: coins.h:33
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:122
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 LogDebug(category,...)
Definition: logging.h:393
#define LogPrintf(...)
Definition: logging.h:373
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:68
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:198
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
int64_t fee
Definition: feefrac.h:107
int32_t size
Definition: feefrac.h:108
CBlockIndex * maxInputBlock
Definition: mempool_entry.h:36
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:3463
static CTxMemPool::Options && Flatten(CTxMemPool::Options &&opts, bilingual_str &error)
Definition: txmempool.cpp:164
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:56
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:60
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:51
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:77
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())