1use self::blob_cache::BlobValidationCache;
2use alloy_consensus::{
3 BlobTransactionValidationError, BlockHeader, EnvKzgSettings, Transaction, TxReceipt,
4};
5use alloy_eip7928::{bal::DecodedBal, compute_block_access_list_hash};
6use alloy_eips::eip7685::RequestsOrHash;
7use alloy_primitives::{map::AddressSet, Address, B256, U256};
8use alloy_rpc_types_beacon::relay::{
9 BidTrace, BuilderBlockValidationRequest, BuilderBlockValidationRequestV2,
10 BuilderBlockValidationRequestV3, BuilderBlockValidationRequestV4,
11 BuilderBlockValidationRequestV5, BuilderBlockValidationRequestV6,
12};
13use alloy_rpc_types_engine::{
14 BlobsBundleV1, BlobsBundleV2, CancunPayloadFields, ExecutionData, ExecutionPayload,
15 ExecutionPayloadSidecar, PraguePayloadFields,
16};
17use core::fmt;
18use evm2::interpreter::gas::COLD_ACCOUNT_ACCESS_COST;
19use jsonrpsee::core::RpcResult;
20use jsonrpsee_types::error::ErrorObject;
21use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
22use reth_consensus::FullConsensus;
23use reth_consensus_common::validation::MAX_RLP_BLOCK_SIZE;
24use reth_engine_primitives::PayloadValidator;
25use reth_errors::{BlockExecutionError, ConsensusError, ProviderError};
26use reth_evm::{
27 cached::CachedReads, database::StateProviderDatabase, execute::Executor, ConfigureEvm,
28 SenderRecoveryCache,
29};
30use reth_execution_types::BlockExecutionOutput;
31use reth_metrics::{
32 metrics,
33 metrics::{gauge, Counter, Gauge},
34 Metrics,
35};
36use reth_payload_primitives::{NewPayloadError, PayloadTypes};
37use reth_primitives_traits::{
38 block::error::SealedBlockRecoveryError, BlockBody, GotExpected, NodePrimitives, RecoveredBlock,
39 SealedBlock, SealedHeaderFor,
40};
41use reth_rpc_api::BlockSubmissionValidationApiServer;
42use reth_rpc_server_types::result::{internal_rpc_err, invalid_params_rpc_err};
43use reth_storage_api::{
44 BlockReaderIdExt, HashedPostStateProvider, StateProvider, StateProviderFactory,
45};
46use reth_tasks::Runtime;
47use serde::{Deserialize, Serialize};
48use sha2::{Digest, Sha256};
49use std::sync::Arc;
50use tokio::sync::{oneshot, RwLock};
51use tracing::warn;
52
53mod blob_cache;
54
55#[derive(Clone, Debug, derive_more::Deref)]
57pub struct ValidationApi<Provider, E: ConfigureEvm, T: PayloadTypes> {
58 #[deref]
59 inner: Arc<ValidationApiInner<Provider, E, T>>,
60}
61
62impl<Provider, E, T> ValidationApi<Provider, E, T>
63where
64 E: ConfigureEvm,
65 T: PayloadTypes,
66{
67 pub fn new(
72 provider: Provider,
73 consensus: Arc<dyn FullConsensus<E::Primitives>>,
74 evm_config: E,
75 config: ValidationApiConfig,
76 task_spawner: Runtime,
77 payload_validator: Arc<
78 dyn PayloadValidator<T, Block = <E::Primitives as NodePrimitives>::Block>,
79 >,
80 sender_recovery_cache: Option<SenderRecoveryCache>,
81 ) -> Self {
82 let ValidationApiConfig { disallow, validation_window } = config;
83
84 let inner = Arc::new(ValidationApiInner {
85 provider,
86 consensus,
87 payload_validator,
88 evm_config,
89 disallow,
90 validation_window,
91 cached_state: Default::default(),
92 validated_blobs: Default::default(),
93 task_spawner,
94 sender_recovery_cache,
95 metrics: Default::default(),
96 });
97
98 inner.metrics.disallow_size.set(inner.disallow.len() as f64);
99
100 let disallow_hash = hash_disallow_list(&inner.disallow);
101 let hash_gauge = gauge!("builder_validation_disallow_hash", "hash" => disallow_hash);
102 hash_gauge.set(1.0);
103
104 Self { inner }
105 }
106
107 async fn cached_reads(&self, head: B256) -> CachedState {
109 let cache = self.inner.cached_state.read().await;
110 if cache.head == head {
111 cache.clone()
112 } else {
113 CachedState { head, ..Default::default() }
114 }
115 }
116
117 async fn update_cached_reads(&self, update: CachedState, gas: u64, max_gas: u64) {
122 let mut cache = self.inner.cached_state.write().await;
123 if cache.head == update.head {
124 let gas = cache.gas.saturating_add(gas);
128 if (update.generation == cache.generation || update.generation == 0) && gas <= max_gas {
129 cache.reads.extend(update.reads);
130 cache.gas = gas;
131 return
132 }
133 } else {
134 let gas = update.gas.saturating_add(gas);
135 if gas <= max_gas {
136 let generation = cache.generation + 1;
137 *cache = CachedState { generation, gas, ..update };
138 return
139 }
140 }
141 self.metrics.cached_reads_skipped.increment(1);
142 }
143
144 async fn spawn_validation<F>(&self, validation: F) -> RpcResult<()>
149 where
150 F: Future<Output = Result<(), ValidationApiError>> + Send + 'static,
151 {
152 let (mut tx, rx) = oneshot::channel();
153
154 self.task_spawner.spawn_blocking_task(async move {
155 let result = tokio::select! {
156 biased;
157 _ = tx.closed() => return,
158 result = validation => result.map_err(ErrorObject::from),
159 };
160 let _ = tx.send(result);
161 });
162
163 rx.await.map_err(|_| internal_rpc_err("Internal blocking task error"))?
164 }
165}
166
167impl<Provider, E, T> ValidationApi<Provider, E, T>
168where
169 Provider: BlockReaderIdExt<Header = <E::Primitives as NodePrimitives>::BlockHeader>
170 + ChainSpecProvider<ChainSpec: EthereumHardforks>
171 + StateProviderFactory
172 + 'static,
173 E: ConfigureEvm + 'static,
174 T: PayloadTypes<ExecutionData = ExecutionData>,
175{
176 pub async fn validate_message_against_block(
178 &self,
179 block: RecoveredBlock<<E::Primitives as NodePrimitives>::Block>,
180 message: BidTrace,
181 registered_gas_limit: u64,
182 decoded_bal: Option<DecodedBal>,
183 ) -> Result<(), ValidationApiError> {
184 self.validate_message_against_header(block.sealed_header(), &message)?;
185
186 self.consensus.validate_header(block.sealed_header())?;
187 self.consensus.validate_block_pre_execution(block.sealed_block())?;
188
189 if !self.disallow.is_empty() {
190 if self.disallow.contains(&block.beneficiary()) {
191 return Err(ValidationApiError::Blacklist(block.beneficiary()))
192 }
193 if self.disallow.contains(&message.proposer_fee_recipient) {
194 return Err(ValidationApiError::Blacklist(message.proposer_fee_recipient))
195 }
196 for (sender, tx) in block.senders_iter().zip(block.body().transactions()) {
197 if self.disallow.contains(sender) {
198 return Err(ValidationApiError::Blacklist(*sender))
199 }
200 if let Some(to) = tx.to() &&
201 self.disallow.contains(&to)
202 {
203 return Err(ValidationApiError::Blacklist(to))
204 }
205 }
206 }
207
208 let latest_header =
209 self.provider.latest_header()?.ok_or_else(|| ValidationApiError::MissingLatestBlock)?;
210
211 let parent_header = if block.parent_hash() == latest_header.hash() {
212 latest_header
213 } else {
214 let parent_header = self
216 .provider
217 .sealed_header_by_hash(block.parent_hash())?
218 .ok_or_else(|| ValidationApiError::MissingParentBlock)?;
219
220 if latest_header.number().saturating_sub(parent_header.number()) >
221 self.validation_window
222 {
223 return Err(ValidationApiError::BlockTooOld)
224 }
225 parent_header
226 };
227
228 self.consensus.validate_header_against_parent(block.sealed_header(), &parent_header)?;
229 parent_header.validate_gas_limit(registered_gas_limit, block.gas_limit()).map_err(
230 |err| {
231 ValidationApiError::GasLimitMismatch(GotExpected {
232 got: err.got,
233 expected: err.expected,
234 })
235 },
236 )?;
237
238 if let Some(decoded_bal) = decoded_bal {
240 decoded_bal
241 .as_bal()
242 .validate_gas_limit(block.gas_limit())
243 .map_err(ConsensusError::from)?;
244 }
245
246 let parent_header_hash = parent_header.hash();
247 let state_provider = self.provider.state_by_block_hash(parent_header_hash)?;
248
249 let mut request_cache = self.cached_reads(parent_header_hash).await;
250
251 let (output, block_access_list_hash) = {
252 let cached_db = request_cache
253 .reads
254 .as_db_mut(StateProviderDatabase::new((&state_provider).into_evm_state_provider()));
255 let mut executor = self.evm_config.batch_executor(cached_db);
256
257 let result = executor.execute_one(&block)?;
258
259 let block_access_list_hash =
264 executor.take_bal().map(|bal| compute_block_access_list_hash(&bal));
265
266 let state = executor.into_state();
267 if !self.disallow.is_empty() {
268 for account in request_cache.reads.accounts.keys().chain(state.state.keys()) {
271 if self.disallow.contains(account) {
272 return Err(ValidationApiError::Blacklist(*account))
273 }
274 }
275 }
276
277 (BlockExecutionOutput { state, result }, block_access_list_hash)
278 };
279
280 let withdrawals = block.body().withdrawals().map_or(0, |w| w.len() as u64);
283 let read_gas = output
284 .result
285 .gas_used
286 .saturating_add(withdrawals.saturating_mul(u64::from(COLD_ACCOUNT_ACCESS_COST)));
287 self.update_cached_reads(
288 request_cache,
289 read_gas,
290 block.gas_limit().saturating_mul(MAX_CACHED_READS_BLOCKS),
291 )
292 .await;
293
294 self.consensus.validate_block_post_execution(
295 &block,
296 &output,
297 None,
298 block_access_list_hash,
299 )?;
300
301 self.ensure_payment(&block, &output, &message)?;
302
303 let hashed_state = state_provider.hashed_post_state(&output.state)?;
304 let state_root = state_provider.state_root(hashed_state)?;
305
306 if state_root != block.header().state_root() {
307 return Err(ConsensusError::BodyStateRootDiff(
308 GotExpected { got: state_root, expected: block.header().state_root() }.into(),
309 )
310 .into())
311 }
312
313 Ok(())
314 }
315
316 fn validate_message_against_header(
318 &self,
319 header: &SealedHeaderFor<E::Primitives>,
320 message: &BidTrace,
321 ) -> Result<(), ValidationApiError> {
322 if header.hash() != message.block_hash {
323 Err(ValidationApiError::BlockHashMismatch(GotExpected {
324 got: message.block_hash,
325 expected: header.hash(),
326 }))
327 } else if header.parent_hash() != message.parent_hash {
328 Err(ValidationApiError::ParentHashMismatch(GotExpected {
329 got: message.parent_hash,
330 expected: header.parent_hash(),
331 }))
332 } else if header.gas_limit() != message.gas_limit {
333 Err(ValidationApiError::GasLimitMismatch(GotExpected {
334 got: message.gas_limit,
335 expected: header.gas_limit(),
336 }))
337 } else if header.gas_used() != message.gas_used {
338 Err(ValidationApiError::GasUsedMismatch(GotExpected {
339 got: message.gas_used,
340 expected: header.gas_used(),
341 }))
342 } else {
343 Ok(())
344 }
345 }
346
347 fn ensure_payment(
352 &self,
353 block: &SealedBlock<<E::Primitives as NodePrimitives>::Block>,
354 output: &BlockExecutionOutput<<E::Primitives as NodePrimitives>::Receipt>,
355 message: &BidTrace,
356 ) -> Result<(), ValidationApiError> {
357 if message.value.is_zero() {
359 return Ok(())
360 }
361
362 let (mut balance_before, balance_after) = if let Some(acc) =
363 output.account_state(&message.proposer_fee_recipient)
364 {
365 let balance_before = acc.original_info.as_ref().map(|i| i.balance).unwrap_or_default();
366 let balance_after = acc.info.as_ref().map(|i| i.balance).unwrap_or_default();
367
368 (balance_before, balance_after)
369 } else {
370 (U256::ZERO, U256::ZERO)
373 };
374
375 if let Some(withdrawals) = block.body().withdrawals() {
376 for withdrawal in withdrawals {
377 if withdrawal.address == message.proposer_fee_recipient {
378 balance_before += withdrawal.amount_wei();
379 }
380 }
381 }
382
383 if balance_after >= balance_before.saturating_add(message.value) {
384 return Ok(())
385 }
386
387 let (receipt, tx) = output
388 .receipts
389 .last()
390 .zip(block.body().transactions().last())
391 .ok_or(ValidationApiError::ProposerPayment)?;
392
393 if !receipt.status() {
394 return Err(ValidationApiError::ProposerPayment)
395 }
396
397 if tx.to() != Some(message.proposer_fee_recipient) {
398 return Err(ValidationApiError::ProposerPayment)
399 }
400
401 if tx.value() != message.value {
402 return Err(ValidationApiError::ProposerPayment)
403 }
404
405 if !tx.input().is_empty() {
406 return Err(ValidationApiError::ProposerPayment)
407 }
408
409 if let Some(block_base_fee) = block.header().base_fee_per_gas() &&
410 tx.effective_tip_per_gas(block_base_fee).unwrap_or_default() != 0
411 {
412 return Err(ValidationApiError::ProposerPayment)
413 }
414
415 Ok(())
416 }
417
418 pub fn validate_blobs_bundle(
420 &self,
421 blobs_bundle: BlobsBundleV1,
422 ) -> Result<Vec<B256>, ValidationApiError> {
423 let versioned_hashes = blobs_bundle.versioned_hashes();
424 let sidecar =
425 blobs_bundle.try_into_sidecar().map_err(|_| ValidationApiError::InvalidBlobsBundle)?;
426
427 sidecar.validate(&versioned_hashes, EnvKzgSettings::default().get())?;
428 Ok(versioned_hashes)
429 }
430
431 pub fn validate_blobs_bundle_v2(
437 &self,
438 blobs_bundle: BlobsBundleV2,
439 ) -> Result<Vec<B256>, ValidationApiError> {
440 self.validated_blobs.validate(blobs_bundle)
441 }
442
443 fn recover_payload(
455 &self,
456 payload: ExecutionData,
457 ) -> Result<RecoveredBlock<<E::Primitives as NodePrimitives>::Block>, ValidationApiError> {
458 let Some(cache) = &self.sender_recovery_cache else {
459 return self.payload_validator.ensure_well_formed_payload(payload).map_err(Into::into)
460 };
461
462 let block = Arc::unwrap_or_clone(self.payload_validator.convert_payload_to_block(payload)?);
463 let recovered = match cache.recover_signers(block.body().transactions()) {
464 Ok(senders) => Ok(RecoveredBlock::new_sealed(block, senders)),
465 Err(_) => Err(SealedBlockRecoveryError::new(block)),
466 };
467 recovered.map_err(|err| NewPayloadError::Other(err.into()).into())
468 }
469
470 async fn validate_builder_submission_v3(
472 &self,
473 request: BuilderBlockValidationRequestV3,
474 ) -> Result<(), ValidationApiError> {
475 let block = self.recover_payload(ExecutionData {
476 payload: ExecutionPayload::V3(request.request.execution_payload),
477 sidecar: ExecutionPayloadSidecar::v3(CancunPayloadFields {
478 parent_beacon_block_root: request.parent_beacon_block_root,
479 versioned_hashes: self.validate_blobs_bundle(request.request.blobs_bundle)?,
480 }),
481 })?;
482
483 self.validate_message_against_block(
484 block,
485 request.request.message,
486 request.registered_gas_limit,
487 None,
488 )
489 .await
490 }
491
492 async fn validate_builder_submission_v4(
494 &self,
495 request: BuilderBlockValidationRequestV4,
496 ) -> Result<(), ValidationApiError> {
497 let block = self.recover_payload(ExecutionData {
498 payload: ExecutionPayload::V3(request.request.execution_payload),
499 sidecar: ExecutionPayloadSidecar::v4(
500 CancunPayloadFields {
501 parent_beacon_block_root: request.parent_beacon_block_root,
502 versioned_hashes: self.validate_blobs_bundle(request.request.blobs_bundle)?,
503 },
504 PraguePayloadFields {
505 requests: RequestsOrHash::Requests(
506 request.request.execution_requests.to_requests(),
507 ),
508 },
509 ),
510 })?;
511
512 self.validate_message_against_block(
513 block,
514 request.request.message,
515 request.registered_gas_limit,
516 None,
517 )
518 .await
519 }
520
521 async fn validate_builder_submission_v5(
523 &self,
524 request: BuilderBlockValidationRequestV5,
525 ) -> Result<(), ValidationApiError> {
526 let payload = ExecutionPayload::V3(request.request.execution_payload);
527 validate_message_against_payload(&request.request.message, &payload)?;
528
529 let block = self.recover_payload(ExecutionData {
530 payload,
531 sidecar: ExecutionPayloadSidecar::v4(
532 CancunPayloadFields {
533 parent_beacon_block_root: request.parent_beacon_block_root,
534 versioned_hashes: self
535 .validate_blobs_bundle_v2(request.request.blobs_bundle)?,
536 },
537 PraguePayloadFields {
538 requests: RequestsOrHash::Requests(
539 request.request.execution_requests.to_requests(),
540 ),
541 },
542 ),
543 })?;
544
545 let chain_spec = self.provider.chain_spec();
547 if chain_spec.is_osaka_active_at_timestamp(block.timestamp()) {
548 let rlp_length = block.rlp_length();
549 if rlp_length > MAX_RLP_BLOCK_SIZE {
550 return Err(ValidationApiError::Consensus(ConsensusError::BlockTooLarge {
551 rlp_length,
552 max_rlp_length: MAX_RLP_BLOCK_SIZE,
553 }));
554 }
555 }
556
557 self.validate_message_against_block(
558 block,
559 request.request.message,
560 request.registered_gas_limit,
561 None,
562 )
563 .await
564 }
565
566 async fn validate_builder_submission_v6(
568 &self,
569 request: BuilderBlockValidationRequestV6,
570 ) -> Result<(), ValidationApiError> {
571 let payload = ExecutionPayload::V4(request.request.execution_payload);
572 validate_message_against_payload(&request.request.message, &payload)?;
573
574 let decoded_bal =
575 DecodedBal::from_rlp_bytes(payload.as_v4().unwrap().block_access_list.clone())
576 .map_err(ValidationApiError::InvalidBlockAccessList)?;
577
578 let block = self.recover_payload(ExecutionData {
579 payload,
580 sidecar: ExecutionPayloadSidecar::v4(
581 CancunPayloadFields {
582 parent_beacon_block_root: request.parent_beacon_block_root,
583 versioned_hashes: self
584 .validate_blobs_bundle_v2(request.request.blobs_bundle)?,
585 },
586 PraguePayloadFields {
587 requests: RequestsOrHash::Requests(
588 request.request.execution_requests.to_requests(),
589 ),
590 },
591 ),
592 })?;
593
594 let chain_spec = self.provider.chain_spec();
595 if chain_spec.is_osaka_active_at_timestamp(block.timestamp()) {
596 let rlp_length = block.rlp_length();
597 if rlp_length > MAX_RLP_BLOCK_SIZE {
598 return Err(ValidationApiError::Consensus(ConsensusError::BlockTooLarge {
599 rlp_length,
600 max_rlp_length: MAX_RLP_BLOCK_SIZE,
601 }));
602 }
603 }
604
605 self.validate_message_against_block(
606 block,
607 request.request.message,
608 request.registered_gas_limit,
609 Some(decoded_bal),
610 )
611 .await
612 }
613}
614
615impl<Provider, E, T> BlockSubmissionValidationApiServer for ValidationApi<Provider, E, T>
616where
617 Provider: BlockReaderIdExt<Header = <E::Primitives as NodePrimitives>::BlockHeader>
618 + ChainSpecProvider<ChainSpec: EthereumHardforks>
619 + StateProviderFactory
620 + Clone
621 + 'static,
622 E: ConfigureEvm + 'static,
623 T: PayloadTypes<ExecutionData = ExecutionData>,
624{
625 async fn validate_builder_submission_v1(
626 &self,
627 _request: BuilderBlockValidationRequest,
628 ) -> RpcResult<()> {
629 warn!(target: "rpc::flashbots", "Method `flashbots_validateBuilderSubmissionV1` is not supported");
630 Err(internal_rpc_err("unimplemented"))
631 }
632
633 async fn validate_builder_submission_v2(
634 &self,
635 _request: BuilderBlockValidationRequestV2,
636 ) -> RpcResult<()> {
637 warn!(target: "rpc::flashbots", "Method `flashbots_validateBuilderSubmissionV2` is not supported");
638 Err(internal_rpc_err("unimplemented"))
639 }
640
641 async fn validate_builder_submission_v3(
643 &self,
644 request: BuilderBlockValidationRequestV3,
645 ) -> RpcResult<()> {
646 let this = self.clone();
647 let validation = async move { Self::validate_builder_submission_v3(&this, request).await };
648 self.spawn_validation(validation).await
649 }
650
651 async fn validate_builder_submission_v4(
653 &self,
654 request: BuilderBlockValidationRequestV4,
655 ) -> RpcResult<()> {
656 let this = self.clone();
657 let validation = async move { Self::validate_builder_submission_v4(&this, request).await };
658 self.spawn_validation(validation).await
659 }
660
661 async fn validate_builder_submission_v5(
663 &self,
664 request: BuilderBlockValidationRequestV5,
665 ) -> RpcResult<()> {
666 let this = self.clone();
667 let validation = async move { Self::validate_builder_submission_v5(&this, request).await };
668 self.spawn_validation(validation).await
669 }
670
671 async fn validate_builder_submission_v6(
673 &self,
674 request: BuilderBlockValidationRequestV6,
675 ) -> RpcResult<()> {
676 let this = self.clone();
677 let validation = async move { Self::validate_builder_submission_v6(&this, request).await };
678 self.spawn_validation(validation).await
679 }
680}
681
682pub struct ValidationApiInner<Provider, E: ConfigureEvm, T: PayloadTypes> {
683 provider: Provider,
685 consensus: Arc<dyn FullConsensus<E::Primitives>>,
687 payload_validator:
689 Arc<dyn PayloadValidator<T, Block = <E::Primitives as NodePrimitives>::Block>>,
690 evm_config: E,
692 disallow: AddressSet,
694 validation_window: u64,
696 cached_state: RwLock<CachedState>,
700 validated_blobs: BlobValidationCache,
702 task_spawner: Runtime,
704 sender_recovery_cache: Option<SenderRecoveryCache>,
707 metrics: ValidationMetrics,
709}
710
711const MAX_CACHED_READS_BLOCKS: u64 = 16;
713
714#[derive(Debug, Clone, Default)]
716struct CachedState {
717 head: B256,
719 generation: u64,
721 reads: CachedReads,
723 gas: u64,
725}
726
727fn validate_message_against_payload(
729 message: &BidTrace,
730 payload: &ExecutionPayload,
731) -> Result<(), ValidationApiError> {
732 let payload = payload.as_v1();
733
734 if payload.block_hash != message.block_hash {
735 Err(ValidationApiError::BlockHashMismatch(GotExpected {
736 got: message.block_hash,
737 expected: payload.block_hash,
738 }))
739 } else if payload.parent_hash != message.parent_hash {
740 Err(ValidationApiError::ParentHashMismatch(GotExpected {
741 got: message.parent_hash,
742 expected: payload.parent_hash,
743 }))
744 } else if payload.gas_limit != message.gas_limit {
745 Err(ValidationApiError::GasLimitMismatch(GotExpected {
746 got: message.gas_limit,
747 expected: payload.gas_limit,
748 }))
749 } else if payload.gas_used != message.gas_used {
750 Err(ValidationApiError::GasUsedMismatch(GotExpected {
751 got: message.gas_used,
752 expected: payload.gas_used,
753 }))
754 } else {
755 Ok(())
756 }
757}
758
759fn hash_disallow_list(disallow: &AddressSet) -> String {
764 let mut sorted: Vec<_> = disallow.iter().collect();
765 sorted.sort_unstable(); let mut hasher = Sha256::new();
768 for addr in sorted {
769 hasher.update(addr.as_slice());
770 }
771
772 format!("{:x}", hasher.finalize())
773}
774
775impl<Provider, E: ConfigureEvm, T: PayloadTypes> fmt::Debug for ValidationApiInner<Provider, E, T> {
776 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777 f.debug_struct("ValidationApiInner").finish_non_exhaustive()
778 }
779}
780
781#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
783pub struct ValidationApiConfig {
784 pub disallow: AddressSet,
786 pub validation_window: u64,
788}
789
790impl ValidationApiConfig {
791 pub const DEFAULT_VALIDATION_WINDOW: u64 = 3;
793}
794
795impl Default for ValidationApiConfig {
796 fn default() -> Self {
797 Self { disallow: Default::default(), validation_window: Self::DEFAULT_VALIDATION_WINDOW }
798 }
799}
800
801#[derive(Debug, thiserror::Error)]
803pub enum ValidationApiError {
804 #[error("block gas limit mismatch: {_0}")]
805 GasLimitMismatch(GotExpected<u64>),
806 #[error("block gas used mismatch: {_0}")]
807 GasUsedMismatch(GotExpected<u64>),
808 #[error("block parent hash mismatch: {_0}")]
809 ParentHashMismatch(GotExpected<B256>),
810 #[error("block hash mismatch: {_0}")]
811 BlockHashMismatch(GotExpected<B256>),
812 #[error("missing latest block in database")]
813 MissingLatestBlock,
814 #[error("parent block not found")]
815 MissingParentBlock,
816 #[error("block is too old, outside validation window")]
817 BlockTooOld,
818 #[error("could not verify proposer payment")]
819 ProposerPayment,
820 #[error("invalid blobs bundle")]
821 InvalidBlobsBundle,
822 #[error("invalid block access list: {_0}")]
823 InvalidBlockAccessList(alloy_rlp::Error),
824 #[error("block accesses blacklisted address: {_0}")]
825 Blacklist(Address),
826 #[error(transparent)]
827 Blob(#[from] BlobTransactionValidationError),
828 #[error(transparent)]
829 Consensus(#[from] ConsensusError),
830 #[error(transparent)]
831 Provider(#[from] ProviderError),
832 #[error(transparent)]
833 Execution(#[from] BlockExecutionError),
834 #[error(transparent)]
835 Payload(#[from] NewPayloadError),
836}
837
838impl From<ValidationApiError> for ErrorObject<'static> {
839 fn from(error: ValidationApiError) -> Self {
840 match error {
841 ValidationApiError::GasLimitMismatch(_) |
842 ValidationApiError::GasUsedMismatch(_) |
843 ValidationApiError::ParentHashMismatch(_) |
844 ValidationApiError::BlockHashMismatch(_) |
845 ValidationApiError::Blacklist(_) |
846 ValidationApiError::ProposerPayment |
847 ValidationApiError::InvalidBlobsBundle |
848 ValidationApiError::InvalidBlockAccessList(_) |
849 ValidationApiError::Blob(_) |
850 ValidationApiError::Consensus(_) => invalid_params_rpc_err(error.to_string()),
851
852 ValidationApiError::MissingLatestBlock |
853 ValidationApiError::MissingParentBlock |
854 ValidationApiError::BlockTooOld |
855 ValidationApiError::Provider(_) => internal_rpc_err(error.to_string()),
856 ValidationApiError::Execution(err) => match err {
857 error @ BlockExecutionError::Validation(_) => {
858 invalid_params_rpc_err(error.to_string())
859 }
860 error @ BlockExecutionError::Internal(_) => internal_rpc_err(error.to_string()),
861 },
862 ValidationApiError::Payload(err) => match err {
863 error @ NewPayloadError::Eth(_) => invalid_params_rpc_err(error.to_string()),
864 error @ NewPayloadError::Other(_) => internal_rpc_err(error.to_string()),
865 },
866 }
867 }
868}
869
870#[derive(Metrics)]
872#[metrics(scope = "builder.validation")]
873pub(crate) struct ValidationMetrics {
874 pub(crate) disallow_size: Gauge,
876 pub(crate) cached_reads_skipped: Counter,
878}
879
880#[cfg(test)]
881mod tests {
882 use super::{
883 hash_disallow_list, validate_message_against_payload, AddressSet, CachedState,
884 ValidationApi, ValidationApiConfig, ValidationApiError,
885 };
886 use alloy_consensus::{BlockHeader, Header};
887 use alloy_primitives::{Address, B256, U256};
888 use alloy_rpc_types_beacon::relay::BidTrace;
889 use alloy_rpc_types_engine::{ExecutionData, ExecutionPayload, ExecutionPayloadV1};
890 use evm2::evm::AccountInfo;
891 use reth_consensus::noop::NoopConsensus;
892 use reth_engine_primitives::PayloadValidator;
893 use reth_errors::ConsensusError;
894 use reth_ethereum_engine_primitives::EthPayloadTypes;
895 use reth_ethereum_primitives::Block;
896 use reth_evm_ethereum::EthEvmConfig;
897 use reth_execution_types::BlockExecutionOutput;
898 use reth_payload_primitives::NewPayloadError;
899 use reth_primitives_traits::{RecoveredBlock, SealedBlock, SealedHeader};
900 use reth_provider::test_utils::MockEthProvider;
901 use reth_tasks::Runtime;
902 use reth_trie_common::bundle_state::{AccountStatus, BundleAccount, BundleState};
903 use std::sync::Arc;
904
905 fn test_execution_payload() -> ExecutionPayload {
906 ExecutionPayload::V1(ExecutionPayloadV1 {
907 parent_hash: B256::repeat_byte(0x11),
908 fee_recipient: Address::ZERO,
909 state_root: B256::ZERO,
910 receipts_root: B256::ZERO,
911 logs_bloom: Default::default(),
912 prev_randao: B256::ZERO,
913 block_number: 1,
914 gas_limit: 30_000_000,
915 gas_used: 15_000_000,
916 timestamp: 1,
917 extra_data: Default::default(),
918 base_fee_per_gas: Default::default(),
919 block_hash: B256::repeat_byte(0x22),
920 transactions: Default::default(),
921 })
922 }
923
924 fn matching_bid_trace(payload: &ExecutionPayload) -> BidTrace {
925 let payload = payload.as_v1();
926 BidTrace {
927 parent_hash: payload.parent_hash,
928 block_hash: payload.block_hash,
929 gas_limit: payload.gas_limit,
930 gas_used: payload.gas_used,
931 ..Default::default()
932 }
933 }
934
935 #[test]
936 fn test_validate_message_against_payload_block_hash_mismatch() {
937 let payload = test_execution_payload();
938 let mut message = matching_bid_trace(&payload);
939 message.block_hash = B256::repeat_byte(0x33);
940
941 let err = validate_message_against_payload(&message, &payload).unwrap_err();
942 let ValidationApiError::BlockHashMismatch(mismatch) = err else {
943 panic!("unexpected error: {err}")
944 };
945 assert_eq!(mismatch.got, message.block_hash);
946 assert_eq!(mismatch.expected, payload.block_hash());
947 }
948
949 #[test]
950 fn test_validate_message_against_payload_parent_hash_mismatch() {
951 let payload = test_execution_payload();
952 let mut message = matching_bid_trace(&payload);
953 message.parent_hash = B256::repeat_byte(0x33);
954
955 let err = validate_message_against_payload(&message, &payload).unwrap_err();
956 let ValidationApiError::ParentHashMismatch(mismatch) = err else {
957 panic!("unexpected error: {err}")
958 };
959 assert_eq!(mismatch.got, message.parent_hash);
960 assert_eq!(mismatch.expected, payload.parent_hash());
961 }
962
963 #[test]
964 fn test_validate_message_against_payload_gas_limit_mismatch() {
965 let payload = test_execution_payload();
966 let mut message = matching_bid_trace(&payload);
967 message.gas_limit += 1;
968
969 let err = validate_message_against_payload(&message, &payload).unwrap_err();
970 let ValidationApiError::GasLimitMismatch(mismatch) = err else {
971 panic!("unexpected error: {err}")
972 };
973 assert_eq!(mismatch.got, message.gas_limit);
974 assert_eq!(mismatch.expected, payload.gas_limit());
975 }
976
977 #[test]
978 fn test_validate_message_against_payload_gas_used_mismatch() {
979 let payload = test_execution_payload();
980 let mut message = matching_bid_trace(&payload);
981 message.gas_used += 1;
982
983 let err = validate_message_against_payload(&message, &payload).unwrap_err();
984 let ValidationApiError::GasUsedMismatch(mismatch) = err else {
985 panic!("unexpected error: {err}")
986 };
987 assert_eq!(mismatch.got, message.gas_used);
988 assert_eq!(mismatch.expected, payload.as_v1().gas_used);
989 }
990
991 #[test]
992 fn test_hash_disallow_list_deterministic() {
993 let mut addresses = AddressSet::default();
994 addresses.insert(Address::repeat_byte(1u8));
995 addresses.insert(Address::repeat_byte(2u8));
996
997 let hash1 = hash_disallow_list(&addresses);
998 let hash2 = hash_disallow_list(&addresses);
999
1000 assert_eq!(hash1, hash2);
1001 }
1002
1003 #[test]
1004 fn test_hash_disallow_list_different_content() {
1005 let mut addresses1 = AddressSet::default();
1006 addresses1.insert(Address::repeat_byte(1u8));
1007
1008 let mut addresses2 = AddressSet::default();
1009 addresses2.insert(Address::repeat_byte(2u8));
1010
1011 let hash1 = hash_disallow_list(&addresses1);
1012 let hash2 = hash_disallow_list(&addresses2);
1013
1014 assert_ne!(hash1, hash2);
1015 }
1016
1017 #[test]
1018 fn test_hash_disallow_list_order_independent() {
1019 let mut addresses1 = AddressSet::default();
1020 addresses1.insert(Address::repeat_byte(1u8));
1021 addresses1.insert(Address::repeat_byte(2u8));
1022
1023 let mut addresses2 = AddressSet::default();
1024 addresses2.insert(Address::repeat_byte(2u8)); addresses2.insert(Address::repeat_byte(1u8));
1026
1027 let hash1 = hash_disallow_list(&addresses1);
1028 let hash2 = hash_disallow_list(&addresses2);
1029
1030 assert_eq!(hash1, hash2);
1031 }
1032
1033 #[test]
1034 fn test_disallow_list_hash_rbuilder_parity() {
1036 let json = r#"["0x05E0b5B40B7b66098C2161A5EE11C5740A3A7C45","0x01e2919679362dFBC9ee1644Ba9C6da6D6245BB1","0x03893a7c7463AE47D46bc7f091665f1893656003","0x04DBA1194ee10112fE6C3207C0687DEf0e78baCf"]"#;
1037 let blocklist: Vec<Address> = serde_json::from_str(json).unwrap();
1038 let blocklist: AddressSet = blocklist.into_iter().collect();
1039 let expected_hash = "ee14e9d115e182f61871a5a385ab2f32ecf434f3b17bdbacc71044810d89e608";
1040 let hash = hash_disallow_list(&blocklist);
1041 assert_eq!(expected_hash, hash);
1042 }
1043
1044 #[derive(Debug)]
1047 struct UnusedPayloadValidator;
1048
1049 impl PayloadValidator<EthPayloadTypes> for UnusedPayloadValidator {
1050 type Block = Block;
1051
1052 fn convert_payload_to_block(
1053 &self,
1054 _payload: ExecutionData,
1055 ) -> Result<Arc<SealedBlock<Self::Block>>, NewPayloadError> {
1056 unimplemented!()
1057 }
1058 }
1059
1060 #[derive(Debug)]
1061 struct SpecializedPayloadValidator;
1062
1063 impl PayloadValidator<EthPayloadTypes> for SpecializedPayloadValidator {
1064 type Block = Block;
1065
1066 fn convert_payload_to_block(
1067 &self,
1068 _payload: ExecutionData,
1069 ) -> Result<Arc<SealedBlock<Self::Block>>, NewPayloadError> {
1070 panic!("the specialized recovery method must be used without a cache")
1071 }
1072
1073 fn ensure_well_formed_payload(
1074 &self,
1075 _payload: ExecutionData,
1076 ) -> Result<RecoveredBlock<Self::Block>, NewPayloadError> {
1077 Ok(SealedBlock::seal_slow(Block::default()).try_recover().unwrap())
1078 }
1079 }
1080
1081 #[test]
1082 fn recover_payload_without_cache_uses_validator_override() {
1083 let api = ValidationApi::new(
1084 MockEthProvider::default(),
1085 NoopConsensus::arc(),
1086 EthEvmConfig::mainnet(),
1087 ValidationApiConfig::default(),
1088 Runtime::test(),
1089 Arc::new(SpecializedPayloadValidator),
1090 None,
1091 );
1092
1093 api.recover_payload(ExecutionData {
1094 payload: test_execution_payload(),
1095 sidecar: Default::default(),
1096 })
1097 .unwrap();
1098 }
1099
1100 fn test_validation_api(
1101 provider: MockEthProvider,
1102 ) -> ValidationApi<MockEthProvider, EthEvmConfig, EthPayloadTypes> {
1103 ValidationApi::new(
1104 provider,
1105 NoopConsensus::arc(),
1106 EthEvmConfig::mainnet(),
1107 ValidationApiConfig::default(),
1108 Runtime::test(),
1109 Arc::new(UnusedPayloadValidator),
1110 None,
1111 )
1112 }
1113
1114 fn payment_free_submission() -> (MockEthProvider, RecoveredBlock<Block>, BidTrace) {
1117 let provider = MockEthProvider::default();
1118
1119 let parent = Header { gas_limit: 30_000_000, ..Default::default() };
1120 let parent = SealedHeader::seal_slow(parent);
1121 provider.add_block(
1122 parent.hash(),
1123 Block { header: parent.clone_header(), body: Default::default() },
1124 );
1125
1126 let header = Header {
1127 parent_hash: parent.hash(),
1128 number: parent.number() + 1,
1129 gas_limit: parent.gas_limit(),
1130 timestamp: parent.timestamp() + 12,
1131 ..Default::default()
1132 };
1133 let block = SealedBlock::seal_slow(Block { header, body: Default::default() })
1134 .try_recover()
1135 .unwrap();
1136 provider.state_roots.lock().push(block.state_root());
1137
1138 let message = BidTrace {
1139 parent_hash: block.parent_hash(),
1140 block_hash: block.hash(),
1141 gas_limit: block.gas_limit(),
1142 gas_used: block.gas_used(),
1143 proposer_fee_recipient: Address::repeat_byte(0x42),
1144 value: U256::from(1_000_000_000_000_000_000u64),
1145 ..Default::default()
1146 };
1147
1148 (provider, block, message)
1149 }
1150
1151 #[tokio::test]
1152 async fn execution_invalid_submission_is_invalid_params() {
1153 let (provider, parent_block, mut message) = payment_free_submission();
1154 let transaction = reth_ethereum_primitives::TransactionSigned::new_unhashed(
1155 reth_ethereum_primitives::Transaction::Legacy(alloy_consensus::TxLegacy {
1156 gas_limit: 20_999,
1157 to: alloy_primitives::TxKind::Call(Address::with_last_byte(1)),
1158 ..Default::default()
1159 }),
1160 alloy_primitives::Signature::test_signature(),
1161 );
1162 let block = RecoveredBlock::new_unhashed(
1163 Block {
1164 header: parent_block.clone_header(),
1165 body: alloy_consensus::BlockBody {
1166 transactions: vec![transaction],
1167 ..Default::default()
1168 },
1169 },
1170 vec![Address::ZERO],
1171 );
1172 message.block_hash = block.hash();
1173 let error = test_validation_api(provider)
1174 .validate_message_against_block(block, message, parent_block.gas_limit(), None)
1175 .await
1176 .unwrap_err();
1177 assert!(
1178 matches!(
1179 error,
1180 ValidationApiError::Execution(reth_errors::BlockExecutionError::Validation(_))
1181 ),
1182 "{error}"
1183 );
1184 let error = jsonrpsee::types::ErrorObjectOwned::from(error);
1185 assert_eq!(error.code(), jsonrpsee::types::error::INVALID_PARAMS_CODE);
1186 }
1187
1188 #[tokio::test]
1189 async fn consensus_invalid_submission_is_invalid_params() {
1190 let (provider, block, mut message) = payment_free_submission();
1191 *provider.state_roots.lock() = vec![B256::repeat_byte(0xab)];
1194 message.value = U256::ZERO;
1197 let registered_gas_limit = block.gas_limit();
1198
1199 let error = test_validation_api(provider)
1200 .validate_message_against_block(block, message, registered_gas_limit, None)
1201 .await
1202 .unwrap_err();
1203 assert!(
1204 matches!(error, ValidationApiError::Consensus(ConsensusError::BodyStateRootDiff(_))),
1205 "{error}"
1206 );
1207 let error = jsonrpsee::types::ErrorObjectOwned::from(error);
1208 assert_eq!(error.code(), jsonrpsee::types::error::INVALID_PARAMS_CODE);
1209 }
1210
1211 #[test]
1212 fn node_fault_is_internal_error() {
1213 let error =
1214 jsonrpsee::types::ErrorObjectOwned::from(ValidationApiError::MissingParentBlock);
1215 assert_eq!(error.code(), jsonrpsee::types::error::INTERNAL_ERROR_CODE);
1216 }
1217
1218 #[tokio::test]
1219 async fn test_payment_check_runs_for_a_nonzero_bid() {
1220 let (provider, block, message) = payment_free_submission();
1221 let registered_gas_limit = block.gas_limit();
1222
1223 let err = test_validation_api(provider)
1224 .validate_message_against_block(block, message, registered_gas_limit, None)
1225 .await
1226 .unwrap_err();
1227
1228 assert!(matches!(err, ValidationApiError::ProposerPayment), "unexpected error: {err}");
1229 }
1230
1231 #[tokio::test]
1232 async fn test_zero_value_bid_skips_the_payment_check() {
1233 let (provider, block, mut message) = payment_free_submission();
1234 let registered_gas_limit = block.gas_limit();
1235 message.value = U256::ZERO;
1236
1237 test_validation_api(provider)
1238 .validate_message_against_block(block, message, registered_gas_limit, None)
1239 .await
1240 .unwrap();
1241 }
1242
1243 #[test]
1248 fn test_zero_value_bid_is_accepted_when_the_fee_recipient_spends() {
1249 let (provider, block, mut message) = payment_free_submission();
1250 message.value = U256::ZERO;
1251
1252 let output = BlockExecutionOutput {
1253 result: Default::default(),
1254 state: fee_recipient_spent(message.proposer_fee_recipient),
1255 };
1256
1257 test_validation_api(provider)
1258 .ensure_payment(block.sealed_block(), &output, &message)
1259 .unwrap();
1260 }
1261
1262 fn fee_recipient_spent(address: Address) -> BundleState {
1264 let balance =
1265 |wei: u64| Some(AccountInfo { balance: U256::from(wei), ..Default::default() });
1266
1267 let mut state = BundleState::default();
1268 state.state.insert(
1269 address,
1270 BundleAccount {
1271 original_info: balance(1_000),
1272 info: balance(999),
1273 storage: Default::default(),
1274 status: AccountStatus::Changed,
1275 },
1276 );
1277 state
1278 }
1279
1280 async fn cached_reads_with(
1282 api: &ValidationApi<MockEthProvider, EthEvmConfig, EthPayloadTypes>,
1283 head: B256,
1284 address: Address,
1285 ) -> CachedState {
1286 let mut update = api.cached_reads(head).await;
1287 update.reads.insert_account(address, AccountInfo::default(), Default::default());
1288 update
1289 }
1290
1291 #[tokio::test]
1292 async fn test_cached_reads_stop_growing_at_the_gas_budget() {
1293 let api = test_validation_api(MockEthProvider::default());
1294 let head = B256::repeat_byte(0x11);
1295
1296 let first = cached_reads_with(&api, head, Address::repeat_byte(1)).await;
1297 api.update_cached_reads(first, 60, 100).await;
1298 let second = cached_reads_with(&api, head, Address::repeat_byte(2)).await;
1299 api.update_cached_reads(second, 40, 100).await;
1300 let third = cached_reads_with(&api, head, Address::repeat_byte(3)).await;
1301 api.update_cached_reads(third, 1, 100).await;
1302
1303 let cache = api.cached_reads(head).await;
1304 assert_eq!(cache.gas, 100);
1305 assert_eq!(cache.reads.accounts.len(), 2);
1306 assert!(!cache.reads.accounts.contains_key(&Address::repeat_byte(3)));
1307 }
1308
1309 #[tokio::test]
1310 async fn test_cached_reads_of_a_replaced_cache_are_not_merged() {
1311 let api = test_validation_api(MockEthProvider::default());
1312 let (head, other) = (B256::repeat_byte(0x11), B256::repeat_byte(0x22));
1313
1314 let first = cached_reads_with(&api, head, Address::repeat_byte(1)).await;
1315 api.update_cached_reads(first, 10, 100).await;
1316 let stale = cached_reads_with(&api, head, Address::repeat_byte(2)).await;
1317
1318 let replacement = cached_reads_with(&api, other, Address::repeat_byte(3)).await;
1320 api.update_cached_reads(replacement, 10, 100).await;
1321 let replacement = cached_reads_with(&api, head, Address::repeat_byte(4)).await;
1322 api.update_cached_reads(replacement, 10, 100).await;
1323
1324 api.update_cached_reads(stale, 10, 100).await;
1325
1326 let cache = api.cached_reads(head).await;
1327 assert_eq!(cache.gas, 10);
1328 assert_eq!(cache.reads.accounts.len(), 1);
1329 assert!(cache.reads.accounts.contains_key(&Address::repeat_byte(4)));
1330 }
1331
1332 #[tokio::test]
1333 async fn test_replacing_cached_reads_keeps_the_gas_of_the_copy() {
1334 let api = test_validation_api(MockEthProvider::default());
1335 let (head, other) = (B256::repeat_byte(0x11), B256::repeat_byte(0x22));
1336
1337 let first = cached_reads_with(&api, head, Address::repeat_byte(1)).await;
1338 api.update_cached_reads(first, 60, 100).await;
1339 let copy = cached_reads_with(&api, head, Address::repeat_byte(2)).await;
1340
1341 let replacement = cached_reads_with(&api, other, Address::repeat_byte(3)).await;
1342 api.update_cached_reads(replacement, 10, 100).await;
1343
1344 api.update_cached_reads(copy, 30, 100).await;
1346 let cache = api.cached_reads(head).await;
1347 assert_eq!(cache.gas, 90);
1348 assert_eq!(cache.reads.accounts.len(), 2);
1349
1350 let next = cached_reads_with(&api, head, Address::repeat_byte(4)).await;
1351 api.update_cached_reads(next, 20, 100).await;
1352 assert_eq!(api.cached_reads(head).await.gas, 90);
1353 }
1354
1355 #[tokio::test]
1356 async fn test_cached_reads_replacement_respects_the_gas_budget() {
1357 let api = test_validation_api(MockEthProvider::default());
1358 let (head, other) = (B256::repeat_byte(0x11), B256::repeat_byte(0x22));
1359
1360 let first = cached_reads_with(&api, head, Address::repeat_byte(1)).await;
1361 api.update_cached_reads(first, 60, 100).await;
1362 let copy = cached_reads_with(&api, head, Address::repeat_byte(2)).await;
1363
1364 let replacement = cached_reads_with(&api, other, Address::repeat_byte(3)).await;
1365 api.update_cached_reads(replacement, 10, 100).await;
1366
1367 api.update_cached_reads(copy, 50, 100).await;
1369 let cache = api.cached_reads(other).await;
1370 assert_eq!(cache.gas, 10);
1371 assert_eq!(cache.reads.accounts.len(), 1);
1372 }
1373
1374 #[tokio::test]
1375 async fn test_cached_reads_of_an_uncached_head_are_merged() {
1376 let api = test_validation_api(MockEthProvider::default());
1377 let head = B256::repeat_byte(0x11);
1378
1379 let first = cached_reads_with(&api, head, Address::repeat_byte(1)).await;
1381 let second = cached_reads_with(&api, head, Address::repeat_byte(2)).await;
1382 api.update_cached_reads(first, 10, 100).await;
1383 api.update_cached_reads(second, 10, 100).await;
1384
1385 let cache = api.cached_reads(head).await;
1386 assert_eq!(cache.gas, 20);
1387 assert_eq!(cache.reads.accounts.len(), 2);
1388 }
1389}