Bitcoin Core 30.99.0
P2P Digital Currency
txmempool.h
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#ifndef BITCOIN_TXMEMPOOL_H
7#define BITCOIN_TXMEMPOOL_H
8
9#include <coins.h>
10#include <consensus/amount.h>
11#include <indirectmap.h>
12#include <kernel/cs_main.h>
13#include <kernel/mempool_entry.h> // IWYU pragma: export
14#include <kernel/mempool_limits.h> // IWYU pragma: export
15#include <kernel/mempool_options.h> // IWYU pragma: export
16#include <kernel/mempool_removal_reason.h> // IWYU pragma: export
17#include <policy/feerate.h>
18#include <policy/packages.h>
21#include <sync.h>
22#include <txgraph.h>
23#include <util/epochguard.h>
24#include <util/feefrac.h>
25#include <util/hasher.h>
26#include <util/result.h>
27
28#include <boost/multi_index/hashed_index.hpp>
29#include <boost/multi_index/identity.hpp>
30#include <boost/multi_index/indexed_by.hpp>
31#include <boost/multi_index/ordered_index.hpp>
32#include <boost/multi_index/sequenced_index.hpp>
33#include <boost/multi_index/tag.hpp>
34#include <boost/multi_index_container.hpp>
35
36#include <atomic>
37#include <map>
38#include <optional>
39#include <set>
40#include <string>
41#include <string_view>
42#include <utility>
43#include <vector>
44
45class CChain;
47
48struct bilingual_str;
49
51static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
52
56static constexpr uint64_t ACCEPTABLE_ITERS = 1'700;
57
60static constexpr uint64_t POST_CHANGE_WORK = 5 * ACCEPTABLE_ITERS;
61
66
67// extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
69{
72 {
73 return entry.GetTx().GetHash();
74 }
75
77 {
78 return tx->GetHash();
79 }
80};
81
82// extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
84{
87 {
88 return entry.GetTx().GetWitnessHash();
89 }
90
92 {
93 return tx->GetWitnessHash();
94 }
95};
96
98{
99public:
100 bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
101 {
102 return a.GetTime() < b.GetTime();
103 }
104};
105
106// Multi_index tag names
107struct entry_time {};
109
114{
117
119 std::chrono::seconds m_time;
120
123
125 int32_t vsize;
126
128 int64_t nFeeDelta;
129};
130
189{
190protected:
191 std::atomic<unsigned int> nTransactionsUpdated{0};
192
193 uint64_t totalTxSize GUARDED_BY(cs){0};
194 CAmount m_total_fee GUARDED_BY(cs){0};
195 uint64_t cachedInnerUsage GUARDED_BY(cs){0};
196
197 mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs){GetTime()};
198 mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs){false};
199 mutable double rollingMinimumFeeRate GUARDED_BY(cs){0};
201
202 // In-memory counter for external mempool tracking purposes.
203 // This number is incremented once every time a transaction
204 // is added or removed from the mempool for any reason.
205 mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
206
208
209 bool m_load_tried GUARDED_BY(cs){false};
210
211 CFeeRate GetMinFee(size_t sizelimit) const;
212
213public:
214
215 static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
216
217 struct CTxMemPoolEntry_Indices final : boost::multi_index::indexed_by<
218 // sorted by txid
219 boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
220 // sorted by wtxid
221 boost::multi_index::hashed_unique<
222 boost::multi_index::tag<index_by_wtxid>,
223 mempoolentry_wtxid,
224 SaltedWtxidHasher
225 >,
226 // sorted by entry time
227 boost::multi_index::ordered_non_unique<
228 boost::multi_index::tag<entry_time>,
229 boost::multi_index::identity<CTxMemPoolEntry>,
230 CompareTxMemPoolEntryByEntryTime
231 >
232 >
233 {};
234 typedef boost::multi_index_container<
238
264 std::unique_ptr<TxGraph> m_txgraph GUARDED_BY(cs);
265 mutable std::unique_ptr<TxGraph::BlockBuilder> m_builder GUARDED_BY(cs);
267
268 using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
269 std::vector<std::pair<Wtxid, txiter>> txns_randomized GUARDED_BY(cs);
270
271 typedef std::set<txiter, CompareIteratorByHash> setEntries;
272
274
275 std::tuple<size_t, size_t, CAmount> CalculateAncestorData(const CTxMemPoolEntry& entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
276 std::tuple<size_t, size_t, CAmount> CalculateDescendantData(const CTxMemPoolEntry& entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
277 int64_t GetDescendantCount(txiter it) const { LOCK(cs); return m_txgraph->GetDescendants(*it, TxGraph::Level::MAIN).size(); }
278 int64_t GetDescendantCount(const CTxMemPoolEntry &e) const { LOCK(cs); return m_txgraph->GetDescendants(e, TxGraph::Level::MAIN).size(); }
279 int64_t GetAncestorCount(const CTxMemPoolEntry &e) const { LOCK(cs); return m_txgraph->GetAncestors(e, TxGraph::Level::MAIN).size(); }
280 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> GetChildren(const CTxMemPoolEntry &entry) const;
281 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> GetParents(const CTxMemPoolEntry &entry) const;
282
283private:
284 typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
285
286
287 std::vector<indexed_transaction_set::const_iterator> GetSortedScoreWithTopology() const EXCLUSIVE_LOCKS_REQUIRED(cs);
288
292 std::set<Txid> m_unbroadcast_txids GUARDED_BY(cs);
293
295 {
296 return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
297 }
298
299 // Helper to remove all transactions that conflict with a given
300 // transaction (used for transactions appearing in a block).
302
303public:
305 std::map<Txid, CAmount> mapDeltas GUARDED_BY(cs);
306
308
310
316 explicit CTxMemPool(Options opts, bilingual_str& error);
317
324 void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
325
334 void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
335 void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
336
337 bool CompareMiningScoreWithTopology(const Wtxid& hasha, const Wtxid& hashb) const;
338 bool isSpent(const COutPoint& outpoint) const;
339 unsigned int GetTransactionsUpdated() const;
340 void AddTransactionsUpdated(unsigned int n);
346
348 void PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta);
349 void ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
351
352 struct delta_info {
354 const bool in_mempool;
358 std::optional<CAmount> modified_fee;
360 const Txid txid;
361 };
363 std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
364
366 const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
367
369 std::optional<txiter> GetIter(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
370 std::optional<txiter> GetIter(const Wtxid& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
371
375 setEntries GetIterSet(const std::set<Txid>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
376
380 std::vector<txiter> GetIterVec(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
381
396
399 return m_txgraph->GetMainChunkFeerate(tx);
400 }
401 std::vector<const CTxMemPoolEntry*> GetCluster(Txid txid) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
402 auto tx = GetIter(txid);
403 if (!tx) return {};
404 auto cluster = m_txgraph->GetCluster(**tx, TxGraph::Level::MAIN);
405 std::vector<const CTxMemPoolEntry*> ret;
406 ret.reserve(cluster.size());
407 for (const auto& tx : cluster) {
408 ret.emplace_back(static_cast<const CTxMemPoolEntry*>(tx));
409 }
410 return ret;
411 }
412
413
414 size_t GetUniqueClusterCount(const setEntries& iters_conflicting) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
415 std::vector<const TxGraph::Ref *> entries;
416 entries.reserve(iters_conflicting.size());
417 for (auto it : iters_conflicting) {
418 entries.emplace_back(&*it);
419 }
420 Assume(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
421 return m_txgraph->CountDistinctClusters(entries, TxGraph::Level::MAIN);
422 }
423
432
433 bool HasDescendants(const Txid& txid) const;
434
439 std::vector<txiter> GatherClusters(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
440
446
455 }
456
461 void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
462
464 int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
465
472 void GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
473
478 bool GetLoadTried() const;
479
484 void SetLoadTried(bool load_tried);
485
486 unsigned long size() const
487 {
488 LOCK(cs);
489 return mapTx.size();
490 }
491
493 {
495 return totalTxSize;
496 }
497
499 {
501 return m_total_fee;
502 }
503
504 bool exists(const Txid& txid) const
505 {
506 LOCK(cs);
507 return (mapTx.count(txid) != 0);
508 }
509
510 bool exists(const Wtxid& wtxid) const
511 {
512 LOCK(cs);
513 return (mapTx.get<index_by_wtxid>().count(wtxid) != 0);
514 }
515
517
518 CTransactionRef get(const Txid& hash) const;
519
520 template <TxidOrWtxid T>
521 TxMempoolInfo info(const T& id) const
522 {
523 LOCK(cs);
524 auto i{GetIter(id)};
525 return i.has_value() ? GetInfo(*i) : TxMempoolInfo{};
526 }
527
529 template <TxidOrWtxid T>
530 TxMempoolInfo info_for_relay(const T& id, uint64_t last_sequence) const
531 {
532 LOCK(cs);
533 auto i{GetIter(id)};
534 return (i.has_value() && i.value()->GetSequence() < last_sequence) ? GetInfo(*i) : TxMempoolInfo{};
535 }
536
537 std::vector<CTxMemPoolEntryRef> entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs);
538 std::vector<TxMempoolInfo> infoAll() const;
539
540 size_t DynamicMemoryUsage() const;
541
543 void AddUnbroadcastTx(const Txid& txid)
544 {
545 LOCK(cs);
546 // Sanity check the transaction is in the mempool & insert into
547 // unbroadcast set.
548 if (exists(txid)) m_unbroadcast_txids.insert(txid);
549 };
550
551 bool CheckPolicyLimits(const CTransactionRef& tx);
552
554 void RemoveUnbroadcastTx(const Txid& txid, const bool unchecked = false);
555
557 std::set<Txid> GetUnbroadcastTxs() const
558 {
559 LOCK(cs);
560 return m_unbroadcast_txids;
561 }
562
565 {
567 return m_unbroadcast_txids.count(txid) != 0;
568 }
569
572 return m_sequence_number++;
573 }
574
576 return m_sequence_number;
577 }
578
579private:
587 void RemoveStaged(setEntries& stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
588
598public:
608 {
609 return m_epoch.visited(it->m_epoch_marker);
610 }
611
612 bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
613 {
614 assert(m_epoch.guarded()); // verify guard even when it==nullopt
615 return !it || visited(*it);
616 }
617
618 /*
619 * CTxMemPool::ChangeSet:
620 *
621 * This class is used for all mempool additions and associated removals (eg
622 * due to rbf). Removals that don't need to be evaluated for acceptance,
623 * such as removing transactions that appear in a block, or due to reorg,
624 * or removals related to mempool limiting or expiry do not need to use
625 * this.
626 *
627 * Callers can interleave calls to StageAddition()/StageRemoval(), and
628 * removals may be invoked in any order, but additions must be done in a
629 * topological order in the case of transaction packages (ie, parents must
630 * be added before children).
631 *
632 * CalculateChunksForRBF() can be used to calculate the feerate diagram of
633 * the proposed set of new transactions and compare with the existing
634 * mempool.
635 *
636 * CalculateMemPoolAncestors() calculates the in-mempool (not including
637 * what is in the change set itself) ancestors of a given transaction.
638 *
639 * Apply() will apply the removals and additions that are staged into the
640 * mempool.
641 *
642 * Only one changeset may exist at a time. While a changeset is
643 * outstanding, no removals or additions may be made directly to the
644 * mempool.
645 */
646 class ChangeSet {
647 public:
648 explicit ChangeSet(CTxMemPool* pool) : m_pool(pool) { m_pool->m_txgraph->StartStaging(); }
651 if (m_pool->m_txgraph->HaveStaging()) {
652 m_pool->m_txgraph->AbortStaging();
653 }
654 m_pool->m_have_changeset = false;
655 }
656
657 ChangeSet(const ChangeSet&) = delete;
658 ChangeSet& operator=(const ChangeSet&) = delete;
659
661
662 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);
663
665
667
670
672 {
673 // Look up transaction in our cache first
674 auto it = m_ancestors.find(tx);
675 if (it != m_ancestors.end()) return it->second;
676
677 // If not found, try to have the mempool calculate it, and cache
678 // for later.
679 LOCK(m_pool->cs);
681 m_ancestors.try_emplace(tx, ret);
682 return ret;
683 }
684
685 std::vector<CTransactionRef> GetAddedTxns() const {
686 std::vector<CTransactionRef> ret;
687 ret.reserve(m_entry_vec.size());
688 for (const auto& entry : m_entry_vec) {
689 ret.emplace_back(entry->GetSharedTx());
690 }
691 return ret;
692 }
693
701
702 size_t GetTxCount() const { return m_entry_vec.size(); }
703 const CTransaction& GetAddedTxn(size_t index) const { return m_entry_vec.at(index)->GetTx(); }
704
706
707 private:
708 void ProcessDependencies();
709
712 std::vector<CTxMemPool::txiter> m_entry_vec; // track the added transactions' insertion order
713 // map from the m_to_add index to the ancestors for the transaction
717
718 friend class CTxMemPool;
719 };
720
721 std::unique_ptr<ChangeSet> GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs) {
722 Assume(!m_have_changeset);
723 m_have_changeset = true;
724 return std::make_unique<ChangeSet>(this);
725 }
726
727 bool m_have_changeset GUARDED_BY(cs){false};
728
730
731private:
732 // Apply the given changeset to the mempool, by removing transactions in
733 // the to_remove set and adding transactions in the to_add set.
735
736 // addNewTransaction must update state for all ancestors of a given transaction,
737 // to track size/count of descendant transactions. First version of
738 // addNewTransaction can be used to have it call CalculateMemPoolAncestors(), and
739 // then invoke the second version.
740 // Note that addNewTransaction is ONLY called (via Apply()) from ATMP
741 // outside of tests and any other callers may break wallet's in-mempool
742 // tracking (due to lack of CValidationInterface::TransactionAddedToMempool
743 // callbacks).
745public:
746 void StartBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs) { assert(!m_builder); m_builder = m_txgraph->GetBlockBuilder(); }
747 FeePerWeight GetBlockBuilderChunk(std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef>& entries) const EXCLUSIVE_LOCKS_REQUIRED(cs)
748 {
749 if (!m_builder) { return {}; }
750
751 auto res = m_builder->GetCurrentChunk();
752 if (!res) { return {}; }
753
754 auto [chunk_entries, chunk_feerate] = *res;
755 for (TxGraph::Ref* ref : chunk_entries) {
756 entries.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref));
757 }
758 return chunk_feerate;
759 }
760 void IncludeBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder->Include(); }
761 void SkipBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder->Skip(); }
762 void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder.reset(); }
763};
764
779{
784 std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
785
790 mutable std::unordered_set<COutPoint, SaltedOutpointHasher> m_non_base_coins;
791protected:
793
794public:
795 CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
798 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
803 const std::unordered_set<COutPoint, SaltedOutpointHasher>& GetNonBaseCoins() const { return m_non_base_coins; }
805 void Reset();
806};
807#endif // BITCOIN_TXMEMPOOL_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define LIFETIMEBOUND
Definition: attributes.h:16
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
CCoinsView backed by another CCoinsView.
Definition: coins.h:342
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
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:779
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
const std::unordered_set< COutPoint, SaltedOutpointHasher > & GetNonBaseCoins() const
Get all coins in m_non_base_coins.
Definition: txmempool.h:803
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
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:344
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
size_t GetTxCount() const
Definition: txmempool.h:702
const CTransaction & GetAddedTxn(size_t index) const
Definition: txmempool.h:703
CTxMemPool::setEntries m_to_remove
Definition: txmempool.h:715
ChangeSet(CTxMemPool *pool)
Definition: txmempool.h:648
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
~ChangeSet() EXCLUSIVE_LOCKS_REQUIRED(m_pool -> cs)
Definition: txmempool.h:649
ChangeSet(const ChangeSet &)=delete
const CTxMemPool::setEntries & GetRemovals() const
Definition: txmempool.h:666
CTxMemPool::setEntries CalculateMemPoolAncestors(TxHandle tx)
Definition: txmempool.h:671
bool CheckMemPoolPolicyLimits()
Check if any cluster limits are exceeded.
Definition: txmempool.cpp:1022
std::map< CTxMemPool::txiter, CTxMemPool::setEntries, CompareIteratorByHash > m_ancestors
Definition: txmempool.h:714
std::vector< CTransactionRef > GetAddedTxns() const
Definition: txmempool.h:685
ChangeSet & operator=(const ChangeSet &)=delete
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
std::chrono::seconds GetTime() const
const CTransaction & GetTx() 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
std::map< Txid, CAmount > mapDeltas GUARDED_BY(cs)
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
Definition: txmempool.h:294
TxMempoolInfo info_for_relay(const T &id, uint64_t last_sequence) const
Returns info for a transaction if its entry_sequence < last_sequence.
Definition: txmempool.h:530
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
std::vector< const CTxMemPoolEntry * > GetCluster(Txid txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:401
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
uint64_t cachedInnerUsage GUARDED_BY(cs)
sum of all mempool tx's fees (NOT modified fee)
Definition: txmempool.h:195
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
bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs
visited marks a CTxMemPoolEntry as having been traversed during the lifetime of the most recently cre...
void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:762
bool exists(const Wtxid &wtxid) const
Definition: txmempool.h:510
bool visited(std::optional< txiter > it) const EXCLUSIVE_LOCKS_REQUIRED(cs
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
std::vector< std::pair< Wtxid, txiter > > txns_randomized GUARDED_BY(cs)
All transactions in mapTx with their wtxids, in arbitrary order.
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
bool blockSinceLastRollingFeeBump GUARDED_BY(cs)
Definition: txmempool.h:198
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
bool m_have_changeset GUARDED_BY(cs)
Definition: txmempool.h:727
void cs_main LOCKS_EXCLUDED(m_epoch)
size_t GetUniqueClusterCount(const setEntries &iters_conflicting) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:414
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:732
const Options m_opts
Definition: txmempool.h:309
Epoch m_epoch GUARDED_BY(cs)
minimum fee to get into the pool, decreases exponentially
Definition: txmempool.h:200
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:554
indexed_transaction_set mapTx GUARDED_BY(cs)
TxMempoolInfo info(const T &id) const
Definition: txmempool.h:521
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
uint64_t totalTxSize GUARDED_BY(cs)
Definition: txmempool.h:193
boost::multi_index_container< CTxMemPoolEntry, CTxMemPoolEntry_Indices > indexed_transaction_set
Definition: txmempool.h:237
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
int64_t GetDescendantCount(txiter it) const
Definition: txmempool.h:277
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
int64_t lastRollingFeeUpdate GUARDED_BY(cs)
sum of dynamic memory usage of all the map elements (NOT the maps themselves)
Definition: txmempool.h:197
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
bool m_load_tried GUARDED_BY(cs)
Definition: txmempool.h:209
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
FeePerWeight GetMainChunkFeerate(const CTxMemPoolEntry &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:398
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
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:575
int64_t GetAncestorCount(const CTxMemPoolEntry &e) const
Definition: txmempool.h:279
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
double rollingMinimumFeeRate GUARDED_BY(cs)
Definition: txmempool.h:199
std::map< txiter, setEntries, CompareIteratorByHash > cacheMap
Definition: txmempool.h:284
bool m_epoch
Definition: txmempool.h:608
int64_t GetDescendantCount(const CTxMemPoolEntry &e) const
Definition: txmempool.h:278
void SkipBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:761
void AddUnbroadcastTx(const Txid &txid)
Adds a transaction to the unbroadcast set.
Definition: txmempool.h:543
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
bool IsUnbroadcastTx(const Txid &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns whether a txid is in the unbroadcast set.
Definition: txmempool.h:564
std::unique_ptr< TxGraph > m_txgraph GUARDED_BY(cs)
std::set< Txid > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:557
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
unsigned long size() const
Definition: txmempool.h:486
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
uint64_t m_sequence_number GUARDED_BY(cs)
Definition: txmempool.h:205
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::unique_ptr< TxGraph::BlockBuilder > m_builder GUARDED_BY(cs)
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:542
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:498
indirectmap< COutPoint, txiter > mapNextTx GUARDED_BY(cs)
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:492
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
CAmount m_total_fee GUARDED_BY(cs)
sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discount...
Definition: txmempool.h:194
Definition: txmempool.h:98
bool operator()(const CTxMemPoolEntry &a, const CTxMemPoolEntry &b) const
Definition: txmempool.h:100
Epoch: RAII-style guard for using epoch-based graph traversal algorithms.
Definition: epochguard.h:35
@ MAIN
Always refers to the main graph, whether staging is present or not.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
uint64_t fee
LockPoints lp
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
T check(T ptr)
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
Definition: txmempool.h:233
const CAmount delta
The fee delta added using PrioritiseTransaction().
Definition: txmempool.h:356
const bool in_mempool
Whether this transaction is in the mempool.
Definition: txmempool.h:354
std::optional< CAmount > modified_fee
The modified fee (base fee + delta) of this entry.
Definition: txmempool.h:358
const Txid txid
The prioritised transaction's txid.
Definition: txmempool.h:360
Tagged wrapper around FeeFrac to avoid unit confusion.
Definition: feefrac.h:239
Information about a mempool transaction.
Definition: txmempool.h:114
int64_t nFeeDelta
The fee delta.
Definition: txmempool.h:128
int32_t vsize
Virtual size of the transaction.
Definition: txmempool.h:125
CAmount fee
Fee of the transaction.
Definition: txmempool.h:122
CTransactionRef tx
The transaction itself.
Definition: txmempool.h:116
std::chrono::seconds m_time
Time the transaction entered the mempool.
Definition: txmempool.h:119
Bilingual messages:
Definition: translation.h:24
Options struct containing limit options for a CTxMemPool.
Options struct containing options for constructing a CTxMemPool.
result_type operator()(const CTxMemPoolEntry &entry) const
Definition: txmempool.h:71
result_type operator()(const CTxMemPoolEntry &entry) const
Definition: txmempool.h:86
#define LOCK(cs)
Definition: sync.h:259
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
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
bool TestLockPointValidity(CChain &active_chain, const LockPoints &lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Test whether the LockPoints height and time are still valid on the current chain.
Definition: txmempool.cpp:40
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())