reth_transaction_pool/
noop.rs

1//! A transaction pool implementation that does nothing.
2//!
3//! This is useful for wiring components together that don't require an actual pool but still need
4//! to be generic over it.
5
6use crate::{
7    blobstore::BlobStoreError,
8    error::{InvalidPoolTransactionError, PoolError},
9    pool::TransactionListenerKind,
10    traits::{BestTransactionsAttributes, GetPooledTransactionLimit, NewBlobSidecar},
11    validate::ValidTransaction,
12    AddedTransactionOutcome, AllPoolTransactions, AllTransactionsEvents, BestTransactions,
13    BlockInfo, EthPoolTransaction, EthPooledTransaction, NewTransactionEvent, PoolResult, PoolSize,
14    PoolTransaction, PropagatedTransactions, TransactionEvents, TransactionOrigin, TransactionPool,
15    TransactionValidationOutcome, TransactionValidator, ValidPoolTransaction,
16};
17use alloy_eips::{
18    eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M,
19    eip4844::{BlobAndProofV1, BlobAndProofV2},
20    eip7594::BlobTransactionSidecarVariant,
21};
22use alloy_primitives::{Address, TxHash, B256, U256};
23use reth_eth_wire_types::HandleMempoolData;
24use reth_primitives_traits::Recovered;
25use std::{collections::HashSet, marker::PhantomData, sync::Arc};
26use tokio::sync::{mpsc, mpsc::Receiver};
27
28/// A [`TransactionPool`] implementation that does nothing.
29///
30/// All transactions are rejected and no events are emitted.
31/// This type will never hold any transactions and is only useful for wiring components together.
32#[derive(Debug, Clone)]
33#[non_exhaustive]
34pub struct NoopTransactionPool<T = EthPooledTransaction> {
35    /// Type marker
36    _marker: PhantomData<T>,
37}
38
39impl<T> NoopTransactionPool<T> {
40    /// Creates a new [`NoopTransactionPool`].
41    pub fn new() -> Self {
42        Self { _marker: Default::default() }
43    }
44}
45
46impl Default for NoopTransactionPool<EthPooledTransaction> {
47    fn default() -> Self {
48        Self { _marker: Default::default() }
49    }
50}
51
52impl<T: EthPoolTransaction> TransactionPool for NoopTransactionPool<T> {
53    type Transaction = T;
54
55    fn pool_size(&self) -> PoolSize {
56        Default::default()
57    }
58
59    fn block_info(&self) -> BlockInfo {
60        BlockInfo {
61            block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,
62            last_seen_block_hash: Default::default(),
63            last_seen_block_number: 0,
64            pending_basefee: 0,
65            pending_blob_fee: None,
66        }
67    }
68
69    async fn add_transaction_and_subscribe(
70        &self,
71        _origin: TransactionOrigin,
72        transaction: Self::Transaction,
73    ) -> PoolResult<TransactionEvents> {
74        let hash = *transaction.hash();
75        Err(PoolError::other(hash, Box::new(NoopInsertError::new(transaction))))
76    }
77
78    async fn add_transaction(
79        &self,
80        _origin: TransactionOrigin,
81        transaction: Self::Transaction,
82    ) -> PoolResult<AddedTransactionOutcome> {
83        let hash = *transaction.hash();
84        Err(PoolError::other(hash, Box::new(NoopInsertError::new(transaction))))
85    }
86
87    async fn add_transactions(
88        &self,
89        _origin: TransactionOrigin,
90        transactions: Vec<Self::Transaction>,
91    ) -> Vec<PoolResult<AddedTransactionOutcome>> {
92        transactions
93            .into_iter()
94            .map(|transaction| {
95                let hash = *transaction.hash();
96                Err(PoolError::other(hash, Box::new(NoopInsertError::new(transaction))))
97            })
98            .collect()
99    }
100
101    async fn add_transactions_with_origins(
102        &self,
103        transactions: Vec<(TransactionOrigin, Self::Transaction)>,
104    ) -> Vec<PoolResult<AddedTransactionOutcome>> {
105        transactions
106            .into_iter()
107            .map(|(_, transaction)| {
108                let hash = *transaction.hash();
109                Err(PoolError::other(hash, Box::new(NoopInsertError::new(transaction))))
110            })
111            .collect()
112    }
113
114    fn transaction_event_listener(&self, _tx_hash: TxHash) -> Option<TransactionEvents> {
115        None
116    }
117
118    fn all_transactions_event_listener(&self) -> AllTransactionsEvents<Self::Transaction> {
119        AllTransactionsEvents::new(mpsc::channel(1).1)
120    }
121
122    fn pending_transactions_listener_for(
123        &self,
124        _kind: TransactionListenerKind,
125    ) -> Receiver<TxHash> {
126        mpsc::channel(1).1
127    }
128
129    fn new_transactions_listener(&self) -> Receiver<NewTransactionEvent<Self::Transaction>> {
130        mpsc::channel(1).1
131    }
132
133    fn blob_transaction_sidecars_listener(&self) -> Receiver<NewBlobSidecar> {
134        mpsc::channel(1).1
135    }
136
137    fn new_transactions_listener_for(
138        &self,
139        _kind: TransactionListenerKind,
140    ) -> Receiver<NewTransactionEvent<Self::Transaction>> {
141        mpsc::channel(1).1
142    }
143
144    fn pooled_transaction_hashes(&self) -> Vec<TxHash> {
145        vec![]
146    }
147
148    fn pooled_transaction_hashes_max(&self, _max: usize) -> Vec<TxHash> {
149        vec![]
150    }
151
152    fn pooled_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
153        vec![]
154    }
155
156    fn pooled_transactions_max(
157        &self,
158        _max: usize,
159    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
160        vec![]
161    }
162
163    fn get_pooled_transaction_elements(
164        &self,
165        _tx_hashes: Vec<TxHash>,
166        _limit: GetPooledTransactionLimit,
167    ) -> Vec<<Self::Transaction as PoolTransaction>::Pooled> {
168        vec![]
169    }
170
171    fn get_pooled_transaction_element(
172        &self,
173        _tx_hash: TxHash,
174    ) -> Option<Recovered<<Self::Transaction as PoolTransaction>::Pooled>> {
175        None
176    }
177
178    fn best_transactions(
179        &self,
180    ) -> Box<dyn BestTransactions<Item = Arc<ValidPoolTransaction<Self::Transaction>>>> {
181        Box::new(std::iter::empty())
182    }
183
184    fn best_transactions_with_attributes(
185        &self,
186        _: BestTransactionsAttributes,
187    ) -> Box<dyn BestTransactions<Item = Arc<ValidPoolTransaction<Self::Transaction>>>> {
188        Box::new(std::iter::empty())
189    }
190
191    fn pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
192        vec![]
193    }
194
195    fn pending_transactions_max(
196        &self,
197        _max: usize,
198    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
199        vec![]
200    }
201
202    fn queued_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
203        vec![]
204    }
205
206    fn pending_and_queued_txn_count(&self) -> (usize, usize) {
207        (0, 0)
208    }
209
210    fn all_transactions(&self) -> AllPoolTransactions<Self::Transaction> {
211        AllPoolTransactions::default()
212    }
213
214    fn all_transaction_hashes(&self) -> Vec<TxHash> {
215        vec![]
216    }
217
218    fn remove_transactions(
219        &self,
220        _hashes: Vec<TxHash>,
221    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
222        vec![]
223    }
224
225    fn remove_transactions_and_descendants(
226        &self,
227        _hashes: Vec<TxHash>,
228    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
229        vec![]
230    }
231
232    fn remove_transactions_by_sender(
233        &self,
234        _sender: Address,
235    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
236        vec![]
237    }
238
239    fn retain_unknown<A>(&self, _announcement: &mut A)
240    where
241        A: HandleMempoolData,
242    {
243    }
244
245    fn get(&self, _tx_hash: &TxHash) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
246        None
247    }
248
249    fn get_all(&self, _txs: Vec<TxHash>) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
250        vec![]
251    }
252
253    fn on_propagated(&self, _txs: PropagatedTransactions) {}
254
255    fn get_transactions_by_sender(
256        &self,
257        _sender: Address,
258    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
259        vec![]
260    }
261
262    fn get_pending_transactions_with_predicate(
263        &self,
264        _predicate: impl FnMut(&ValidPoolTransaction<Self::Transaction>) -> bool,
265    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
266        vec![]
267    }
268
269    fn get_pending_transactions_by_sender(
270        &self,
271        _sender: Address,
272    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
273        vec![]
274    }
275
276    fn get_queued_transactions_by_sender(
277        &self,
278        _sender: Address,
279    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
280        vec![]
281    }
282
283    fn get_highest_transaction_by_sender(
284        &self,
285        _sender: Address,
286    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
287        None
288    }
289
290    fn get_highest_consecutive_transaction_by_sender(
291        &self,
292        _sender: Address,
293        _on_chain_nonce: u64,
294    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
295        None
296    }
297
298    fn get_transaction_by_sender_and_nonce(
299        &self,
300        _sender: Address,
301        _nonce: u64,
302    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
303        None
304    }
305
306    fn get_transactions_by_origin(
307        &self,
308        _origin: TransactionOrigin,
309    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
310        vec![]
311    }
312
313    fn get_pending_transactions_by_origin(
314        &self,
315        _origin: TransactionOrigin,
316    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
317        vec![]
318    }
319
320    fn unique_senders(&self) -> HashSet<Address> {
321        Default::default()
322    }
323
324    fn get_blob(
325        &self,
326        _tx_hash: TxHash,
327    ) -> Result<Option<Arc<BlobTransactionSidecarVariant>>, BlobStoreError> {
328        Ok(None)
329    }
330
331    fn get_all_blobs(
332        &self,
333        _tx_hashes: Vec<TxHash>,
334    ) -> Result<Vec<(TxHash, Arc<BlobTransactionSidecarVariant>)>, BlobStoreError> {
335        Ok(vec![])
336    }
337
338    fn get_all_blobs_exact(
339        &self,
340        tx_hashes: Vec<TxHash>,
341    ) -> Result<Vec<Arc<BlobTransactionSidecarVariant>>, BlobStoreError> {
342        if tx_hashes.is_empty() {
343            return Ok(vec![])
344        }
345        Err(BlobStoreError::MissingSidecar(tx_hashes[0]))
346    }
347
348    fn get_blobs_for_versioned_hashes_v1(
349        &self,
350        versioned_hashes: &[B256],
351    ) -> Result<Vec<Option<BlobAndProofV1>>, BlobStoreError> {
352        Ok(vec![None; versioned_hashes.len()])
353    }
354
355    fn get_blobs_for_versioned_hashes_v2(
356        &self,
357        _versioned_hashes: &[B256],
358    ) -> Result<Option<Vec<BlobAndProofV2>>, BlobStoreError> {
359        Ok(None)
360    }
361}
362
363/// A [`TransactionValidator`] that does nothing.
364#[derive(Debug, Clone)]
365#[non_exhaustive]
366pub struct MockTransactionValidator<T> {
367    propagate_local: bool,
368    return_invalid: bool,
369    _marker: PhantomData<T>,
370}
371
372impl<T: EthPoolTransaction> TransactionValidator for MockTransactionValidator<T> {
373    type Transaction = T;
374
375    async fn validate_transaction(
376        &self,
377        origin: TransactionOrigin,
378        mut transaction: Self::Transaction,
379    ) -> TransactionValidationOutcome<Self::Transaction> {
380        if self.return_invalid {
381            return TransactionValidationOutcome::Invalid(
382                transaction,
383                InvalidPoolTransactionError::Underpriced,
384            );
385        }
386        let maybe_sidecar = transaction.take_blob().maybe_sidecar().cloned();
387        // we return `balance: U256::MAX` to simulate a valid transaction which will never go into
388        // overdraft
389        TransactionValidationOutcome::Valid {
390            balance: U256::MAX,
391            state_nonce: 0,
392            bytecode_hash: None,
393            transaction: ValidTransaction::new(transaction, maybe_sidecar),
394            propagate: match origin {
395                TransactionOrigin::External => true,
396                TransactionOrigin::Local => self.propagate_local,
397                TransactionOrigin::Private => false,
398            },
399            authorities: None,
400        }
401    }
402}
403
404impl<T> MockTransactionValidator<T> {
405    /// Creates a new [`MockTransactionValidator`] that does not allow local transactions to be
406    /// propagated.
407    pub fn no_propagate_local() -> Self {
408        Self { propagate_local: false, return_invalid: false, _marker: Default::default() }
409    }
410    /// Creates a new [`MockTransactionValidator`] that always return a invalid outcome.
411    pub fn return_invalid() -> Self {
412        Self { propagate_local: false, return_invalid: true, _marker: Default::default() }
413    }
414}
415
416impl<T> Default for MockTransactionValidator<T> {
417    fn default() -> Self {
418        Self { propagate_local: true, return_invalid: false, _marker: Default::default() }
419    }
420}
421
422/// An error that contains the transaction that failed to be inserted into the noop pool.
423#[derive(Debug, Clone, thiserror::Error)]
424#[error("can't insert transaction into the noop pool that does nothing")]
425pub struct NoopInsertError<T: EthPoolTransaction = EthPooledTransaction> {
426    tx: T,
427}
428
429impl<T: EthPoolTransaction> NoopInsertError<T> {
430    const fn new(tx: T) -> Self {
431        Self { tx }
432    }
433
434    /// Returns the transaction that failed to be inserted.
435    pub fn into_inner(self) -> T {
436        self.tx
437    }
438}