Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #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>
19 : : #include <primitives/transaction.h>
20 : : #include <primitives/transaction_identifier.h>
21 : : #include <sync.h>
22 : : #include <txgraph.h>
23 : : #include <util/feefrac.h>
24 : : #include <util/hasher.h>
25 : : #include <util/result.h>
26 : :
27 : : #include <boost/multi_index/hashed_index.hpp>
28 : : #include <boost/multi_index/identity.hpp>
29 : : #include <boost/multi_index/indexed_by.hpp>
30 : : #include <boost/multi_index/ordered_index.hpp>
31 : : #include <boost/multi_index/sequenced_index.hpp>
32 : : #include <boost/multi_index/tag.hpp>
33 : : #include <boost/multi_index_container.hpp>
34 : :
35 : : #include <atomic>
36 : : #include <map>
37 : : #include <optional>
38 : : #include <set>
39 : : #include <string>
40 : : #include <string_view>
41 : : #include <utility>
42 : : #include <vector>
43 : :
44 : : class CChain;
45 : : class ValidationSignals;
46 : :
47 : : struct bilingual_str;
48 : :
49 : : /** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
50 : : static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
51 : :
52 : : /** How much linearization cost required for TxGraph clusters to have
53 : : * "acceptable" quality, if they cannot be optimally linearized with less cost. */
54 : : static constexpr uint64_t ACCEPTABLE_COST = 75'000;
55 : :
56 : : /** How much work we ask TxGraph to do after a mempool change occurs (either
57 : : * due to a changeset being applied, a new block being found, or a reorg). */
58 : : static constexpr uint64_t POST_CHANGE_COST = 5 * ACCEPTABLE_COST;
59 : :
60 : : /**
61 : : * Test whether the LockPoints height and time are still valid on the current chain
62 : : */
63 : : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
64 : :
65 : : // extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
66 : : struct mempoolentry_txid
67 : : {
68 : : typedef Txid result_type;
69 : 20459032 : result_type operator() (const CTxMemPoolEntry &entry) const
70 : : {
71 [ + + ][ - + : 20459032 : return entry.GetTx().GetHash();
+ + - - ]
72 : : }
73 : :
74 : : result_type operator() (const CTransactionRef& tx) const
75 : : {
76 : : return tx->GetHash();
77 : : }
78 : : };
79 : :
80 : : // extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
81 : : struct mempoolentry_wtxid
82 : : {
83 : : typedef Wtxid result_type;
84 : 346635 : result_type operator() (const CTxMemPoolEntry &entry) const
85 : : {
86 [ + + ]: 346635 : return entry.GetTx().GetWitnessHash();
[ - + + + ]
87 : : }
88 : :
89 : : result_type operator() (const CTransactionRef& tx) const
90 : : {
91 : : return tx->GetWitnessHash();
92 : : }
93 : : };
94 : :
95 : : class CompareTxMemPoolEntryByEntryTime
96 : : {
97 : : public:
98 : 438566 : bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
99 : : {
100 : 438566 : return a.GetTime() < b.GetTime();
101 : : }
102 : : };
103 : :
104 : : // Multi_index tag names
105 : : struct entry_time {};
106 : : struct index_by_wtxid {};
107 : :
108 : : /**
109 : : * Information about a mempool transaction.
110 : : */
111 [ # # ][ + - : 22255 : struct TxMempoolInfo
- + - - ]
[ - - - -
- + - - ]
[ + - - - ]
112 : : {
113 : : /** The transaction itself */
114 : : CTransactionRef tx;
115 : :
116 : : /** Time the transaction entered the mempool. */
117 : : std::chrono::seconds m_time;
118 : :
119 : : /** Fee of the transaction. */
120 : : CAmount fee;
121 : :
122 : : /** Virtual size of the transaction. */
123 : : int32_t vsize;
124 : :
125 : : /** The fee delta. */
126 : : int64_t nFeeDelta;
127 : : };
128 : :
129 : : /**
130 : : * CTxMemPool stores valid-according-to-the-current-best-chain transactions
131 : : * that may be included in the next block.
132 : : *
133 : : * Transactions are added when they are seen on the network (or created by the
134 : : * local node), but not all transactions seen are added to the pool. For
135 : : * example, the following new transactions will not be added to the mempool:
136 : : * - a transaction which doesn't meet the minimum fee requirements.
137 : : * - a new transaction that double-spends an input of a transaction already in
138 : : * the pool where the new transaction does not meet the Replace-By-Fee
139 : : * requirements as defined in doc/policy/mempool-replacements.md.
140 : : * - a non-standard transaction.
141 : : *
142 : : * TxGraph (CTxMemPool::m_txgraph) provides an abstraction layer for separating
143 : : * the transaction graph parts of the mempool from the rest of the
144 : : * Bitcoin-specific logic. Specifically, TxGraph handles (for each transaction)
145 : : * managing the in-mempool parents and children, and has knowledge of the fee
146 : : * and size of every transaction. It uses this to partition the mempool into
147 : : * connected clusters, and it implements (among other things):
148 : : * - limits on the size of a cluster (in both number of transactions
149 : : * and total weight)
150 : : * - sorting the mempool optimally for block inclusion, taking into account
151 : : * dependencies
152 : : * - selecting transactions for removal due to cluster size limit violations
153 : : * after a reorg.
154 : : * See txgraph.h and txgraph.cpp for more details.
155 : : *
156 : : * CTxMemPool itself handles the Bitcoin-specific parts of mempool
157 : : * transactions; it stores the full transaction inside CTxMemPoolEntry, along
158 : : * with other consensus-specific fields (such as whether a transaction spends a
159 : : * coinbase, or the LockPoints for transaction finality). And it provides
160 : : * interfaces to the rest of the codebase, such as:
161 : : * - to validation for replace-by-fee calculations and cluster size limits
162 : : * when evaluating unconfirmed transactions
163 : : * - to validation for evicting transactions due to expiry or the mempool size
164 : : * limit being hit
165 : : * - to validation for updating the mempool to be consistent with the best
166 : : * chain after a new block is connected or after a reorg.
167 : : * - to net_processing for ordering transactions that are to-be-announced to
168 : : * other peers
169 : : * - to RPC code for inspecting the mempool
170 : : *
171 : : * (Many of these interfaces are just wrappers around corresponding TxGraph
172 : : * functions.)
173 : : *
174 : : * Within CTxMemPool, the mempool entries are stored in a boost::multi_index
175 : : * mapTx, which sorts the mempool on 3 criteria:
176 : : * - transaction hash (txid)
177 : : * - witness-transaction hash (wtxid)
178 : : * - time in mempool
179 : : *
180 : : * We also maintain a map from COutPoint to the (in-mempool) transaction that
181 : : * spends it (mapNextTx). This allows us to recover from a reorg and find
182 : : * transactions in the mempool that conflict with transactions that are
183 : : * confirmed in a block.
184 : : *
185 : : */
186 : : class CTxMemPool
187 : : {
188 : : protected:
189 : : std::atomic<unsigned int> nTransactionsUpdated{0}; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
190 : :
191 : : uint64_t totalTxSize GUARDED_BY(cs){0}; //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141.
192 : : CAmount m_total_fee GUARDED_BY(cs){0}; //!< sum of all mempool tx's fees (NOT modified fee)
193 : : uint64_t cachedInnerUsage GUARDED_BY(cs){0}; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
194 : :
195 : : mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs){GetTime()};
196 : : mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs){false};
197 : : mutable double rollingMinimumFeeRate GUARDED_BY(cs){0}; //!< minimum fee to get into the pool, decreases exponentially
198 : :
199 : : // In-memory counter for external mempool tracking purposes.
200 : : // This number is incremented once every time a transaction
201 : : // is added or removed from the mempool for any reason.
202 : : mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
203 : :
204 : : void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);
205 : :
206 : : bool m_load_tried GUARDED_BY(cs){false};
207 : :
208 : : CFeeRate GetMinFee(size_t sizelimit) const;
209 : :
210 : : public:
211 : :
212 : : static constexpr int ROLLING_FEE_HALFLIFE{60 * 60 * 12}; // public only for testing
213 : :
214 : : using indexed_transaction_set = boost::multi_index_container<
215 : : CTxMemPoolEntry,
216 : : boost::multi_index::indexed_by<
217 : : // sorted by txid
218 : : boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
219 : : // sorted by wtxid
220 : : boost::multi_index::hashed_unique<
221 : : boost::multi_index::tag<index_by_wtxid>,
222 : : mempoolentry_wtxid,
223 : : SaltedWtxidHasher
224 : : >,
225 : : // sorted by entry time
226 : : boost::multi_index::ordered_non_unique<
227 : : boost::multi_index::tag<entry_time>,
228 : : boost::multi_index::identity<CTxMemPoolEntry>,
229 : : CompareTxMemPoolEntryByEntryTime
230 : : >
231 : : >
232 : : >;
233 : :
234 : : /**
235 : : * This mutex needs to be locked when accessing `mapTx` or other members
236 : : * that are guarded by it.
237 : : *
238 : : * @par Consistency guarantees
239 : : * By design, it is guaranteed that:
240 : : * 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool
241 : : * that is consistent with current chain tip (`ActiveChain()` and
242 : : * `CoinsTip()`) and is fully populated. Fully populated means that if the
243 : : * current active chain is missing transactions that were present in a
244 : : * previously active chain, all the missing transactions will have been
245 : : * re-added to the mempool and should be present if they meet size and
246 : : * consistency constraints.
247 : : * 2. Locking `mempool.cs` without `cs_main` will give a view of a mempool
248 : : * consistent with some chain that was active since `cs_main` was last
249 : : * locked, and that is fully populated as described above. It is ok for
250 : : * code that only needs to query or remove transactions from the mempool
251 : : * to lock just `mempool.cs` without `cs_main`.
252 : : *
253 : : * To provide these guarantees, it is necessary to lock both `cs_main` and
254 : : * `mempool.cs` whenever adding transactions to the mempool and whenever
255 : : * changing the chain tip. It's necessary to keep both mutexes locked until
256 : : * the mempool is consistent with the new chain tip and fully populated.
257 : : */
258 : : mutable RecursiveMutex cs ACQUIRED_AFTER(::cs_main);
259 : : std::unique_ptr<TxGraph> m_txgraph GUARDED_BY(cs);
260 : : mutable std::unique_ptr<TxGraph::BlockBuilder> m_builder GUARDED_BY(cs);
261 : : indexed_transaction_set mapTx GUARDED_BY(cs);
262 : :
263 : : using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
264 : : std::vector<std::pair<Wtxid, txiter>> txns_randomized GUARDED_BY(cs); //!< All transactions in mapTx with their wtxids, in arbitrary order
265 : :
266 : : typedef std::set<txiter, CompareIteratorByHash> setEntries;
267 : :
268 : : using Limits = kernel::MemPoolLimits;
269 : :
270 : : std::tuple<size_t, size_t, CAmount> CalculateAncestorData(const CTxMemPoolEntry& entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
271 : : std::tuple<size_t, size_t, CAmount> CalculateDescendantData(const CTxMemPoolEntry& entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
272 [ - + + - ]: 1 : int64_t GetDescendantCount(txiter it) const { LOCK(cs); return m_txgraph->GetDescendants(*it, TxGraph::Level::MAIN).size(); }
273 [ - + + - ]: 86 : int64_t GetDescendantCount(const CTxMemPoolEntry &e) const { LOCK(cs); return m_txgraph->GetDescendants(e, TxGraph::Level::MAIN).size(); }
274 [ - + + - ]: 88 : int64_t GetAncestorCount(const CTxMemPoolEntry &e) const { LOCK(cs); return m_txgraph->GetAncestors(e, TxGraph::Level::MAIN).size(); }
275 : : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> GetChildren(const CTxMemPoolEntry &entry) const;
276 : : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> GetParents(const CTxMemPoolEntry &entry) const;
277 : :
278 : : private:
279 : : std::vector<indexed_transaction_set::const_iterator> GetSortedScoreWithTopology() const EXCLUSIVE_LOCKS_REQUIRED(cs);
280 : :
281 : : /**
282 : : * Track locally submitted transactions to periodically retry initial broadcast.
283 : : */
284 : : std::set<Txid> m_unbroadcast_txids GUARDED_BY(cs);
285 : :
286 : 14952 : static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
287 : : {
288 [ + - + - : 29904 : return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
- - ]
289 : : }
290 : :
291 : : // Helper to remove all transactions that conflict with a given
292 : : // transaction (used for transactions appearing in a block).
293 : : void removeConflicts(const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
294 : :
295 : : public:
296 : : indirectmap<COutPoint, txiter> mapNextTx GUARDED_BY(cs);
297 : : std::map<Txid, CAmount> mapDeltas GUARDED_BY(cs);
298 : :
299 : : using Options = kernel::MemPoolOptions;
300 : :
301 : : const Options m_opts;
302 : :
303 : : /** Create a new CTxMemPool.
304 : : * Sanity checks will be off by default for performance, because otherwise
305 : : * accepting transactions becomes O(N^2) where N is the number of transactions
306 : : * in the pool.
307 : : */
308 : : explicit CTxMemPool(Options opts, bilingual_str& error);
309 : :
310 : : /**
311 : : * If sanity-checking is turned on, check makes sure the pool is
312 : : * consistent (does not contain two transactions that spend the same inputs,
313 : : * all inputs are in the mapNextTx array). If sanity-checking is turned off,
314 : : * check does nothing.
315 : : */
316 : : void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
317 : :
318 : : /**
319 : : * Remove a transaction from the mempool along with any descendants.
320 : : * If the transaction is not already in the mempool, find any descendants
321 : : * and remove them.
322 : : */
323 : : void removeRecursive(const CTransaction& tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
324 : : /** After reorg, filter the entries that would no longer be valid in the next block, and update
325 : : * the entries' cached LockPoints if needed. The mempool does not have any knowledge of
326 : : * consensus rules. It just applies the callable function and removes the ones for which it
327 : : * returns true.
328 : : * @param[in] filter_final_and_mature Predicate that checks the relevant validation rules
329 : : * and updates an entry's LockPoints.
330 : : * */
331 : : void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
332 : : void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
333 : :
334 : : /** Look up wtxids in the mempool and (partially) sort by mining score.
335 : : *
336 : : * The @p n_to_sort best entries are removed from @p wtxids and their
337 : : * corresponding txiter entries are returned. In addition wtxids
338 : : * that are duplicates or were not found in the mempool are silently
339 : : * dropped from @p wtxids. The returned vector is ordered from best
340 : : * to worst (by CompareMainOrder). Entries remaining in @p wtxids
341 : : * are in unspecified order.
342 : : *
343 : : * Note that the returned `txiter` values may become invalidated once
344 : : * mempool.cs is released.
345 : : */
346 : : std::vector<txiter> ExtractBestByMiningScoreWithTopology(std::vector<Wtxid>& wtxids, size_t n_to_sort) const EXCLUSIVE_LOCKS_REQUIRED(cs);
347 : : bool isSpent(const COutPoint& outpoint) const;
348 : : unsigned int GetTransactionsUpdated() const;
349 : : void AddTransactionsUpdated(unsigned int n);
350 : : /**
351 : : * Check that none of this transactions inputs are in the mempool, and thus
352 : : * the tx is not dependent on other mempool transactions to be included in a block.
353 : : */
354 : : bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs);
355 : :
356 : : /** Affect CreateNewBlock prioritisation of transactions */
357 : : void PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta);
358 : : void ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
359 : : void ClearPrioritisation(const Txid& hash) EXCLUSIVE_LOCKS_REQUIRED(cs);
360 : :
361 : : struct delta_info {
362 : : /** Whether this transaction is in the mempool. */
363 : : const bool in_mempool;
364 : : /** The fee delta added using PrioritiseTransaction(). */
365 : : const CAmount delta;
366 : : /** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */
367 : : std::optional<CAmount> modified_fee;
368 : : /** The prioritised transaction's txid. */
369 : : const Txid txid;
370 : : };
371 : : /** Return a vector of all entries in mapDeltas with their corresponding delta_info. */
372 : : std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
373 : :
374 : : /** Get the transaction in the pool that spends the same prevout */
375 : : const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
376 : :
377 : : /** Returns an iterator to the given hash, if found */
378 : : std::optional<txiter> GetIter(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
379 : : std::optional<txiter> GetIter(const Wtxid& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
380 : :
381 : : /** Translate a set of hashes into a set of pool iterators to avoid repeated lookups.
382 : : * Does not require that all of the hashes correspond to actual transactions in the mempool,
383 : : * only returns the ones that exist. */
384 : : setEntries GetIterSet(const std::set<Txid>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
385 : :
386 : : /** Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
387 : : * The nth element in txids becomes the nth element in the returned vector. If any of the txids
388 : : * don't actually exist in the mempool, returns an empty vector. */
389 : : std::vector<txiter> GetIterVec(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
390 : :
391 : : /** UpdateTransactionsFromBlock is called when adding transactions from a
392 : : * disconnected block back to the mempool, new mempool entries may have
393 : : * children in the mempool (which is generally not the case when otherwise
394 : : * adding transactions).
395 : : * @post updated descendant state for descendants of each transaction in
396 : : * vHashesToUpdate (excluding any child transactions present in
397 : : * vHashesToUpdate, which are already accounted for). Updated state
398 : : * includes add fee/size information for such descendants to the
399 : : * parent and updated ancestor state to include the parent.
400 : : *
401 : : * @param[in] vHashesToUpdate The set of txids from the
402 : : * disconnected block that have been accepted back into the mempool.
403 : : */
404 : : void UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
405 : :
406 : : std::vector<FeePerWeight> GetFeerateDiagram() const EXCLUSIVE_LOCKS_REQUIRED(cs);
407 : 60249 : FeePerWeight GetMainChunkFeerate(const CTxMemPoolEntry& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
408 : 60249 : return m_txgraph->GetMainChunkFeerate(tx);
409 : : }
410 : 1144 : std::vector<const CTxMemPoolEntry*> GetCluster(Txid txid) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
411 : 1144 : auto tx = GetIter(txid);
412 [ - + ]: 1144 : if (!tx) return {};
413 : 1144 : auto cluster = m_txgraph->GetCluster(**tx, TxGraph::Level::MAIN);
414 : 1144 : std::vector<const CTxMemPoolEntry*> ret;
415 [ - + + - ]: 1144 : ret.reserve(cluster.size());
416 [ + + ]: 27046 : for (const auto& tx : cluster) {
417 [ + - ]: 25902 : ret.emplace_back(static_cast<const CTxMemPoolEntry*>(tx));
418 : : }
419 : 1144 : return ret;
420 : 1144 : }
421 : :
422 : :
423 : 1347 : size_t GetUniqueClusterCount(const setEntries& iters_conflicting) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
424 : 1347 : std::vector<const TxGraph::Ref *> entries;
425 [ + - ]: 1347 : entries.reserve(iters_conflicting.size());
426 [ + + ]: 3949 : for (auto it : iters_conflicting) {
427 [ + - ]: 2602 : entries.emplace_back(&*it);
428 : : }
429 [ - + ]: 1347 : Assume(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
430 [ - + ]: 1347 : return m_txgraph->CountDistinctClusters(entries, TxGraph::Level::MAIN);
431 : 1347 : }
432 : :
433 : : /**
434 : : * Calculate all in-mempool ancestors of entry (not including the tx itself)
435 : : *
436 : : * @param[in] entry CTxMemPoolEntry of which all in-mempool ancestors are calculated
437 : : *
438 : : * @return all in-mempool ancestors
439 : : */
440 : : setEntries CalculateMemPoolAncestors(const CTxMemPoolEntry& entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
441 : :
442 : : bool HasDescendants(const Txid& txid) const;
443 : :
444 : : /** Collect the entire cluster of connected transactions for each transaction in txids.
445 : : * All txids must correspond to transaction entries in the mempool, otherwise this returns an
446 : : * empty vector. This call will also exit early and return an empty vector if it collects 500 or
447 : : * more transactions as a DoS protection. */
448 : : std::vector<txiter> GatherClusters(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
449 : :
450 : : /** Populate setDescendants with all in-mempool descendants of given transaction.
451 : : * Assumes that setDescendants includes all in-mempool descendants of anything
452 : : * already in it. */
453 : : void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
454 : : CTxMemPool::txiter CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
455 : :
456 : : /** The minimum fee to get into the mempool, which may itself not be enough
457 : : * for larger-sized transactions.
458 : : * The m_incremental_relay_feerate policy variable is used to bound the time it
459 : : * takes the fee rate to go back down all the way to 0. When the feerate
460 : : * would otherwise be half of this, it is set to 0 instead.
461 : : */
462 : 452799 : CFeeRate GetMinFee() const {
463 [ + - ][ + - : 452799 : return GetMinFee(m_opts.max_size_bytes);
+ - + - +
- ]
464 : : }
465 : :
466 : : /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
467 : : * pvNoSpendsRemaining, if set, will be populated with the list of outpoints
468 : : * which are not in mempool which no longer have any spends in this mempool.
469 : : */
470 : : void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
471 : :
472 : : /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
473 : : int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
474 : :
475 : : /**
476 : : * Calculate the ancestor and cluster count for the given transaction.
477 : : * The counts include the transaction itself.
478 : : * When ancestors is non-zero (ie, the transaction itself is in the mempool),
479 : : * ancestorsize and ancestorfees will also be set to the appropriate values.
480 : : */
481 : : void GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
482 : :
483 : : /**
484 : : * @returns true if an initial attempt to load the persisted mempool was made, regardless of
485 : : * whether the attempt was successful or not
486 : : */
487 : : bool GetLoadTried() const;
488 : :
489 : : /**
490 : : * Set whether or not an initial attempt to load the persisted mempool was made (regardless
491 : : * of whether the attempt was successful or not)
492 : : */
493 : : void SetLoadTried(bool load_tried);
494 : :
495 : 5690316 : unsigned long size() const
496 : : {
497 : 5690316 : LOCK(cs);
498 [ + - ]: 5690316 : return mapTx.size();
499 : 5690316 : }
500 : :
501 : 1250 : uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
502 : : {
503 : 1250 : AssertLockHeld(cs);
504 [ + - ]: 1250 : return totalTxSize;
505 : : }
506 : :
507 : 1250 : CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
508 : : {
509 : 1250 : AssertLockHeld(cs);
510 [ + - ]: 1250 : return m_total_fee;
511 : : }
512 : :
513 : 310556 : bool exists(const Txid& txid) const
514 : : {
515 : 310556 : LOCK(cs);
516 [ + - ]: 310556 : return (mapTx.count(txid) != 0);
517 : 310556 : }
518 : :
519 : 100618 : bool exists(const Wtxid& wtxid) const
520 : : {
521 : 100618 : LOCK(cs);
522 [ + - ]: 100618 : return (mapTx.get<index_by_wtxid>().count(wtxid) != 0);
523 : 100618 : }
524 : :
525 : : const CTxMemPoolEntry* GetEntry(const Txid& txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs);
526 : :
527 : : /**
528 : : * Return a mempool transaction with a given hash.
529 : : *
530 : : * @param[in] hash the txid
531 : : * @returns the tx if found, otherwise nullptr
532 : : */
533 : : CTransactionRef get(const Txid& hash) const;
534 : :
535 : : /**
536 : : * Return a mempool transaction with a given witness hash.
537 : : *
538 : : * @param[in] hash the wtxid
539 : : * @returns the tx if found, otherwise nullptr
540 : : */
541 : : CTransactionRef get(const Wtxid& hash) const;
542 : :
543 : : template <TxidOrWtxid T>
544 : 3490 : TxMempoolInfo info(const T& id) const
545 : : {
546 : 3490 : LOCK(cs);
547 [ + - ]: 3490 : auto i{GetIter(id)};
548 [ + - + - ]: 3490 : return i.has_value() ? GetInfo(*i) : TxMempoolInfo{};
549 : 3490 : }
550 : :
551 : : /** Returns info for a transaction if its entry_sequence < last_sequence */
552 : : template <TxidOrWtxid T>
553 : 10235 : TxMempoolInfo info_for_relay(const T& id, uint64_t last_sequence) const
554 : : {
555 : 10235 : LOCK(cs);
556 [ + - ]: 10235 : auto i{GetIter(id)};
557 [ + + + + : 10235 : return (i.has_value() && i.value()->GetSequence() < last_sequence) ? GetInfo(*i) : TxMempoolInfo{};
+ - ]
558 : 10235 : }
559 : :
560 : : std::vector<CTxMemPoolEntryRef> entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs);
561 : : std::vector<TxMempoolInfo> infoAll() const;
562 : :
563 : : size_t DynamicMemoryUsage() const;
564 : :
565 : : /** Adds a transaction to the unbroadcast set */
566 : 15014 : void AddUnbroadcastTx(const Txid& txid)
567 : : {
568 : 15014 : LOCK(cs);
569 : : // Sanity check the transaction is in the mempool & insert into
570 : : // unbroadcast set.
571 [ + - + - : 15014 : if (exists(txid)) m_unbroadcast_txids.insert(txid);
+ - ]
572 : 15014 : };
573 : :
574 : : bool CheckPolicyLimits(const CTransactionRef& tx);
575 : :
576 : : /** Removes a transaction from the unbroadcast set */
577 : : void RemoveUnbroadcastTx(const Txid& txid, bool unchecked = false);
578 : :
579 : : /** Returns transactions in unbroadcast set */
580 : 2252 : std::set<Txid> GetUnbroadcastTxs() const
581 : : {
582 : 2252 : LOCK(cs);
583 [ + - + - ]: 2252 : return m_unbroadcast_txids;
584 : 2252 : }
585 : :
586 : : /** Returns whether a txid is in the unbroadcast set */
587 : 8469 : bool IsUnbroadcastTx(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
588 : : {
589 : 8469 : AssertLockHeld(cs);
590 : 8469 : return m_unbroadcast_txids.contains(txid);
591 : : }
592 : :
593 : : /** Guards this internal counter for external reporting */
594 : 97603 : uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
595 [ + - + - ]: 97603 : return m_sequence_number++;
[ + + ][ + -
+ - + - ]
596 : : }
597 : :
598 : 57445 : uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
599 [ + - ]: 57445 : return m_sequence_number;
600 : : }
601 : :
602 : : private:
603 : : /** Remove a set of transactions from the mempool.
604 : : * If a transaction is in this set, then all in-mempool descendants must
605 : : * also be in the set, unless this transaction is being removed for being
606 : : * in a block.
607 : : */
608 : : void RemoveStaged(setEntries& stage, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
609 : :
610 : : /* Helper for the public removeRecursive() */
611 : : void removeRecursive(txiter to_remove, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
612 : :
613 : : /* Removal from the mempool also triggers removal of the entry's Ref from txgraph. */
614 : : void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
615 : : public:
616 : : /*
617 : : * CTxMemPool::ChangeSet:
618 : : *
619 : : * This class is used for all mempool additions and associated removals (eg
620 : : * due to rbf). Removals that don't need to be evaluated for acceptance,
621 : : * such as removing transactions that appear in a block, or due to reorg,
622 : : * or removals related to mempool limiting or expiry do not need to use
623 : : * this.
624 : : *
625 : : * Callers can interleave calls to StageAddition()/StageRemoval(), and
626 : : * removals may be invoked in any order, but additions must be done in a
627 : : * topological order in the case of transaction packages (ie, parents must
628 : : * be added before children).
629 : : *
630 : : * CalculateChunksForRBF() can be used to calculate the feerate diagram of
631 : : * the proposed set of new transactions and compare with the existing
632 : : * mempool.
633 : : *
634 : : * CalculateMemPoolAncestors() calculates the in-mempool (not including
635 : : * what is in the change set itself) ancestors of a given transaction.
636 : : *
637 : : * Apply() will apply the removals and additions that are staged into the
638 : : * mempool.
639 : : *
640 : : * Only one changeset may exist at a time. While a changeset is
641 : : * outstanding, no removals or additions may be made directly to the
642 : : * mempool.
643 : : */
644 : : class ChangeSet {
645 : : public:
646 : 72400 : explicit ChangeSet(CTxMemPool* pool) : m_pool(pool) { m_pool->m_txgraph->StartStaging(); }
647 : 72400 : ~ChangeSet() EXCLUSIVE_LOCKS_REQUIRED(m_pool->cs) {
648 : 72400 : AssertLockHeld(m_pool->cs);
649 [ + + ]: 72400 : if (m_pool->m_txgraph->HaveStaging()) {
650 : 20896 : m_pool->m_txgraph->AbortStaging();
651 : : }
652 : 72400 : m_pool->m_have_changeset = false;
653 : 72400 : }
654 : :
655 : : ChangeSet(const ChangeSet&) = delete;
656 : : ChangeSet& operator=(const ChangeSet&) = delete;
657 : :
658 : : using TxHandle = CTxMemPool::txiter;
659 : :
660 : : 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);
661 : :
662 : : void StageRemoval(CTxMemPool::txiter it);
663 : :
664 [ + + ]: 25822 : const CTxMemPool::setEntries& GetRemovals() const { return m_to_remove; }
665 : :
666 : : /** Check if any cluster limits are exceeded. Returns true if pass, false if fail. */
667 : : bool CheckMemPoolPolicyLimits();
668 : :
669 : 1272 : CTxMemPool::setEntries CalculateMemPoolAncestors(TxHandle tx)
670 : : {
671 : : // Look up transaction in our cache first
672 : 1272 : auto it = m_ancestors.find(tx);
673 [ - + ]: 1272 : if (it != m_ancestors.end()) return it->second;
674 : :
675 : : // If not found, try to have the mempool calculate it, and cache
676 : : // for later.
677 : 1272 : LOCK(m_pool->cs);
678 [ + - ]: 1272 : auto ret = m_pool->CalculateMemPoolAncestors(*tx);
679 [ + - ]: 1272 : m_ancestors.try_emplace(tx, ret);
680 : 1272 : return ret;
681 [ + - ]: 2544 : }
682 : :
683 : 379 : std::vector<CTransactionRef> GetAddedTxns() const {
684 : 379 : std::vector<CTransactionRef> ret;
685 [ - + + - ]: 379 : ret.reserve(m_entry_vec.size());
686 [ + + ]: 1137 : for (const auto& entry : m_entry_vec) {
687 [ + - + - ]: 2274 : ret.emplace_back(entry->GetSharedTx());
688 : : }
689 : 379 : return ret;
690 : 0 : }
691 : :
692 : : /**
693 : : * Calculate the sorted chunks for the old and new mempool relating to the
694 : : * clusters that would be affected by a potential replacement transaction.
695 : : *
696 : : * @return old and new diagram pair respectively, or an error string if the conflicts don't match a calculable topology
697 : : */
698 : : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CalculateChunksForRBF();
699 : :
700 [ - + + + : 1927 : size_t GetTxCount() const { return m_entry_vec.size(); }
- + + - ]
701 [ + - + - ]: 1169 : const CTransaction& GetAddedTxn(size_t index) const { return m_entry_vec.at(index)->GetTx(); }
702 : :
703 : : void Apply() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
704 : :
705 : : private:
706 : : void ProcessDependencies();
707 : :
708 : : CTxMemPool* m_pool;
709 : : CTxMemPool::indexed_transaction_set m_to_add;
710 : : std::vector<CTxMemPool::txiter> m_entry_vec; // track the added transactions' insertion order
711 : : // map from the m_to_add index to the ancestors for the transaction
712 : : std::map<CTxMemPool::txiter, CTxMemPool::setEntries, CompareIteratorByHash> m_ancestors;
713 : : CTxMemPool::setEntries m_to_remove;
714 : : bool m_dependencies_processed{false};
715 : :
716 : : friend class CTxMemPool;
717 : : };
718 : :
719 : 72400 : std::unique_ptr<ChangeSet> GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs) {
720 : 72400 : Assume(!m_have_changeset);
721 : 72400 : m_have_changeset = true;
722 : 72400 : return std::make_unique<ChangeSet>(this);
723 : : }
724 : :
725 : : bool m_have_changeset GUARDED_BY(cs){false};
726 : :
727 : : friend class CTxMemPool::ChangeSet;
728 : :
729 : : private:
730 : : // Apply the given changeset to the mempool, by removing transactions in
731 : : // the to_remove set and adding transactions in the to_add set.
732 : : void Apply(CTxMemPool::ChangeSet* changeset) EXCLUSIVE_LOCKS_REQUIRED(cs);
733 : :
734 : : // addNewTransaction must update state for all ancestors of a given transaction,
735 : : // to track size/count of descendant transactions. First version of
736 : : // addNewTransaction can be used to have it call CalculateMemPoolAncestors(), and
737 : : // then invoke the second version.
738 : : // Note that addNewTransaction is ONLY called (via Apply()) from ATMP
739 : : // outside of tests and any other callers may break wallet's in-mempool
740 : : // tracking (due to lack of CValidationInterface::TransactionAddedToMempool
741 : : // callbacks).
742 : : void addNewTransaction(CTxMemPool::txiter it) EXCLUSIVE_LOCKS_REQUIRED(cs);
743 : : public:
744 [ - + ]: 214914 : void StartBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs) { assert(!m_builder); m_builder = m_txgraph->GetBlockBuilder(); }
745 : 10314854 : FeePerWeight GetBlockBuilderChunk(std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef>& entries) const EXCLUSIVE_LOCKS_REQUIRED(cs)
746 : : {
747 [ - + ]: 10314854 : if (!m_builder) { return {}; }
748 : :
749 : 10314854 : auto res = m_builder->GetCurrentChunk();
750 [ + + ]: 10314854 : if (!res) { return {}; }
751 : :
752 [ + - ]: 10100001 : auto [chunk_entries, chunk_feerate] = *res;
753 [ + + ]: 20223178 : for (TxGraph::Ref* ref : chunk_entries) {
754 [ + - ]: 10123177 : entries.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref));
755 : : }
756 : 10100001 : return chunk_feerate;
757 : 20414855 : }
758 : 10060249 : void IncludeBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder->Include(); }
759 : 39706 : void SkipBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder->Skip(); }
760 [ + - ]: 214914 : void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder.reset(); }
761 : : };
762 : :
763 : : /**
764 : : * CCoinsView that brings transactions from a mempool into view.
765 : : * It does not check for spendings by memory pool transactions.
766 : : * Instead, it provides access to all Coins which are either unspent in the
767 : : * base CCoinsView, are outputs from any mempool transaction, or are
768 : : * tracked temporarily to allow transaction dependencies in package validation.
769 : : * This allows transaction replacement to work as expected, as you want to
770 : : * have all inputs "available" to check signatures, and any cycles in the
771 : : * dependency graph are checked directly in AcceptToMemoryPool.
772 : : * It also allows you to sign a double-spend directly in
773 : : * signrawtransactionwithkey and signrawtransactionwithwallet,
774 : : * as long as the conflicting transaction is not yet confirmed.
775 : : */
776 : : class CCoinsViewMemPool : public CCoinsViewBacked
777 : : {
778 : : /**
779 : : * Coins made available by transactions being validated. Tracking these allows for package
780 : : * validation, since we can access transaction outputs without submitting them to mempool.
781 : : */
782 : : std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
783 : :
784 : : /**
785 : : * Set of all coins that have been fetched from mempool or created using PackageAddTransaction
786 : : * (not base). Used to track the origin of a coin, see GetNonBaseCoins().
787 : : */
788 : : mutable std::unordered_set<COutPoint, SaltedOutpointHasher> m_non_base_coins;
789 : : protected:
790 : : const CTxMemPool& mempool;
791 : :
792 : : public:
793 : : CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
794 : : /** GetCoin, returning whether it exists and is not spent. Also updates m_non_base_coins if the
795 : : * coin is not fetched from base. May populate the base view on cache misses. */
796 : : std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
797 : : /** Add the coins created by this transaction. These coins are only temporarily stored in
798 : : * m_temp_added and cannot be flushed to the back end. Only used for package validation. */
799 : : void PackageAddTransaction(const CTransactionRef& tx);
800 : : /** Get all coins in m_non_base_coins. */
801 : 73712 : const std::unordered_set<COutPoint, SaltedOutpointHasher>& GetNonBaseCoins() const { return m_non_base_coins; }
802 : : /** Clear m_temp_added and m_non_base_coins. */
803 : : void Reset();
804 : : };
805 : : #endif // BITCOIN_TXMEMPOOL_H
|