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