Skip to main content

reth_rpc/
validation.rs

1use alloy_consensus::{
2    BlobTransactionValidationError, BlockHeader, EnvKzgSettings, Transaction, TxReceipt,
3};
4use alloy_eip7928::{bal::DecodedBal, compute_block_access_list_hash};
5use alloy_eips::eip7685::RequestsOrHash;
6use alloy_primitives::{map::AddressSet, Address, B256, U256};
7use alloy_rpc_types_beacon::relay::{
8    BidTrace, BuilderBlockValidationRequest, BuilderBlockValidationRequestV2,
9    BuilderBlockValidationRequestV3, BuilderBlockValidationRequestV4,
10    BuilderBlockValidationRequestV5, BuilderBlockValidationRequestV6,
11};
12use alloy_rpc_types_engine::{
13    BlobsBundleV1, BlobsBundleV2, CancunPayloadFields, ExecutionData, ExecutionPayload,
14    ExecutionPayloadSidecar, PraguePayloadFields,
15};
16use async_trait::async_trait;
17use core::fmt;
18use jsonrpsee::core::RpcResult;
19use jsonrpsee_types::error::ErrorObject;
20use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
21use reth_consensus::{Consensus, FullConsensus};
22use reth_consensus_common::validation::MAX_RLP_BLOCK_SIZE;
23use reth_engine_primitives::PayloadValidator;
24use reth_errors::{BlockExecutionError, ConsensusError, ProviderError};
25use reth_evm::{execute::Executor, ConfigureEvm};
26use reth_execution_types::BlockExecutionOutput;
27use reth_metrics::{
28    metrics,
29    metrics::{gauge, Gauge},
30    Metrics,
31};
32use reth_node_api::{NewPayloadError, PayloadTypes};
33use reth_primitives_traits::{
34    BlockBody, GotExpected, NodePrimitives, RecoveredBlock, SealedBlock, SealedHeaderFor,
35};
36use reth_revm::{cached::CachedReads, database::StateProviderDatabase};
37use reth_rpc_api::BlockSubmissionValidationApiServer;
38use reth_rpc_server_types::result::{internal_rpc_err, invalid_params_rpc_err};
39use reth_storage_api::{BlockReaderIdExt, HashedPostStateProvider, StateProviderFactory};
40use reth_tasks::Runtime;
41use serde::{Deserialize, Serialize};
42use sha2::{Digest, Sha256};
43use std::sync::Arc;
44use tokio::sync::{oneshot, RwLock};
45use tracing::warn;
46
47/// The type that implements the `validation` rpc namespace trait
48#[derive(Clone, Debug, derive_more::Deref)]
49pub struct ValidationApi<Provider, E: ConfigureEvm, T: PayloadTypes> {
50    #[deref]
51    inner: Arc<ValidationApiInner<Provider, E, T>>,
52}
53
54impl<Provider, E, T> ValidationApi<Provider, E, T>
55where
56    E: ConfigureEvm,
57    T: PayloadTypes,
58{
59    /// Create a new instance of the [`ValidationApi`]
60    pub fn new(
61        provider: Provider,
62        consensus: Arc<dyn FullConsensus<E::Primitives>>,
63        evm_config: E,
64        config: ValidationApiConfig,
65        task_spawner: Runtime,
66        payload_validator: Arc<
67            dyn PayloadValidator<T, Block = <E::Primitives as NodePrimitives>::Block>,
68        >,
69    ) -> Self {
70        let ValidationApiConfig { disallow, validation_window } = config;
71
72        let inner = Arc::new(ValidationApiInner {
73            provider,
74            consensus,
75            payload_validator,
76            evm_config,
77            disallow,
78            validation_window,
79            cached_state: Default::default(),
80            task_spawner,
81            metrics: Default::default(),
82        });
83
84        inner.metrics.disallow_size.set(inner.disallow.len() as f64);
85
86        let disallow_hash = hash_disallow_list(&inner.disallow);
87        let hash_gauge = gauge!("builder_validation_disallow_hash", "hash" => disallow_hash);
88        hash_gauge.set(1.0);
89
90        Self { inner }
91    }
92
93    /// Returns the cached reads for the given head hash.
94    async fn cached_reads(&self, head: B256) -> CachedReads {
95        let cache = self.inner.cached_state.read().await;
96        if cache.0 == head {
97            cache.1.clone()
98        } else {
99            Default::default()
100        }
101    }
102
103    /// Updates the cached state for the given head hash.
104    async fn update_cached_reads(&self, head: B256, cached_state: CachedReads) {
105        let mut cache = self.inner.cached_state.write().await;
106        if cache.0 == head {
107            cache.1.extend(cached_state);
108        } else {
109            *cache = (head, cached_state)
110        }
111    }
112}
113
114impl<Provider, E, T> ValidationApi<Provider, E, T>
115where
116    Provider: BlockReaderIdExt<Header = <E::Primitives as NodePrimitives>::BlockHeader>
117        + ChainSpecProvider<ChainSpec: EthereumHardforks>
118        + StateProviderFactory
119        + 'static,
120    E: ConfigureEvm + 'static,
121    T: PayloadTypes<ExecutionData = ExecutionData>,
122{
123    /// Validates the given block and a [`BidTrace`] against it.
124    pub async fn validate_message_against_block(
125        &self,
126        block: RecoveredBlock<<E::Primitives as NodePrimitives>::Block>,
127        message: BidTrace,
128        registered_gas_limit: u64,
129        decoded_bal: Option<DecodedBal>,
130    ) -> Result<(), ValidationApiError> {
131        self.validate_message_against_header(block.sealed_header(), &message)?;
132
133        self.consensus.validate_header(block.sealed_header())?;
134        self.consensus.validate_block_pre_execution(block.sealed_block())?;
135
136        if !self.disallow.is_empty() {
137            if self.disallow.contains(&block.beneficiary()) {
138                return Err(ValidationApiError::Blacklist(block.beneficiary()))
139            }
140            if self.disallow.contains(&message.proposer_fee_recipient) {
141                return Err(ValidationApiError::Blacklist(message.proposer_fee_recipient))
142            }
143            for (sender, tx) in block.senders_iter().zip(block.body().transactions()) {
144                if self.disallow.contains(sender) {
145                    return Err(ValidationApiError::Blacklist(*sender))
146                }
147                if let Some(to) = tx.to() &&
148                    self.disallow.contains(&to)
149                {
150                    return Err(ValidationApiError::Blacklist(to))
151                }
152            }
153        }
154
155        let latest_header =
156            self.provider.latest_header()?.ok_or_else(|| ValidationApiError::MissingLatestBlock)?;
157
158        let parent_header = if block.parent_hash() == latest_header.hash() {
159            latest_header
160        } else {
161            // parent is not the latest header so we need to fetch it and ensure it's not too old
162            let parent_header = self
163                .provider
164                .sealed_header_by_hash(block.parent_hash())?
165                .ok_or_else(|| ValidationApiError::MissingParentBlock)?;
166
167            if latest_header.number().saturating_sub(parent_header.number()) >
168                self.validation_window
169            {
170                return Err(ValidationApiError::BlockTooOld)
171            }
172            parent_header
173        };
174
175        self.consensus.validate_header_against_parent(block.sealed_header(), &parent_header)?;
176        parent_header.validate_gas_limit(registered_gas_limit, block.gas_limit()).map_err(
177            |err| {
178                ValidationApiError::GasLimitMismatch(GotExpected {
179                    got: err.got,
180                    expected: err.expected,
181                })
182            },
183        )?;
184
185        // Ensure the submitted block access list does not exceed the block gas limit (EIP-7928)
186        if let Some(decoded_bal) = decoded_bal {
187            decoded_bal
188                .as_bal()
189                .validate_gas_limit(block.gas_limit())
190                .map_err(ConsensusError::from)?;
191        }
192
193        let parent_header_hash = parent_header.hash();
194        let state_provider = self.provider.state_by_block_hash(parent_header_hash)?;
195
196        let mut request_cache = self.cached_reads(parent_header_hash).await;
197
198        let (output, block_access_list_hash) = {
199            let cached_db = request_cache.as_db_mut(StateProviderDatabase::new(&state_provider));
200            let mut executor = self.evm_config.batch_executor(cached_db);
201
202            let result = executor.execute_one(&block)?;
203
204            // The executor rebuilds the block access list whenever the block header contains a
205            // BAL hash. Comparing the rebuilt hash against the header post execution also
206            // commits to the submitted access list, because the header's BAL hash is derived
207            // from the submitted bytes.
208            let block_access_list_hash =
209                executor.take_bal().map(|bal| compute_block_access_list_hash(&bal));
210
211            let mut state = executor.into_state();
212            if !self.disallow.is_empty() {
213                // Check whether the submission interacted with any blacklisted account by
214                // scanning the `State`'s cache that records everything read from database
215                // during execution.
216                for account in state.cache.accounts.keys() {
217                    if self.disallow.contains(account) {
218                        return Err(ValidationApiError::Blacklist(*account))
219                    }
220                }
221            }
222
223            (BlockExecutionOutput { state: state.take_bundle(), result }, block_access_list_hash)
224        };
225
226        // update the cached reads
227        self.update_cached_reads(parent_header_hash, request_cache).await;
228
229        self.consensus.validate_block_post_execution(
230            &block,
231            &output,
232            None,
233            block_access_list_hash,
234        )?;
235
236        self.ensure_payment(&block, &output, &message)?;
237
238        let hashed_state = state_provider.hashed_post_state(&output.state)?;
239        let state_root = state_provider.state_root(hashed_state)?;
240
241        if state_root != block.header().state_root() {
242            return Err(ConsensusError::BodyStateRootDiff(
243                GotExpected { got: state_root, expected: block.header().state_root() }.into(),
244            )
245            .into())
246        }
247
248        Ok(())
249    }
250
251    /// Ensures that fields of [`BidTrace`] match the fields of the [`SealedHeaderFor`].
252    fn validate_message_against_header(
253        &self,
254        header: &SealedHeaderFor<E::Primitives>,
255        message: &BidTrace,
256    ) -> Result<(), ValidationApiError> {
257        if header.hash() != message.block_hash {
258            Err(ValidationApiError::BlockHashMismatch(GotExpected {
259                got: message.block_hash,
260                expected: header.hash(),
261            }))
262        } else if header.parent_hash() != message.parent_hash {
263            Err(ValidationApiError::ParentHashMismatch(GotExpected {
264                got: message.parent_hash,
265                expected: header.parent_hash(),
266            }))
267        } else if header.gas_limit() != message.gas_limit {
268            Err(ValidationApiError::GasLimitMismatch(GotExpected {
269                got: message.gas_limit,
270                expected: header.gas_limit(),
271            }))
272        } else if header.gas_used() != message.gas_used {
273            Err(ValidationApiError::GasUsedMismatch(GotExpected {
274                got: message.gas_used,
275                expected: header.gas_used(),
276            }))
277        } else {
278            Ok(())
279        }
280    }
281
282    /// Ensures that the proposer has received [`BidTrace::value`] for this block.
283    ///
284    /// Firstly attempts to verify the payment by checking the state changes, otherwise falls back
285    /// to checking the latest block transaction.
286    fn ensure_payment(
287        &self,
288        block: &SealedBlock<<E::Primitives as NodePrimitives>::Block>,
289        output: &BlockExecutionOutput<<E::Primitives as NodePrimitives>::Receipt>,
290        message: &BidTrace,
291    ) -> Result<(), ValidationApiError> {
292        let (mut balance_before, balance_after) = if let Some(acc) =
293            output.state.state.get(&message.proposer_fee_recipient)
294        {
295            let balance_before = acc.original_info.as_ref().map(|i| i.balance).unwrap_or_default();
296            let balance_after = acc.info.as_ref().map(|i| i.balance).unwrap_or_default();
297
298            (balance_before, balance_after)
299        } else {
300            // account might have balance but considering it zero is fine as long as we know
301            // that balance have not changed
302            (U256::ZERO, U256::ZERO)
303        };
304
305        if let Some(withdrawals) = block.body().withdrawals() {
306            for withdrawal in withdrawals {
307                if withdrawal.address == message.proposer_fee_recipient {
308                    balance_before += withdrawal.amount_wei();
309                }
310            }
311        }
312
313        if balance_after >= balance_before.saturating_add(message.value) {
314            return Ok(())
315        }
316
317        let (receipt, tx) = output
318            .receipts
319            .last()
320            .zip(block.body().transactions().last())
321            .ok_or(ValidationApiError::ProposerPayment)?;
322
323        if !receipt.status() {
324            return Err(ValidationApiError::ProposerPayment)
325        }
326
327        if tx.to() != Some(message.proposer_fee_recipient) {
328            return Err(ValidationApiError::ProposerPayment)
329        }
330
331        if tx.value() != message.value {
332            return Err(ValidationApiError::ProposerPayment)
333        }
334
335        if !tx.input().is_empty() {
336            return Err(ValidationApiError::ProposerPayment)
337        }
338
339        if let Some(block_base_fee) = block.header().base_fee_per_gas() &&
340            tx.effective_tip_per_gas(block_base_fee).unwrap_or_default() != 0
341        {
342            return Err(ValidationApiError::ProposerPayment)
343        }
344
345        Ok(())
346    }
347
348    /// Validates the given [`BlobsBundleV1`] and returns versioned hashes for blobs.
349    pub fn validate_blobs_bundle(
350        &self,
351        blobs_bundle: BlobsBundleV1,
352    ) -> Result<Vec<B256>, ValidationApiError> {
353        let versioned_hashes = blobs_bundle.versioned_hashes();
354        let sidecar =
355            blobs_bundle.try_into_sidecar().map_err(|_| ValidationApiError::InvalidBlobsBundle)?;
356
357        sidecar.validate(&versioned_hashes, EnvKzgSettings::default().get())?;
358        Ok(versioned_hashes)
359    }
360
361    /// Validates the given [`BlobsBundleV2`] and returns versioned hashes for blobs.
362    pub fn validate_blobs_bundle_v2(
363        &self,
364        blobs_bundle: BlobsBundleV2,
365    ) -> Result<Vec<B256>, ValidationApiError> {
366        let versioned_hashes = blobs_bundle.versioned_hashes();
367        let sidecar =
368            blobs_bundle.try_into_sidecar().map_err(|_| ValidationApiError::InvalidBlobsBundle)?;
369
370        sidecar.validate(&versioned_hashes, EnvKzgSettings::default().get())?;
371        Ok(versioned_hashes)
372    }
373
374    /// Core logic for validating the builder submission v3
375    async fn validate_builder_submission_v3(
376        &self,
377        request: BuilderBlockValidationRequestV3,
378    ) -> Result<(), ValidationApiError> {
379        let block = self.payload_validator.ensure_well_formed_payload(ExecutionData {
380            payload: ExecutionPayload::V3(request.request.execution_payload),
381            sidecar: ExecutionPayloadSidecar::v3(CancunPayloadFields {
382                parent_beacon_block_root: request.parent_beacon_block_root,
383                versioned_hashes: self.validate_blobs_bundle(request.request.blobs_bundle)?,
384            }),
385        })?;
386
387        self.validate_message_against_block(
388            block,
389            request.request.message,
390            request.registered_gas_limit,
391            None,
392        )
393        .await
394    }
395
396    /// Core logic for validating the builder submission v4
397    async fn validate_builder_submission_v4(
398        &self,
399        request: BuilderBlockValidationRequestV4,
400    ) -> Result<(), ValidationApiError> {
401        let block = self.payload_validator.ensure_well_formed_payload(ExecutionData {
402            payload: ExecutionPayload::V3(request.request.execution_payload),
403            sidecar: ExecutionPayloadSidecar::v4(
404                CancunPayloadFields {
405                    parent_beacon_block_root: request.parent_beacon_block_root,
406                    versioned_hashes: self.validate_blobs_bundle(request.request.blobs_bundle)?,
407                },
408                PraguePayloadFields {
409                    requests: RequestsOrHash::Requests(
410                        request.request.execution_requests.to_requests(),
411                    ),
412                },
413            ),
414        })?;
415
416        self.validate_message_against_block(
417            block,
418            request.request.message,
419            request.registered_gas_limit,
420            None,
421        )
422        .await
423    }
424
425    /// Core logic for validating the builder submission v5
426    async fn validate_builder_submission_v5(
427        &self,
428        request: BuilderBlockValidationRequestV5,
429    ) -> Result<(), ValidationApiError> {
430        let block = self.payload_validator.ensure_well_formed_payload(ExecutionData {
431            payload: ExecutionPayload::V3(request.request.execution_payload),
432            sidecar: ExecutionPayloadSidecar::v4(
433                CancunPayloadFields {
434                    parent_beacon_block_root: request.parent_beacon_block_root,
435                    versioned_hashes: self
436                        .validate_blobs_bundle_v2(request.request.blobs_bundle)?,
437                },
438                PraguePayloadFields {
439                    requests: RequestsOrHash::Requests(
440                        request.request.execution_requests.to_requests(),
441                    ),
442                },
443            ),
444        })?;
445
446        // Check block size as per EIP-7934 (only applies when Osaka hardfork is active)
447        let chain_spec = self.provider.chain_spec();
448        if chain_spec.is_osaka_active_at_timestamp(block.timestamp()) {
449            let rlp_length = block.rlp_length();
450            if rlp_length > MAX_RLP_BLOCK_SIZE {
451                return Err(ValidationApiError::Consensus(ConsensusError::BlockTooLarge {
452                    rlp_length,
453                    max_rlp_length: MAX_RLP_BLOCK_SIZE,
454                }));
455            }
456        }
457
458        self.validate_message_against_block(
459            block,
460            request.request.message,
461            request.registered_gas_limit,
462            None,
463        )
464        .await
465    }
466
467    /// Core logic for validating the builder submission v6
468    async fn validate_builder_submission_v6(
469        &self,
470        request: BuilderBlockValidationRequestV6,
471    ) -> Result<(), ValidationApiError> {
472        let decoded_bal =
473            DecodedBal::from_rlp_bytes(request.request.execution_payload.block_access_list.clone())
474                .map_err(ValidationApiError::InvalidBlockAccessList)?;
475
476        let block = self.payload_validator.ensure_well_formed_payload(ExecutionData {
477            payload: ExecutionPayload::V4(request.request.execution_payload),
478            sidecar: ExecutionPayloadSidecar::v4(
479                CancunPayloadFields {
480                    parent_beacon_block_root: request.parent_beacon_block_root,
481                    versioned_hashes: self
482                        .validate_blobs_bundle_v2(request.request.blobs_bundle)?,
483                },
484                PraguePayloadFields {
485                    requests: RequestsOrHash::Requests(
486                        request.request.execution_requests.to_requests(),
487                    ),
488                },
489            ),
490        })?;
491
492        let chain_spec = self.provider.chain_spec();
493        if chain_spec.is_osaka_active_at_timestamp(block.timestamp()) {
494            let rlp_length = block.rlp_length();
495            if rlp_length > MAX_RLP_BLOCK_SIZE {
496                return Err(ValidationApiError::Consensus(ConsensusError::BlockTooLarge {
497                    rlp_length,
498                    max_rlp_length: MAX_RLP_BLOCK_SIZE,
499                }));
500            }
501        }
502
503        self.validate_message_against_block(
504            block,
505            request.request.message,
506            request.registered_gas_limit,
507            Some(decoded_bal),
508        )
509        .await
510    }
511}
512
513#[async_trait]
514impl<Provider, E, T> BlockSubmissionValidationApiServer for ValidationApi<Provider, E, T>
515where
516    Provider: BlockReaderIdExt<Header = <E::Primitives as NodePrimitives>::BlockHeader>
517        + ChainSpecProvider<ChainSpec: EthereumHardforks>
518        + StateProviderFactory
519        + Clone
520        + 'static,
521    E: ConfigureEvm + 'static,
522    T: PayloadTypes<ExecutionData = ExecutionData>,
523{
524    async fn validate_builder_submission_v1(
525        &self,
526        _request: BuilderBlockValidationRequest,
527    ) -> RpcResult<()> {
528        warn!(target: "rpc::flashbots", "Method `flashbots_validateBuilderSubmissionV1` is not supported");
529        Err(internal_rpc_err("unimplemented"))
530    }
531
532    async fn validate_builder_submission_v2(
533        &self,
534        _request: BuilderBlockValidationRequestV2,
535    ) -> RpcResult<()> {
536        warn!(target: "rpc::flashbots", "Method `flashbots_validateBuilderSubmissionV2` is not supported");
537        Err(internal_rpc_err("unimplemented"))
538    }
539
540    /// Validates a block submitted to the relay
541    async fn validate_builder_submission_v3(
542        &self,
543        request: BuilderBlockValidationRequestV3,
544    ) -> RpcResult<()> {
545        let this = self.clone();
546        let (tx, rx) = oneshot::channel();
547
548        self.task_spawner.spawn_blocking_task(async move {
549            let result = Self::validate_builder_submission_v3(&this, request)
550                .await
551                .map_err(ErrorObject::from);
552            let _ = tx.send(result);
553        });
554
555        rx.await.map_err(|_| internal_rpc_err("Internal blocking task error"))?
556    }
557
558    /// Validates a block submitted to the relay
559    async fn validate_builder_submission_v4(
560        &self,
561        request: BuilderBlockValidationRequestV4,
562    ) -> RpcResult<()> {
563        let this = self.clone();
564        let (tx, rx) = oneshot::channel();
565
566        self.task_spawner.spawn_blocking_task(async move {
567            let result = Self::validate_builder_submission_v4(&this, request)
568                .await
569                .map_err(ErrorObject::from);
570            let _ = tx.send(result);
571        });
572
573        rx.await.map_err(|_| internal_rpc_err("Internal blocking task error"))?
574    }
575
576    /// Validates a block submitted to the relay
577    async fn validate_builder_submission_v5(
578        &self,
579        request: BuilderBlockValidationRequestV5,
580    ) -> RpcResult<()> {
581        let this = self.clone();
582        let (tx, rx) = oneshot::channel();
583
584        self.task_spawner.spawn_blocking_task(async move {
585            let result = Self::validate_builder_submission_v5(&this, request)
586                .await
587                .map_err(ErrorObject::from);
588            let _ = tx.send(result);
589        });
590
591        rx.await.map_err(|_| internal_rpc_err("Internal blocking task error"))?
592    }
593
594    /// Validates a block submitted to the relay
595    async fn validate_builder_submission_v6(
596        &self,
597        request: BuilderBlockValidationRequestV6,
598    ) -> RpcResult<()> {
599        let this = self.clone();
600        let (tx, rx) = oneshot::channel();
601
602        self.task_spawner.spawn_blocking_task(async move {
603            let result = Self::validate_builder_submission_v6(&this, request)
604                .await
605                .map_err(ErrorObject::from);
606            let _ = tx.send(result);
607        });
608
609        rx.await.map_err(|_| internal_rpc_err("Internal blocking task error"))?
610    }
611}
612
613pub struct ValidationApiInner<Provider, E: ConfigureEvm, T: PayloadTypes> {
614    /// The provider that can interact with the chain.
615    provider: Provider,
616    /// Consensus implementation.
617    consensus: Arc<dyn FullConsensus<E::Primitives>>,
618    /// Execution payload validator.
619    payload_validator:
620        Arc<dyn PayloadValidator<T, Block = <E::Primitives as NodePrimitives>::Block>>,
621    /// Block executor factory.
622    evm_config: E,
623    /// Set of disallowed addresses
624    disallow: AddressSet,
625    /// The maximum block distance - parent to latest - allowed for validation
626    validation_window: u64,
627    /// Cached state reads to avoid redundant disk I/O across multiple validation attempts
628    /// targeting the same state. Stores a tuple of (`block_hash`, `cached_reads`) for the
629    /// latest head block state. Uses async `RwLock` to safely handle concurrent validation
630    /// requests.
631    cached_state: RwLock<(B256, CachedReads)>,
632    /// Task spawner for blocking operations
633    task_spawner: Runtime,
634    /// Validation metrics
635    metrics: ValidationMetrics,
636}
637
638/// Calculates a deterministic hash of the blocklist for change detection.
639///
640/// This function sorts addresses to ensure deterministic output regardless of
641/// insertion order, then computes a SHA256 hash of the concatenated addresses.
642fn hash_disallow_list(disallow: &AddressSet) -> String {
643    let mut sorted: Vec<_> = disallow.iter().collect();
644    sorted.sort_unstable(); // sort for deterministic hashing
645
646    let mut hasher = Sha256::new();
647    for addr in sorted {
648        hasher.update(addr.as_slice());
649    }
650
651    format!("{:x}", hasher.finalize())
652}
653
654impl<Provider, E: ConfigureEvm, T: PayloadTypes> fmt::Debug for ValidationApiInner<Provider, E, T> {
655    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656        f.debug_struct("ValidationApiInner").finish_non_exhaustive()
657    }
658}
659
660/// Configuration for validation API.
661#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
662pub struct ValidationApiConfig {
663    /// Disallowed addresses.
664    pub disallow: AddressSet,
665    /// The maximum block distance - parent to latest - allowed for validation
666    pub validation_window: u64,
667}
668
669impl ValidationApiConfig {
670    /// Default validation blocks window of 3 blocks
671    pub const DEFAULT_VALIDATION_WINDOW: u64 = 3;
672}
673
674impl Default for ValidationApiConfig {
675    fn default() -> Self {
676        Self { disallow: Default::default(), validation_window: Self::DEFAULT_VALIDATION_WINDOW }
677    }
678}
679
680/// Errors thrown by the validation API.
681#[derive(Debug, thiserror::Error)]
682pub enum ValidationApiError {
683    #[error("block gas limit mismatch: {_0}")]
684    GasLimitMismatch(GotExpected<u64>),
685    #[error("block gas used mismatch: {_0}")]
686    GasUsedMismatch(GotExpected<u64>),
687    #[error("block parent hash mismatch: {_0}")]
688    ParentHashMismatch(GotExpected<B256>),
689    #[error("block hash mismatch: {_0}")]
690    BlockHashMismatch(GotExpected<B256>),
691    #[error("missing latest block in database")]
692    MissingLatestBlock,
693    #[error("parent block not found")]
694    MissingParentBlock,
695    #[error("block is too old, outside validation window")]
696    BlockTooOld,
697    #[error("could not verify proposer payment")]
698    ProposerPayment,
699    #[error("invalid blobs bundle")]
700    InvalidBlobsBundle,
701    #[error("invalid block access list: {_0}")]
702    InvalidBlockAccessList(alloy_rlp::Error),
703    #[error("block accesses blacklisted address: {_0}")]
704    Blacklist(Address),
705    #[error(transparent)]
706    Blob(#[from] BlobTransactionValidationError),
707    #[error(transparent)]
708    Consensus(#[from] ConsensusError),
709    #[error(transparent)]
710    Provider(#[from] ProviderError),
711    #[error(transparent)]
712    Execution(#[from] BlockExecutionError),
713    #[error(transparent)]
714    Payload(#[from] NewPayloadError),
715}
716
717impl From<ValidationApiError> for ErrorObject<'static> {
718    fn from(error: ValidationApiError) -> Self {
719        match error {
720            ValidationApiError::GasLimitMismatch(_) |
721            ValidationApiError::GasUsedMismatch(_) |
722            ValidationApiError::ParentHashMismatch(_) |
723            ValidationApiError::BlockHashMismatch(_) |
724            ValidationApiError::Blacklist(_) |
725            ValidationApiError::ProposerPayment |
726            ValidationApiError::InvalidBlobsBundle |
727            ValidationApiError::InvalidBlockAccessList(_) |
728            ValidationApiError::Blob(_) => invalid_params_rpc_err(error.to_string()),
729
730            ValidationApiError::Consensus(
731                error @ (ConsensusError::BlockAccessListCostMoreThanGasLimit(_) |
732                ConsensusError::BlockAccessListHashMismatch(_)),
733            ) => invalid_params_rpc_err(error.to_string()),
734            ValidationApiError::MissingLatestBlock |
735            ValidationApiError::MissingParentBlock |
736            ValidationApiError::BlockTooOld |
737            ValidationApiError::Consensus(_) |
738            ValidationApiError::Provider(_) => internal_rpc_err(error.to_string()),
739            ValidationApiError::Execution(err) => match err {
740                error @ BlockExecutionError::Validation(_) => {
741                    invalid_params_rpc_err(error.to_string())
742                }
743                error @ BlockExecutionError::Internal(_) => internal_rpc_err(error.to_string()),
744            },
745            ValidationApiError::Payload(err) => match err {
746                error @ NewPayloadError::Eth(_) => invalid_params_rpc_err(error.to_string()),
747                error @ NewPayloadError::Other(_) => internal_rpc_err(error.to_string()),
748            },
749        }
750    }
751}
752
753/// Metrics for the validation endpoint.
754#[derive(Metrics)]
755#[metrics(scope = "builder.validation")]
756pub(crate) struct ValidationMetrics {
757    /// The number of entries configured in the builder validation disallow list.
758    pub(crate) disallow_size: Gauge,
759}
760
761#[cfg(test)]
762mod tests {
763    use super::{hash_disallow_list, AddressSet};
764    use alloy_primitives::Address;
765
766    #[test]
767    fn test_hash_disallow_list_deterministic() {
768        let mut addresses = AddressSet::default();
769        addresses.insert(Address::from([1u8; 20]));
770        addresses.insert(Address::from([2u8; 20]));
771
772        let hash1 = hash_disallow_list(&addresses);
773        let hash2 = hash_disallow_list(&addresses);
774
775        assert_eq!(hash1, hash2);
776    }
777
778    #[test]
779    fn test_hash_disallow_list_different_content() {
780        let mut addresses1 = AddressSet::default();
781        addresses1.insert(Address::from([1u8; 20]));
782
783        let mut addresses2 = AddressSet::default();
784        addresses2.insert(Address::from([2u8; 20]));
785
786        let hash1 = hash_disallow_list(&addresses1);
787        let hash2 = hash_disallow_list(&addresses2);
788
789        assert_ne!(hash1, hash2);
790    }
791
792    #[test]
793    fn test_hash_disallow_list_order_independent() {
794        let mut addresses1 = AddressSet::default();
795        addresses1.insert(Address::from([1u8; 20]));
796        addresses1.insert(Address::from([2u8; 20]));
797
798        let mut addresses2 = AddressSet::default();
799        addresses2.insert(Address::from([2u8; 20])); // Different insertion order
800        addresses2.insert(Address::from([1u8; 20]));
801
802        let hash1 = hash_disallow_list(&addresses1);
803        let hash2 = hash_disallow_list(&addresses2);
804
805        assert_eq!(hash1, hash2);
806    }
807
808    #[test]
809    //ensures parity with rbuilder hashing https://github.com/flashbots/rbuilder/blob/962c8444cdd490a216beda22c7eec164db9fc3ac/crates/rbuilder/src/live_builder/block_list_provider.rs#L248
810    fn test_disallow_list_hash_rbuilder_parity() {
811        let json = r#"["0x05E0b5B40B7b66098C2161A5EE11C5740A3A7C45","0x01e2919679362dFBC9ee1644Ba9C6da6D6245BB1","0x03893a7c7463AE47D46bc7f091665f1893656003","0x04DBA1194ee10112fE6C3207C0687DEf0e78baCf"]"#;
812        let blocklist: Vec<Address> = serde_json::from_str(json).unwrap();
813        let blocklist: AddressSet = blocklist.into_iter().collect();
814        let expected_hash = "ee14e9d115e182f61871a5a385ab2f32ecf434f3b17bdbacc71044810d89e608";
815        let hash = hash_disallow_list(&blocklist);
816        assert_eq!(expected_hash, hash);
817    }
818}