Skip to main content

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::{map::AddressSet, Address, TxHash, B256, U256};
23use reth_eth_wire_types::HandleMempoolData;
24use reth_primitives_traits::Recovered;
25use std::{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 append_pooled_transaction_elements(
172        &self,
173        _tx_hashes: &[TxHash],
174        _limit: GetPooledTransactionLimit,
175        _out: &mut Vec<<Self::Transaction as PoolTransaction>::Pooled>,
176    ) {
177    }
178
179    fn get_pooled_transaction_element(
180        &self,
181        _tx_hash: TxHash,
182    ) -> Option<Recovered<<Self::Transaction as PoolTransaction>::Pooled>> {
183        None
184    }
185
186    fn best_transactions(
187        &self,
188    ) -> Box<dyn BestTransactions<Item = Arc<ValidPoolTransaction<Self::Transaction>>>> {
189        Box::new(std::iter::empty())
190    }
191
192    fn best_transactions_with_attributes(
193        &self,
194        _: BestTransactionsAttributes,
195    ) -> Box<dyn BestTransactions<Item = Arc<ValidPoolTransaction<Self::Transaction>>>> {
196        Box::new(std::iter::empty())
197    }
198
199    fn pending_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
200        vec![]
201    }
202
203    fn pending_transactions_max(
204        &self,
205        _max: usize,
206    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
207        vec![]
208    }
209
210    fn queued_transactions(&self) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
211        vec![]
212    }
213
214    fn pending_and_queued_txn_count(&self) -> (usize, usize) {
215        (0, 0)
216    }
217
218    fn all_transactions(&self) -> AllPoolTransactions<Self::Transaction> {
219        AllPoolTransactions::default()
220    }
221
222    fn all_transaction_hashes(&self) -> Vec<TxHash> {
223        vec![]
224    }
225
226    fn remove_transactions(
227        &self,
228        _hashes: Vec<TxHash>,
229    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
230        vec![]
231    }
232
233    fn remove_transactions_and_descendants(
234        &self,
235        _hashes: Vec<TxHash>,
236    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
237        vec![]
238    }
239
240    fn remove_transactions_by_sender(
241        &self,
242        _sender: Address,
243    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
244        vec![]
245    }
246
247    fn prune_transactions(
248        &self,
249        _hashes: Vec<TxHash>,
250    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
251        vec![]
252    }
253
254    fn retain_unknown<A>(&self, _announcement: &mut A)
255    where
256        A: HandleMempoolData,
257    {
258    }
259
260    fn get(&self, _tx_hash: &TxHash) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
261        None
262    }
263
264    fn get_all(&self, _txs: Vec<TxHash>) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
265        vec![]
266    }
267
268    fn on_propagated(&self, _txs: PropagatedTransactions) {}
269
270    fn get_transactions_by_sender(
271        &self,
272        _sender: Address,
273    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
274        vec![]
275    }
276
277    fn get_pending_transactions_with_predicate(
278        &self,
279        _predicate: impl FnMut(&ValidPoolTransaction<Self::Transaction>) -> bool,
280    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
281        vec![]
282    }
283
284    fn get_pending_transactions_by_sender(
285        &self,
286        _sender: Address,
287    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
288        vec![]
289    }
290
291    fn get_queued_transactions_by_sender(
292        &self,
293        _sender: Address,
294    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
295        vec![]
296    }
297
298    fn get_highest_transaction_by_sender(
299        &self,
300        _sender: Address,
301    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
302        None
303    }
304
305    fn get_highest_consecutive_transaction_by_sender(
306        &self,
307        _sender: Address,
308        _on_chain_nonce: u64,
309    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
310        None
311    }
312
313    fn get_transaction_by_sender_and_nonce(
314        &self,
315        _sender: Address,
316        _nonce: u64,
317    ) -> Option<Arc<ValidPoolTransaction<Self::Transaction>>> {
318        None
319    }
320
321    fn get_transactions_by_origin(
322        &self,
323        _origin: TransactionOrigin,
324    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
325        vec![]
326    }
327
328    fn get_pending_transactions_by_origin(
329        &self,
330        _origin: TransactionOrigin,
331    ) -> Vec<Arc<ValidPoolTransaction<Self::Transaction>>> {
332        vec![]
333    }
334
335    fn unique_senders(&self) -> AddressSet {
336        Default::default()
337    }
338
339    fn get_blob(
340        &self,
341        _tx_hash: TxHash,
342    ) -> Result<Option<Arc<BlobTransactionSidecarVariant>>, BlobStoreError> {
343        Ok(None)
344    }
345
346    fn get_all_blobs(
347        &self,
348        _tx_hashes: Vec<TxHash>,
349    ) -> Result<Vec<(TxHash, Arc<BlobTransactionSidecarVariant>)>, BlobStoreError> {
350        Ok(vec![])
351    }
352
353    fn get_all_blobs_exact(
354        &self,
355        tx_hashes: Vec<TxHash>,
356    ) -> Result<Vec<Arc<BlobTransactionSidecarVariant>>, BlobStoreError> {
357        if tx_hashes.is_empty() {
358            return Ok(vec![])
359        }
360        Err(BlobStoreError::MissingSidecar(tx_hashes[0]))
361    }
362
363    fn get_blobs_for_versioned_hashes_v1(
364        &self,
365        versioned_hashes: &[B256],
366    ) -> Result<Vec<Option<BlobAndProofV1>>, BlobStoreError> {
367        Ok(vec![None; versioned_hashes.len()])
368    }
369
370    fn get_blobs_for_versioned_hashes_v2(
371        &self,
372        _versioned_hashes: &[B256],
373    ) -> Result<Option<Vec<BlobAndProofV2>>, BlobStoreError> {
374        Ok(None)
375    }
376
377    fn get_blobs_for_versioned_hashes_v3(
378        &self,
379        versioned_hashes: &[B256],
380    ) -> Result<Vec<Option<BlobAndProofV2>>, BlobStoreError> {
381        Ok(vec![None; versioned_hashes.len()])
382    }
383}
384
385/// A [`TransactionValidator`] that does nothing.
386#[derive(Debug, Clone)]
387#[non_exhaustive]
388pub struct MockTransactionValidator<T> {
389    propagate_local: bool,
390    return_invalid: bool,
391    _marker: PhantomData<T>,
392}
393
394impl<T: EthPoolTransaction> TransactionValidator for MockTransactionValidator<T> {
395    type Transaction = T;
396    type Block = reth_ethereum_primitives::Block;
397
398    async fn validate_transaction(
399        &self,
400        origin: TransactionOrigin,
401        mut transaction: Self::Transaction,
402    ) -> TransactionValidationOutcome<Self::Transaction> {
403        if self.return_invalid {
404            return TransactionValidationOutcome::Invalid(
405                transaction,
406                InvalidPoolTransactionError::Underpriced,
407            );
408        }
409        let maybe_sidecar = transaction.take_blob().maybe_sidecar().cloned();
410        // we return `balance: U256::MAX` to simulate a valid transaction which will never go into
411        // overdraft
412        TransactionValidationOutcome::Valid {
413            balance: U256::MAX,
414            state_nonce: 0,
415            bytecode_hash: None,
416            transaction: ValidTransaction::new(transaction, maybe_sidecar),
417            propagate: match origin {
418                TransactionOrigin::External => true,
419                TransactionOrigin::Local => self.propagate_local,
420                TransactionOrigin::Private => false,
421            },
422            authorities: None,
423        }
424    }
425}
426
427impl<T> MockTransactionValidator<T> {
428    /// Creates a new [`MockTransactionValidator`] that does not allow local transactions to be
429    /// propagated.
430    pub fn no_propagate_local() -> Self {
431        Self { propagate_local: false, return_invalid: false, _marker: Default::default() }
432    }
433    /// Creates a new [`MockTransactionValidator`] that always returns an invalid outcome.
434    pub fn return_invalid() -> Self {
435        Self { propagate_local: false, return_invalid: true, _marker: Default::default() }
436    }
437}
438
439impl<T> Default for MockTransactionValidator<T> {
440    fn default() -> Self {
441        Self { propagate_local: true, return_invalid: false, _marker: Default::default() }
442    }
443}
444
445/// An error that contains the transaction that failed to be inserted into the noop pool.
446#[derive(Debug, Clone, thiserror::Error)]
447#[error("can't insert transaction into the noop pool that does nothing")]
448pub struct NoopInsertError<T: EthPoolTransaction = EthPooledTransaction> {
449    tx: T,
450}
451
452impl<T: EthPoolTransaction> NoopInsertError<T> {
453    const fn new(tx: T) -> Self {
454        Self { tx }
455    }
456
457    /// Returns the transaction that failed to be inserted.
458    pub fn into_inner(self) -> T {
459        self.tx
460    }
461}