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