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