Skip to main content

reth_transaction_pool/
traits.rs

1//! Transaction Pool Traits and Types
2//!
3//! This module defines the core abstractions for transaction pool implementations,
4//! handling the complexity of different transaction representations across the
5//! network, mempool, and the chain itself.
6//!
7//! ## Key Concepts
8//!
9//! ### Transaction Representations
10//!
11//! Transactions exist in different formats throughout their lifecycle:
12//!
13//! 1. **Consensus Format** ([`PoolTransaction::Consensus`])
14//!    - The canonical format stored in blocks
15//!    - Minimal size for efficient storage
16//!    - Example: EIP-4844 transactions store only blob hashes: ([`TransactionSigned::Eip4844`])
17//!
18//! 2. **Pooled Format** ([`PoolTransaction::Pooled`])
19//!    - Extended format for network propagation
20//!    - Includes additional validation data
21//!    - Example: EIP-4844 transactions include full blob sidecars: ([`PooledTransactionVariant`])
22//!
23//! ### Type Relationships
24//!
25//! ```text
26//! NodePrimitives::SignedTx  ←──   NetworkPrimitives::BroadcastedTransaction
27//!        │                              │
28//!        │ (consensus format)           │ (announced to peers)
29//!        │                              │
30//!        └──────────┐  ┌────────────────┘
31//!                   ▼  ▼
32//!            PoolTransaction::Consensus
33//!                   │ ▲
34//!                   │ │ from pooled (always succeeds)
35//!                   │ │
36//!                   ▼ │ try_from consensus (may fail)
37//!            PoolTransaction::Pooled  ←──→  NetworkPrimitives::PooledTransaction
38//!                                             (sent on request)
39//! ```
40//!
41//! ### Special Cases
42//!
43//! #### EIP-4844 Blob Transactions
44//! - Consensus format: Only blob hashes (32 bytes each)
45//! - Pooled format: Full blobs + commitments + proofs (large data per blob)
46//! - Network behavior: Not broadcast automatically, only sent on explicit request
47//!
48//! #### Optimism Deposit Transactions
49//! - Only exist in consensus format
50//! - Never enter the mempool (system transactions)
51//! - Conversion from consensus to pooled always fails
52
53use crate::{
54    blobstore::{BlobCellAvailability, BlobStore, BlobStoreError, PooledBlobSidecar},
55    error::{InvalidPoolTransactionError, PoolError, PoolResult, RawPoolTransactionError},
56    pool::{
57        state::SubPool, BestTransactionFilter, NewTransactionEvent, TransactionEvents,
58        TransactionListenerKind,
59    },
60    validate::{TransactionValidationOutcome, TransactionValidator, ValidPoolTransaction},
61    AddedTransactionOutcome, AllTransactionsEvents, PriceBumpConfig,
62};
63use alloy_consensus::{error::ValueError, transaction::TxHashRef, BlockHeader, Signed, Typed2718};
64use alloy_eips::{
65    eip2718::{Decodable2718, Encodable2718, WithEncoded},
66    eip2930::AccessList,
67    eip4844::{
68        env_settings::KzgSettings, BlobAndProofV1, BlobAndProofV2, BlobCellsAndProofsV1,
69        BlobTransactionValidationError, BYTES_PER_BLOB,
70    },
71    eip7594::{
72        BlobCellMask, BlobSidecarEncoding, BlobTransactionSidecarEip7594,
73        BlobTransactionSidecarVariant, Encodable7594,
74    },
75    eip7702::SignedAuthorization,
76};
77use alloy_primitives::{
78    map::{AddressSet, B256Map},
79    Address, Bytes, TxHash, TxKind, B256, U256,
80};
81use alloy_rlp::{length_of_length, Header};
82use futures_util::{ready, Stream};
83use reth_eth_wire_types::HandleMempoolData;
84use reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};
85use reth_execution_types::ChangedAccount;
86use reth_primitives_traits::{Block, InMemorySize, Recovered, SealedBlock, SignedTransaction};
87use serde::{Deserialize, Serialize};
88use std::{
89    fmt,
90    fmt::Debug,
91    future::Future,
92    num::NonZeroUsize,
93    pin::Pin,
94    sync::Arc,
95    task::{Context, Poll},
96};
97use tokio::sync::mpsc::Receiver;
98
99/// The `PeerId` type.
100pub type PeerId = alloy_primitives::B512;
101
102/// Helper type alias to access [`PoolTransaction`] for a given [`TransactionPool`].
103pub type PoolTx<P> = <P as TransactionPool>::Transaction;
104/// Helper type alias to access [`PoolTransaction::Consensus`] for a given [`TransactionPool`].
105pub type PoolConsensusTx<P> = <<P as TransactionPool>::Transaction as PoolTransaction>::Consensus;
106
107/// Helper type alias to access [`PoolTransaction::Pooled`] for a given [`TransactionPool`].
108pub type PoolPooledTx<P> = <<P as TransactionPool>::Transaction as PoolTransaction>::Pooled;
109
110/// General purpose abstraction of a transaction-pool.
111///
112/// This is intended to be used by API-consumers such as RPC that need inject new incoming,
113/// unverified transactions. And by block production that needs to get transactions to execute in a
114/// new block.
115///
116/// Note: This requires `Clone` for convenience, since it is assumed that this will be implemented
117/// for a wrapped `Arc` type, see also [`Pool`](crate::Pool).
118#[auto_impl::auto_impl(&, Arc)]
119pub trait TransactionPool: Clone + Debug + Send + Sync {
120    /// The transaction type of the pool
121    type Transaction: EthPoolTransaction;
122
123    /// Returns stats about the pool and all sub-pools.
124    fn pool_size(&self) -> PoolSize;
125
126    /// Returns the block the pool is currently tracking.
127    ///
128    /// This tracks the block that the pool has last seen.
129    fn block_info(&self) -> BlockInfo;
130
131    /// Imports an _external_ transaction.
132    ///
133    /// This is intended to be used by the network to insert incoming transactions received over the
134    /// p2p network.
135    ///
136    /// Consumer: P2P
137    fn add_external_transaction(
138        &self,
139        transaction: Self::Transaction,
140    ) -> impl Future<Output = PoolResult<AddedTransactionOutcome>> + Send {
141        self.add_transaction(TransactionOrigin::External, transaction)
142    }
143
144    /// Imports all _external_ transactions
145    ///
146    /// Consumer: Utility
147    fn add_external_transactions(
148        &self,
149        transactions: Vec<Self::Transaction>,
150    ) -> impl Future<Output = Vec<PoolResult<AddedTransactionOutcome>>> + Send {
151        self.add_transactions(TransactionOrigin::External, transactions)
152    }
153
154    /// Adds an _unvalidated_ transaction into the pool and subscribe to state changes.
155    ///
156    /// This is the same as [`TransactionPool::add_transaction`] but returns an event stream for the
157    /// given transaction.
158    ///
159    /// Consumer: Custom
160    fn add_transaction_and_subscribe(
161        &self,
162        origin: TransactionOrigin,
163        transaction: Self::Transaction,
164    ) -> impl Future<Output = PoolResult<TransactionEvents>> + Send;
165
166    /// Adds an _unvalidated_ transaction into the pool.
167    ///
168    /// Consumer: RPC
169    fn add_transaction(
170        &self,
171        origin: TransactionOrigin,
172        transaction: Self::Transaction,
173    ) -> impl Future<Output = PoolResult<AddedTransactionOutcome>> + Send;
174
175    /// Adds the given _unvalidated_ transactions into the pool.
176    ///
177    /// All transactions will use the same `origin`.
178    ///
179    /// Returns a list of results.
180    ///
181    /// Consumer: RPC
182    fn add_transactions(
183        &self,
184        origin: TransactionOrigin,
185        transactions: Vec<Self::Transaction>,
186    ) -> impl Future<Output = Vec<PoolResult<AddedTransactionOutcome>>> + Send;
187
188    /// Adds the given _unvalidated_ transactions into the pool.
189    ///
190    /// Each transaction is paired with its own [`TransactionOrigin`].
191    ///
192    /// Returns a list of results.
193    ///
194    /// Consumer: RPC
195    fn add_transactions_with_origins(
196        &self,
197        transactions: Vec<(TransactionOrigin, Self::Transaction)>,
198    ) -> impl Future<Output = Vec<PoolResult<AddedTransactionOutcome>>> + Send;
199
200    /// Submit a consensus transaction directly to the pool
201    fn add_consensus_transaction(
202        &self,
203        tx: Recovered<<Self::Transaction as PoolTransaction>::Consensus>,
204        origin: TransactionOrigin,
205    ) -> impl Future<Output = PoolResult<AddedTransactionOutcome>> + Send {
206        async move {
207            let tx_hash = *tx.tx_hash();
208
209            let pool_transaction = match Self::Transaction::try_from_consensus(tx) {
210                Ok(tx) => tx,
211                Err(e) => return Err(PoolError::other(tx_hash, e.to_string())),
212            };
213
214            self.add_transaction(origin, pool_transaction).await
215        }
216    }
217
218    /// Submit a consensus transaction and subscribe to event stream
219    fn add_consensus_transaction_and_subscribe(
220        &self,
221        tx: Recovered<<Self::Transaction as PoolTransaction>::Consensus>,
222        origin: TransactionOrigin,
223    ) -> impl Future<Output = PoolResult<TransactionEvents>> + Send {
224        async move {
225            let tx_hash = *tx.tx_hash();
226
227            let pool_transaction = match Self::Transaction::try_from_consensus(tx) {
228                Ok(tx) => tx,
229                Err(e) => return Err(PoolError::other(tx_hash, e.to_string())),
230            };
231
232            self.add_transaction_and_subscribe(origin, pool_transaction).await
233        }
234    }
235
236    /// Returns a new transaction change event stream for the given transaction.
237    ///
238    /// Returns `None` if the transaction is not in the pool.
239    fn transaction_event_listener(&self, tx_hash: TxHash) -> Option<TransactionEvents>;
240
241    /// Returns a new transaction change event stream for _all_ transactions in the pool.
242    fn all_transactions_event_listener(&self) -> AllTransactionsEvents<Self::Transaction>;
243
244    /// Returns a new Stream that yields transactions hashes for new __pending__ transactions
245    /// inserted into the pool that are allowed to be propagated.
246    ///
247    /// Note: This is intended for networking and will __only__ yield transactions that are allowed
248    /// to be propagated over the network, see also [`TransactionListenerKind`].
249    ///
250    /// Consumer: RPC/P2P
251    fn pending_transactions_listener(&self) -> Receiver<TxHash> {
252        self.pending_transactions_listener_for(TransactionListenerKind::PropagateOnly)
253    }
254
255    /// Returns a new [Receiver] that yields transactions hashes for new __pending__ transactions
256    /// inserted into the pending pool depending on the given [`TransactionListenerKind`] argument.
257    fn pending_transactions_listener_for(&self, kind: TransactionListenerKind) -> Receiver<TxHash>;
258
259    /// Returns a new stream that yields new valid transactions added to the pool.
260    fn new_transactions_listener(&self) -> Receiver<NewTransactionEvent<Self::Transaction>> {
261        self.new_transactions_listener_for(TransactionListenerKind::PropagateOnly)
262    }
263
264    /// Returns a new [Receiver] that yields blob "sidecars" (blobs w/ assoc. kzg
265    /// commitments/proofs) for eip-4844 transactions inserted into the pool
266    fn blob_transaction_sidecars_listener(&self) -> Receiver<NewBlobSidecar>;
267
268    /// Returns a new stream that yields new valid transactions added to the pool
269    /// depending on the given [`TransactionListenerKind`] argument.
270    fn new_transactions_listener_for(
271        &self,
272        kind: TransactionListenerKind,
273    ) -> Receiver<NewTransactionEvent<Self::Transaction>>;
274
275    /// Returns a new Stream that yields new transactions added to the pending sub-pool.
276    ///
277    /// This is a convenience wrapper around [`Self::new_transactions_listener`] that filters for
278    /// [`SubPool::Pending`](crate::SubPool).
279    fn new_pending_pool_transactions_listener(
280        &self,
281    ) -> NewSubpoolTransactionStream<Self::Transaction> {
282        NewSubpoolTransactionStream::new(
283            self.new_transactions_listener_for(TransactionListenerKind::PropagateOnly),
284            SubPool::Pending,
285        )
286    }
287
288    /// Returns a new Stream that yields new transactions added to the basefee sub-pool.
289    ///
290    /// This is a convenience wrapper around [`Self::new_transactions_listener`] that filters for
291    /// [`SubPool::BaseFee`](crate::SubPool).
292    fn new_basefee_pool_transactions_listener(
293        &self,
294    ) -> NewSubpoolTransactionStream<Self::Transaction> {
295        NewSubpoolTransactionStream::new(self.new_transactions_listener(), SubPool::BaseFee)
296    }
297
298    /// Returns a new Stream that yields new transactions added to the queued-pool.
299    ///
300    /// This is a convenience wrapper around [`Self::new_transactions_listener`] that filters for
301    /// [`SubPool::Queued`](crate::SubPool).
302    fn new_queued_transactions_listener(&self) -> NewSubpoolTransactionStream<Self::Transaction> {
303        NewSubpoolTransactionStream::new(self.new_transactions_listener(), SubPool::Queued)
304    }
305
306    /// Returns a new Stream that yields new transactions added to the blob sub-pool.
307    ///
308    /// This is a convenience wrapper around [`Self::new_transactions_listener`] that filters for
309    /// [`SubPool::Blob`](crate::SubPool).
310    fn new_blob_pool_transactions_listener(
311        &self,
312    ) -> NewSubpoolTransactionStream<Self::Transaction> {
313        NewSubpoolTransactionStream::new(self.new_transactions_listener(), SubPool::Blob)
314    }
315
316    /// Returns the _hashes_ of all transactions in the pool that are allowed to be propagated.
317    ///
318    /// This excludes hashes that aren't allowed to be propagated.
319    ///
320    /// Note: This returns a `Vec` but should guarantee that all hashes are unique.
321    ///
322    /// Consumer: P2P
323    fn pooled_transaction_hashes(&self) -> Vec<TxHash>;
324
325    /// Returns only the first `max` hashes of transactions in the pool.
326    ///
327    /// Consumer: P2P
328    fn pooled_transaction_hashes_max(&self, max: usize) -> Vec<TxHash>;
329
330    /// Returns the _full_ transaction objects all transactions in the pool that are allowed to be
331    /// propagated.
332    ///
333    /// This is intended to be used by the network for the initial exchange of pooled transaction
334    /// _hashes_
335    ///
336    /// Note: This returns a `Vec` but should guarantee that all transactions are unique.
337    ///
338    /// Caution: In case of blob transactions, this does not include the sidecar.
339    ///
340    /// Consumer: P2P
341    fn pooled_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
342
343    /// Returns only the first `max` transactions in the pool.
344    ///
345    /// Consumer: P2P
346    fn pooled_transactions_max(
347        &self,
348        max: usize,
349    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
350
351    /// Returns converted [`PooledTransactionVariant`] for the given transaction hashes that are
352    /// allowed to be propagated.
353    ///
354    /// This adheres to the expected behavior of
355    /// [`GetPooledTransactions`](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#getpooledtransactions-0x09):
356    ///
357    /// The transactions must be in same order as in the request, but it is OK to skip transactions
358    /// which are not available.
359    ///
360    /// If the transaction is a blob transaction, the sidecar will be included.
361    ///
362    /// Consumer: P2P
363    fn get_pooled_transaction_elements(
364        &self,
365        tx_hashes: Vec<TxHash>,
366        limit: GetPooledTransactionLimit,
367    ) -> Vec<<Self::Transaction as PoolTransaction>::Pooled>;
368
369    /// Extends the given vector with pooled transactions for the given hashes that are allowed to
370    /// be propagated.
371    ///
372    /// This adheres to the expected behavior of [`Self::get_pooled_transaction_elements`].
373    ///
374    /// Consumer: P2P
375    fn append_pooled_transaction_elements(
376        &self,
377        tx_hashes: &[TxHash],
378        limit: GetPooledTransactionLimit,
379        out: &mut Vec<<Self::Transaction as PoolTransaction>::Pooled>,
380    ) {
381        out.extend(self.get_pooled_transaction_elements(tx_hashes.to_vec(), limit));
382    }
383
384    /// Returns pooled transactions for eth/72 peers, converted with
385    /// [`PoolTransaction::pooled_without_blobs`]. The default counts blobs against the size limit.
386    ///
387    /// Consumer: P2P
388    fn get_pooled_transaction_elements_without_blobs(
389        &self,
390        tx_hashes: Vec<TxHash>,
391        limit: GetPooledTransactionLimit,
392    ) -> Vec<<Self::Transaction as PoolTransaction>::Pooled> {
393        self.get_pooled_transaction_elements(tx_hashes, limit)
394            .into_iter()
395            .filter_map(Self::Transaction::pooled_without_blobs)
396            .collect()
397    }
398
399    /// Returns the pooled transaction variant for the given transaction hash.
400    ///
401    /// This adheres to the expected behavior of
402    /// [`GetPooledTransactions`](https://github.com/ethereum/devp2p/blob/master/caps/eth.md#getpooledtransactions-0x09):
403    ///
404    /// If the transaction is a blob transaction, the sidecar will be included.
405    ///
406    /// It is expected that this variant represents the valid p2p format for full transactions.
407    /// E.g. for EIP-4844 transactions this is the consensus transaction format with the blob
408    /// sidecar.
409    ///
410    /// Consumer: P2P
411    fn get_pooled_transaction_element(
412        &self,
413        tx_hash: TxHash,
414    ) -> Option<Recovered<<Self::Transaction as PoolTransaction>::Pooled>>;
415
416    /// Returns an iterator that yields transactions that are ready for block production.
417    ///
418    /// Consumer: Block production
419    fn best_transactions(
420        &self,
421    ) -> Box<dyn BestTransactions<Item = Arc<ValidPoolTransaction<Self::Transaction>>>>;
422
423    /// Returns an iterator that yields transactions that are ready for block production with the
424    /// given base fee and optional blob fee attributes.
425    ///
426    /// Consumer: Block production
427    fn best_transactions_with_attributes(
428        &self,
429        best_transactions_attributes: BestTransactionsAttributes,
430    ) -> Box<dyn BestTransactions<Item = Arc<ValidPoolTransaction<Self::Transaction>>>>;
431
432    /// Returns all transactions that can be included in the next block.
433    ///
434    /// This is primarily used for the `txpool_` RPC namespace:
435    /// <https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool> which distinguishes
436    /// between `pending` and `queued` transactions, where `pending` are transactions ready for
437    /// inclusion in the next block and `queued` are transactions that are ready for inclusion in
438    /// future blocks.
439    ///
440    /// Consumer: RPC
441    fn pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
442
443    /// Returns a pending transaction if it exists and is ready for immediate execution
444    /// (i.e., has the lowest nonce among the sender's pending transactions).
445    fn get_pending_transaction_by_sender_and_nonce(
446        &self,
447        sender: Address,
448        nonce: u64,
449    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
450        self.best_transactions().find(|tx| tx.sender() == sender && tx.nonce() == nonce)
451    }
452
453    /// Returns first `max` transactions that can be included in the next block.
454    /// See <https://github.com/paradigmxyz/reth/issues/12767#issuecomment-2493223579>
455    ///
456    /// Consumer: Block production
457    fn pending_transactions_max(
458        &self,
459        max: usize,
460    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
461
462    /// Returns all transactions that can be included in _future_ blocks.
463    ///
464    /// This and [`Self::pending_transactions`] are mutually exclusive.
465    ///
466    /// Consumer: RPC
467    fn queued_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
468
469    /// Returns the number of transactions that are ready for inclusion in the next block and the
470    /// number of transactions that are ready for inclusion in future blocks: `(pending, queued)`.
471    fn pending_and_queued_txn_count(&self) -> (usize, usize);
472
473    /// Returns all transactions that are currently in the pool grouped by whether they are ready
474    /// for inclusion in the next block or not.
475    ///
476    /// This is primarily used for the `txpool_` namespace: <https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool>
477    ///
478    /// Consumer: RPC
479    fn all_transactions(&self) -> AllPoolTransactions<Self::Transaction>;
480
481    /// Returns all transactions of the given sender that are currently in the pool, grouped by
482    /// whether they are ready for inclusion in the next block or not.
483    ///
484    /// Both groups are collected from one snapshot of the pool, so a transaction that is moved
485    /// between sub-pools concurrently shows up in exactly one of them.
486    ///
487    /// Consumer: RPC
488    fn all_transactions_by_sender(&self, sender: Address)
489        -> AllPoolTransactions<Self::Transaction>;
490
491    /// Returns the _hashes_ of all transactions regardless of whether they can be propagated or
492    /// not.
493    ///
494    /// Unlike [`Self::pooled_transaction_hashes`] this doesn't consider whether the transaction can
495    /// be propagated or not.
496    ///
497    /// Note: This returns a `Vec` but should guarantee that all hashes are unique.
498    ///
499    /// Consumer: Utility
500    fn all_transaction_hashes(&self) -> Vec<TxHash>;
501
502    /// Removes a single transaction corresponding to the given hash.
503    ///
504    /// Note: This removes the transaction as if it got discarded (_not_ mined).
505    ///
506    /// Returns the removed transaction if it was found in the pool.
507    ///
508    /// Consumer: Utility
509    fn remove_transaction(
510        &self,
511        hash: TxHash,
512    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
513        self.remove_transactions(vec![hash]).pop()
514    }
515
516    /// Removes all transactions corresponding to the given hashes.
517    ///
518    /// Note: This removes the transactions as if they got discarded (_not_ mined).
519    ///
520    /// Consumer: Utility
521    fn remove_transactions(
522        &self,
523        hashes: Vec<TxHash>,
524    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
525
526    /// Removes all transactions corresponding to the given hashes.
527    ///
528    /// Also removes all _dependent_ transactions.
529    ///
530    /// Consumer: Utility
531    fn remove_transactions_and_descendants(
532        &self,
533        hashes: Vec<TxHash>,
534    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
535
536    /// Removes all transactions from the given sender
537    ///
538    /// Consumer: Utility
539    fn remove_transactions_by_sender(
540        &self,
541        sender: Address,
542    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
543
544    /// Prunes a single transaction from the pool.
545    ///
546    /// This is similar to [`Self::remove_transaction`] but treats the transaction as _mined_
547    /// rather than discarded. The key difference is that pruning does **not** park descendant
548    /// transactions: their nonce requirements are considered satisfied, so they remain in whatever
549    /// sub-pool they currently occupy and can be included in the next block.
550    ///
551    /// In contrast, [`Self::remove_transaction`] treats the removal as a discard, which
552    /// introduces a nonce gap and moves all descendant transactions to the queued (parked)
553    /// sub-pool.
554    ///
555    /// Returns the pruned transaction if it existed in the pool.
556    ///
557    /// Consumer: Utility
558    fn prune_transaction(
559        &self,
560        hash: TxHash,
561    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
562        self.prune_transactions(vec![hash]).pop()
563    }
564
565    /// Prunes all transactions corresponding to the given hashes from the pool.
566    ///
567    /// This behaves like [`Self::prune_transaction`] but for multiple transactions at once.
568    /// Each transaction is removed as if it was mined: descendant transactions are **not** parked
569    /// and their nonce requirements are considered satisfied.
570    ///
571    /// This is useful for scenarios like Flashblocks where transactions are committed across
572    /// multiple partial blocks without a canonical state update: previously committed transactions
573    /// can be pruned so that the best-transactions iterator yields their descendants in the
574    /// correct priority order.
575    ///
576    /// Consumer: Utility
577    fn prune_transactions(
578        &self,
579        hashes: Vec<TxHash>,
580    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
581
582    /// Retains only those hashes that are unknown to the pool.
583    ///
584    /// In other words, removes all transactions from the given set that are currently present in
585    /// the pool.
586    ///
587    /// Consumer: P2P
588    fn retain_unknown<A>(&self, announcement: &mut A)
589    where
590        A: HandleMempoolData;
591
592    /// Retains only those hashes that are known to the pool.
593    ///
594    /// In other words, removes all transactions from the given set that are not currently present
595    /// in the pool.
596    ///
597    /// Consumer: P2P
598    fn retain_contains<A>(&self, announcement: &mut A)
599    where
600        A: HandleMempoolData;
601
602    /// Returns if the transaction for the given hash is already included in this pool.
603    fn contains(&self, tx_hash: &TxHash) -> bool {
604        self.get(tx_hash).is_some()
605    }
606
607    /// Returns the transaction for the given hash.
608    fn get(&self, tx_hash: &TxHash) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>>;
609
610    /// Returns all transaction objects for the given hashes.
611    ///
612    /// Caution: In case of blob transactions, this does not include the sidecar.
613    fn get_all(&self, txs: Vec<TxHash>) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
614
615    /// Notify the pool about transactions that are propagated to peers.
616    ///
617    /// Consumer: P2P
618    fn on_propagated(&self, txs: PropagatedTransactions);
619
620    /// Returns all transactions sent by a given user
621    fn get_transactions_by_sender(
622        &self,
623        sender: Address,
624    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
625
626    /// Returns all pending transactions filtered by predicate
627    fn get_pending_transactions_with_predicate(
628        &self,
629        predicate: impl FnMut(&ValidPoolTransaction<Self::Transaction>) -> bool,
630    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
631
632    /// Returns all pending transactions sent by a given user
633    fn get_pending_transactions_by_sender(
634        &self,
635        sender: Address,
636    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
637
638    /// Returns all queued transactions sent by a given user
639    fn get_queued_transactions_by_sender(
640        &self,
641        sender: Address,
642    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
643
644    /// Returns the highest transaction sent by a given user
645    fn get_highest_transaction_by_sender(
646        &self,
647        sender: Address,
648    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>>;
649
650    /// Returns the transaction with the highest nonce that is executable given the on chain nonce.
651    /// In other words the highest non nonce gapped transaction.
652    ///
653    /// Note: The next pending pooled transaction must have the on chain nonce.
654    ///
655    /// For example, for a given on chain nonce of `5`, the next transaction must have that nonce.
656    /// If the pool contains txs `[5,6,7]` this returns tx `7`.
657    /// If the pool contains txs `[6,7]` this returns `None` because the next valid nonce (5) is
658    /// missing, which means txs `[6,7]` are nonce gapped.
659    fn get_highest_consecutive_transaction_by_sender(
660        &self,
661        sender: Address,
662        on_chain_nonce: u64,
663    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>>;
664
665    /// Returns a transaction sent by a given user and a nonce
666    fn get_transaction_by_sender_and_nonce(
667        &self,
668        sender: Address,
669        nonce: u64,
670    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>>;
671
672    /// Returns all transactions that where submitted with the given [`TransactionOrigin`]
673    fn get_transactions_by_origin(
674        &self,
675        origin: TransactionOrigin,
676    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
677
678    /// Returns all pending transactions filtered by [`TransactionOrigin`]
679    fn get_pending_transactions_by_origin(
680        &self,
681        origin: TransactionOrigin,
682    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>>;
683
684    /// Returns all transactions that where submitted as [`TransactionOrigin::Local`]
685    fn get_local_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
686        self.get_transactions_by_origin(TransactionOrigin::Local)
687    }
688
689    /// Returns all transactions that where submitted as [`TransactionOrigin::Private`]
690    fn get_private_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
691        self.get_transactions_by_origin(TransactionOrigin::Private)
692    }
693
694    /// Returns all transactions that where submitted as [`TransactionOrigin::External`]
695    fn get_external_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
696        self.get_transactions_by_origin(TransactionOrigin::External)
697    }
698
699    /// Returns all pending transactions that where submitted as [`TransactionOrigin::Local`]
700    fn get_local_pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
701        self.get_pending_transactions_by_origin(TransactionOrigin::Local)
702    }
703
704    /// Returns all pending transactions that where submitted as [`TransactionOrigin::Private`]
705    fn get_private_pending_transactions(
706        &self,
707    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
708        self.get_pending_transactions_by_origin(TransactionOrigin::Private)
709    }
710
711    /// Returns all pending transactions that where submitted as [`TransactionOrigin::External`]
712    fn get_external_pending_transactions(
713        &self,
714    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
715        self.get_pending_transactions_by_origin(TransactionOrigin::External)
716    }
717
718    /// Returns a set of all senders of transactions in the pool
719    fn unique_senders(&self) -> AddressSet;
720
721    /// Returns the [`BlobTransactionSidecarVariant`] for the given transaction hash if it exists in
722    /// the blob store.
723    fn get_blob(
724        &self,
725        tx_hash: TxHash,
726    ) -> Result<Option<Arc<BlobTransactionSidecarVariant>>, BlobStoreError>;
727
728    /// Returns all [`BlobTransactionSidecarVariant`] for the given transaction hashes if they
729    /// exists in the blob store.
730    ///
731    /// This only returns the blobs that were found in the store.
732    /// If there's no blob it will not be returned.
733    fn get_all_blobs(
734        &self,
735        tx_hashes: Vec<TxHash>,
736    ) -> Result<Vec<(TxHash, Arc<BlobTransactionSidecarVariant>)>, BlobStoreError>;
737
738    /// Returns the exact [`BlobTransactionSidecarVariant`] for the given transaction hashes in the
739    /// order they were requested.
740    ///
741    /// Returns an error if any of the blobs are not found in the blob store.
742    fn get_all_blobs_exact(
743        &self,
744        tx_hashes: Vec<TxHash>,
745    ) -> Result<Vec<Arc<BlobTransactionSidecarVariant>>, BlobStoreError>;
746
747    /// Return the [`BlobAndProofV1`]s for a list of blob versioned hashes.
748    fn get_blobs_for_versioned_hashes_v1(
749        &self,
750        versioned_hashes: &[B256],
751    ) -> Result<Vec<Option<BlobAndProofV1>>, BlobStoreError>;
752
753    /// Return the [`BlobAndProofV2`]s for a list of blob versioned hashes.
754    /// Blobs and proofs are returned only if they are present for _all_ of the requested versioned
755    /// hashes.
756    fn get_blobs_for_versioned_hashes_v2(
757        &self,
758        versioned_hashes: &[B256],
759    ) -> Result<Option<Vec<BlobAndProofV2>>, BlobStoreError>;
760
761    /// Return the [`BlobAndProofV2`]s for a list of blob versioned hashes.
762    ///
763    /// The response is always the same length as the request. Missing or older-version blobs are
764    /// returned as `None` elements.
765    fn get_blobs_for_versioned_hashes_v3(
766        &self,
767        versioned_hashes: &[B256],
768    ) -> Result<Vec<Option<BlobAndProofV2>>, BlobStoreError>;
769
770    /// Return the [`BlobCellsAndProofsV1`]s for a list of blob versioned hashes and requested cell
771    /// indices.
772    ///
773    /// The response is always the same length as the request. Missing or older-version blobs are
774    /// returned as `None` elements.
775    fn get_blobs_for_versioned_hashes_v4(
776        &self,
777        versioned_hashes: &[B256],
778        cell_mask: BlobCellMask,
779    ) -> Result<Vec<Option<BlobCellsAndProofsV1>>, BlobStoreError>;
780
781    /// Return whether each requested blob versioned hash is available.
782    ///
783    /// The response is always the same length and order as the request.
784    fn has_blobs_for_versioned_hashes(
785        &self,
786        versioned_hashes: &[B256],
787    ) -> Result<Vec<bool>, BlobStoreError>;
788
789    /// Returns the blob store used by the pool.
790    fn blob_store(&self) -> Box<dyn BlobStore>;
791}
792
793/// Extension for [`TransactionPool`] trait that allows to set the current block info.
794#[auto_impl::auto_impl(&, Arc)]
795pub trait TransactionPoolExt: TransactionPool {
796    /// The block type used for chain tip updates.
797    type Block: Block;
798
799    /// Sets the current block info for the pool.
800    fn set_block_info(&self, info: BlockInfo);
801
802    /// Event listener for when the pool needs to be updated.
803    ///
804    /// Implementers need to update the pool accordingly:
805    ///
806    /// ## Fee changes
807    ///
808    /// The [`CanonicalStateUpdate`] includes the base and blob fee of the pending block, which
809    /// affects the dynamic fee requirement of pending transactions in the pool.
810    ///
811    /// ## EIP-4844 Blob transactions
812    ///
813    /// Mined blob transactions need to be removed from the pool, but from the pool only. The blob
814    /// sidecar must not be removed from the blob store. Only after a blob transaction is
815    /// finalized, its sidecar is removed from the blob store. This ensures that in case of a reorg,
816    /// the sidecar is still available.
817    fn on_canonical_state_change(&self, update: CanonicalStateUpdate<'_, Self::Block>);
818
819    /// Updates the accounts in the pool
820    fn update_accounts(&self, accounts: Vec<ChangedAccount>);
821
822    /// Deletes the blob sidecar for the given transaction from the blob store
823    fn delete_blob(&self, tx: B256);
824
825    /// Deletes multiple blob sidecars from the blob store
826    fn delete_blobs(&self, txs: Vec<B256>);
827
828    /// Maintenance function to cleanup blobs that are no longer needed.
829    fn cleanup_blobs(&self);
830}
831
832/// Extension for [`TransactionPool`] that exposes the pool's underlying [`TransactionValidator`].
833///
834/// This is implemented by pools that validate transactions through a single validator before
835/// insertion (e.g. [`Pool`](crate::Pool)). It lets consumers and wrapper pools reach the validator
836/// directly, for example to validate a transaction without inserting it into the pool.
837pub trait ValidatingPool: TransactionPool {
838    /// The validator used to validate transactions before they are inserted into the pool.
839    type Validator: TransactionValidator<Transaction = Self::Transaction>;
840
841    /// Returns a reference to the pool's transaction validator.
842    fn validator(&self) -> &Self::Validator;
843
844    /// Validates the given transaction without inserting it into the pool.
845    ///
846    /// This is a convenience wrapper around [`TransactionValidator::validate_transaction`].
847    fn validate(
848        &self,
849        origin: TransactionOrigin,
850        transaction: Self::Transaction,
851    ) -> impl Future<Output = TransactionValidationOutcome<Self::Transaction>> + Send {
852        self.validator().validate_transaction(origin, transaction)
853    }
854}
855
856/// A Helper type that bundles all transactions in the pool.
857#[derive(Debug, Clone)]
858pub struct AllPoolTransactions<T: PoolTransaction> {
859    /// Transactions that are ready for inclusion in the next block.
860    pub pending: Vec<Arc<ValidPoolTransaction<T>>>,
861    /// Transactions that are ready for inclusion in _future_ blocks, but are currently parked,
862    /// because they depend on other transactions that are not yet included in the pool (nonce gap)
863    /// or otherwise blocked.
864    pub queued: Vec<Arc<ValidPoolTransaction<T>>>,
865}
866
867// === impl AllPoolTransactions ===
868
869impl<T: PoolTransaction> AllPoolTransactions<T> {
870    /// Returns the combined number of all transactions.
871    pub const fn count(&self) -> usize {
872        self.pending.len() + self.queued.len()
873    }
874
875    /// Returns an iterator over all pending and queued transactions.
876    pub fn iter(&self) -> impl Iterator<Item = &Arc<ValidPoolTransaction<T>>> + '_ {
877        self.pending.iter().chain(self.queued.iter())
878    }
879
880    /// Returns an iterator over all pending [`Recovered`] transactions.
881    pub fn pending_recovered(&self) -> impl Iterator<Item = Recovered<T::Consensus>> + '_ {
882        self.pending.iter().map(|tx| tx.to_consensus())
883    }
884
885    /// Returns an iterator over all queued [`Recovered`] transactions.
886    pub fn queued_recovered(&self) -> impl Iterator<Item = Recovered<T::Consensus>> + '_ {
887        self.queued.iter().map(|tx| tx.to_consensus())
888    }
889
890    /// Returns an iterator over all transactions, both pending and queued.
891    pub fn all(&self) -> impl Iterator<Item = Recovered<T::Consensus>> + '_ {
892        self.pending.iter().chain(self.queued.iter()).map(|tx| tx.to_consensus())
893    }
894}
895
896impl<T: PoolTransaction> Default for AllPoolTransactions<T> {
897    fn default() -> Self {
898        Self { pending: Default::default(), queued: Default::default() }
899    }
900}
901
902impl<T: PoolTransaction> IntoIterator for AllPoolTransactions<T> {
903    type Item = Arc<ValidPoolTransaction<T>>;
904    type IntoIter = std::iter::Chain<
905        std::vec::IntoIter<Arc<ValidPoolTransaction<T>>>,
906        std::vec::IntoIter<Arc<ValidPoolTransaction<T>>>,
907    >;
908
909    fn into_iter(self) -> Self::IntoIter {
910        self.pending.into_iter().chain(self.queued)
911    }
912}
913
914/// Represents transactions that were propagated over the network.
915#[derive(Debug, Clone, Eq, PartialEq, Default)]
916pub struct PropagatedTransactions(pub B256Map<Vec<PropagateKind>>);
917
918impl PropagatedTransactions {
919    /// Records a propagation of a transaction to a peer.
920    pub fn record(&mut self, hash: TxHash, kind: PropagateKind) {
921        self.0.entry(hash).or_default().push(kind);
922    }
923
924    /// Returns the number of distinct transactions that were propagated.
925    pub fn len(&self) -> usize {
926        self.0.len()
927    }
928
929    /// Returns true if no transactions were propagated.
930    pub fn is_empty(&self) -> bool {
931        self.0.is_empty()
932    }
933
934    /// Returns the propagation info for a specific transaction.
935    pub fn get(&self, hash: &TxHash) -> Option<&[PropagateKind]> {
936        self.0.get(hash).map(Vec::as_slice)
937    }
938}
939
940impl IntoIterator for PropagatedTransactions {
941    type Item = (TxHash, Vec<PropagateKind>);
942    type IntoIter = alloy_primitives::map::hash_map::IntoIter<TxHash, Vec<PropagateKind>>;
943
944    fn into_iter(self) -> Self::IntoIter {
945        self.0.into_iter()
946    }
947}
948
949/// Represents how a transaction was propagated over the network.
950#[derive(Debug, Copy, Clone, Eq, PartialEq)]
951#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
952pub enum PropagateKind {
953    /// The full transaction object was sent to the peer.
954    ///
955    /// This is equivalent to the `Transaction` message
956    Full(PeerId),
957    /// Only the Hash was propagated to the peer.
958    Hash(PeerId),
959}
960
961// === impl PropagateKind ===
962
963impl PropagateKind {
964    /// Returns the peer the transaction was sent to
965    pub const fn peer(&self) -> &PeerId {
966        match self {
967            Self::Full(peer) | Self::Hash(peer) => peer,
968        }
969    }
970
971    /// Returns true if the transaction was sent as a full transaction
972    pub const fn is_full(&self) -> bool {
973        matches!(self, Self::Full(_))
974    }
975
976    /// Returns true if the transaction was sent as a hash
977    pub const fn is_hash(&self) -> bool {
978        matches!(self, Self::Hash(_))
979    }
980}
981
982impl From<PropagateKind> for PeerId {
983    fn from(value: PropagateKind) -> Self {
984        match value {
985            PropagateKind::Full(peer) | PropagateKind::Hash(peer) => peer,
986        }
987    }
988}
989
990/// This type represents a new blob sidecar that has been stored in the transaction pool's
991/// blobstore; it includes the `TransactionHash` of the blob transaction along with the assoc.
992/// sidecar (blobs, commitments, proofs)
993#[derive(Debug, Clone)]
994pub struct NewBlobSidecar {
995    /// hash of the EIP-4844 transaction.
996    pub tx_hash: TxHash,
997    /// the blob transaction sidecar.
998    pub sidecar: Arc<BlobTransactionSidecarVariant>,
999}
1000
1001/// Where the transaction originates from.
1002///
1003/// Depending on where the transaction was picked up, it affects how the transaction is handled
1004/// internally, e.g. limits for simultaneous transaction of one sender.
1005#[derive(Debug, Copy, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
1006pub enum TransactionOrigin {
1007    /// Transaction is coming from a local source.
1008    #[default]
1009    Local,
1010    /// Transaction has been received externally.
1011    ///
1012    /// This is usually considered an "untrusted" source, for example received from another in the
1013    /// network.
1014    External,
1015    /// Transaction is originated locally and is intended to remain private.
1016    ///
1017    /// This type of transaction should not be propagated to the network. It's meant for
1018    /// private usage within the local node only.
1019    Private,
1020}
1021
1022// === impl TransactionOrigin ===
1023
1024impl TransactionOrigin {
1025    /// Whether the transaction originates from a local source.
1026    pub const fn is_local(&self) -> bool {
1027        matches!(self, Self::Local)
1028    }
1029
1030    /// Whether the transaction originates from an external source.
1031    pub const fn is_external(&self) -> bool {
1032        matches!(self, Self::External)
1033    }
1034    /// Whether the transaction originates from a private source.
1035    pub const fn is_private(&self) -> bool {
1036        matches!(self, Self::Private)
1037    }
1038}
1039
1040/// Represents the kind of update to the canonical state.
1041#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1042pub enum PoolUpdateKind {
1043    /// The update was due to a block commit.
1044    Commit,
1045    /// The update was due to a reorganization.
1046    Reorg,
1047}
1048
1049/// Represents changes after a new canonical block or range of canonical blocks was added to the
1050/// chain.
1051///
1052/// It is expected that this is only used if the added blocks are canonical to the pool's last known
1053/// block hash. In other words, the first added block of the range must be the child of the last
1054/// known block hash.
1055///
1056/// This is used to update the pool state accordingly.
1057#[derive(Clone, Debug)]
1058pub struct CanonicalStateUpdate<'a, B: Block> {
1059    /// Hash of the tip block.
1060    pub new_tip: &'a SealedBlock<B>,
1061    /// EIP-1559 Base fee of the _next_ (pending) block
1062    ///
1063    /// The base fee of a block depends on the utilization of the last block and its base fee.
1064    pub pending_block_base_fee: u64,
1065    /// EIP-4844 blob fee of the _next_ (pending) block
1066    ///
1067    /// Only after Cancun
1068    pub pending_block_blob_fee: Option<u128>,
1069    /// A set of changed accounts across a range of blocks.
1070    pub changed_accounts: Vec<ChangedAccount>,
1071    /// All mined transactions in the block range.
1072    pub mined_transactions: Vec<B256>,
1073    /// The kind of update to the canonical state.
1074    pub update_kind: PoolUpdateKind,
1075}
1076
1077impl<B> CanonicalStateUpdate<'_, B>
1078where
1079    B: Block,
1080{
1081    /// Returns the number of the tip block.
1082    pub fn number(&self) -> u64 {
1083        self.new_tip.number()
1084    }
1085
1086    /// Returns the hash of the tip block.
1087    pub fn hash(&self) -> B256 {
1088        self.new_tip.hash()
1089    }
1090
1091    /// Timestamp of the latest chain update
1092    pub fn timestamp(&self) -> u64 {
1093        self.new_tip.timestamp()
1094    }
1095
1096    /// Returns the block info for the tip block.
1097    pub fn block_info(&self) -> BlockInfo {
1098        BlockInfo {
1099            block_gas_limit: self.new_tip.gas_limit(),
1100            last_seen_block_hash: self.hash(),
1101            last_seen_block_number: self.number(),
1102            pending_basefee: self.pending_block_base_fee,
1103            pending_blob_fee: self.pending_block_blob_fee,
1104        }
1105    }
1106}
1107
1108impl<B> fmt::Display for CanonicalStateUpdate<'_, B>
1109where
1110    B: Block,
1111{
1112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1113        f.debug_struct("CanonicalStateUpdate")
1114            .field("hash", &self.hash())
1115            .field("number", &self.number())
1116            .field("pending_block_base_fee", &self.pending_block_base_fee)
1117            .field("pending_block_blob_fee", &self.pending_block_blob_fee)
1118            .field("changed_accounts", &self.changed_accounts.len())
1119            .field("mined_transactions", &self.mined_transactions.len())
1120            .finish()
1121    }
1122}
1123
1124/// Alias to restrict the [`BestTransactions`] items to the pool's transaction type.
1125pub type BestTransactionsFor<Pool> = Box<
1126    dyn BestTransactions<Item = Arc<ValidPoolTransaction<<Pool as TransactionPool>::Transaction>>>,
1127>;
1128
1129/// An `Iterator` that only returns transactions that are ready to be executed.
1130///
1131/// This makes no assumptions about the order of the transactions, but expects that _all_
1132/// transactions are valid (no nonce gaps.) for the tracked state of the pool.
1133///
1134/// Note: this iterator will always return the best transaction that it currently knows.
1135/// There is no guarantee transactions will be returned sequentially in decreasing
1136/// priority order.
1137pub trait BestTransactions: Iterator + Send {
1138    /// Mark the transaction as invalid.
1139    ///
1140    /// Implementers must ensure all subsequent transaction _don't_ depend on this transaction.
1141    /// In other words, this must remove the given transaction _and_ drain all transaction that
1142    /// depend on it.
1143    fn mark_invalid(&mut self, transaction: &Self::Item, kind: InvalidPoolTransactionError);
1144
1145    /// An iterator may be able to receive additional pending transactions that weren't present it
1146    /// the pool when it was created.
1147    ///
1148    /// This ensures that iterator will return the best transaction that it currently knows and not
1149    /// listen to pool updates.
1150    fn no_updates(&mut self);
1151
1152    /// Allows newly received transactions to be yielded even if their priority is higher than a
1153    /// transaction that was already yielded.
1154    ///
1155    /// This is useful for long-lived consumers that prefer seeing every update over preserving
1156    /// decreasing priority order. The default implementation leaves the iterator's ordering
1157    /// behavior unchanged. Implementations must still preserve transaction dependency ordering.
1158    fn allow_updates_out_of_order(&mut self) {}
1159
1160    /// Convenience function for [`Self::no_updates`] that returns the iterator again.
1161    fn without_updates(mut self) -> Self
1162    where
1163        Self: Sized,
1164    {
1165        self.no_updates();
1166        self
1167    }
1168
1169    /// Skip all blob transactions.
1170    ///
1171    /// There's only limited blob space available in a block, once exhausted, EIP-4844 transactions
1172    /// can no longer be included.
1173    ///
1174    /// If called then the iterator will no longer yield blob transactions.
1175    ///
1176    /// Note: this will also exclude any transactions that depend on blob transactions.
1177    fn skip_blobs(&mut self) {
1178        self.set_skip_blobs(true);
1179    }
1180
1181    /// Controls whether the iterator skips blob transactions or not.
1182    ///
1183    /// If set to true, no blob transactions will be returned.
1184    fn set_skip_blobs(&mut self, skip_blobs: bool);
1185
1186    /// Convenience function for [`Self::skip_blobs`] that returns the iterator again.
1187    fn without_blobs(mut self) -> Self
1188    where
1189        Self: Sized,
1190    {
1191        self.skip_blobs();
1192        self
1193    }
1194
1195    /// Creates an iterator which uses a closure to determine whether a transaction should be
1196    /// returned by the iterator.
1197    ///
1198    /// All items the closure returns false for are marked as invalid via [`Self::mark_invalid`] and
1199    /// descendant transactions will be skipped.
1200    fn filter_transactions<P>(self, predicate: P) -> BestTransactionFilter<Self, P>
1201    where
1202        P: FnMut(&Self::Item) -> bool,
1203        Self: Sized,
1204    {
1205        BestTransactionFilter::new(self, predicate)
1206    }
1207}
1208
1209impl<T> BestTransactions for Box<T>
1210where
1211    T: BestTransactions + ?Sized,
1212{
1213    fn mark_invalid(&mut self, transaction: &Self::Item, kind: InvalidPoolTransactionError) {
1214        (**self).mark_invalid(transaction, kind)
1215    }
1216
1217    fn no_updates(&mut self) {
1218        (**self).no_updates();
1219    }
1220
1221    fn allow_updates_out_of_order(&mut self) {
1222        (**self).allow_updates_out_of_order();
1223    }
1224
1225    fn skip_blobs(&mut self) {
1226        (**self).skip_blobs();
1227    }
1228
1229    fn set_skip_blobs(&mut self, skip_blobs: bool) {
1230        (**self).set_skip_blobs(skip_blobs);
1231    }
1232}
1233
1234/// A no-op implementation that yields no transactions.
1235impl<T> BestTransactions for std::iter::Empty<T> {
1236    fn mark_invalid(&mut self, _tx: &T, _kind: InvalidPoolTransactionError) {}
1237
1238    fn no_updates(&mut self) {}
1239
1240    fn skip_blobs(&mut self) {}
1241
1242    fn set_skip_blobs(&mut self, _skip_blobs: bool) {}
1243}
1244
1245/// A filter that allows to check if a transaction satisfies a set of conditions
1246pub trait TransactionFilter {
1247    /// The type of the transaction to check.
1248    type Transaction;
1249
1250    /// Returns true if the transaction satisfies the conditions.
1251    fn is_valid(&self, transaction: &Self::Transaction) -> bool;
1252}
1253
1254/// A no-op implementation of [`TransactionFilter`] which
1255/// marks all transactions as valid.
1256#[derive(Debug, Clone)]
1257pub struct NoopTransactionFilter<T>(std::marker::PhantomData<T>);
1258
1259// We can't derive Default because this forces T to be
1260// Default as well, which isn't necessary.
1261impl<T> Default for NoopTransactionFilter<T> {
1262    fn default() -> Self {
1263        Self(std::marker::PhantomData)
1264    }
1265}
1266
1267impl<T> TransactionFilter for NoopTransactionFilter<T> {
1268    type Transaction = T;
1269
1270    fn is_valid(&self, _transaction: &Self::Transaction) -> bool {
1271        true
1272    }
1273}
1274
1275/// A Helper type that bundles the best transactions attributes together.
1276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1277pub struct BestTransactionsAttributes {
1278    /// The base fee attribute for best transactions.
1279    pub basefee: u64,
1280    /// The blob fee attribute for best transactions.
1281    pub blob_fee: Option<u64>,
1282}
1283
1284// === impl BestTransactionsAttributes ===
1285
1286impl BestTransactionsAttributes {
1287    /// Creates a new `BestTransactionsAttributes` with the given basefee and blob fee.
1288    pub const fn new(basefee: u64, blob_fee: Option<u64>) -> Self {
1289        Self { basefee, blob_fee }
1290    }
1291
1292    /// Creates a new `BestTransactionsAttributes` with the given basefee.
1293    pub const fn base_fee(basefee: u64) -> Self {
1294        Self::new(basefee, None)
1295    }
1296
1297    /// Sets the given blob fee.
1298    pub const fn with_blob_fee(mut self, blob_fee: u64) -> Self {
1299        self.blob_fee = Some(blob_fee);
1300        self
1301    }
1302}
1303
1304/// Trait for transaction types stored in the transaction pool.
1305///
1306/// This trait represents the actual transaction object stored in the mempool, which includes not
1307/// only the transaction data itself but also additional metadata needed for efficient pool
1308/// operations. Implementations typically cache values that are frequently accessed during
1309/// transaction ordering, validation, and eviction.
1310///
1311/// ## Key Responsibilities
1312///
1313/// 1. **Metadata Caching**: Store computed values like address, cost and encoded size
1314/// 2. **Representation Conversion**: Handle conversions between consensus and pooled
1315///    representations
1316/// 3. **Validation Support**: Provide methods for pool-specific validation rules
1317///
1318/// ## Cached Metadata
1319///
1320/// Implementations should cache frequently accessed values to avoid recomputation:
1321/// - **Address**: Recovered sender address of the transaction
1322/// - **Cost**: Max amount spendable (gas × price + value + blob costs)
1323/// - **Size**: RLP encoded length for mempool size limits
1324///
1325/// See [`EthPooledTransaction`] for a reference implementation.
1326///
1327/// ## Transaction Representations
1328///
1329/// This trait abstracts over the different representations a transaction can have:
1330///
1331/// 1. **Consensus representation** (`Consensus` associated type): The canonical form included in
1332///    blocks
1333///    - Compact representation without networking metadata
1334///    - For EIP-4844: includes only blob hashes, not the actual blobs
1335///    - Used for block execution and state transitions
1336///
1337/// 2. **Pooled representation** (`Pooled` associated type): The form used for network propagation
1338///    - May include additional data for validation
1339///    - For EIP-4844: includes full blob sidecars (blobs, commitments, proofs)
1340///    - Used for mempool validation and p2p gossiping
1341///
1342/// ## Why Two Representations?
1343///
1344/// This distinction is necessary because:
1345///
1346/// - **EIP-4844 blob transactions**: Require large blob sidecars for validation that would bloat
1347///   blocks if included. Only blob hashes are stored on-chain.
1348///
1349/// - **Network efficiency**: Blob transactions are not broadcast to all peers automatically but
1350///   must be explicitly requested to reduce bandwidth usage.
1351///
1352/// - **Special transactions**: Some transactions (like OP deposit transactions) exist only in
1353///   consensus format and are never in the mempool.
1354///
1355/// ## Conversion Rules
1356///
1357/// - `Consensus` → `Pooled`: May fail for transactions that cannot be pooled (e.g., OP deposit
1358///   transactions, blob transactions without sidecars)
1359/// - `Pooled` → `Consensus`: Always succeeds (pooled is a superset)
1360pub trait PoolTransaction:
1361    alloy_consensus::Transaction + InMemorySize + Debug + Send + Sync + Clone
1362{
1363    /// Associated error type for the `try_from_consensus` method.
1364    type TryFromConsensusError: fmt::Display;
1365
1366    /// Associated type representing the raw consensus variant of the transaction.
1367    type Consensus: SignedTransaction + From<Self::Pooled>;
1368
1369    /// Associated type representing the recovered pooled variant of the transaction.
1370    type Pooled: TryFrom<Self::Consensus, Error = Self::TryFromConsensusError> + SignedTransaction;
1371
1372    /// Define a method to convert from the `Consensus` type to `Self`
1373    ///
1374    /// This conversion may fail for transactions that are valid for inclusion in blocks
1375    /// but cannot exist in the transaction pool. Examples include:
1376    ///
1377    /// - **OP Deposit transactions**: These are special system transactions that are directly
1378    ///   included in blocks by the sequencer/validator and never enter the mempool
1379    /// - **Blob transactions without sidecars**: After being included in a block, the sidecar data
1380    ///   is pruned, making the consensus transaction unpoolable
1381    fn try_from_consensus(
1382        tx: Recovered<Self::Consensus>,
1383    ) -> Result<Self, Self::TryFromConsensusError> {
1384        Ok(Self::from_pooled(tx.try_convert()?))
1385    }
1386
1387    /// Clone the transaction into a consensus variant.
1388    ///
1389    /// This method is preferred when the [`PoolTransaction`] already wraps the consensus variant.
1390    fn clone_into_consensus(&self) -> Recovered<Self::Consensus> {
1391        self.clone().into_consensus()
1392    }
1393
1394    /// Returns the EIP-2718 encoded consensus transaction.
1395    ///
1396    /// Implementations that synthesize the consensus representation should override this method.
1397    fn encoded_2718_consensus(&self) -> Bytes {
1398        self.consensus_ref().encoded_2718().into()
1399    }
1400
1401    /// Returns a reference to the consensus transaction with the recovered sender.
1402    fn consensus_ref(&self) -> Recovered<&Self::Consensus>;
1403
1404    /// Define a method to convert from the `Self` type to `Consensus`
1405    fn into_consensus(self) -> Recovered<Self::Consensus>;
1406
1407    /// Converts the transaction into consensus format while preserving the EIP-2718 encoded bytes.
1408    /// This is used to optimize transaction execution by reusing cached encoded bytes instead of
1409    /// re-encoding the transaction. The cached bytes are particularly useful in payload building
1410    /// where the same transaction may be executed multiple times.
1411    fn into_consensus_with2718(self) -> WithEncoded<Recovered<Self::Consensus>> {
1412        self.into_consensus().into_encoded()
1413    }
1414
1415    /// Define a method to convert from the `Pooled` type to `Self`
1416    fn from_pooled(pooled: Recovered<Self::Pooled>) -> Self;
1417
1418    /// Recovers and converts a pooled transaction into this pool transaction type.
1419    ///
1420    /// Implementations can override this to combine signature recovery with construction of
1421    /// transaction-specific cached metadata.
1422    fn try_recover(pooled: Self::Pooled) -> Result<Self, Self::Pooled> {
1423        pooled.try_into_recovered().map(Self::from_pooled)
1424    }
1425
1426    /// Recovers and converts a pooled transaction using the provided sender recovery cache.
1427    fn try_recover_with_cache(
1428        pooled: Self::Pooled,
1429        cache: &reth_evm::SenderRecoveryCache,
1430    ) -> Result<Self, Self::Pooled> {
1431        match cache.recover(&pooled) {
1432            Ok(signer) => Ok(Self::from_pooled(Recovered::new_unchecked(pooled, signer))),
1433            Err(_) => Err(pooled),
1434        }
1435    }
1436
1437    /// Recovers and converts a pooled transaction, using the sender recovery cache if provided.
1438    ///
1439    /// Delegates to [`Self::try_recover`] when no cache is configured.
1440    fn try_recover_with_cache_opt(
1441        pooled: Self::Pooled,
1442        cache: Option<&reth_evm::SenderRecoveryCache>,
1443    ) -> Result<Self, Self::Pooled> {
1444        match cache {
1445            Some(cache) => Self::try_recover_with_cache(pooled, cache),
1446            None => Self::try_recover(pooled),
1447        }
1448    }
1449
1450    /// Decodes and recovers a raw transaction into this pool transaction type.
1451    ///
1452    /// Implementations can override this to avoid constructing the pooled transaction as an
1453    /// intermediate value when the raw representation can be converted directly into `Self`.
1454    /// RPC uses this hook when no sender recovery cache is configured. Override
1455    /// [`Self::recover_raw_transaction_with_cache`] to specialize the cached path as well.
1456    fn recover_raw_transaction(data: &[u8]) -> Result<Self, RawPoolTransactionError> {
1457        Self::try_recover(Self::decode_raw_transaction(data)?)
1458            .map_err(|_| RawPoolTransactionError::InvalidTransactionSignature)
1459    }
1460
1461    /// Decodes and recovers a raw pool transaction using the provided sender recovery cache.
1462    ///
1463    /// RPC uses this hook when a sender recovery cache is configured. Implementations can override
1464    /// it to reuse the raw bytes or encoded length during recovery and construction. The default
1465    /// implementation decodes and recovers separately; it does not call
1466    /// [`Self::recover_raw_transaction`].
1467    fn recover_raw_transaction_with_cache(
1468        data: &[u8],
1469        cache: &reth_evm::SenderRecoveryCache,
1470    ) -> Result<Self, RawPoolTransactionError> {
1471        Self::try_recover_with_cache(Self::decode_raw_transaction(data)?, cache)
1472            .map_err(|_| RawPoolTransactionError::InvalidTransactionSignature)
1473    }
1474
1475    /// Decodes a raw pooled transaction without recovering its sender.
1476    ///
1477    /// The entire input must be consumed; trailing bytes are rejected. Implementations can override
1478    /// this to customize raw decoding independently of sender recovery.
1479    fn decode_raw_transaction(data: &[u8]) -> Result<Self::Pooled, RawPoolTransactionError> {
1480        if data.is_empty() {
1481            return Err(RawPoolTransactionError::EmptyRawTransactionData)
1482        }
1483
1484        Self::Pooled::decode_2718_exact(data)
1485            .map_err(|_| RawPoolTransactionError::FailedToDecodeSignedTransaction)
1486    }
1487
1488    /// Tries to convert the `Consensus` type into the `Pooled` type.
1489    fn try_into_pooled(self) -> Result<Recovered<Self::Pooled>, Self::TryFromConsensusError> {
1490        self.into_consensus().try_convert()
1491    }
1492
1493    /// Clones the consensus transactions and tries to convert the `Consensus` type into the
1494    /// `Pooled` type.
1495    fn clone_into_pooled(&self) -> Result<Recovered<Self::Pooled>, Self::TryFromConsensusError> {
1496        self.clone_into_consensus().try_convert()
1497    }
1498
1499    /// Converts the `Pooled` type into the `Consensus` type.
1500    fn pooled_into_consensus(tx: Self::Pooled) -> Self::Consensus {
1501        tx.into()
1502    }
1503
1504    /// Hash of the transaction.
1505    fn hash(&self) -> &TxHash;
1506
1507    /// The Sender of the transaction.
1508    fn sender(&self) -> Address;
1509
1510    /// Reference to the Sender of the transaction.
1511    fn sender_ref(&self) -> &Address;
1512
1513    /// Returns the cost that this transaction is allowed to consume:
1514    ///
1515    /// For EIP-1559 transactions: `max_fee_per_gas * gas_limit + tx_value`.
1516    /// For legacy transactions: `gas_price * gas_limit + tx_value`.
1517    /// For EIP-4844 blob transactions: `max_fee_per_gas * gas_limit + tx_value +
1518    /// max_blob_fee_per_gas * blob_gas_used`.
1519    fn cost(&self) -> &U256;
1520
1521    /// Returns the length of the rlp encoded transaction object
1522    ///
1523    /// Note: Implementations should cache this value.
1524    fn encoded_length(&self) -> usize;
1525
1526    /// Returns the EIP-2718 size to announce to eth/72 peers, or `None` if the pool cannot
1527    /// serve the transaction in that version. Blob pools can cache this before detaching the
1528    /// sidecar.
1529    fn encoded_length_eth72(&self) -> Option<usize> {
1530        (!self.is_eip4844()).then(|| self.encoded_length())
1531    }
1532
1533    /// Returns the transaction as served to eth/72 peers, without its blobs, or `None` if it can't
1534    /// be served. Must return `Some` whenever [`Self::encoded_length_eth72`] does.
1535    fn pooled_without_blobs(pooled: Self::Pooled) -> Option<Self::Pooled> {
1536        (!pooled.is_eip4844()).then_some(pooled)
1537    }
1538
1539    /// Returns the shared blob cell availability, if this is a blob transaction.
1540    ///
1541    /// For blob transactions, `None` tells the network to assume it can serve full blobs to
1542    /// eth/66–71 peers and to advertise all cells to eth/72 and newer peers when
1543    /// [`Self::encoded_length_eth72`] returns `Some`. Pools that store only a subset of a
1544    /// transaction's cells must return `Some` with the actual availability.
1545    fn blob_cell_availability(&self) -> Option<&BlobCellAvailability> {
1546        None
1547    }
1548
1549    /// Returns the attached blob sidecar, if any.
1550    fn blob_sidecar(&self) -> Option<&PooledBlobSidecar> {
1551        None
1552    }
1553
1554    /// Attaches `sidecar` to a blob transaction, for example one fetched as cells.
1555    ///
1556    /// Returns `false` if this transaction can't carry a sidecar.
1557    fn set_blob_sidecar(&mut self, _sidecar: PooledBlobSidecar) -> bool {
1558        false
1559    }
1560
1561    /// Ensures that the transaction's code size does not exceed the provided `max_init_code_size`.
1562    ///
1563    /// This is specifically relevant for contract creation transactions ([`TxKind::Create`]),
1564    /// where the input data contains the initialization code. If the input code size exceeds
1565    /// the configured limit, an [`InvalidPoolTransactionError::ExceedsMaxInitCodeSize`] error is
1566    /// returned.
1567    fn ensure_max_init_code_size(
1568        &self,
1569        max_init_code_size: usize,
1570    ) -> Result<(), InvalidPoolTransactionError> {
1571        let input_len = self.input().len();
1572        if self.is_create() && input_len > max_init_code_size {
1573            Err(InvalidPoolTransactionError::ExceedsMaxInitCodeSize(input_len, max_init_code_size))
1574        } else {
1575            Ok(())
1576        }
1577    }
1578
1579    /// Returns whether `replacement` is underpriced relative to this transaction.
1580    ///
1581    /// Called on the existing transaction when another transaction would replace it.
1582    /// By default, delegates to [`PriceBumpConfig::is_replacement_underpriced`].
1583    /// Implementations may override this to define transaction-specific replacement semantics.
1584    fn is_replacement_underpriced(
1585        &self,
1586        replacement: &Self,
1587        price_bumps: &PriceBumpConfig,
1588    ) -> bool {
1589        price_bumps.is_replacement_underpriced(self, replacement)
1590    }
1591
1592    /// Whether the transaction's nonce must be below [`u64::MAX`] according to EIP-2681.
1593    ///
1594    /// Defaults to `true`. Transactions with alternative nonce semantics can override this
1595    /// independently of the sender nonce check in [`Self::requires_nonce_check`].
1596    fn requires_nonce_bound_check(&self) -> bool {
1597        true
1598    }
1599
1600    /// Allows to communicate to the pool that the transaction doesn't require a nonce check.
1601    fn requires_nonce_check(&self) -> bool {
1602        true
1603    }
1604}
1605
1606/// Super trait for transactions that can be converted to and from Eth transactions intended for the
1607/// ethereum style pool.
1608///
1609/// This extends the [`PoolTransaction`] trait with additional methods that are specific to the
1610/// Ethereum pool.
1611pub trait EthPoolTransaction: PoolTransaction {
1612    /// Extracts the blob sidecar from the transaction.
1613    fn take_blob(&mut self) -> EthBlobTransactionSidecar;
1614
1615    /// A specialization for the EIP-4844 transaction type.
1616    /// Tries to reattach the blob sidecar to the transaction.
1617    ///
1618    /// This returns an option, but callers should ensure that the transaction is an EIP-4844
1619    /// transaction: [`Typed2718::is_eip4844`].
1620    fn try_into_pooled_eip4844(
1621        self,
1622        sidecar: Arc<BlobTransactionSidecarVariant>,
1623    ) -> Option<Recovered<Self::Pooled>>;
1624
1625    /// Tries to convert the `Consensus` type with a blob sidecar into the `Pooled` type.
1626    ///
1627    /// Returns `None` if passed transaction is not a blob transaction.
1628    fn try_from_eip4844(
1629        tx: Recovered<Self::Consensus>,
1630        sidecar: BlobTransactionSidecarVariant,
1631    ) -> Option<Self>;
1632
1633    /// Validates the blob sidecar of the transaction with the given settings.
1634    fn validate_blob(
1635        &self,
1636        blob: &BlobTransactionSidecarVariant,
1637        settings: &KzgSettings,
1638    ) -> Result<(), BlobTransactionValidationError>;
1639}
1640
1641/// The default [`PoolTransaction`] for the [Pool](crate::Pool) for Ethereum.
1642///
1643/// This type wraps a consensus transaction with additional cached data that's
1644/// frequently accessed by the pool for transaction ordering and validation:
1645///
1646/// - `cost`: Pre-calculated max cost (gas * price + value + blob costs)
1647/// - `encoded_length`: Cached RLP encoding length for size limits
1648/// - `in_memory_size`: Cached transaction size for subpool memory accounting
1649/// - `blob_sidecar`: Blob data state (None/Missing/Present)
1650/// - `blob_cell_availability`: Cached blob cell availability for eth/72 announcements
1651///
1652/// This avoids recalculating these values repeatedly during pool operations.
1653#[derive(Debug, Clone, PartialEq, Eq)]
1654pub struct EthPooledTransaction<T = TransactionSigned> {
1655    /// `EcRecovered` transaction, the consensus format.
1656    pub transaction: Recovered<T>,
1657
1658    /// For EIP-1559 transactions: `max_fee_per_gas * gas_limit + tx_value`.
1659    /// For legacy transactions: `gas_price * gas_limit + tx_value`.
1660    /// For EIP-4844 blob transactions: `max_fee_per_gas * gas_limit + tx_value +
1661    /// max_blob_fee_per_gas * blob_gas_used`.
1662    pub cost: U256,
1663
1664    /// This is the RLP length of the transaction, computed when the transaction is added to the
1665    /// pool.
1666    pub encoded_length: usize,
1667
1668    /// EIP-2718 size with blobs elided, retained after detaching an EIP-7594 sidecar.
1669    /// Transactions without a known EIP-7594 sidecar have no cached blobless size.
1670    pub blobless_encoded_length: Option<NonZeroUsize>,
1671
1672    /// Cached in-memory size of `transaction`, excluding the blob sidecar.
1673    ///
1674    /// Must be updated if `transaction` is modified or replaced.
1675    pub in_memory_size: usize,
1676
1677    /// The blob side car for this transaction
1678    pub blob_sidecar: EthBlobTransactionSidecar,
1679
1680    /// Cached blob cell availability for this transaction.
1681    ///
1682    /// This is shared with the blob sidecar so that availability updates are reflected here.
1683    pub blob_cell_availability: Option<BlobCellAvailability>,
1684}
1685
1686impl<T: SignedTransaction> EthPooledTransaction<T> {
1687    /// Create new instance of [Self].
1688    ///
1689    /// Caution: In case of blob transactions, this marks the blob sidecar as
1690    /// [`EthBlobTransactionSidecar::Missing`]
1691    pub fn new(transaction: Recovered<T>, encoded_length: usize) -> Self {
1692        let mut blob_cell_availability = None;
1693        let mut blob_sidecar = EthBlobTransactionSidecar::None;
1694
1695        let gas_cost = U256::from(transaction.max_fee_per_gas())
1696            .saturating_mul(U256::from(transaction.gas_limit()));
1697
1698        let mut cost = gas_cost.saturating_add(transaction.value());
1699
1700        if let (Some(blob_gas_used), Some(max_fee_per_blob_gas)) =
1701            (transaction.blob_gas_used(), transaction.max_fee_per_blob_gas())
1702        {
1703            // Add max blob cost using saturating math to avoid overflow
1704            cost = cost.saturating_add(U256::from(
1705                max_fee_per_blob_gas.saturating_mul(blob_gas_used as u128),
1706            ));
1707
1708            // because the blob sidecar is not included in this transaction variant, mark it as
1709            // missing
1710            blob_sidecar = EthBlobTransactionSidecar::Missing;
1711            // TODO: Initialize this with the actual mask once sparse sidecars are supported.
1712            blob_cell_availability = Some(BlobCellAvailability::full());
1713        }
1714
1715        let in_memory_size = transaction.size();
1716        Self {
1717            transaction,
1718            cost,
1719            encoded_length,
1720            blobless_encoded_length: None,
1721            in_memory_size,
1722            blob_sidecar,
1723            blob_cell_availability,
1724        }
1725    }
1726
1727    /// Return the reference to the underlying transaction.
1728    pub const fn transaction(&self) -> &Recovered<T> {
1729        &self.transaction
1730    }
1731
1732    /// Returns the shared blob cell availability, if this is a blob transaction.
1733    pub const fn blob_cell_availability(&self) -> Option<&BlobCellAvailability> {
1734        self.blob_cell_availability.as_ref()
1735    }
1736
1737    // Attaches the sidecar of this blob transaction and caches the sizes it implies.
1738    fn attach_blob_sidecar(&mut self, sidecar: PooledBlobSidecar) {
1739        match sidecar.sidecar() {
1740            BlobTransactionSidecarVariant::Eip7594(sidecar) => self.cache_eip7594_lengths(sidecar),
1741            // Legacy sidecars have no cell proofs, so eth/72 can't carry them.
1742            BlobTransactionSidecarVariant::Eip4844(sidecar) => {
1743                let payload_length =
1744                    self.transaction.encode_2718_len() - 1 + sidecar.rlp_encoded_fields_length();
1745                self.encoded_length =
1746                    1 + Header { list: true, payload_length }.length_with_payload();
1747                self.blobless_encoded_length = None;
1748            }
1749        }
1750        self.blob_cell_availability = Some(sidecar.availability().clone());
1751        self.blob_sidecar = EthBlobTransactionSidecar::Present(sidecar);
1752    }
1753
1754    // Caches the sizes with and without blobs, since eth/72 serves the body without them while
1755    // eth/68 to eth/71 and pool limits count them.
1756    fn cache_eip7594_lengths(&mut self, sidecar: &BlobTransactionSidecarEip7594) {
1757        // The consensus encoding without its type byte is the body of the network encoding.
1758        let without_blobs = self.transaction.encode_2718_len() - 1 +
1759            sidecar.encode_7594_len_with(BlobSidecarEncoding::WithoutBlobs);
1760        let blob = BYTES_PER_BLOB + length_of_length(BYTES_PER_BLOB);
1761        // An eth/72 body counts the blobs its cells rebuild, a malformed one at least those it has.
1762        let count = sidecar.blobs.len().max(sidecar.commitments.len());
1763        let blobs = Header { list: true, payload_length: count * blob };
1764        let encoded =
1765            |payload_length| 1 + Header { list: true, payload_length }.length_with_payload();
1766        self.encoded_length = encoded(without_blobs - 1 + blobs.length_with_payload());
1767        self.blobless_encoded_length = NonZeroUsize::new(encoded(without_blobs));
1768    }
1769}
1770
1771impl PoolTransaction for EthPooledTransaction {
1772    type TryFromConsensusError = ValueError<TransactionSigned>;
1773
1774    type Consensus = TransactionSigned;
1775
1776    type Pooled = PooledTransactionVariant;
1777
1778    fn clone_into_consensus(&self) -> Recovered<Self::Consensus> {
1779        self.transaction().clone()
1780    }
1781
1782    fn consensus_ref(&self) -> Recovered<&Self::Consensus> {
1783        self.transaction.as_recovered_ref()
1784    }
1785
1786    fn into_consensus(self) -> Recovered<Self::Consensus> {
1787        self.transaction
1788    }
1789
1790    fn from_pooled(tx: Recovered<Self::Pooled>) -> Self {
1791        let encoded_length = tx.encode_2718_len();
1792        let (tx, signer) = tx.into_parts();
1793        match tx {
1794            PooledTransactionVariant::Eip4844(tx) => {
1795                // include the blob sidecar
1796                let (tx, sig, hash) = tx.into_parts();
1797                let (tx, blob) = tx.into_parts();
1798                let tx = Signed::new_unchecked(tx, sig, hash);
1799                let tx = TransactionSigned::from(tx);
1800                let tx = Recovered::new_unchecked(tx, signer);
1801                let mut pooled = Self::new(tx, encoded_length);
1802                // eth/72 peers send the sidecar without blobs, and its cells are fetched later.
1803                let availability =
1804                    if blob.as_eip7594().is_some_and(|sidecar| sidecar.blobs.is_empty()) {
1805                        BlobCellAvailability::new(BlobCellMask::from_bits(0))
1806                    } else {
1807                        BlobCellAvailability::full()
1808                    };
1809                pooled.attach_blob_sidecar(PooledBlobSidecar::new(blob, availability));
1810                pooled
1811            }
1812            tx => {
1813                // no blob sidecar
1814                let tx = Recovered::new_unchecked(tx.into(), signer);
1815                Self::new(tx, encoded_length)
1816            }
1817        }
1818    }
1819
1820    /// Returns hash of the transaction.
1821    fn hash(&self) -> &TxHash {
1822        self.transaction.tx_hash()
1823    }
1824
1825    /// Returns the Sender of the transaction.
1826    fn sender(&self) -> Address {
1827        self.transaction.signer()
1828    }
1829
1830    /// Returns a reference to the Sender of the transaction.
1831    fn sender_ref(&self) -> &Address {
1832        self.transaction.signer_ref()
1833    }
1834
1835    /// Returns the cost that this transaction is allowed to consume:
1836    ///
1837    /// For EIP-1559 transactions: `max_fee_per_gas * gas_limit + tx_value`.
1838    /// For legacy transactions: `gas_price * gas_limit + tx_value`.
1839    /// For EIP-4844 blob transactions: `max_fee_per_gas * gas_limit + tx_value +
1840    /// max_blob_fee_per_gas * blob_gas_used`.
1841    fn cost(&self) -> &U256 {
1842        &self.cost
1843    }
1844
1845    /// Returns the length of the rlp encoded object
1846    fn encoded_length(&self) -> usize {
1847        self.encoded_length
1848    }
1849
1850    fn encoded_length_eth72(&self) -> Option<usize> {
1851        if self.is_eip4844() {
1852            self.blobless_encoded_length
1853                .filter(|_| {
1854                    self.blob_cell_availability().is_some_and(|cells| cells.get().bits() != 0)
1855                })
1856                .map(NonZeroUsize::get)
1857        } else {
1858            Some(self.encoded_length)
1859        }
1860    }
1861
1862    fn pooled_without_blobs(mut pooled: Self::Pooled) -> Option<Self::Pooled> {
1863        // Legacy sidecars have no cell proofs, so eth/72 can't carry them.
1864        if pooled.as_eip4844().is_some_and(|tx| !tx.tx().sidecar.is_eip7594()) {
1865            return None
1866        }
1867        pooled.clear_eip7594_blobs();
1868        Some(pooled)
1869    }
1870
1871    fn blob_cell_availability(&self) -> Option<&BlobCellAvailability> {
1872        Self::blob_cell_availability(self)
1873    }
1874
1875    fn blob_sidecar(&self) -> Option<&PooledBlobSidecar> {
1876        match &self.blob_sidecar {
1877            EthBlobTransactionSidecar::Present(sidecar) => Some(sidecar),
1878            _ => None,
1879        }
1880    }
1881
1882    fn set_blob_sidecar(&mut self, sidecar: PooledBlobSidecar) -> bool {
1883        if !self.is_eip4844() {
1884            return false
1885        }
1886        self.attach_blob_sidecar(sidecar);
1887        true
1888    }
1889}
1890
1891impl<T: Typed2718> Typed2718 for EthPooledTransaction<T> {
1892    fn ty(&self) -> u8 {
1893        self.transaction.ty()
1894    }
1895}
1896
1897impl<T: InMemorySize> InMemorySize for EthPooledTransaction<T> {
1898    #[inline]
1899    fn size(&self) -> usize {
1900        self.in_memory_size
1901    }
1902}
1903
1904impl<T: alloy_consensus::Transaction> alloy_consensus::Transaction for EthPooledTransaction<T> {
1905    fn chain_id(&self) -> Option<alloy_primitives::ChainId> {
1906        self.transaction.chain_id()
1907    }
1908
1909    fn nonce(&self) -> u64 {
1910        self.transaction.nonce()
1911    }
1912
1913    fn gas_limit(&self) -> u64 {
1914        self.transaction.gas_limit()
1915    }
1916
1917    fn gas_price(&self) -> Option<u128> {
1918        self.transaction.gas_price()
1919    }
1920
1921    fn max_fee_per_gas(&self) -> u128 {
1922        self.transaction.max_fee_per_gas()
1923    }
1924
1925    fn max_priority_fee_per_gas(&self) -> Option<u128> {
1926        self.transaction.max_priority_fee_per_gas()
1927    }
1928
1929    fn max_fee_per_blob_gas(&self) -> Option<u128> {
1930        self.transaction.max_fee_per_blob_gas()
1931    }
1932
1933    fn priority_fee_or_price(&self) -> u128 {
1934        self.transaction.priority_fee_or_price()
1935    }
1936
1937    fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
1938        self.transaction.effective_gas_price(base_fee)
1939    }
1940
1941    fn is_dynamic_fee(&self) -> bool {
1942        self.transaction.is_dynamic_fee()
1943    }
1944
1945    fn kind(&self) -> TxKind {
1946        self.transaction.kind()
1947    }
1948
1949    fn is_create(&self) -> bool {
1950        self.transaction.is_create()
1951    }
1952
1953    fn value(&self) -> U256 {
1954        self.transaction.value()
1955    }
1956
1957    fn input(&self) -> &Bytes {
1958        self.transaction.input()
1959    }
1960
1961    fn access_list(&self) -> Option<&AccessList> {
1962        self.transaction.access_list()
1963    }
1964
1965    fn blob_versioned_hashes(&self) -> Option<&[B256]> {
1966        self.transaction.blob_versioned_hashes()
1967    }
1968
1969    fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
1970        self.transaction.authorization_list()
1971    }
1972}
1973
1974impl EthPoolTransaction for EthPooledTransaction {
1975    fn take_blob(&mut self) -> EthBlobTransactionSidecar {
1976        if self.is_eip4844() {
1977            std::mem::replace(&mut self.blob_sidecar, EthBlobTransactionSidecar::Missing)
1978        } else {
1979            EthBlobTransactionSidecar::None
1980        }
1981    }
1982
1983    fn try_into_pooled_eip4844(
1984        self,
1985        sidecar: Arc<BlobTransactionSidecarVariant>,
1986    ) -> Option<Recovered<Self::Pooled>> {
1987        self.into_consensus()
1988            .try_map(|tx| tx.try_into_pooled_eip4844(Arc::unwrap_or_clone(sidecar)))
1989            .ok()
1990    }
1991
1992    fn try_from_eip4844(
1993        tx: Recovered<Self::Consensus>,
1994        sidecar: BlobTransactionSidecarVariant,
1995    ) -> Option<Self> {
1996        let (tx, signer) = tx.into_parts();
1997        tx.try_into_pooled_eip4844(sidecar)
1998            .ok()
1999            .map(|tx| tx.with_signer(signer))
2000            .map(Self::from_pooled)
2001    }
2002
2003    fn validate_blob(
2004        &self,
2005        sidecar: &BlobTransactionSidecarVariant,
2006        settings: &KzgSettings,
2007    ) -> Result<(), BlobTransactionValidationError> {
2008        match self.transaction.inner().as_eip4844() {
2009            Some(tx) => tx.tx().validate_blob(sidecar, settings),
2010            _ => Err(BlobTransactionValidationError::NotBlobTransaction(self.ty())),
2011        }
2012    }
2013}
2014
2015/// Represents the blob sidecar of the [`EthPooledTransaction`].
2016///
2017/// EIP-4844 blob transactions require additional data (blobs, commitments, proofs)
2018/// for validation that is not included in the consensus format. This enum tracks
2019/// the sidecar state throughout the transaction's lifecycle in the pool.
2020#[derive(Debug, Clone, PartialEq, Eq)]
2021pub enum EthBlobTransactionSidecar {
2022    /// This transaction does not have a blob sidecar
2023    /// (applies to all non-EIP-4844 transaction types)
2024    None,
2025    /// This transaction has a blob sidecar (EIP-4844) but it is missing.
2026    ///
2027    /// This can happen when:
2028    /// - The sidecar was extracted after the transaction was added to the pool
2029    /// - The transaction was re-injected after a reorg without its sidecar
2030    /// - The transaction was recovered from the consensus format (e.g., from a block)
2031    Missing,
2032    /// The EIP-4844 transaction was received from the network with its complete sidecar.
2033    ///
2034    /// This sidecar contains:
2035    /// - The actual blob data (large data per blob)
2036    /// - KZG commitments for each blob
2037    /// - KZG proofs for validation
2038    ///
2039    /// The sidecar is required for validating the transaction but is not included
2040    /// in blocks (only the blob hashes are included in the consensus format).
2041    Present(PooledBlobSidecar),
2042}
2043
2044impl EthBlobTransactionSidecar {
2045    /// Returns the blob sidecar if it is present
2046    pub const fn maybe_sidecar(&self) -> Option<&BlobTransactionSidecarVariant> {
2047        match self {
2048            Self::Present(sidecar) => Some(sidecar.sidecar()),
2049            _ => None,
2050        }
2051    }
2052}
2053
2054/// Represents the current status of the pool.
2055#[derive(Debug, Clone, Copy, Default)]
2056pub struct PoolSize {
2057    /// Number of transactions in the _pending_ sub-pool.
2058    pub pending: usize,
2059    /// Reported size of transactions in the _pending_ sub-pool.
2060    pub pending_size: usize,
2061    /// Number of transactions in the _blob_ pool.
2062    pub blob: usize,
2063    /// Reported size of transactions in the _blob_ pool.
2064    pub blob_size: usize,
2065    /// Number of transactions in the _basefee_ pool.
2066    pub basefee: usize,
2067    /// Reported size of transactions in the _basefee_ sub-pool.
2068    pub basefee_size: usize,
2069    /// Number of transactions in the _queued_ sub-pool.
2070    pub queued: usize,
2071    /// Reported size of transactions in the _queued_ sub-pool.
2072    pub queued_size: usize,
2073    /// Number of all transactions of all sub-pools
2074    ///
2075    /// Note: this is the sum of ```pending + basefee + queued + blob```
2076    pub total: usize,
2077}
2078
2079// === impl PoolSize ===
2080
2081impl PoolSize {
2082    /// Asserts that the invariants of the pool size are met.
2083    #[cfg(test)]
2084    pub(crate) fn assert_invariants(&self) {
2085        assert_eq!(self.total, self.pending + self.basefee + self.queued + self.blob);
2086    }
2087}
2088
2089/// Represents the current status of the pool.
2090#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
2091pub struct BlockInfo {
2092    /// Hash for the currently tracked block.
2093    pub last_seen_block_hash: B256,
2094    /// Currently tracked block.
2095    pub last_seen_block_number: u64,
2096    /// Current block gas limit for the latest block.
2097    pub block_gas_limit: u64,
2098    /// Currently enforced base fee: the threshold for the basefee sub-pool.
2099    ///
2100    /// Note: this is the derived base fee of the _next_ block that builds on the block the pool is
2101    /// currently tracking.
2102    pub pending_basefee: u64,
2103    /// Currently enforced blob fee: the threshold for eip-4844 blob transactions.
2104    ///
2105    /// Note: this is the derived blob fee of the _next_ block that builds on the block the pool is
2106    /// currently tracking
2107    pub pending_blob_fee: Option<u128>,
2108}
2109
2110/// The limit to enforce for [`TransactionPool::get_pooled_transaction_elements`].
2111#[derive(Debug, Clone, Copy, Eq, PartialEq)]
2112pub enum GetPooledTransactionLimit {
2113    /// No limit, return all transactions.
2114    None,
2115    /// Enforce a size limit on the returned transactions, for example 2MB
2116    ResponseSizeSoftLimit(usize),
2117}
2118
2119impl GetPooledTransactionLimit {
2120    /// Returns true if the given size exceeds the limit.
2121    #[inline]
2122    pub const fn exceeds(&self, size: usize) -> bool {
2123        match self {
2124            Self::None => false,
2125            Self::ResponseSizeSoftLimit(limit) => size > *limit,
2126        }
2127    }
2128}
2129
2130/// A Stream that yields full transactions the subpool
2131#[must_use = "streams do nothing unless polled"]
2132#[derive(Debug)]
2133pub struct NewSubpoolTransactionStream<Tx: PoolTransaction> {
2134    st: Receiver<NewTransactionEvent<Tx>>,
2135    subpool: SubPool,
2136}
2137
2138// === impl NewSubpoolTransactionStream ===
2139
2140impl<Tx: PoolTransaction> NewSubpoolTransactionStream<Tx> {
2141    /// Create a new stream that yields full transactions from the subpool
2142    pub const fn new(st: Receiver<NewTransactionEvent<Tx>>, subpool: SubPool) -> Self {
2143        Self { st, subpool }
2144    }
2145
2146    /// Tries to receive the next value for this stream.
2147    pub fn try_recv(
2148        &mut self,
2149    ) -> Result<NewTransactionEvent<Tx>, tokio::sync::mpsc::error::TryRecvError> {
2150        loop {
2151            let event = self.st.try_recv()?;
2152            if event.subpool == self.subpool {
2153                return Ok(event)
2154            }
2155        }
2156    }
2157
2158    /// Returns the capacity of the channel behind this stream.
2159    pub fn max_capacity(&self) -> usize {
2160        self.st.max_capacity()
2161    }
2162}
2163
2164impl<Tx: PoolTransaction> Stream for NewSubpoolTransactionStream<Tx> {
2165    type Item = NewTransactionEvent<Tx>;
2166
2167    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2168        loop {
2169            match ready!(self.st.poll_recv(cx)) {
2170                Some(event) => {
2171                    if event.subpool == self.subpool {
2172                        return Poll::Ready(Some(event))
2173                    }
2174                }
2175                None => return Poll::Ready(None),
2176            }
2177        }
2178    }
2179}
2180
2181#[cfg(test)]
2182mod tests {
2183    use super::*;
2184    use crate::blobstore::{BlobCellAvailability, BlobTransactionCellSidecar};
2185    use alloy_consensus::{
2186        EthereumTxEnvelope, SignableTransaction, TxEip1559, TxEip2930, TxEip4844,
2187        TxEip4844WithSidecar, TxEip7702, TxEnvelope, TxLegacy,
2188    };
2189    use alloy_eips::{
2190        eip4844::{
2191            env_settings::EnvKzgSettings, Blob, BlobTransactionSidecar, Bytes48, DATA_GAS_PER_BLOB,
2192        },
2193        eip7594::{BlobTransactionSidecarEip7594, CELLS_PER_EXT_BLOB},
2194    };
2195    use alloy_primitives::Signature;
2196
2197    #[test]
2198    fn test_pool_size_invariants() {
2199        let pool_size = PoolSize {
2200            pending: 10,
2201            pending_size: 1000,
2202            blob: 5,
2203            blob_size: 500,
2204            basefee: 8,
2205            basefee_size: 800,
2206            queued: 7,
2207            queued_size: 700,
2208            total: 10 + 5 + 8 + 7, // Correct total
2209        };
2210
2211        // Call the assert_invariants method to check if the invariants are correct
2212        pool_size.assert_invariants();
2213    }
2214
2215    #[test]
2216    #[should_panic]
2217    fn test_pool_size_invariants_fail() {
2218        let pool_size = PoolSize {
2219            pending: 10,
2220            pending_size: 1000,
2221            blob: 5,
2222            blob_size: 500,
2223            basefee: 8,
2224            basefee_size: 800,
2225            queued: 7,
2226            queued_size: 700,
2227            total: 10 + 5 + 8, // Incorrect total
2228        };
2229
2230        // Call the assert_invariants method, which should panic
2231        pool_size.assert_invariants();
2232    }
2233
2234    #[test]
2235    fn test_eth_pooled_transaction_new_legacy() {
2236        // Create a legacy transaction with specific parameters
2237        let tx = EthereumTxEnvelope::<TxEip4844>::Legacy(
2238            TxLegacy {
2239                gas_price: 10,
2240                gas_limit: 1000,
2241                value: U256::from(100),
2242                ..Default::default()
2243            }
2244            .into_signed(Signature::test_signature()),
2245        );
2246        let transaction = Recovered::new_unchecked(tx, Default::default());
2247        let pooled_tx = EthPooledTransaction::new(transaction.clone(), 200);
2248
2249        // Check that the pooled transaction is created correctly
2250        assert_eq!(pooled_tx.transaction, transaction);
2251        assert_eq!(pooled_tx.encoded_length, 200);
2252        assert_eq!(pooled_tx.blob_sidecar, EthBlobTransactionSidecar::None);
2253        assert!(pooled_tx.blob_cell_availability.is_none());
2254        assert_eq!(pooled_tx.blob_cell_availability().map(BlobCellAvailability::get), None);
2255        assert_eq!(pooled_tx.cost, U256::from(100) + U256::from(10 * 1000));
2256        assert_eq!(pooled_tx.encoded_2718_consensus(), transaction.encoded_2718());
2257    }
2258
2259    #[test]
2260    fn test_eth_pooled_transaction_new_eip2930() {
2261        // Create an EIP-2930 transaction with specific parameters
2262        let tx = TxEnvelope::Eip2930(
2263            TxEip2930 {
2264                gas_price: 10,
2265                gas_limit: 1000,
2266                value: U256::from(100),
2267                ..Default::default()
2268            }
2269            .into_signed(Signature::test_signature()),
2270        );
2271        let transaction = Recovered::new_unchecked(tx, Default::default());
2272        let pooled_tx = EthPooledTransaction::new(transaction.clone(), 200);
2273        let expected_cost = U256::from(100) + (U256::from(10 * 1000));
2274
2275        assert_eq!(pooled_tx.transaction, transaction);
2276        assert_eq!(pooled_tx.encoded_length, 200);
2277        assert_eq!(pooled_tx.blob_sidecar, EthBlobTransactionSidecar::None);
2278        assert!(pooled_tx.blob_cell_availability.is_none());
2279        assert_eq!(pooled_tx.blob_cell_availability().map(BlobCellAvailability::get), None);
2280        assert_eq!(pooled_tx.cost, expected_cost);
2281    }
2282
2283    #[test]
2284    fn test_eth_pooled_transaction_new_eip1559() {
2285        // Create an EIP-1559 transaction with specific parameters
2286        let tx = TxEnvelope::Eip1559(
2287            TxEip1559 {
2288                max_fee_per_gas: 10,
2289                gas_limit: 1000,
2290                value: U256::from(100),
2291                ..Default::default()
2292            }
2293            .into_signed(Signature::test_signature()),
2294        );
2295        let transaction = Recovered::new_unchecked(tx, Default::default());
2296        let pooled_tx = EthPooledTransaction::new(transaction.clone(), 200);
2297
2298        // Check that the pooled transaction is created correctly
2299        assert_eq!(pooled_tx.transaction, transaction);
2300        assert_eq!(pooled_tx.encoded_length, 200);
2301        assert_eq!(pooled_tx.blob_sidecar, EthBlobTransactionSidecar::None);
2302        assert!(pooled_tx.blob_cell_availability.is_none());
2303        assert_eq!(pooled_tx.blob_cell_availability().map(BlobCellAvailability::get), None);
2304        assert_eq!(pooled_tx.cost, U256::from(100) + U256::from(10 * 1000));
2305    }
2306
2307    #[test]
2308    fn test_eth_pooled_transaction_new_eip4844() {
2309        // Create an EIP-4844 transaction with specific parameters
2310        let tx = EthereumTxEnvelope::Eip4844(
2311            TxEip4844 {
2312                max_fee_per_gas: 10,
2313                gas_limit: 1000,
2314                value: U256::from(100),
2315                max_fee_per_blob_gas: 5,
2316                blob_versioned_hashes: vec![B256::default()],
2317                ..Default::default()
2318            }
2319            .into_signed(Signature::test_signature()),
2320        );
2321        let transaction = Recovered::new_unchecked(tx, Default::default());
2322        let pooled_tx = EthPooledTransaction::new(transaction.clone(), 300);
2323
2324        // Check that the pooled transaction is created correctly
2325        assert_eq!(pooled_tx.transaction, transaction);
2326        assert_eq!(pooled_tx.encoded_length, 300);
2327        assert_eq!(pooled_tx.blob_sidecar, EthBlobTransactionSidecar::Missing);
2328        assert!(pooled_tx.blob_cell_availability.is_some());
2329        assert_eq!(
2330            pooled_tx.blob_cell_availability().map(BlobCellAvailability::get),
2331            Some(BlobCellMask::ALL)
2332        );
2333        let expected_cost =
2334            U256::from(100) + U256::from(10 * 1000) + U256::from(5 * DATA_GAS_PER_BLOB);
2335        assert_eq!(pooled_tx.cost, expected_cost);
2336    }
2337
2338    #[test]
2339    fn test_eth_pooled_transaction_new_eip7702() {
2340        // Init an EIP-7702 transaction with specific parameters
2341        let tx = EthereumTxEnvelope::<TxEip4844>::Eip7702(
2342            TxEip7702 {
2343                max_fee_per_gas: 10,
2344                gas_limit: 1000,
2345                value: U256::from(100),
2346                ..Default::default()
2347            }
2348            .into_signed(Signature::test_signature()),
2349        );
2350        let transaction = Recovered::new_unchecked(tx, Default::default());
2351        let pooled_tx = EthPooledTransaction::new(transaction.clone(), 200);
2352
2353        // Check that the pooled transaction is created correctly
2354        assert_eq!(pooled_tx.transaction, transaction);
2355        assert_eq!(pooled_tx.encoded_length, 200);
2356        assert_eq!(pooled_tx.blob_sidecar, EthBlobTransactionSidecar::None);
2357        assert!(pooled_tx.blob_cell_availability.is_none());
2358        assert_eq!(pooled_tx.blob_cell_availability().map(BlobCellAvailability::get), None);
2359        assert_eq!(pooled_tx.cost, U256::from(100) + U256::from(10 * 1000));
2360    }
2361
2362    #[test]
2363    fn test_pooled_transaction_limit() {
2364        // No limit should never exceed
2365        let limit_none = GetPooledTransactionLimit::None;
2366        // Any size should return false
2367        assert!(!limit_none.exceeds(1000));
2368
2369        // Size limit of 2MB (2 * 1024 * 1024 bytes)
2370        let size_limit_2mb = GetPooledTransactionLimit::ResponseSizeSoftLimit(2 * 1024 * 1024);
2371
2372        // Test with size below the limit
2373        // 1MB is below 2MB, should return false
2374        assert!(!size_limit_2mb.exceeds(1024 * 1024));
2375
2376        // Test with size exactly at the limit
2377        // 2MB equals the limit, should return false
2378        assert!(!size_limit_2mb.exceeds(2 * 1024 * 1024));
2379
2380        // Test with size exceeding the limit
2381        // 3MB is above the 2MB limit, should return true
2382        assert!(size_limit_2mb.exceeds(3 * 1024 * 1024));
2383    }
2384
2385    #[test]
2386    fn eth72_announced_transactions_are_served() {
2387        let blob_tx = |sidecar: BlobTransactionSidecarVariant| {
2388            PooledTransactionVariant::Eip4844(
2389                TxEip4844WithSidecar {
2390                    tx: TxEip4844 { blob_versioned_hashes: vec![B256::ZERO], ..Default::default() },
2391                    sidecar,
2392                }
2393                .into_signed(Signature::test_signature()),
2394            )
2395        };
2396        let eip7594 = blob_tx(
2397            BlobTransactionSidecarEip7594::new(
2398                vec![Blob::repeat_byte(1)],
2399                vec![Bytes48::repeat_byte(2)],
2400                vec![Bytes48::repeat_byte(3); CELLS_PER_EXT_BLOB],
2401            )
2402            .into(),
2403        );
2404        let eip4844 = blob_tx(
2405            BlobTransactionSidecar::new(
2406                vec![Blob::repeat_byte(1)],
2407                vec![Bytes48::repeat_byte(2)],
2408                vec![Bytes48::repeat_byte(3)],
2409            )
2410            .into(),
2411        );
2412        let eip1559 = PooledTransactionVariant::Eip1559(
2413            TxEip1559::default().into_signed(Signature::test_signature()),
2414        );
2415        let mut without_blobs = eip7594.clone();
2416        without_blobs.clear_eip7594_blobs();
2417
2418        for (tx, served) in
2419            [(eip1559.clone(), Some(eip1559)), (eip7594, Some(without_blobs)), (eip4844, None)]
2420        {
2421            let pooled = EthPooledTransaction::from_pooled(Recovered::new_unchecked(
2422                tx.clone(),
2423                Default::default(),
2424            ));
2425            // The default eth/72 response uses this, so it serves what the pool announces.
2426            assert_eq!(EthPooledTransaction::pooled_without_blobs(tx), served);
2427            assert_eq!(
2428                pooled.encoded_length_eth72(),
2429                served.as_ref().map(Encodable2718::encode_2718_len)
2430            );
2431        }
2432    }
2433
2434    #[test]
2435    fn blob_transaction_fetched_as_cells_keeps_the_size_with_blobs() {
2436        let full = BlobTransactionSidecarEip7594::try_from_blobs(vec![Blob::default(); 2]).unwrap();
2437        let cells =
2438            BlobTransactionCellSidecar::try_from_sidecar(&full, EnvKzgSettings::Default.get())
2439                .unwrap();
2440        let blob_tx = |sidecar: BlobTransactionSidecarVariant| {
2441            PooledTransactionVariant::Eip4844(
2442                TxEip4844WithSidecar {
2443                    tx: TxEip4844 {
2444                        blob_versioned_hashes: cells.versioned_hashes().collect(),
2445                        ..Default::default()
2446                    },
2447                    sidecar,
2448                }
2449                .into_signed(Signature::test_signature()),
2450            )
2451        };
2452        let with_blobs = blob_tx(full.clone().into());
2453        let without_blobs = blob_tx(cells.without_blobs().into());
2454
2455        // An eth/72 body has no blobs, so none of its cells are available yet.
2456        let mut pooled = EthPooledTransaction::from_pooled(Recovered::new_unchecked(
2457            without_blobs.clone(),
2458            Default::default(),
2459        ));
2460        assert_eq!(pooled.blob_cell_availability().unwrap().get(), BlobCellMask::from_bits(0));
2461        assert_eq!(pooled.encoded_length(), with_blobs.encode_2718_len());
2462
2463        assert!(pooled.set_blob_sidecar(PooledBlobSidecar::from_cells(cells.clone())));
2464        assert_eq!(pooled.blob_cell_availability().unwrap().get(), cells.mask());
2465        assert_eq!(pooled.blob_sidecar().and_then(PooledBlobSidecar::cells), Some(&cells));
2466
2467        // Both sizes follow the attached sidecar, however the transaction was built.
2468        let full = BlobTransactionSidecarVariant::Eip7594(full);
2469        for sidecar in [PooledBlobSidecar::from_cells(cells.clone()), full.into()] {
2470            let built = EthPooledTransaction::new(
2471                Recovered::new_unchecked(with_blobs.clone().into(), Default::default()),
2472                0,
2473            );
2474            for mut pooled in [pooled.clone(), built] {
2475                assert!(pooled.set_blob_sidecar(sidecar.clone()));
2476                assert_eq!(pooled.encoded_length(), with_blobs.encode_2718_len());
2477                assert_eq!(pooled.encoded_length_eth72(), Some(without_blobs.encode_2718_len()));
2478            }
2479        }
2480
2481        // A legacy sidecar replacing it can't be served to eth/72 peers.
2482        let legacy = BlobTransactionSidecarVariant::Eip4844(BlobTransactionSidecar::new(
2483            vec![Blob::default(); 2],
2484            vec![Bytes48::default(); 2],
2485            vec![Bytes48::default(); 2],
2486        ));
2487        assert!(pooled.set_blob_sidecar(legacy.clone().into()));
2488        assert_eq!(pooled.encoded_length(), blob_tx(legacy).encode_2718_len());
2489        assert_eq!(pooled.encoded_length_eth72(), None);
2490
2491        // Blobs without commitments still count, so pending imports are charged for them.
2492        let malformed = blob_tx(
2493            BlobTransactionSidecarEip7594::new(vec![Blob::default(); 2], vec![], vec![]).into(),
2494        );
2495        let pooled = EthPooledTransaction::from_pooled(Recovered::new_unchecked(
2496            malformed.clone(),
2497            Default::default(),
2498        ));
2499        assert_eq!(pooled.encoded_length(), malformed.encode_2718_len());
2500
2501        // Other transactions can't carry a sidecar.
2502        let mut plain = EthPooledTransaction::new(
2503            Recovered::new_unchecked(
2504                TransactionSigned::from(
2505                    TxEip1559::default().into_signed(Signature::test_signature()),
2506                ),
2507                Default::default(),
2508            ),
2509            0,
2510        );
2511        assert!(!plain.set_blob_sidecar(PooledBlobSidecar::from_cells(cells)));
2512        assert_eq!(plain.blob_sidecar(), None);
2513    }
2514}