Skip to main content

reth_transaction_pool/validate/
eth.rs

1//! Ethereum transaction validator.
2
3use super::constants::DEFAULT_MAX_TX_INPUT_BYTES;
4use crate::{
5    blobstore::BlobStore,
6    error::{
7        Eip4844PoolTransactionError, Eip7702PoolTransactionError, InvalidPoolTransactionError,
8    },
9    metrics::TxPoolValidationMetrics,
10    traits::TransactionOrigin,
11    validate::ValidTransaction,
12    Address, BlobTransactionSidecarVariant, EthBlobTransactionSidecar, EthPoolTransaction,
13    LocalTransactionConfig, TransactionValidationOutcome, TransactionValidationTaskExecutor,
14    TransactionValidator,
15};
16
17use alloy_consensus::{
18    constants::{
19        EIP1559_TX_TYPE_ID, EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, EIP7702_TX_TYPE_ID,
20        LEGACY_TX_TYPE_ID,
21    },
22    BlockHeader,
23};
24use alloy_eips::{
25    eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, eip4844::env_settings::EnvKzgSettings,
26    eip7840::BlobParams, BlockId,
27};
28use alloy_primitives::U256;
29use alloy_rlp::Encodable;
30use reth_chainspec::{ChainSpecProvider, EthChainSpec, EthereumHardforks};
31use reth_evm::ConfigureEvm;
32use reth_primitives_traits::{
33    transaction::error::InvalidTransactionError, Account, BlockTy, GotExpected, HeaderTy,
34    SealedBlock,
35};
36use reth_storage_api::{
37    errors::ProviderError, AccountInfoReader, BlockReaderIdExt, BytecodeReader, StateProviderBox,
38    StateProviderFactory,
39};
40use reth_tasks::Runtime;
41use revm::context_interface::Cfg;
42use std::{
43    fmt,
44    marker::PhantomData,
45    sync::{
46        atomic::{AtomicBool, AtomicU64, AtomicUsize},
47        Arc,
48    },
49    time::{Instant, SystemTime},
50};
51
52/// Additional stateless validation function signature.
53///
54/// Receives the transaction origin and a reference to the transaction. Returns `Ok(())` if the
55/// transaction passes or `Err` to reject it.
56pub type StatelessValidationFn<T> =
57    Arc<dyn Fn(TransactionOrigin, &T) -> Result<(), InvalidPoolTransactionError> + Send + Sync>;
58
59/// Additional stateful validation function signature.
60///
61/// Receives the transaction origin, a reference to the transaction, and an account state reader.
62/// Returns `Ok(())` if the transaction passes or `Err` to reject it.
63pub type StatefulValidationFn<T> = Arc<
64    dyn Fn(TransactionOrigin, &T, &dyn AccountInfoReader) -> Result<(), InvalidPoolTransactionError>
65        + Send
66        + Sync,
67>;
68
69/// A [`TransactionValidator`] implementation that validates ethereum transaction.
70///
71/// It supports all known ethereum transaction types:
72/// - Legacy
73/// - EIP-2718
74/// - EIP-1559
75/// - EIP-4844
76/// - EIP-7702
77///
78/// And enforces additional constraints such as:
79/// - Maximum transaction size
80/// - Maximum gas limit
81///
82/// And adheres to the configured [`LocalTransactionConfig`].
83pub struct EthTransactionValidator<Client, T, Evm> {
84    /// This type fetches account info from the db
85    client: Client,
86    /// The chain ID transactions must use.
87    chain_id: u64,
88    /// Blobstore used for fetching re-injected blob transactions.
89    blob_store: Box<dyn BlobStore>,
90    /// tracks activated forks relevant for transaction validation
91    fork_tracker: ForkTracker,
92    /// Fork indicator whether we are using EIP-2718 type transactions.
93    eip2718: bool,
94    /// Fork indicator whether we are using EIP-1559 type transactions.
95    eip1559: bool,
96    /// Fork indicator whether we are using EIP-4844 blob transactions.
97    eip4844: bool,
98    /// Fork indicator whether we are using EIP-7702 type transactions.
99    eip7702: bool,
100    /// The current max gas limit
101    block_gas_limit: AtomicU64,
102    /// The current tx fee cap limit in wei locally submitted into the pool.
103    tx_fee_cap: Option<u128>,
104    /// Minimum priority fee to enforce for acceptance into the pool.
105    minimum_priority_fee: Option<u128>,
106    /// Stores the setup and parameters needed for validating KZG proofs.
107    kzg_settings: EnvKzgSettings,
108    /// How to handle [`TransactionOrigin::Local`](TransactionOrigin) transactions.
109    local_transactions_config: LocalTransactionConfig,
110    /// Maximum size in bytes a single transaction can have in order to be accepted into the pool.
111    max_tx_input_bytes: usize,
112    /// Maximum gas limit for individual transactions
113    max_tx_gas_limit: Option<u64>,
114    /// Disable balance checks during transaction validation
115    disable_balance_check: bool,
116    /// EVM configuration for fetching execution limits
117    evm_config: Evm,
118    /// Marker for the transaction type
119    _marker: PhantomData<T>,
120    /// Metrics for tsx pool validation
121    validation_metrics: TxPoolValidationMetrics,
122    /// Bitmap of custom transaction types that are allowed.
123    other_tx_types: U256,
124    /// Whether EIP-7594 blob sidecars are accepted.
125    /// When false, EIP-7594 (v1) sidecars are always rejected and EIP-4844 (v0) sidecars
126    /// are always accepted, regardless of Osaka fork activation.
127    eip7594: bool,
128    /// Optional additional stateless validation check applied at the end of
129    /// [`validate_stateless`](Self::validate_stateless).
130    additional_stateless_validation: Option<StatelessValidationFn<T>>,
131    /// Optional additional stateful validation check applied at the end of
132    /// [`validate_stateful`](Self::validate_stateful).
133    additional_stateful_validation: Option<StatefulValidationFn<T>>,
134}
135
136impl<Client, Tx, Evm> fmt::Debug for EthTransactionValidator<Client, Tx, Evm> {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        f.debug_struct("EthTransactionValidator")
139            .field("fork_tracker", &self.fork_tracker)
140            .field("eip2718", &self.eip2718)
141            .field("eip1559", &self.eip1559)
142            .field("eip4844", &self.eip4844)
143            .field("eip7702", &self.eip7702)
144            .field("block_gas_limit", &self.block_gas_limit)
145            .field("tx_fee_cap", &self.tx_fee_cap)
146            .field("minimum_priority_fee", &self.minimum_priority_fee)
147            .field("max_tx_input_bytes", &self.max_tx_input_bytes)
148            .field("max_tx_gas_limit", &self.max_tx_gas_limit)
149            .field("disable_balance_check", &self.disable_balance_check)
150            .field("eip7594", &self.eip7594)
151            .field(
152                "additional_stateless_validation",
153                &self.additional_stateless_validation.as_ref().map(|_| "..."),
154            )
155            .field(
156                "additional_stateful_validation",
157                &self.additional_stateful_validation.as_ref().map(|_| "..."),
158            )
159            .finish()
160    }
161}
162
163impl<Client, Tx, Evm> EthTransactionValidator<Client, Tx, Evm> {
164    /// Returns the configured chain spec
165    pub fn chain_spec(&self) -> Arc<Client::ChainSpec>
166    where
167        Client: ChainSpecProvider,
168    {
169        self.client().chain_spec()
170    }
171
172    /// Returns the configured chain id
173    pub const fn chain_id(&self) -> u64 {
174        self.chain_id
175    }
176
177    /// Returns the configured client
178    pub const fn client(&self) -> &Client {
179        &self.client
180    }
181
182    /// Returns the tracks activated forks relevant for transaction validation
183    pub const fn fork_tracker(&self) -> &ForkTracker {
184        &self.fork_tracker
185    }
186
187    /// Returns the EVM config used for transaction validation.
188    pub const fn evm_config(&self) -> &Evm {
189        &self.evm_config
190    }
191
192    /// Returns if there are EIP-2718 type transactions
193    pub const fn eip2718(&self) -> bool {
194        self.eip2718
195    }
196
197    /// Returns if there are EIP-1559 type transactions
198    pub const fn eip1559(&self) -> bool {
199        self.eip1559
200    }
201
202    /// Returns if there are EIP-4844 blob transactions
203    pub const fn eip4844(&self) -> bool {
204        self.eip4844
205    }
206
207    /// Returns if there are EIP-7702 type transactions
208    pub const fn eip7702(&self) -> bool {
209        self.eip7702
210    }
211
212    /// Returns the current tx fee cap limit in wei locally submitted into the pool
213    pub const fn tx_fee_cap(&self) -> &Option<u128> {
214        &self.tx_fee_cap
215    }
216
217    /// Returns the minimum priority fee to enforce for acceptance into the pool
218    pub const fn minimum_priority_fee(&self) -> &Option<u128> {
219        &self.minimum_priority_fee
220    }
221
222    /// Returns the setup and parameters needed for validating KZG proofs.
223    pub const fn kzg_settings(&self) -> &EnvKzgSettings {
224        &self.kzg_settings
225    }
226
227    /// Returns the config to handle [`TransactionOrigin::Local`](TransactionOrigin) transactions..
228    pub const fn local_transactions_config(&self) -> &LocalTransactionConfig {
229        &self.local_transactions_config
230    }
231
232    /// Returns the maximum size in bytes a single transaction can have in order to be accepted into
233    /// the pool.
234    pub const fn max_tx_input_bytes(&self) -> usize {
235        self.max_tx_input_bytes
236    }
237
238    /// Returns whether balance checks are disabled for this validator.
239    pub const fn disable_balance_check(&self) -> bool {
240        self.disable_balance_check
241    }
242
243    /// Sets an additional stateless validation check that is applied at the end of
244    /// [`validate_stateless`](Self::validate_stateless).
245    ///
246    /// The check receives the transaction origin and a reference to the transaction, and
247    /// should return `Ok(())` if the transaction is valid or
248    /// `Err(InvalidPoolTransactionError)` to reject it.
249    ///
250    /// # Example
251    ///
252    /// ```ignore
253    /// use reth_transaction_pool::{error::InvalidPoolTransactionError, TransactionOrigin};
254    ///
255    /// let mut validator = builder.build(blob_store);
256    /// // Reject external transactions with input data exceeding 1KB
257    /// validator.set_additional_stateless_validation(|origin, tx| {
258    ///     if origin.is_external() && tx.input().len() > 1024 {
259    ///         return Err(InvalidPoolTransactionError::OversizedData {
260    ///             size: tx.input().len(),
261    ///             limit: 1024,
262    ///         });
263    ///     }
264    ///     Ok(())
265    /// });
266    /// ```
267    pub fn set_additional_stateless_validation<F>(&mut self, f: F)
268    where
269        F: Fn(TransactionOrigin, &Tx) -> Result<(), InvalidPoolTransactionError>
270            + Send
271            + Sync
272            + 'static,
273    {
274        self.additional_stateless_validation = Some(Arc::new(f));
275    }
276
277    /// Sets the additional stateless validation check from an already shared
278    /// [`StatelessValidationFn`].
279    ///
280    /// This is useful when the same hook is shared across multiple validators, avoiding an extra
281    /// allocation compared to
282    /// [`set_additional_stateless_validation`](Self::set_additional_stateless_validation).
283    pub fn set_additional_stateless_validation_fn(&mut self, f: StatelessValidationFn<Tx>) {
284        self.additional_stateless_validation = Some(f);
285    }
286
287    /// Sets or clears the additional stateless validation check from an optional
288    /// [`StatelessValidationFn`].
289    ///
290    /// Passing `None` removes any previously configured check.
291    pub fn set_additional_stateless_validation_fn_opt(
292        &mut self,
293        f: Option<StatelessValidationFn<Tx>>,
294    ) {
295        self.additional_stateless_validation = f;
296    }
297
298    /// Sets an additional stateful validation check that is applied at the end of
299    /// [`validate_stateful`](Self::validate_stateful).
300    ///
301    /// The check receives the transaction origin, a reference to the transaction, and the
302    /// account state reader, and should return `Ok(())` if the transaction is valid or
303    /// `Err(InvalidPoolTransactionError)` to reject it.
304    ///
305    /// # Example
306    ///
307    /// ```ignore
308    /// use reth_transaction_pool::{error::InvalidPoolTransactionError, TransactionOrigin};
309    ///
310    /// let mut validator = builder.build(blob_store);
311    /// // Reject transactions from accounts with zero balance
312    /// validator.set_additional_stateful_validation(|origin, tx, state| {
313    ///     let account = state.basic_account(tx.sender_ref())?.unwrap_or_default();
314    ///     if account.balance.is_zero() {
315    ///         return Err(InvalidPoolTransactionError::Other(Box::new(
316    ///             std::io::Error::new(std::io::ErrorKind::Other, "zero balance"),
317    ///         )));
318    ///     }
319    ///     Ok(())
320    /// });
321    /// ```
322    pub fn set_additional_stateful_validation<F>(&mut self, f: F)
323    where
324        F: Fn(
325                TransactionOrigin,
326                &Tx,
327                &dyn AccountInfoReader,
328            ) -> Result<(), InvalidPoolTransactionError>
329            + Send
330            + Sync
331            + 'static,
332    {
333        self.additional_stateful_validation = Some(Arc::new(f));
334    }
335
336    /// Sets the additional stateful validation check from an already shared
337    /// [`StatefulValidationFn`].
338    ///
339    /// This is useful when the same hook is shared across multiple validators, avoiding an extra
340    /// allocation compared to
341    /// [`set_additional_stateful_validation`](Self::set_additional_stateful_validation).
342    pub fn set_additional_stateful_validation_fn(&mut self, f: StatefulValidationFn<Tx>) {
343        self.additional_stateful_validation = Some(f);
344    }
345
346    /// Sets or clears the additional stateful validation check from an optional
347    /// [`StatefulValidationFn`].
348    ///
349    /// Passing `None` removes any previously configured check.
350    pub fn set_additional_stateful_validation_fn_opt(
351        &mut self,
352        f: Option<StatefulValidationFn<Tx>>,
353    ) {
354        self.additional_stateful_validation = f;
355    }
356}
357
358impl<Client, Tx, Evm> EthTransactionValidator<Client, Tx, Evm>
359where
360    Client: ChainSpecProvider<ChainSpec: EthChainSpec + EthereumHardforks> + StateProviderFactory,
361    Tx: EthPoolTransaction,
362    Evm: ConfigureEvm,
363{
364    /// Returns the current max gas limit
365    pub fn block_gas_limit(&self) -> u64 {
366        self.max_gas_limit()
367    }
368
369    /// Validates a single transaction.
370    ///
371    /// See also [`TransactionValidator::validate_transaction`]
372    pub fn validate_one(
373        &self,
374        origin: TransactionOrigin,
375        transaction: Tx,
376    ) -> TransactionValidationOutcome<Tx> {
377        let mut state: Option<StateProviderBox> = None;
378        self.validate_one_with_provider(origin, transaction, &mut state, || self.client.latest())
379    }
380
381    /// Validates a single transaction with the provided state provider.
382    ///
383    /// This allows reusing the same provider across multiple transaction validations,
384    /// which can improve performance when validating many transactions.
385    ///
386    /// If `state` is `None`, a new state provider will be created.
387    pub fn validate_one_with_state(
388        &self,
389        origin: TransactionOrigin,
390        transaction: Tx,
391        state: &mut Option<Box<dyn AccountInfoReader + Send>>,
392    ) -> TransactionValidationOutcome<Tx> {
393        self.validate_one_with_provider(origin, transaction, state, || {
394            self.client.latest().map(|state| Box::new(state) as Box<dyn AccountInfoReader + Send>)
395        })
396    }
397
398    /// Validates a single transaction using an optional cached state provider.
399    /// If no provider is passed, a new one will be created. This allows reusing
400    /// the same provider across multiple txs.
401    fn validate_one_with_provider<P, F>(
402        &self,
403        origin: TransactionOrigin,
404        transaction: Tx,
405        maybe_state: &mut Option<P>,
406        state_provider: F,
407    ) -> TransactionValidationOutcome<Tx>
408    where
409        P: AccountInfoReader,
410        F: FnOnce() -> Result<P, ProviderError>,
411    {
412        match self.validate_stateless(origin, &transaction) {
413            Ok(()) => {
414                // stateless checks passed, pass transaction down stateful validation pipeline
415                // If we don't have a state provider yet, fetch the latest state
416                if maybe_state.is_none() {
417                    match state_provider() {
418                        Ok(new_state) => {
419                            *maybe_state = Some(new_state);
420                        }
421                        Err(err) => {
422                            return TransactionValidationOutcome::Error(
423                                *transaction.hash(),
424                                Box::new(err),
425                            )
426                        }
427                    }
428                }
429
430                let state = maybe_state.as_ref().expect("provider is set");
431
432                self.validate_stateful(origin, transaction, state)
433            }
434            Err(err) => TransactionValidationOutcome::Invalid(transaction, err),
435        }
436    }
437
438    /// Validates a single transaction against the given state provider, performing both
439    /// [stateless](Self::validate_stateless) and [stateful](Self::validate_stateful) checks.
440    pub fn validate_one_with_state_provider(
441        &self,
442        origin: TransactionOrigin,
443        transaction: Tx,
444        state: impl AccountInfoReader,
445    ) -> TransactionValidationOutcome<Tx> {
446        if let Err(err) = self.validate_stateless(origin, &transaction) {
447            return TransactionValidationOutcome::Invalid(transaction, err);
448        }
449        self.validate_stateful(origin, transaction, state)
450    }
451
452    /// Validates a single transaction without requiring any state access (stateless checks only).
453    ///
454    /// Checks tx type support, nonce bounds, size limits, gas limits, fee constraints, chain ID,
455    /// intrinsic gas, and blob tx pre-checks.
456    pub fn validate_stateless(
457        &self,
458        origin: TransactionOrigin,
459        transaction: &Tx,
460    ) -> Result<(), InvalidPoolTransactionError> {
461        // Checks for tx_type
462        match transaction.ty() {
463            // Accept only legacy transactions until EIP-2718/2930 activates
464            EIP2930_TX_TYPE_ID if !self.eip2718 => {
465                return Err(InvalidTransactionError::Eip2930Disabled.into())
466            }
467            // Reject dynamic fee transactions until EIP-1559 activates.
468            EIP1559_TX_TYPE_ID if !self.eip1559 => {
469                return Err(InvalidTransactionError::Eip1559Disabled.into())
470            }
471            // Reject blob transactions.
472            EIP4844_TX_TYPE_ID if !self.eip4844 => {
473                return Err(InvalidTransactionError::Eip4844Disabled.into())
474            }
475            // Reject EIP-7702 transactions.
476            EIP7702_TX_TYPE_ID if !self.eip7702 => {
477                return Err(InvalidTransactionError::Eip7702Disabled.into())
478            }
479            // Accept known transaction types when their respective fork is active
480            LEGACY_TX_TYPE_ID | EIP2930_TX_TYPE_ID | EIP1559_TX_TYPE_ID | EIP4844_TX_TYPE_ID |
481            EIP7702_TX_TYPE_ID => {}
482
483            ty if !self.other_tx_types.bit(ty as usize) => {
484                return Err(InvalidTransactionError::TxTypeNotSupported.into())
485            }
486
487            _ => {}
488        };
489
490        // Reject transactions with a nonce equal to U64::max according to EIP-2681
491        let tx_nonce = transaction.nonce();
492        if tx_nonce == u64::MAX {
493            return Err(InvalidPoolTransactionError::Eip2681)
494        }
495
496        // Reject transactions over defined size to prevent DOS attacks
497        if transaction.is_eip4844() {
498            // Since blob transactions are pulled instead of pushed, and only the consensus data is
499            // kept in memory while the sidecar is cached on disk, there is no critical limit that
500            // should be enforced. Still, enforcing some cap on the dynamic transaction data. blob
501            // txs also must be executable right away when they enter the pool.
502            let tx_size = transaction.input().len().saturating_add(
503                transaction
504                    .access_list()
505                    .map(|access_list| access_list.length())
506                    .unwrap_or_default(),
507            );
508            if tx_size > self.max_tx_input_bytes {
509                return Err(InvalidPoolTransactionError::OversizedData {
510                    size: tx_size,
511                    limit: self.max_tx_input_bytes,
512                })
513            }
514        } else {
515            // ensure the size of the non-blob transaction
516            let tx_size = transaction.encoded_length();
517            if tx_size > self.max_tx_input_bytes {
518                return Err(InvalidPoolTransactionError::OversizedData {
519                    size: tx_size,
520                    limit: self.max_tx_input_bytes,
521                })
522            }
523        }
524
525        // Check whether the init code size has been exceeded.
526        if self.fork_tracker.is_shanghai_activated() {
527            let max_initcode_size =
528                self.fork_tracker.max_initcode_size.load(std::sync::atomic::Ordering::Relaxed);
529            transaction.ensure_max_init_code_size(max_initcode_size)?;
530        }
531
532        // Checks for gas limit
533        let transaction_gas_limit = transaction.gas_limit();
534        let block_gas_limit = self.max_gas_limit();
535        if transaction_gas_limit > block_gas_limit {
536            return Err(InvalidPoolTransactionError::ExceedsGasLimit(
537                transaction_gas_limit,
538                block_gas_limit,
539            ))
540        }
541
542        // Check individual transaction gas limit if configured
543        if let Some(max_tx_gas_limit) = self.max_tx_gas_limit &&
544            transaction_gas_limit > max_tx_gas_limit
545        {
546            return Err(InvalidPoolTransactionError::MaxTxGasLimitExceeded(
547                transaction_gas_limit,
548                max_tx_gas_limit,
549            ))
550        }
551
552        // Ensure max_priority_fee_per_gas (if EIP1559) is less than max_fee_per_gas if any.
553        if transaction.max_priority_fee_per_gas() > Some(transaction.max_fee_per_gas()) {
554            return Err(InvalidTransactionError::TipAboveFeeCap.into())
555        }
556
557        // determine whether the transaction should be treated as local
558        let is_local = self.local_transactions_config.is_local(origin, transaction.sender_ref());
559
560        // Ensure max possible transaction fee doesn't exceed configured transaction fee cap.
561        // Only for transactions locally submitted for acceptance into the pool.
562        if is_local {
563            match self.tx_fee_cap {
564                Some(0) | None => {} // Skip if cap is 0 or None
565                Some(tx_fee_cap_wei) => {
566                    let max_tx_fee_wei = transaction.cost().saturating_sub(transaction.value());
567                    if max_tx_fee_wei > tx_fee_cap_wei {
568                        return Err(InvalidPoolTransactionError::ExceedsFeeCap {
569                            max_tx_fee_wei: max_tx_fee_wei.saturating_to(),
570                            tx_fee_cap_wei,
571                        })
572                    }
573                }
574            }
575        }
576
577        // Drop non-local transactions with a fee lower than the configured fee for acceptance into
578        // the pool.
579        if !is_local &&
580            transaction.is_dynamic_fee() &&
581            transaction.max_priority_fee_per_gas() < self.minimum_priority_fee
582        {
583            return Err(InvalidPoolTransactionError::PriorityFeeBelowMinimum {
584                minimum_priority_fee: self
585                    .minimum_priority_fee
586                    .expect("minimum priority fee is expected inside if statement"),
587            })
588        }
589
590        // Checks for chainid
591        if let Some(chain_id) = transaction.chain_id() &&
592            chain_id != self.chain_id()
593        {
594            return Err(InvalidTransactionError::ChainIdMismatch.into())
595        }
596
597        if transaction.is_eip7702() {
598            // Prague fork is required for 7702 txs
599            if !self.fork_tracker.is_prague_activated() {
600                return Err(InvalidTransactionError::TxTypeNotSupported.into())
601            }
602
603            if transaction.authorization_list().is_none_or(|l| l.is_empty()) {
604                return Err(Eip7702PoolTransactionError::MissingEip7702AuthorizationList.into())
605            }
606        }
607
608        ensure_intrinsic_gas(transaction, &self.fork_tracker)?;
609
610        // light blob tx pre-checks
611        if transaction.is_eip4844() {
612            // Cancun fork is required for blob txs
613            if !self.fork_tracker.is_cancun_activated() {
614                return Err(InvalidTransactionError::TxTypeNotSupported.into())
615            }
616
617            let blob_count = transaction.blob_count().unwrap_or(0);
618            if blob_count == 0 {
619                // no blobs
620                return Err(InvalidPoolTransactionError::Eip4844(
621                    Eip4844PoolTransactionError::NoEip4844Blobs,
622                ))
623            }
624
625            let max_blob_count = self.fork_tracker.max_blob_count();
626            if blob_count > max_blob_count {
627                return Err(InvalidPoolTransactionError::Eip4844(
628                    Eip4844PoolTransactionError::TooManyEip4844Blobs {
629                        have: blob_count,
630                        permitted: max_blob_count,
631                    },
632                ))
633            }
634        }
635
636        // Transaction gas limit validation (EIP-7825 for Osaka+)
637        let tx_gas_limit_cap =
638            self.fork_tracker.tx_gas_limit_cap.load(std::sync::atomic::Ordering::Relaxed);
639        if tx_gas_limit_cap > 0 && transaction.gas_limit() > tx_gas_limit_cap {
640            return Err(InvalidTransactionError::GasLimitTooHigh.into())
641        }
642
643        // Run additional stateless validation if configured
644        if let Some(check) = &self.additional_stateless_validation {
645            check(origin, transaction)?;
646        }
647
648        Ok(())
649    }
650
651    /// Validates a single transaction against the given state (stateful checks only).
652    ///
653    /// Checks sender account balance, nonce, bytecode, and validates blob sidecars. The
654    /// transaction must have already passed [`validate_stateless`](Self::validate_stateless).
655    pub fn validate_stateful<P>(
656        &self,
657        origin: TransactionOrigin,
658        mut transaction: Tx,
659        state: P,
660    ) -> TransactionValidationOutcome<Tx>
661    where
662        P: AccountInfoReader,
663    {
664        // Use provider to get account info
665        let account = match state.basic_account(transaction.sender_ref()) {
666            Ok(account) => account.unwrap_or_default(),
667            Err(err) => {
668                return TransactionValidationOutcome::Error(*transaction.hash(), Box::new(err))
669            }
670        };
671
672        // check for bytecode
673        match self.validate_sender_bytecode(&transaction, &account, &state) {
674            Err(outcome) => return outcome,
675            Ok(Err(err)) => return TransactionValidationOutcome::Invalid(transaction, err),
676            _ => {}
677        };
678
679        // Checks for nonce
680        if transaction.requires_nonce_check() &&
681            let Err(err) = self.validate_sender_nonce(&transaction, &account)
682        {
683            return TransactionValidationOutcome::Invalid(transaction, err)
684        }
685
686        // checks for max cost not exceedng account_balance
687        if let Err(err) = self.validate_sender_balance(&transaction, &account) {
688            return TransactionValidationOutcome::Invalid(transaction, err)
689        }
690
691        // heavy blob tx validation
692        let maybe_blob_sidecar = match self.validate_eip4844(&mut transaction) {
693            Err(err) => return TransactionValidationOutcome::Invalid(transaction, err),
694            Ok(sidecar) => sidecar,
695        };
696
697        // Run additional stateful validation if configured
698        if let Some(check) = &self.additional_stateful_validation &&
699            let Err(err) = check(origin, &transaction, &state)
700        {
701            return TransactionValidationOutcome::Invalid(transaction, err)
702        }
703
704        let authorities = self.recover_authorities(&transaction);
705        // Return the valid transaction
706        TransactionValidationOutcome::Valid {
707            balance: account.balance,
708            state_nonce: account.nonce,
709            bytecode_hash: account.bytecode_hash,
710            transaction: ValidTransaction::new(transaction, maybe_blob_sidecar),
711            // by this point assume all external transactions should be propagated
712            propagate: match origin {
713                TransactionOrigin::External => true,
714                TransactionOrigin::Local => {
715                    self.local_transactions_config.propagate_local_transactions
716                }
717                TransactionOrigin::Private => false,
718            },
719            authorities,
720        }
721    }
722
723    /// Validates that the sender’s account has valid or no bytecode.
724    pub fn validate_sender_bytecode(
725        &self,
726        transaction: &Tx,
727        sender: &Account,
728        state: impl BytecodeReader,
729    ) -> Result<Result<(), InvalidPoolTransactionError>, TransactionValidationOutcome<Tx>> {
730        // Unless Prague is active, the signer account shouldn't have bytecode.
731        //
732        // If Prague is active, only EIP-7702 bytecode is allowed for the sender.
733        //
734        // Any other case means that the account is not an EOA, and should not be able to send
735        // transactions.
736        if let Some(code_hash) = &sender.bytecode_hash {
737            let is_eip7702 = if self.fork_tracker.is_prague_activated() {
738                match state.bytecode_by_hash(code_hash) {
739                    Ok(bytecode) => bytecode.unwrap_or_default().is_eip7702(),
740                    Err(err) => {
741                        return Err(TransactionValidationOutcome::Error(
742                            *transaction.hash(),
743                            Box::new(err),
744                        ))
745                    }
746                }
747            } else {
748                false
749            };
750
751            if !is_eip7702 {
752                return Ok(Err(InvalidTransactionError::SignerAccountHasBytecode.into()))
753            }
754        }
755        Ok(Ok(()))
756    }
757
758    /// Checks if the transaction nonce is valid.
759    pub fn validate_sender_nonce(
760        &self,
761        transaction: &Tx,
762        sender: &Account,
763    ) -> Result<(), InvalidPoolTransactionError> {
764        let tx_nonce = transaction.nonce();
765
766        if tx_nonce < sender.nonce {
767            return Err(InvalidTransactionError::NonceNotConsistent {
768                tx: tx_nonce,
769                state: sender.nonce,
770            }
771            .into())
772        }
773        Ok(())
774    }
775
776    /// Ensures the sender has sufficient account balance.
777    pub fn validate_sender_balance(
778        &self,
779        transaction: &Tx,
780        sender: &Account,
781    ) -> Result<(), InvalidPoolTransactionError> {
782        let cost = transaction.cost();
783
784        if !self.disable_balance_check && cost > &sender.balance {
785            let expected = *cost;
786            return Err(InvalidTransactionError::InsufficientFunds(
787                GotExpected { got: sender.balance, expected }.into(),
788            )
789            .into())
790        }
791        Ok(())
792    }
793
794    /// Validates EIP-4844 blob sidecar data and returns the extracted sidecar, if any.
795    pub fn validate_eip4844(
796        &self,
797        transaction: &mut Tx,
798    ) -> Result<Option<BlobTransactionSidecarVariant>, InvalidPoolTransactionError> {
799        let mut maybe_blob_sidecar = None;
800
801        // heavy blob tx validation
802        if transaction.is_eip4844() {
803            // extract the blob from the transaction
804            match transaction.take_blob() {
805                EthBlobTransactionSidecar::None => {
806                    // this should not happen
807                    return Err(InvalidTransactionError::TxTypeNotSupported.into())
808                }
809                EthBlobTransactionSidecar::Missing => {
810                    // This can happen for re-injected blob transactions (on re-org), since the blob
811                    // is stripped from the transaction and not included in a block.
812                    // check if the blob is in the store, if it's included we previously validated
813                    // it and inserted it
814                    if self.blob_store.contains(*transaction.hash()).is_ok_and(|c| c) {
815                        // validated transaction is already in the store
816                    } else {
817                        return Err(InvalidPoolTransactionError::Eip4844(
818                            Eip4844PoolTransactionError::MissingEip4844BlobSidecar,
819                        ))
820                    }
821                }
822                EthBlobTransactionSidecar::Present(sidecar) => {
823                    let now = Instant::now();
824
825                    // EIP-7594 sidecar version handling
826                    if self.eip7594 {
827                        // Standard Ethereum behavior
828                        if self.fork_tracker.is_osaka_activated() {
829                            if sidecar.is_eip4844() {
830                                return Err(InvalidPoolTransactionError::Eip4844(
831                                    Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka,
832                                ))
833                            }
834                        } else if sidecar.is_eip7594() && !self.allow_7594_sidecars() {
835                            return Err(InvalidPoolTransactionError::Eip4844(
836                                Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka,
837                            ))
838                        }
839                    } else {
840                        // EIP-7594 disabled: always reject v1 sidecars, accept v0
841                        if sidecar.is_eip7594() {
842                            return Err(InvalidPoolTransactionError::Eip4844(
843                                Eip4844PoolTransactionError::Eip7594SidecarDisallowed,
844                            ))
845                        }
846                    }
847
848                    // validate the blob
849                    if let Err(err) = transaction.validate_blob(&sidecar, self.kzg_settings.get()) {
850                        return Err(InvalidPoolTransactionError::Eip4844(
851                            Eip4844PoolTransactionError::InvalidEip4844Blob(err),
852                        ))
853                    }
854                    // Record the duration of successful blob validation as histogram
855                    self.validation_metrics.blob_validation_duration.record(now.elapsed());
856                    // store the extracted blob
857                    maybe_blob_sidecar = Some(sidecar);
858                }
859            }
860        }
861        Ok(maybe_blob_sidecar)
862    }
863
864    /// Returns the recovered authorities for the given transaction
865    fn recover_authorities(&self, transaction: &Tx) -> std::option::Option<Vec<Address>> {
866        transaction
867            .authorization_list()
868            .map(|auths| auths.iter().flat_map(|auth| auth.recover_authority()).collect::<Vec<_>>())
869    }
870
871    /// Validates all given transactions.
872    fn validate_batch(
873        &self,
874        transactions: impl IntoIterator<Item = (TransactionOrigin, Tx)>,
875    ) -> Vec<TransactionValidationOutcome<Tx>> {
876        let mut provider: Option<StateProviderBox> = None;
877        transactions
878            .into_iter()
879            .map(|(origin, tx)| {
880                self.validate_one_with_provider(origin, tx, &mut provider, || self.client.latest())
881            })
882            .collect()
883    }
884
885    /// Validates all given transactions with origin.
886    fn validate_batch_with_origin(
887        &self,
888        origin: TransactionOrigin,
889        transactions: impl IntoIterator<Item = Tx> + Send,
890    ) -> Vec<TransactionValidationOutcome<Tx>> {
891        let mut provider: Option<StateProviderBox> = None;
892        transactions
893            .into_iter()
894            .map(|tx| {
895                self.validate_one_with_provider(origin, tx, &mut provider, || self.client.latest())
896            })
897            .collect()
898    }
899
900    fn on_new_head_block(&self, new_tip_block: &HeaderTy<Evm::Primitives>) {
901        // update all forks
902        if self.chain_spec().is_shanghai_active_at_timestamp(new_tip_block.timestamp()) {
903            self.fork_tracker.shanghai.store(true, std::sync::atomic::Ordering::Relaxed);
904        }
905
906        if self.chain_spec().is_cancun_active_at_timestamp(new_tip_block.timestamp()) {
907            self.fork_tracker.cancun.store(true, std::sync::atomic::Ordering::Relaxed);
908        }
909
910        if self.chain_spec().is_prague_active_at_timestamp(new_tip_block.timestamp()) {
911            self.fork_tracker.prague.store(true, std::sync::atomic::Ordering::Relaxed);
912        }
913
914        if self.chain_spec().is_osaka_active_at_timestamp(new_tip_block.timestamp()) {
915            self.fork_tracker.osaka.store(true, std::sync::atomic::Ordering::Relaxed);
916        }
917
918        self.fork_tracker
919            .tip_timestamp
920            .store(new_tip_block.timestamp(), std::sync::atomic::Ordering::Relaxed);
921
922        if let Some(blob_params) =
923            self.chain_spec().blob_params_at_timestamp(new_tip_block.timestamp())
924        {
925            self.fork_tracker
926                .max_blob_count
927                .store(blob_params.max_blobs_per_tx, std::sync::atomic::Ordering::Relaxed);
928        }
929
930        self.block_gas_limit.store(new_tip_block.gas_limit(), std::sync::atomic::Ordering::Relaxed);
931
932        // Get EVM limits from evm_config.evm_env()
933        let evm_env = self
934            .evm_config
935            .evm_env(new_tip_block)
936            .expect("evm_env should not fail for executed block");
937
938        self.fork_tracker
939            .max_initcode_size
940            .store(evm_env.cfg_env.max_initcode_size(), std::sync::atomic::Ordering::Relaxed);
941        // EIP-8037: When state gas is enabled, `tx.gas` can exceed the per-tx gas limit cap
942        // because the cap only applies to regular gas (state gas uses a reservoir).
943        // Store 0 to disable the txpool-level check.
944        let tx_gas_limit_cap = if evm_env.cfg_env.is_amsterdam_eip8037_enabled() {
945            0
946        } else {
947            evm_env.cfg_env.tx_gas_limit_cap()
948        };
949        self.fork_tracker
950            .tx_gas_limit_cap
951            .store(tx_gas_limit_cap, std::sync::atomic::Ordering::Relaxed);
952    }
953
954    fn max_gas_limit(&self) -> u64 {
955        self.block_gas_limit.load(std::sync::atomic::Ordering::Relaxed)
956    }
957
958    /// Returns whether EIP-7594 sidecars are allowed
959    fn allow_7594_sidecars(&self) -> bool {
960        let tip_timestamp = self.fork_tracker.tip_timestamp();
961
962        // If next block is Osaka, allow 7594 sidecars
963        if self.chain_spec().is_osaka_active_at_timestamp(tip_timestamp.saturating_add(12)) {
964            true
965        } else if self.chain_spec().is_osaka_active_at_timestamp(tip_timestamp.saturating_add(24)) {
966            let current_timestamp =
967                SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
968
969            // Allow after 4 seconds into last non-Osaka slot
970            current_timestamp >= tip_timestamp.saturating_add(4)
971        } else {
972            false
973        }
974    }
975}
976
977impl<Client, Tx, Evm> TransactionValidator for EthTransactionValidator<Client, Tx, Evm>
978where
979    Client: ChainSpecProvider<ChainSpec: EthChainSpec + EthereumHardforks> + StateProviderFactory,
980    Tx: EthPoolTransaction,
981    Evm: ConfigureEvm,
982{
983    type Transaction = Tx;
984    type Block = BlockTy<Evm::Primitives>;
985
986    async fn validate_transaction(
987        &self,
988        origin: TransactionOrigin,
989        transaction: Self::Transaction,
990    ) -> TransactionValidationOutcome<Self::Transaction> {
991        self.validate_one(origin, transaction)
992    }
993
994    async fn validate_transactions(
995        &self,
996        transactions: impl IntoIterator<Item = (TransactionOrigin, Self::Transaction), IntoIter: Send>
997            + Send,
998    ) -> Vec<TransactionValidationOutcome<Self::Transaction>> {
999        self.validate_batch(transactions)
1000    }
1001
1002    async fn validate_transactions_with_origin(
1003        &self,
1004        origin: TransactionOrigin,
1005        transactions: impl IntoIterator<Item = Self::Transaction, IntoIter: Send> + Send,
1006    ) -> Vec<TransactionValidationOutcome<Self::Transaction>> {
1007        self.validate_batch_with_origin(origin, transactions)
1008    }
1009
1010    fn on_new_head_block(&self, new_tip_block: &SealedBlock<Self::Block>) {
1011        Self::on_new_head_block(self, new_tip_block.header())
1012    }
1013}
1014
1015/// A builder for [`EthTransactionValidator`] and [`TransactionValidationTaskExecutor`]
1016#[derive(Debug)]
1017pub struct EthTransactionValidatorBuilder<Client, Evm> {
1018    client: Client,
1019    /// The chain ID transactions must use.
1020    chain_id: u64,
1021    /// The EVM configuration to use for validation.
1022    evm_config: Evm,
1023    /// Fork indicator whether we are in the Shanghai stage.
1024    shanghai: bool,
1025    /// Fork indicator whether we are in the Cancun hardfork.
1026    cancun: bool,
1027    /// Fork indicator whether we are in the Prague hardfork.
1028    prague: bool,
1029    /// Fork indicator whether we are in the Osaka hardfork.
1030    osaka: bool,
1031    /// Timestamp of the tip block.
1032    tip_timestamp: u64,
1033    /// Max blob count at the block's timestamp.
1034    max_blob_count: u64,
1035    /// Whether using EIP-2718 type transactions is allowed
1036    eip2718: bool,
1037    /// Whether using EIP-1559 type transactions is allowed
1038    eip1559: bool,
1039    /// Whether using EIP-4844 type transactions is allowed
1040    eip4844: bool,
1041    /// Whether using EIP-7702 type transactions is allowed
1042    eip7702: bool,
1043    /// The current max gas limit
1044    block_gas_limit: AtomicU64,
1045    /// The current tx fee cap limit in wei locally submitted into the pool.
1046    tx_fee_cap: Option<u128>,
1047    /// Minimum priority fee to enforce for acceptance into the pool.
1048    minimum_priority_fee: Option<u128>,
1049    /// Determines how many additional tasks to spawn
1050    ///
1051    /// Default is 1
1052    additional_tasks: usize,
1053
1054    /// Stores the setup and parameters needed for validating KZG proofs.
1055    kzg_settings: EnvKzgSettings,
1056    /// How to handle [`TransactionOrigin::Local`](TransactionOrigin) transactions.
1057    local_transactions_config: LocalTransactionConfig,
1058    /// Max size in bytes of a single transaction allowed
1059    max_tx_input_bytes: usize,
1060    /// Maximum gas limit for individual transactions
1061    max_tx_gas_limit: Option<u64>,
1062    /// Disable balance checks during transaction validation
1063    disable_balance_check: bool,
1064    /// Bitmap of custom transaction types that are allowed.
1065    other_tx_types: U256,
1066    /// Cached max initcode size from EVM config
1067    max_initcode_size: usize,
1068    /// Cached transaction gas limit cap from EVM config (0 = no cap)
1069    tx_gas_limit_cap: u64,
1070    /// Whether EIP-7594 blob sidecars are accepted.
1071    /// When false, EIP-7594 (v1) sidecars are always rejected and EIP-4844 (v0) sidecars
1072    /// are always accepted, regardless of Osaka fork activation.
1073    eip7594: bool,
1074}
1075
1076impl<Client, Evm> EthTransactionValidatorBuilder<Client, Evm> {
1077    /// Creates a new builder for the given client and EVM config
1078    ///
1079    /// By default this assumes the network is on the `Prague` hardfork and the following
1080    /// transactions are allowed:
1081    ///  - Legacy
1082    ///  - EIP-2718
1083    ///  - EIP-1559
1084    ///  - EIP-4844
1085    ///  - EIP-7702
1086    pub fn new(client: Client, evm_config: Evm) -> Self
1087    where
1088        Client: ChainSpecProvider<ChainSpec: EthChainSpec + EthereumHardforks>
1089            + BlockReaderIdExt<Header = HeaderTy<Evm::Primitives>>,
1090        Evm: ConfigureEvm,
1091    {
1092        let chain_spec = client.chain_spec();
1093        let tip = client
1094            .header_by_id(BlockId::latest())
1095            .expect("failed to fetch latest header")
1096            .expect("latest header is not found");
1097        let evm_env =
1098            evm_config.evm_env(&tip).expect("evm_env should not fail for existing blocks");
1099
1100        Self {
1101            block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M.into(),
1102            client,
1103            chain_id: chain_spec.chain().id(),
1104            evm_config,
1105            minimum_priority_fee: None,
1106            additional_tasks: 1,
1107            kzg_settings: EnvKzgSettings::Default,
1108            local_transactions_config: Default::default(),
1109            max_tx_input_bytes: DEFAULT_MAX_TX_INPUT_BYTES,
1110            tx_fee_cap: Some(1e18 as u128),
1111            max_tx_gas_limit: None,
1112            // by default all transaction types are allowed
1113            eip2718: true,
1114            eip1559: true,
1115            eip4844: true,
1116            eip7702: true,
1117
1118            shanghai: chain_spec.is_shanghai_active_at_timestamp(tip.timestamp()),
1119            cancun: chain_spec.is_cancun_active_at_timestamp(tip.timestamp()),
1120            prague: chain_spec.is_prague_active_at_timestamp(tip.timestamp()),
1121            osaka: chain_spec.is_osaka_active_at_timestamp(tip.timestamp()),
1122
1123            tip_timestamp: tip.timestamp(),
1124
1125            max_blob_count: chain_spec
1126                .blob_params_at_timestamp(tip.timestamp())
1127                .unwrap_or_else(BlobParams::prague)
1128                .max_blobs_per_tx,
1129
1130            // balance checks are enabled by default
1131            disable_balance_check: false,
1132
1133            // no custom transaction types by default
1134            other_tx_types: U256::ZERO,
1135
1136            // EIP-8037: When state gas is enabled, tx.gas can exceed the per-tx cap
1137            tx_gas_limit_cap: if evm_env.cfg_env.is_amsterdam_eip8037_enabled() {
1138                0
1139            } else {
1140                evm_env.cfg_env.tx_gas_limit_cap()
1141            },
1142            max_initcode_size: evm_env.cfg_env.max_initcode_size(),
1143
1144            // EIP-7594 sidecars are accepted by default (standard Ethereum behavior)
1145            eip7594: true,
1146        }
1147    }
1148
1149    /// Disables the Cancun fork.
1150    pub const fn no_cancun(self) -> Self {
1151        self.set_cancun(false)
1152    }
1153
1154    /// Whether to allow exemptions for local transaction exemptions.
1155    pub fn with_local_transactions_config(
1156        mut self,
1157        local_transactions_config: LocalTransactionConfig,
1158    ) -> Self {
1159        self.local_transactions_config = local_transactions_config;
1160        self
1161    }
1162
1163    /// Set the Cancun fork.
1164    pub const fn set_cancun(mut self, cancun: bool) -> Self {
1165        self.cancun = cancun;
1166        self
1167    }
1168
1169    /// Disables the Shanghai fork.
1170    pub const fn no_shanghai(self) -> Self {
1171        self.set_shanghai(false)
1172    }
1173
1174    /// Set the Shanghai fork.
1175    pub const fn set_shanghai(mut self, shanghai: bool) -> Self {
1176        self.shanghai = shanghai;
1177        self
1178    }
1179
1180    /// Disables the Prague fork.
1181    pub const fn no_prague(self) -> Self {
1182        self.set_prague(false)
1183    }
1184
1185    /// Set the Prague fork.
1186    pub const fn set_prague(mut self, prague: bool) -> Self {
1187        self.prague = prague;
1188        self
1189    }
1190
1191    /// Disables the Osaka fork.
1192    pub const fn no_osaka(self) -> Self {
1193        self.set_osaka(false)
1194    }
1195
1196    /// Set the Osaka fork.
1197    pub const fn set_osaka(mut self, osaka: bool) -> Self {
1198        self.osaka = osaka;
1199        self
1200    }
1201
1202    /// Disables the support for EIP-2718 transactions.
1203    pub const fn no_eip2718(self) -> Self {
1204        self.set_eip2718(false)
1205    }
1206
1207    /// Set the support for EIP-2718 transactions.
1208    pub const fn set_eip2718(mut self, eip2718: bool) -> Self {
1209        self.eip2718 = eip2718;
1210        self
1211    }
1212
1213    /// Disables the support for EIP-1559 transactions.
1214    pub const fn no_eip1559(self) -> Self {
1215        self.set_eip1559(false)
1216    }
1217
1218    /// Set the support for EIP-1559 transactions.
1219    pub const fn set_eip1559(mut self, eip1559: bool) -> Self {
1220        self.eip1559 = eip1559;
1221        self
1222    }
1223
1224    /// Disables the support for EIP-4844 transactions.
1225    pub const fn no_eip4844(self) -> Self {
1226        self.set_eip4844(false)
1227    }
1228
1229    /// Set the support for EIP-4844 transactions.
1230    pub const fn set_eip4844(mut self, eip4844: bool) -> Self {
1231        self.eip4844 = eip4844;
1232        self
1233    }
1234
1235    /// Disables the support for EIP-7702 transactions.
1236    pub const fn no_eip7702(self) -> Self {
1237        self.set_eip7702(false)
1238    }
1239
1240    /// Set the support for EIP-7702 transactions.
1241    pub const fn set_eip7702(mut self, eip7702: bool) -> Self {
1242        self.eip7702 = eip7702;
1243        self
1244    }
1245
1246    /// Disables EIP-7594 blob sidecar support.
1247    ///
1248    /// When disabled, EIP-7594 (v1) blob sidecars are always rejected and EIP-4844 (v0)
1249    /// sidecars are always accepted, regardless of Osaka fork activation.
1250    ///
1251    /// Use this for chains that do not adopt EIP-7594 (`PeerDAS`).
1252    pub const fn no_eip7594(self) -> Self {
1253        self.set_eip7594(false)
1254    }
1255
1256    /// Set EIP-7594 blob sidecar support.
1257    ///
1258    /// When true (default), standard Ethereum behavior applies: v0 sidecars before Osaka,
1259    /// v1 sidecars after Osaka. When false, v1 sidecars are always rejected.
1260    pub const fn set_eip7594(mut self, eip7594: bool) -> Self {
1261        self.eip7594 = eip7594;
1262        self
1263    }
1264
1265    /// Sets the [`EnvKzgSettings`] to use for validating KZG proofs.
1266    pub fn kzg_settings(mut self, kzg_settings: EnvKzgSettings) -> Self {
1267        self.kzg_settings = kzg_settings;
1268        self
1269    }
1270
1271    /// Sets a minimum priority fee that's enforced for acceptance into the pool.
1272    pub const fn with_minimum_priority_fee(mut self, minimum_priority_fee: Option<u128>) -> Self {
1273        self.minimum_priority_fee = minimum_priority_fee;
1274        self
1275    }
1276
1277    /// Sets the number of additional tasks to spawn.
1278    pub const fn with_additional_tasks(mut self, additional_tasks: usize) -> Self {
1279        self.additional_tasks = additional_tasks;
1280        self
1281    }
1282
1283    /// Sets a max size in bytes of a single transaction allowed into the pool
1284    pub const fn with_max_tx_input_bytes(mut self, max_tx_input_bytes: usize) -> Self {
1285        self.max_tx_input_bytes = max_tx_input_bytes;
1286        self
1287    }
1288
1289    /// Sets the block gas limit
1290    ///
1291    /// Transactions with a gas limit greater than this will be rejected.
1292    pub fn set_block_gas_limit(self, block_gas_limit: u64) -> Self {
1293        self.block_gas_limit.store(block_gas_limit, std::sync::atomic::Ordering::Relaxed);
1294        self
1295    }
1296
1297    /// Sets the block gas limit
1298    ///
1299    /// Transactions with a gas limit greater than this will be rejected.
1300    pub const fn set_tx_fee_cap(mut self, tx_fee_cap: u128) -> Self {
1301        self.tx_fee_cap = Some(tx_fee_cap);
1302        self
1303    }
1304
1305    /// Sets the maximum gas limit for individual transactions
1306    pub const fn with_max_tx_gas_limit(mut self, max_tx_gas_limit: Option<u64>) -> Self {
1307        self.max_tx_gas_limit = max_tx_gas_limit;
1308        self
1309    }
1310
1311    /// Disables balance checks during transaction validation
1312    pub const fn disable_balance_check(mut self) -> Self {
1313        self.disable_balance_check = true;
1314        self
1315    }
1316
1317    /// Adds a custom transaction type to the validator.
1318    pub const fn with_custom_tx_type(mut self, tx_type: u8) -> Self {
1319        self.other_tx_types.set_bit(tx_type as usize, true);
1320        self
1321    }
1322
1323    /// Builds a the [`EthTransactionValidator`] without spawning validator tasks.
1324    pub fn build<Tx, S>(self, blob_store: S) -> EthTransactionValidator<Client, Tx, Evm>
1325    where
1326        S: BlobStore,
1327    {
1328        let Self {
1329            client,
1330            chain_id,
1331            evm_config,
1332            shanghai,
1333            cancun,
1334            prague,
1335            osaka,
1336            tip_timestamp,
1337            eip2718,
1338            eip1559,
1339            eip4844,
1340            eip7702,
1341            block_gas_limit,
1342            tx_fee_cap,
1343            minimum_priority_fee,
1344            kzg_settings,
1345            local_transactions_config,
1346            max_tx_input_bytes,
1347            max_tx_gas_limit,
1348            disable_balance_check,
1349            max_blob_count,
1350            additional_tasks: _,
1351            other_tx_types,
1352            max_initcode_size,
1353            tx_gas_limit_cap,
1354            eip7594,
1355        } = self;
1356
1357        let fork_tracker = ForkTracker {
1358            shanghai: AtomicBool::new(shanghai),
1359            cancun: AtomicBool::new(cancun),
1360            prague: AtomicBool::new(prague),
1361            osaka: AtomicBool::new(osaka),
1362            tip_timestamp: AtomicU64::new(tip_timestamp),
1363            max_blob_count: AtomicU64::new(max_blob_count),
1364            max_initcode_size: AtomicUsize::new(max_initcode_size),
1365            tx_gas_limit_cap: AtomicU64::new(tx_gas_limit_cap),
1366        };
1367
1368        EthTransactionValidator {
1369            client,
1370            chain_id,
1371            eip2718,
1372            eip1559,
1373            fork_tracker,
1374            eip4844,
1375            eip7702,
1376            block_gas_limit,
1377            tx_fee_cap,
1378            minimum_priority_fee,
1379            blob_store: Box::new(blob_store),
1380            kzg_settings,
1381            local_transactions_config,
1382            max_tx_input_bytes,
1383            max_tx_gas_limit,
1384            disable_balance_check,
1385            evm_config,
1386            _marker: Default::default(),
1387            validation_metrics: TxPoolValidationMetrics::default(),
1388            other_tx_types,
1389            eip7594,
1390            additional_stateless_validation: None,
1391            additional_stateful_validation: None,
1392        }
1393    }
1394
1395    /// Builds a [`EthTransactionValidator`] and spawns validation tasks via the
1396    /// [`TransactionValidationTaskExecutor`]
1397    ///
1398    /// The validator will spawn `additional_tasks` additional tasks for validation.
1399    ///
1400    /// By default this will spawn 1 additional task.
1401    pub fn build_with_tasks<Tx, S>(
1402        self,
1403        tasks: Runtime,
1404        blob_store: S,
1405    ) -> TransactionValidationTaskExecutor<EthTransactionValidator<Client, Tx, Evm>>
1406    where
1407        S: BlobStore,
1408    {
1409        let additional_tasks = self.additional_tasks;
1410        let validator = self.build::<Tx, S>(blob_store);
1411        TransactionValidationTaskExecutor::spawn(validator, &tasks, additional_tasks)
1412    }
1413}
1414
1415/// Keeps track of whether certain forks are activated
1416#[derive(Debug)]
1417pub struct ForkTracker {
1418    /// Tracks if shanghai is activated at the block's timestamp.
1419    pub shanghai: AtomicBool,
1420    /// Tracks if cancun is activated at the block's timestamp.
1421    pub cancun: AtomicBool,
1422    /// Tracks if prague is activated at the block's timestamp.
1423    pub prague: AtomicBool,
1424    /// Tracks if osaka is activated at the block's timestamp.
1425    pub osaka: AtomicBool,
1426    /// Tracks max blob count per transaction at the block's timestamp.
1427    pub max_blob_count: AtomicU64,
1428    /// Tracks the timestamp of the tip block.
1429    pub tip_timestamp: AtomicU64,
1430    /// Cached max initcode size from EVM config
1431    pub max_initcode_size: AtomicUsize,
1432    /// Cached transaction gas limit cap from EVM config (0 = no cap)
1433    pub tx_gas_limit_cap: AtomicU64,
1434}
1435
1436impl ForkTracker {
1437    /// Returns `true` if Shanghai fork is activated.
1438    pub fn is_shanghai_activated(&self) -> bool {
1439        self.shanghai.load(std::sync::atomic::Ordering::Relaxed)
1440    }
1441
1442    /// Returns `true` if Cancun fork is activated.
1443    pub fn is_cancun_activated(&self) -> bool {
1444        self.cancun.load(std::sync::atomic::Ordering::Relaxed)
1445    }
1446
1447    /// Returns `true` if Prague fork is activated.
1448    pub fn is_prague_activated(&self) -> bool {
1449        self.prague.load(std::sync::atomic::Ordering::Relaxed)
1450    }
1451
1452    /// Returns `true` if Osaka fork is activated.
1453    pub fn is_osaka_activated(&self) -> bool {
1454        self.osaka.load(std::sync::atomic::Ordering::Relaxed)
1455    }
1456
1457    /// Returns the timestamp of the tip block.
1458    pub fn tip_timestamp(&self) -> u64 {
1459        self.tip_timestamp.load(std::sync::atomic::Ordering::Relaxed)
1460    }
1461
1462    /// Returns the max allowed blob count per transaction.
1463    pub fn max_blob_count(&self) -> u64 {
1464        self.max_blob_count.load(std::sync::atomic::Ordering::Relaxed)
1465    }
1466}
1467
1468/// Ensures that gas limit of the transaction exceeds the intrinsic gas of the transaction.
1469///
1470/// Caution: This only checks past the Merge hardfork.
1471pub fn ensure_intrinsic_gas<T: EthPoolTransaction>(
1472    transaction: &T,
1473    fork_tracker: &ForkTracker,
1474) -> Result<(), InvalidPoolTransactionError> {
1475    use revm::primitives::hardfork::SpecId;
1476    let spec_id = if fork_tracker.is_prague_activated() {
1477        SpecId::PRAGUE
1478    } else if fork_tracker.is_shanghai_activated() {
1479        SpecId::SHANGHAI
1480    } else {
1481        SpecId::MERGE
1482    };
1483
1484    let gas = revm::interpreter::gas::calculate_initial_tx_gas(
1485        spec_id,
1486        transaction.input(),
1487        transaction.is_create(),
1488        transaction.access_list().map(|l| l.len()).unwrap_or_default() as u64,
1489        transaction
1490            .access_list()
1491            .map(|l| l.iter().map(|i| i.storage_keys.len()).sum::<usize>())
1492            .unwrap_or_default() as u64,
1493        transaction.authorization_list().map(|l| l.len()).unwrap_or_default() as u64,
1494    );
1495
1496    let gas_limit = transaction.gas_limit();
1497    if gas_limit < gas.initial_total_gas() || gas_limit < gas.floor_gas {
1498        Err(InvalidPoolTransactionError::IntrinsicGasTooLow)
1499    } else {
1500        Ok(())
1501    }
1502}
1503
1504#[cfg(test)]
1505mod tests {
1506    use super::*;
1507    use crate::{
1508        blobstore::InMemoryBlobStore, error::PoolErrorKind, test_utils::TransactionBuilder,
1509        traits::PoolTransaction, CoinbaseTipOrdering, EthPooledTransaction, Pool, TransactionPool,
1510    };
1511    use alloy_consensus::Transaction;
1512    use alloy_eips::{
1513        eip2718::{Decodable2718, Encodable2718},
1514        eip2930::{AccessList, AccessListItem},
1515    };
1516    use alloy_primitives::{hex, Address, B256, U256};
1517    use reth_ethereum_primitives::PooledTransactionVariant;
1518    use reth_evm_ethereum::EthEvmConfig;
1519    use reth_primitives_traits::SignedTransaction;
1520    use reth_provider::test_utils::{ExtendedAccount, MockEthProvider};
1521    use revm::primitives::eip3860::MAX_INITCODE_SIZE;
1522
1523    fn test_evm_config() -> EthEvmConfig {
1524        EthEvmConfig::mainnet()
1525    }
1526
1527    fn get_transaction() -> EthPooledTransaction {
1528        let raw = "0x02f914950181ad84b2d05e0085117553845b830f7df88080b9143a6040608081523462000414576200133a803803806200001e8162000419565b9283398101608082820312620004145781516001600160401b03908181116200041457826200004f9185016200043f565b92602092838201519083821162000414576200006d9183016200043f565b8186015190946001600160a01b03821692909183900362000414576060015190805193808511620003145760038054956001938488811c9816801562000409575b89891014620003f3578190601f988981116200039d575b50899089831160011462000336576000926200032a575b505060001982841b1c191690841b1781555b8751918211620003145760049788548481811c9116801562000309575b89821014620002f457878111620002a9575b5087908784116001146200023e5793839491849260009562000232575b50501b92600019911b1c19161785555b6005556007805460ff60a01b19169055600880546001600160a01b0319169190911790553015620001f3575060025469d3c21bcecceda100000092838201809211620001de57506000917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9160025530835282815284832084815401905584519384523093a351610e889081620004b28239f35b601190634e487b7160e01b6000525260246000fd5b90606493519262461bcd60e51b845283015260248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152fd5b0151935038806200013a565b9190601f198416928a600052848a6000209460005b8c8983831062000291575050501062000276575b50505050811b0185556200014a565b01519060f884600019921b161c191690553880808062000267565b86860151895590970196948501948893500162000253565b89600052886000208880860160051c8201928b8710620002ea575b0160051c019085905b828110620002dd5750506200011d565b60008155018590620002cd565b92508192620002c4565b60228a634e487b7160e01b6000525260246000fd5b90607f16906200010b565b634e487b7160e01b600052604160045260246000fd5b015190503880620000dc565b90869350601f19831691856000528b6000209260005b8d8282106200038657505084116200036d575b505050811b018155620000ee565b015160001983861b60f8161c191690553880806200035f565b8385015186558a979095019493840193016200034c565b90915083600052896000208980850160051c8201928c8610620003e9575b918891869594930160051c01915b828110620003d9575050620000c5565b60008155859450889101620003c9565b92508192620003bb565b634e487b7160e01b600052602260045260246000fd5b97607f1697620000ae565b600080fd5b6040519190601f01601f191682016001600160401b038111838210176200031457604052565b919080601f84011215620004145782516001600160401b038111620003145760209062000475601f8201601f1916830162000419565b92818452828287010111620004145760005b8181106200049d57508260009394955001015290565b85810183015184820184015282016200048756fe608060408181526004918236101561001657600080fd5b600092833560e01c91826306fdde0314610a1c57508163095ea7b3146109f257816318160ddd146109d35781631b4c84d2146109ac57816323b872dd14610833578163313ce5671461081757816339509351146107c357816370a082311461078c578163715018a6146107685781638124f7ac146107495781638da5cb5b1461072057816395d89b411461061d578163a457c2d714610575578163a9059cbb146104e4578163c9567bf914610120575063dd62ed3e146100d557600080fd5b3461011c578060031936011261011c57806020926100f1610b5a565b6100f9610b75565b6001600160a01b0391821683526001865283832091168252845220549051908152f35b5080fd5b905082600319360112610338576008546001600160a01b039190821633036104975760079283549160ff8360a01c1661045557737a250d5630b4cf539739df2c5dacb4c659f2488d92836bffffffffffffffffffffffff60a01b8092161786553087526020938785528388205430156104065730895260018652848920828a52865280858a205584519081527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925863092a38554835163c45a015560e01b815290861685828581845afa9182156103dd57849187918b946103e7575b5086516315ab88c960e31b815292839182905afa9081156103dd576044879289928c916103c0575b508b83895196879586946364e329cb60e11b8652308c870152166024850152165af19081156103b6579086918991610389575b50169060065416176006558385541660604730895288865260c4858a20548860085416928751958694859363f305d71960e01b8552308a86015260248501528d60448501528d606485015260848401524260a48401525af1801561037f579084929161034c575b50604485600654169587541691888551978894859363095ea7b360e01b855284015260001960248401525af1908115610343575061030c575b5050805460ff60a01b1916600160a01b17905580f35b81813d831161033c575b6103208183610b8b565b8101031261033857518015150361011c5738806102f6565b8280fd5b503d610316565b513d86823e3d90fd5b6060809293503d8111610378575b6103648183610b8b565b81010312610374578290386102bd565b8580fd5b503d61035a565b83513d89823e3d90fd5b6103a99150863d88116103af575b6103a18183610b8b565b810190610e33565b38610256565b503d610397565b84513d8a823e3d90fd5b6103d79150843d86116103af576103a18183610b8b565b38610223565b85513d8b823e3d90fd5b6103ff919450823d84116103af576103a18183610b8b565b92386101fb565b845162461bcd60e51b81528085018790526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b6020606492519162461bcd60e51b8352820152601760248201527f74726164696e6720697320616c7265616479206f70656e0000000000000000006044820152fd5b608490602084519162461bcd60e51b8352820152602160248201527f4f6e6c79206f776e65722063616e2063616c6c20746869732066756e6374696f6044820152603760f91b6064820152fd5b9050346103385781600319360112610338576104fe610b5a565b9060243593303303610520575b602084610519878633610bc3565b5160018152f35b600594919454808302908382041483151715610562576127109004820391821161054f5750925080602061050b565b634e487b7160e01b815260118552602490fd5b634e487b7160e01b825260118652602482fd5b9050823461061a578260031936011261061a57610590610b5a565b918360243592338152600160205281812060018060a01b03861682526020522054908282106105c9576020856105198585038733610d31565b608490602086519162461bcd60e51b8352820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152fd5b80fd5b83833461011c578160031936011261011c57805191809380549160019083821c92828516948515610716575b6020958686108114610703578589529081156106df5750600114610687575b6106838787610679828c0383610b8b565b5191829182610b11565b0390f35b81529295507f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b8284106106cc57505050826106839461067992820101948680610668565b80548685018801529286019281016106ae565b60ff19168887015250505050151560051b8301019250610679826106838680610668565b634e487b7160e01b845260228352602484fd5b93607f1693610649565b50503461011c578160031936011261011c5760085490516001600160a01b039091168152602090f35b50503461011c578160031936011261011c576020906005549051908152f35b833461061a578060031936011261061a57600880546001600160a01b031916905580f35b50503461011c57602036600319011261011c5760209181906001600160a01b036107b4610b5a565b16815280845220549051908152f35b82843461061a578160031936011261061a576107dd610b5a565b338252600160209081528383206001600160a01b038316845290528282205460243581019290831061054f57602084610519858533610d31565b50503461011c578160031936011261011c576020905160128152f35b83833461011c57606036600319011261011c5761084e610b5a565b610856610b75565b6044359160018060a01b0381169485815260209560018752858220338352875285822054976000198903610893575b505050906105199291610bc3565b85891061096957811561091a5733156108cc5750948481979861051997845260018a528284203385528a52039120558594938780610885565b865162461bcd60e51b8152908101889052602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b865162461bcd60e51b81529081018890526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b865162461bcd60e51b8152908101889052601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606490fd5b50503461011c578160031936011261011c5760209060ff60075460a01c1690519015158152f35b50503461011c578160031936011261011c576020906002549051908152f35b50503461011c578060031936011261011c57602090610519610a12610b5a565b6024359033610d31565b92915034610b0d5783600319360112610b0d57600354600181811c9186908281168015610b03575b6020958686108214610af05750848852908115610ace5750600114610a75575b6106838686610679828b0383610b8b565b929550600383527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b828410610abb575050508261068394610679928201019438610a64565b8054868501880152928601928101610a9e565b60ff191687860152505050151560051b83010192506106798261068338610a64565b634e487b7160e01b845260229052602483fd5b93607f1693610a44565b8380fd5b6020808252825181830181905290939260005b828110610b4657505060409293506000838284010152601f8019910116010190565b818101860151848201604001528501610b24565b600435906001600160a01b0382168203610b7057565b600080fd5b602435906001600160a01b0382168203610b7057565b90601f8019910116810190811067ffffffffffffffff821117610bad57604052565b634e487b7160e01b600052604160045260246000fd5b6001600160a01b03908116918215610cde5716918215610c8d57600082815280602052604081205491808310610c3957604082827fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef958760209652828652038282205586815220818154019055604051908152a3565b60405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608490fd5b60405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608490fd5b60405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608490fd5b6001600160a01b03908116918215610de25716918215610d925760207f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925918360005260018252604060002085600052825280604060002055604051908152a3565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b60405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b90816020910312610b7057516001600160a01b0381168103610b70579056fea2646970667358221220285c200b3978b10818ff576bb83f2dc4a2a7c98dfb6a36ea01170de792aa652764736f6c63430008140033000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000d3fd4f95820a9aa848ce716d6c200eaefb9a2e4900000000000000000000000000000000000000000000000000000000000000640000000000000000000000000000000000000000000000000000000000000003543131000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035431310000000000000000000000000000000000000000000000000000000000c001a04e551c75810ffdfe6caff57da9f5a8732449f42f0f4c57f935b05250a76db3b6a046cd47e6d01914270c1ec0d9ac7fae7dfb240ec9a8b6ec7898c4d6aa174388f2";
1529
1530        let data = hex::decode(raw).unwrap();
1531        let tx = PooledTransactionVariant::decode_2718(&mut data.as_ref()).unwrap();
1532
1533        EthPooledTransaction::from_pooled(tx.try_into_recovered().unwrap())
1534    }
1535
1536    // <https://github.com/paradigmxyz/reth/issues/5178>
1537    #[tokio::test]
1538    async fn validate_transaction() {
1539        let transaction = get_transaction();
1540        let mut fork_tracker = ForkTracker {
1541            shanghai: false.into(),
1542            cancun: false.into(),
1543            prague: false.into(),
1544            osaka: false.into(),
1545            tip_timestamp: 0.into(),
1546            max_blob_count: 0.into(),
1547            max_initcode_size: AtomicUsize::new(MAX_INITCODE_SIZE),
1548            tx_gas_limit_cap: AtomicU64::new(0),
1549        };
1550
1551        let res = ensure_intrinsic_gas(&transaction, &fork_tracker);
1552        assert!(res.is_ok());
1553
1554        fork_tracker.shanghai = true.into();
1555        let res = ensure_intrinsic_gas(&transaction, &fork_tracker);
1556        assert!(res.is_ok());
1557
1558        let provider = MockEthProvider::default().with_genesis_block();
1559        provider.add_account(
1560            transaction.sender(),
1561            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1562        );
1563        let blob_store = InMemoryBlobStore::default();
1564        let validator = EthTransactionValidatorBuilder::new(provider, test_evm_config())
1565            .build(blob_store.clone());
1566
1567        let outcome = validator.validate_one(TransactionOrigin::External, transaction.clone());
1568
1569        assert!(outcome.is_valid());
1570
1571        let pool =
1572            Pool::new(validator, CoinbaseTipOrdering::default(), blob_store, Default::default());
1573
1574        let res = pool.add_external_transaction(transaction.clone()).await;
1575        assert!(res.is_ok());
1576        let tx = pool.get(transaction.hash());
1577        assert!(tx.is_some());
1578    }
1579
1580    #[test]
1581    fn validates_configured_chain_id() {
1582        let provider = MockEthProvider::default().with_genesis_block();
1583        let validator = EthTransactionValidatorBuilder::new(provider, test_evm_config())
1584            .build(InMemoryBlobStore::default());
1585        let transaction = |chain_id| {
1586            EthPooledTransaction::try_from_consensus(
1587                TransactionBuilder::default()
1588                    .chain_id(chain_id)
1589                    .gas_limit(21_000)
1590                    .to(Address::ZERO)
1591                    .into_eip1559()
1592                    .try_into_recovered()
1593                    .unwrap(),
1594            )
1595            .unwrap()
1596        };
1597
1598        assert!(validator
1599            .validate_stateless(TransactionOrigin::External, &transaction(validator.chain_id()))
1600            .is_ok());
1601        assert!(matches!(
1602            validator.validate_stateless(
1603                TransactionOrigin::External,
1604                &transaction(validator.chain_id() + 1)
1605            ),
1606            Err(InvalidPoolTransactionError::Consensus(InvalidTransactionError::ChainIdMismatch))
1607        ));
1608    }
1609
1610    // <https://github.com/paradigmxyz/reth/issues/8550>
1611    #[tokio::test]
1612    async fn invalid_on_gas_limit_too_high() {
1613        let transaction = get_transaction();
1614
1615        let provider = MockEthProvider::default().with_genesis_block();
1616        provider.add_account(
1617            transaction.sender(),
1618            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1619        );
1620
1621        let blob_store = InMemoryBlobStore::default();
1622        let validator = EthTransactionValidatorBuilder::new(provider, test_evm_config())
1623            .set_block_gas_limit(1_000_000) // tx gas limit is 1_015_288
1624            .build(blob_store.clone());
1625
1626        let outcome = validator.validate_one(TransactionOrigin::External, transaction.clone());
1627
1628        assert!(outcome.is_invalid());
1629
1630        let pool =
1631            Pool::new(validator, CoinbaseTipOrdering::default(), blob_store, Default::default());
1632
1633        let res = pool.add_external_transaction(transaction.clone()).await;
1634        assert!(res.is_err());
1635        assert!(matches!(
1636            res.unwrap_err().kind,
1637            PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::ExceedsGasLimit(
1638                1_015_288, 1_000_000
1639            ))
1640        ));
1641        let tx = pool.get(transaction.hash());
1642        assert!(tx.is_none());
1643    }
1644
1645    #[tokio::test]
1646    async fn invalid_on_fee_cap_exceeded() {
1647        let transaction = get_transaction();
1648        let provider = MockEthProvider::default().with_genesis_block();
1649        provider.add_account(
1650            transaction.sender(),
1651            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1652        );
1653
1654        let blob_store = InMemoryBlobStore::default();
1655        let validator = EthTransactionValidatorBuilder::new(provider, test_evm_config())
1656            .set_tx_fee_cap(100) // 100 wei cap
1657            .build(blob_store.clone());
1658
1659        let outcome = validator.validate_one(TransactionOrigin::Local, transaction.clone());
1660        assert!(outcome.is_invalid());
1661
1662        if let TransactionValidationOutcome::Invalid(_, err) = outcome {
1663            assert!(matches!(
1664                err,
1665                InvalidPoolTransactionError::ExceedsFeeCap { max_tx_fee_wei, tx_fee_cap_wei }
1666                if (max_tx_fee_wei > tx_fee_cap_wei)
1667            ));
1668        }
1669
1670        let pool =
1671            Pool::new(validator, CoinbaseTipOrdering::default(), blob_store, Default::default());
1672        let res = pool.add_transaction(TransactionOrigin::Local, transaction.clone()).await;
1673        assert!(res.is_err());
1674        assert!(matches!(
1675            res.unwrap_err().kind,
1676            PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::ExceedsFeeCap { .. })
1677        ));
1678        let tx = pool.get(transaction.hash());
1679        assert!(tx.is_none());
1680    }
1681
1682    #[tokio::test]
1683    async fn valid_on_zero_fee_cap() {
1684        let transaction = get_transaction();
1685        let provider = MockEthProvider::default().with_genesis_block();
1686        provider.add_account(
1687            transaction.sender(),
1688            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1689        );
1690
1691        let blob_store = InMemoryBlobStore::default();
1692        let validator = EthTransactionValidatorBuilder::new(provider, EthEvmConfig::mainnet())
1693            .set_tx_fee_cap(0) // no cap
1694            .build(blob_store);
1695
1696        let outcome = validator.validate_one(TransactionOrigin::Local, transaction);
1697        assert!(outcome.is_valid());
1698    }
1699
1700    #[tokio::test]
1701    async fn valid_on_normal_fee_cap() {
1702        let transaction = get_transaction();
1703        let provider = MockEthProvider::default().with_genesis_block();
1704        provider.add_account(
1705            transaction.sender(),
1706            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1707        );
1708
1709        let blob_store = InMemoryBlobStore::default();
1710        let validator = EthTransactionValidatorBuilder::new(provider, EthEvmConfig::mainnet())
1711            .set_tx_fee_cap(2e18 as u128) // 2 ETH cap
1712            .build(blob_store);
1713
1714        let outcome = validator.validate_one(TransactionOrigin::Local, transaction);
1715        assert!(outcome.is_valid());
1716    }
1717
1718    #[tokio::test]
1719    async fn invalid_on_max_tx_gas_limit_exceeded() {
1720        let transaction = get_transaction();
1721        let provider = MockEthProvider::default().with_genesis_block();
1722        provider.add_account(
1723            transaction.sender(),
1724            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1725        );
1726
1727        let blob_store = InMemoryBlobStore::default();
1728        let validator = EthTransactionValidatorBuilder::new(provider, EthEvmConfig::mainnet())
1729            .with_max_tx_gas_limit(Some(500_000)) // Set limit lower than transaction gas limit (1_015_288)
1730            .build(blob_store.clone());
1731
1732        let outcome = validator.validate_one(TransactionOrigin::External, transaction.clone());
1733        assert!(outcome.is_invalid());
1734
1735        let pool =
1736            Pool::new(validator, CoinbaseTipOrdering::default(), blob_store, Default::default());
1737
1738        let res = pool.add_external_transaction(transaction.clone()).await;
1739        assert!(res.is_err());
1740        assert!(matches!(
1741            res.unwrap_err().kind,
1742            PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::MaxTxGasLimitExceeded(
1743                1_015_288, 500_000
1744            ))
1745        ));
1746        let tx = pool.get(transaction.hash());
1747        assert!(tx.is_none());
1748    }
1749
1750    #[tokio::test]
1751    async fn valid_on_max_tx_gas_limit_disabled() {
1752        let transaction = get_transaction();
1753        let provider = MockEthProvider::default().with_genesis_block();
1754        provider.add_account(
1755            transaction.sender(),
1756            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1757        );
1758
1759        let blob_store = InMemoryBlobStore::default();
1760        let validator = EthTransactionValidatorBuilder::new(provider, EthEvmConfig::mainnet())
1761            .with_max_tx_gas_limit(None) // disabled
1762            .build(blob_store);
1763
1764        let outcome = validator.validate_one(TransactionOrigin::External, transaction);
1765        assert!(outcome.is_valid());
1766    }
1767
1768    #[tokio::test]
1769    async fn valid_on_max_tx_gas_limit_within_limit() {
1770        let transaction = get_transaction();
1771        let provider = MockEthProvider::default().with_genesis_block();
1772        provider.add_account(
1773            transaction.sender(),
1774            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1775        );
1776
1777        let blob_store = InMemoryBlobStore::default();
1778        let validator = EthTransactionValidatorBuilder::new(provider, EthEvmConfig::mainnet())
1779            .with_max_tx_gas_limit(Some(2_000_000)) // Set limit higher than transaction gas limit (1_015_288)
1780            .build(blob_store);
1781
1782        let outcome = validator.validate_one(TransactionOrigin::External, transaction);
1783        assert!(outcome.is_valid());
1784    }
1785
1786    // Helper function to set up common test infrastructure for priority fee tests
1787    fn setup_priority_fee_test() -> (EthPooledTransaction, MockEthProvider) {
1788        let transaction = get_transaction();
1789        let provider = MockEthProvider::default().with_genesis_block();
1790        provider.add_account(
1791            transaction.sender(),
1792            ExtendedAccount::new(transaction.nonce(), U256::MAX),
1793        );
1794        (transaction, provider)
1795    }
1796
1797    // Helper function to create a validator with minimum priority fee
1798    fn create_validator_with_minimum_fee(
1799        provider: MockEthProvider,
1800        minimum_priority_fee: Option<u128>,
1801        local_config: Option<LocalTransactionConfig>,
1802    ) -> EthTransactionValidator<MockEthProvider, EthPooledTransaction, EthEvmConfig> {
1803        let blob_store = InMemoryBlobStore::default();
1804        let mut builder = EthTransactionValidatorBuilder::new(provider, test_evm_config())
1805            .with_minimum_priority_fee(minimum_priority_fee);
1806
1807        if let Some(config) = local_config {
1808            builder = builder.with_local_transactions_config(config);
1809        }
1810
1811        builder.build(blob_store)
1812    }
1813
1814    #[tokio::test]
1815    async fn invalid_on_priority_fee_lower_than_configured_minimum() {
1816        let (transaction, provider) = setup_priority_fee_test();
1817
1818        // Verify the test transaction is a dynamic fee transaction
1819        assert!(transaction.is_dynamic_fee());
1820
1821        // Set minimum priority fee to be double the transaction's priority fee
1822        let minimum_priority_fee =
1823            transaction.max_priority_fee_per_gas().expect("priority fee is expected") * 2;
1824
1825        let validator =
1826            create_validator_with_minimum_fee(provider, Some(minimum_priority_fee), None);
1827
1828        // External transaction should be rejected due to low priority fee
1829        let outcome = validator.validate_one(TransactionOrigin::External, transaction.clone());
1830        assert!(outcome.is_invalid());
1831
1832        if let TransactionValidationOutcome::Invalid(_, err) = outcome {
1833            assert!(matches!(
1834                err,
1835                InvalidPoolTransactionError::PriorityFeeBelowMinimum { minimum_priority_fee: min_fee }
1836                if min_fee == minimum_priority_fee
1837            ));
1838        }
1839
1840        // Test pool integration
1841        let blob_store = InMemoryBlobStore::default();
1842        let pool =
1843            Pool::new(validator, CoinbaseTipOrdering::default(), blob_store, Default::default());
1844
1845        let res = pool.add_external_transaction(transaction.clone()).await;
1846        assert!(res.is_err());
1847        assert!(matches!(
1848            res.unwrap_err().kind,
1849            PoolErrorKind::InvalidTransaction(
1850                InvalidPoolTransactionError::PriorityFeeBelowMinimum { .. }
1851            )
1852        ));
1853        let tx = pool.get(transaction.hash());
1854        assert!(tx.is_none());
1855
1856        // Local transactions should still be accepted regardless of minimum priority fee
1857        let (_, local_provider) = setup_priority_fee_test();
1858        let validator_local =
1859            create_validator_with_minimum_fee(local_provider, Some(minimum_priority_fee), None);
1860
1861        let local_outcome = validator_local.validate_one(TransactionOrigin::Local, transaction);
1862        assert!(local_outcome.is_valid());
1863    }
1864
1865    #[tokio::test]
1866    async fn valid_on_priority_fee_equal_to_minimum() {
1867        let (transaction, provider) = setup_priority_fee_test();
1868
1869        // Set minimum priority fee equal to transaction's priority fee
1870        let tx_priority_fee =
1871            transaction.max_priority_fee_per_gas().expect("priority fee is expected");
1872        let validator = create_validator_with_minimum_fee(provider, Some(tx_priority_fee), None);
1873
1874        let outcome = validator.validate_one(TransactionOrigin::External, transaction);
1875        assert!(outcome.is_valid());
1876    }
1877
1878    #[tokio::test]
1879    async fn valid_on_priority_fee_above_minimum() {
1880        let (transaction, provider) = setup_priority_fee_test();
1881
1882        // Set minimum priority fee below transaction's priority fee
1883        let tx_priority_fee =
1884            transaction.max_priority_fee_per_gas().expect("priority fee is expected");
1885        let minimum_priority_fee = tx_priority_fee / 2; // Half of transaction's priority fee
1886
1887        let validator =
1888            create_validator_with_minimum_fee(provider, Some(minimum_priority_fee), None);
1889
1890        let outcome = validator.validate_one(TransactionOrigin::External, transaction);
1891        assert!(outcome.is_valid());
1892    }
1893
1894    #[tokio::test]
1895    async fn valid_on_minimum_priority_fee_disabled() {
1896        let (transaction, provider) = setup_priority_fee_test();
1897
1898        // No minimum priority fee set (default is None)
1899        let validator = create_validator_with_minimum_fee(provider, None, None);
1900
1901        let outcome = validator.validate_one(TransactionOrigin::External, transaction);
1902        assert!(outcome.is_valid());
1903    }
1904
1905    #[tokio::test]
1906    async fn priority_fee_validation_applies_to_private_transactions() {
1907        let (transaction, provider) = setup_priority_fee_test();
1908
1909        // Set minimum priority fee to be double the transaction's priority fee
1910        let minimum_priority_fee =
1911            transaction.max_priority_fee_per_gas().expect("priority fee is expected") * 2;
1912
1913        let validator =
1914            create_validator_with_minimum_fee(provider, Some(minimum_priority_fee), None);
1915
1916        // Private transactions are also subject to minimum priority fee validation
1917        // because they are not considered "local" by default unless specifically configured
1918        let outcome = validator.validate_one(TransactionOrigin::Private, transaction);
1919        assert!(outcome.is_invalid());
1920
1921        if let TransactionValidationOutcome::Invalid(_, err) = outcome {
1922            assert!(matches!(
1923                err,
1924                InvalidPoolTransactionError::PriorityFeeBelowMinimum { minimum_priority_fee: min_fee }
1925                if min_fee == minimum_priority_fee
1926            ));
1927        }
1928    }
1929
1930    #[tokio::test]
1931    async fn valid_on_local_config_exempts_private_transactions() {
1932        let (transaction, provider) = setup_priority_fee_test();
1933
1934        // Set minimum priority fee to be double the transaction's priority fee
1935        let minimum_priority_fee =
1936            transaction.max_priority_fee_per_gas().expect("priority fee is expected") * 2;
1937
1938        // Configure local transactions to include all private transactions
1939        let local_config =
1940            LocalTransactionConfig { propagate_local_transactions: true, ..Default::default() };
1941
1942        let validator = create_validator_with_minimum_fee(
1943            provider,
1944            Some(minimum_priority_fee),
1945            Some(local_config),
1946        );
1947
1948        // With appropriate local config, the behavior depends on the local transaction logic
1949        // This test documents the current behavior - private transactions are still validated
1950        // unless the sender is specifically whitelisted in local_transactions_config
1951        let outcome = validator.validate_one(TransactionOrigin::Private, transaction);
1952        assert!(outcome.is_invalid()); // Still invalid because sender not in whitelist
1953    }
1954
1955    #[test]
1956    fn reject_oversized_tx() {
1957        let mut transaction = get_transaction();
1958        transaction.encoded_length = DEFAULT_MAX_TX_INPUT_BYTES + 1;
1959        let provider = MockEthProvider::default().with_genesis_block();
1960
1961        // No minimum priority fee set (default is None)
1962        let validator = create_validator_with_minimum_fee(provider, None, None);
1963
1964        let outcome = validator.validate_one(TransactionOrigin::External, transaction);
1965        let invalid = outcome.as_invalid().unwrap();
1966        assert!(invalid.is_oversized());
1967    }
1968
1969    #[test]
1970    fn reject_blob_tx_with_oversized_access_list() {
1971        let max_tx_input_bytes = 512;
1972        let provider = MockEthProvider::default().with_genesis_block();
1973        let validator = EthTransactionValidatorBuilder::new(provider, test_evm_config())
1974            .with_max_tx_input_bytes(max_tx_input_bytes)
1975            .build(InMemoryBlobStore::default());
1976
1977        let blob_tx_with_access_list = |storage_keys: usize| {
1978            let access_list = AccessList(vec![AccessListItem {
1979                address: Address::random(),
1980                storage_keys: (0..storage_keys).map(|_| B256::random()).collect(),
1981            }]);
1982            let tx = TransactionBuilder::default()
1983                .access_list(access_list)
1984                .into_eip4844()
1985                .try_into_recovered()
1986                .unwrap();
1987            let encoded_length = tx.encode_2718_len();
1988            EthPooledTransaction::new(tx, encoded_length)
1989        };
1990
1991        let is_oversized = |tx: &EthPooledTransaction| {
1992            matches!(
1993                validator.validate_stateless(TransactionOrigin::External, tx),
1994                Err(InvalidPoolTransactionError::OversizedData { .. })
1995            )
1996        };
1997
1998        let small = blob_tx_with_access_list(1);
1999        assert!(!is_oversized(&small));
2000
2001        let large = blob_tx_with_access_list(64);
2002        assert!(large.input().is_empty());
2003        assert!(is_oversized(&large));
2004    }
2005
2006    #[tokio::test]
2007    async fn valid_with_disabled_balance_check() {
2008        let transaction = get_transaction();
2009        let provider = MockEthProvider::default().with_genesis_block();
2010
2011        // Set account with 0 balance
2012        provider.add_account(
2013            transaction.sender(),
2014            ExtendedAccount::new(transaction.nonce(), alloy_primitives::U256::ZERO),
2015        );
2016
2017        // Validate with balance check enabled
2018        let validator =
2019            EthTransactionValidatorBuilder::new(provider.clone(), EthEvmConfig::mainnet())
2020                .build(InMemoryBlobStore::default());
2021
2022        let outcome = validator.validate_one(TransactionOrigin::External, transaction.clone());
2023        let expected_cost = *transaction.cost();
2024        if let TransactionValidationOutcome::Invalid(_, err) = outcome {
2025            assert!(matches!(
2026                err,
2027                InvalidPoolTransactionError::Consensus(InvalidTransactionError::InsufficientFunds(ref funds_err))
2028                if funds_err.got == alloy_primitives::U256::ZERO && funds_err.expected == expected_cost
2029            ));
2030        } else {
2031            panic!("Expected Invalid outcome with InsufficientFunds error");
2032        }
2033
2034        // Validate with balance check disabled
2035        let validator = EthTransactionValidatorBuilder::new(provider, EthEvmConfig::mainnet())
2036            .disable_balance_check()
2037            .build(InMemoryBlobStore::default());
2038
2039        let outcome = validator.validate_one(TransactionOrigin::External, transaction);
2040        assert!(outcome.is_valid()); // Should be valid because balance check is disabled
2041    }
2042}