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