reth_transaction_pool/validate/
eth.rs

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