1#![doc(
4 html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5 html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6 issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10#![cfg_attr(not(feature = "std"), no_std)]
11
12extern crate alloc;
13
14use alloc::{fmt::Debug, sync::Arc};
15use alloy_consensus::{constants::MAXIMUM_EXTRA_DATA_SIZE, EMPTY_OMMER_ROOT_HASH};
16use alloy_eips::eip7840::BlobParams;
17use alloy_primitives::B256;
18use reth_chainspec::{EthChainSpec, EthereumHardforks};
19use reth_consensus::{
20 Consensus, ConsensusError, FullConsensus, HeaderValidator, ReceiptRootBloom, TransactionRoot,
21};
22use reth_consensus_common::validation::{
23 validate_4844_header_standalone, validate_against_parent_4844,
24 validate_against_parent_eip1559_base_fee, validate_against_parent_gas_limit,
25 validate_against_parent_hash_number, validate_against_parent_timestamp,
26 validate_block_pre_execution, validate_block_pre_execution_with_tx_root,
27 validate_body_against_header, validate_header_base_fee, validate_header_extra_data,
28 validate_header_gas,
29};
30use reth_execution_types::BlockExecutionResult;
31use reth_primitives_traits::{
32 Block, BlockHeader, NodePrimitives, RecoveredBlock, SealedBlock, SealedHeader,
33};
34
35mod validation;
36pub use validation::{
37 compare_receipts_root_and_logs_bloom, validate_block_post_execution, verify_receipts,
38};
39
40#[derive(Debug, Clone)]
44pub struct EthBeaconConsensus<ChainSpec> {
45 chain_spec: Arc<ChainSpec>,
47 max_extra_data_size: usize,
49 skip_gas_limit_ramp_check: bool,
51 skip_blob_gas_used_check: bool,
53 skip_requests_hash_check: bool,
55 allow_bal_hashes: bool,
57}
58
59impl<ChainSpec: EthChainSpec + EthereumHardforks> EthBeaconConsensus<ChainSpec> {
60 pub const fn new(chain_spec: Arc<ChainSpec>) -> Self {
62 Self {
63 chain_spec,
64 max_extra_data_size: MAXIMUM_EXTRA_DATA_SIZE,
65 skip_gas_limit_ramp_check: false,
66 skip_blob_gas_used_check: false,
67 skip_requests_hash_check: false,
68 allow_bal_hashes: false,
69 }
70 }
71
72 pub const fn max_extra_data_size(&self) -> usize {
74 self.max_extra_data_size
75 }
76
77 pub const fn with_max_extra_data_size(mut self, size: usize) -> Self {
79 self.max_extra_data_size = size;
80 self
81 }
82
83 pub const fn with_skip_gas_limit_ramp_check(mut self, skip: bool) -> Self {
85 self.skip_gas_limit_ramp_check = skip;
86 self
87 }
88
89 pub const fn with_skip_blob_gas_used_check(mut self, skip: bool) -> Self {
91 self.skip_blob_gas_used_check = skip;
92 self
93 }
94
95 pub const fn with_skip_requests_hash_check(mut self, skip: bool) -> Self {
97 self.skip_requests_hash_check = skip;
98 self
99 }
100
101 pub const fn with_allow_bal_hashes(mut self, allow: bool) -> Self {
103 self.allow_bal_hashes = allow;
104 self
105 }
106
107 pub const fn chain_spec(&self) -> &Arc<ChainSpec> {
109 &self.chain_spec
110 }
111}
112
113impl<ChainSpec, N> FullConsensus<N> for EthBeaconConsensus<ChainSpec>
114where
115 ChainSpec: Send + EthChainSpec<Header = N::BlockHeader> + EthereumHardforks,
116 N: NodePrimitives,
117{
118 fn validate_block_post_execution(
119 &self,
120 block: &RecoveredBlock<N::Block>,
121 result: &BlockExecutionResult<N::Receipt>,
122 receipt_root_bloom: Option<ReceiptRootBloom>,
123 block_access_list_hash: Option<B256>,
124 ) -> Result<(), ConsensusError> {
125 validation::validate_block_post_execution_with_bal_hashes(
126 block,
127 &self.chain_spec,
128 result,
129 receipt_root_bloom,
130 block_access_list_hash,
131 self.allow_bal_hashes,
132 self.skip_requests_hash_check,
133 )
134 }
135}
136
137impl<B, ChainSpec> Consensus<B> for EthBeaconConsensus<ChainSpec>
138where
139 B: Block,
140 ChainSpec: EthChainSpec<Header = B::Header> + EthereumHardforks,
141{
142 fn validate_body_against_header(
143 &self,
144 body: &B::Body,
145 header: &SealedHeader<B::Header>,
146 ) -> Result<(), ConsensusError> {
147 validate_body_against_header(body, header.header())
148 }
149
150 fn validate_block_pre_execution(&self, block: &SealedBlock<B>) -> Result<(), ConsensusError> {
151 validate_block_pre_execution(block, &self.chain_spec)
152 }
153
154 fn validate_block_pre_execution_with_tx_root(
155 &self,
156 block: &SealedBlock<B>,
157 transaction_root: Option<TransactionRoot>,
158 ) -> Result<(), ConsensusError> {
159 validate_block_pre_execution_with_tx_root(block, &self.chain_spec, transaction_root)
160 }
161}
162
163impl<H, ChainSpec> HeaderValidator<H> for EthBeaconConsensus<ChainSpec>
164where
165 H: BlockHeader,
166 ChainSpec: EthChainSpec<Header = H> + EthereumHardforks,
167{
168 fn validate_header(&self, header: &SealedHeader<H>) -> Result<(), ConsensusError> {
169 let header = header.header();
170 let is_post_merge = self.chain_spec.is_paris_active_at_block(header.number());
171
172 if is_post_merge {
173 if !header.difficulty().is_zero() {
174 return Err(ConsensusError::TheMergeDifficultyIsNotZero);
175 }
176
177 if !header.nonce().is_some_and(|nonce| nonce.is_zero()) {
178 return Err(ConsensusError::TheMergeNonceIsNotZero);
179 }
180
181 if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH {
182 return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty);
183 }
184 } else {
185 #[cfg(feature = "std")]
186 {
187 let present_timestamp = std::time::SystemTime::now()
188 .duration_since(std::time::SystemTime::UNIX_EPOCH)
189 .unwrap()
190 .as_secs();
191
192 if header.timestamp() >
193 present_timestamp + alloy_eips::merge::ALLOWED_FUTURE_BLOCK_TIME_SECONDS
194 {
195 return Err(ConsensusError::TimestampIsInFuture {
196 timestamp: header.timestamp(),
197 present_timestamp,
198 });
199 }
200 }
201 }
202 validate_header_extra_data(header, self.max_extra_data_size)?;
203 validate_header_gas(header)?;
204 validate_header_base_fee(header, &self.chain_spec)?;
205
206 if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) &&
208 header.withdrawals_root().is_none()
209 {
210 return Err(ConsensusError::WithdrawalsRootMissing)
211 } else if !self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) &&
212 header.withdrawals_root().is_some()
213 {
214 return Err(ConsensusError::WithdrawalsRootUnexpected)
215 }
216
217 if self.chain_spec.is_cancun_active_at_timestamp(header.timestamp()) {
219 if !self.skip_blob_gas_used_check {
220 validate_4844_header_standalone(
221 header,
222 self.chain_spec
223 .blob_params_at_timestamp(header.timestamp())
224 .unwrap_or_else(BlobParams::cancun),
225 )?;
226 }
227 } else if header.blob_gas_used().is_some() {
228 return Err(ConsensusError::BlobGasUsedUnexpected)
229 } else if header.excess_blob_gas().is_some() {
230 return Err(ConsensusError::ExcessBlobGasUnexpected)
231 } else if header.parent_beacon_block_root().is_some() {
232 return Err(ConsensusError::ParentBeaconBlockRootUnexpected)
233 }
234
235 if self.chain_spec.is_prague_active_at_timestamp(header.timestamp()) {
236 if header.requests_hash().is_none() {
237 return Err(ConsensusError::RequestsHashMissing)
238 }
239 } else if header.requests_hash().is_some() {
240 return Err(ConsensusError::RequestsHashUnexpected)
241 }
242
243 if self.chain_spec.is_amsterdam_active_at_timestamp(header.timestamp()) {
244 if header.block_access_list_hash().is_none() {
245 return Err(ConsensusError::BlockAccessListHashMissing)
246 }
247 if header.slot_number().is_none() {
248 return Err(ConsensusError::SlotNumberMissing)
249 }
250 } else {
251 if header.block_access_list_hash().is_some() && !self.allow_bal_hashes {
252 return Err(ConsensusError::BlockAccessListHashUnexpected)
253 }
254 if header.slot_number().is_some() {
255 return Err(ConsensusError::SlotNumberUnexpected)
256 }
257 }
258
259 Ok(())
260 }
261
262 fn validate_header_against_parent(
263 &self,
264 header: &SealedHeader<H>,
265 parent: &SealedHeader<H>,
266 ) -> Result<(), ConsensusError> {
267 validate_against_parent_hash_number(header.header(), parent)?;
268
269 validate_against_parent_timestamp(header.header(), parent.header())?;
270
271 if !self.skip_gas_limit_ramp_check {
272 validate_against_parent_gas_limit(header, parent, &self.chain_spec)?;
273 }
274
275 validate_against_parent_eip1559_base_fee(
276 header.header(),
277 parent.header(),
278 &self.chain_spec,
279 )?;
280
281 if let Some(blob_params) = self.chain_spec.blob_params_at_timestamp(header.timestamp()) {
283 validate_against_parent_4844(header.header(), parent.header(), blob_params)?;
284 }
285
286 Ok(())
287 }
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293 use alloy_consensus::Header;
294 use alloy_eips::eip7685::EMPTY_REQUESTS_HASH;
295 use alloy_primitives::B256;
296 use reth_chainspec::{ChainSpec, ChainSpecBuilder};
297 use reth_consensus_common::validation::validate_against_parent_gas_limit;
298 use reth_ethereum_primitives::{Block as EthBlock, EthPrimitives, Receipt};
299 use reth_primitives_traits::{
300 constants::{GAS_LIMIT_BOUND_DIVISOR, MINIMUM_GAS_LIMIT},
301 proofs,
302 };
303
304 fn header_with_gas_limit(gas_limit: u64) -> SealedHeader {
305 let header = reth_primitives_traits::Header { gas_limit, ..Default::default() };
306 SealedHeader::new(header, B256::ZERO)
307 }
308
309 fn valid_prague_header() -> reth_primitives_traits::Header {
310 reth_primitives_traits::Header {
311 base_fee_per_gas: Some(1337),
312 withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])),
313 blob_gas_used: Some(0),
314 excess_blob_gas: Some(0),
315 parent_beacon_block_root: Some(B256::ZERO),
316 requests_hash: Some(EMPTY_REQUESTS_HASH),
317 ..Default::default()
318 }
319 }
320
321 fn prague_recovered_block_with_bal_hash(hash: B256) -> RecoveredBlock<EthBlock> {
322 let mut header = valid_prague_header();
323 header.block_access_list_hash = Some(hash);
324 RecoveredBlock::new_unhashed(EthBlock { header, body: Default::default() }, Vec::new())
325 }
326
327 #[test]
328 fn test_valid_gas_limit_increase() {
329 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
330 let child = header_with_gas_limit(parent.gas_limit + 5);
331
332 assert!(validate_against_parent_gas_limit(
333 &child,
334 &parent,
335 &ChainSpec::<Header>::default()
336 )
337 .is_ok());
338 }
339
340 #[test]
341 fn test_gas_limit_below_minimum() {
342 let parent = header_with_gas_limit(MINIMUM_GAS_LIMIT);
343 let child = header_with_gas_limit(MINIMUM_GAS_LIMIT - 1);
344
345 assert!(matches!(
346 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
347 ConsensusError::GasLimitInvalidMinimum { child_gas_limit }
348 if child_gas_limit == child.gas_limit
349 ));
350 }
351
352 #[test]
353 fn test_invalid_gas_limit_increase_exceeding_limit() {
354 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
355 let child = header_with_gas_limit(
356 parent.gas_limit + parent.gas_limit / GAS_LIMIT_BOUND_DIVISOR + 1,
357 );
358
359 assert!(matches!(
360 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
361 ConsensusError::GasLimitInvalidIncrease { parent_gas_limit, child_gas_limit }
362 if parent_gas_limit == parent.gas_limit && child_gas_limit == child.gas_limit
363 ));
364 }
365
366 #[test]
367 fn test_valid_gas_limit_decrease_within_limit() {
368 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
369 let child = header_with_gas_limit(parent.gas_limit - 5);
370
371 assert!(validate_against_parent_gas_limit(
372 &child,
373 &parent,
374 &ChainSpec::<Header>::default()
375 )
376 .is_ok());
377 }
378
379 #[test]
380 fn test_invalid_gas_limit_decrease_exceeding_limit() {
381 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
382 let child = header_with_gas_limit(
383 parent.gas_limit - parent.gas_limit / GAS_LIMIT_BOUND_DIVISOR - 1,
384 );
385
386 assert!(matches!(
387 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
388 ConsensusError::GasLimitInvalidDecrease { parent_gas_limit, child_gas_limit }
389 if parent_gas_limit == parent.gas_limit && child_gas_limit == child.gas_limit
390 ));
391 }
392
393 #[test]
394 fn shanghai_block_zero_withdrawals() {
395 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().shanghai_activated().build());
398
399 let header = reth_primitives_traits::Header {
400 base_fee_per_gas: Some(1337),
401 withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])),
402 ..Default::default()
403 };
404
405 assert!(EthBeaconConsensus::new(chain_spec)
406 .validate_header(&SealedHeader::seal_slow(header,))
407 .is_ok());
408 }
409
410 #[test]
411 fn prague_header_rejects_block_access_list_hash_before_amsterdam() {
412 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
413 let mut header = valid_prague_header();
414 header.block_access_list_hash = Some(B256::ZERO);
415
416 assert!(matches!(
417 EthBeaconConsensus::new(chain_spec)
418 .validate_header(&SealedHeader::seal_slow(header,))
419 .unwrap_err(),
420 ConsensusError::BlockAccessListHashUnexpected
421 ));
422 }
423
424 #[test]
425 fn prague_header_allows_block_access_list_hash_before_amsterdam() {
426 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
427 let mut header = valid_prague_header();
428 header.block_access_list_hash = Some(B256::ZERO);
429
430 assert!(EthBeaconConsensus::new(chain_spec)
431 .with_allow_bal_hashes(true)
432 .validate_header(&SealedHeader::seal_slow(header,))
433 .is_ok());
434 }
435
436 #[test]
437 fn prague_header_rejects_slot_number_before_amsterdam() {
438 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
439 let mut header = valid_prague_header();
440 header.slot_number = Some(0);
441
442 assert!(matches!(
443 EthBeaconConsensus::new(chain_spec)
444 .validate_header(&SealedHeader::seal_slow(header,))
445 .unwrap_err(),
446 ConsensusError::SlotNumberUnexpected
447 ));
448 }
449
450 #[test]
451 fn prague_header_rejects_slot_number_with_allowed_bal_hashes_before_amsterdam() {
452 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
453 let mut header = valid_prague_header();
454 header.block_access_list_hash = Some(B256::ZERO);
455 header.slot_number = Some(0);
456
457 assert!(matches!(
458 EthBeaconConsensus::new(chain_spec)
459 .with_allow_bal_hashes(true)
460 .validate_header(&SealedHeader::seal_slow(header,))
461 .unwrap_err(),
462 ConsensusError::SlotNumberUnexpected
463 ));
464 }
465
466 #[test]
467 fn prague_post_execution_allows_block_access_list_hash_before_amsterdam() {
468 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
469 let expected_hash = B256::repeat_byte(0x42);
470 let block = prague_recovered_block_with_bal_hash(expected_hash);
471 let result = BlockExecutionResult::<Receipt>::default();
472 let consensus = EthBeaconConsensus::new(chain_spec).with_allow_bal_hashes(true);
473
474 assert!(FullConsensus::<EthPrimitives>::validate_block_post_execution(
475 &consensus,
476 &block,
477 &result,
478 None,
479 Some(expected_hash),
480 )
481 .is_ok());
482
483 assert!(FullConsensus::<EthPrimitives>::validate_block_post_execution(
484 &consensus, &block, &result, None, None,
485 )
486 .is_ok());
487
488 assert!(matches!(
489 FullConsensus::<EthPrimitives>::validate_block_post_execution(
490 &consensus,
491 &block,
492 &result,
493 None,
494 Some(B256::repeat_byte(0x24)),
495 )
496 .unwrap_err(),
497 ConsensusError::BlockAccessListHashMismatch(_)
498 ));
499 }
500
501 #[test]
502 fn amsterdam_header_requires_block_access_list_hash() {
503 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
504 let mut header = valid_prague_header();
505 header.slot_number = Some(0);
506
507 assert!(matches!(
508 EthBeaconConsensus::new(chain_spec)
509 .validate_header(&SealedHeader::seal_slow(header,))
510 .unwrap_err(),
511 ConsensusError::BlockAccessListHashMissing
512 ));
513 }
514
515 #[test]
516 fn amsterdam_header_requires_slot_number() {
517 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
518 let mut header = valid_prague_header();
519 header.block_access_list_hash = Some(B256::ZERO);
520
521 assert!(matches!(
522 EthBeaconConsensus::new(chain_spec)
523 .validate_header(&SealedHeader::seal_slow(header,))
524 .unwrap_err(),
525 ConsensusError::SlotNumberMissing
526 ));
527 }
528
529 #[test]
530 fn amsterdam_header_accepts_block_access_list_hash_and_slot_number() {
531 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
532 let mut header = valid_prague_header();
533 header.block_access_list_hash = Some(B256::ZERO);
534 header.slot_number = Some(0);
535
536 assert!(EthBeaconConsensus::new(chain_spec)
537 .validate_header(&SealedHeader::seal_slow(header,))
538 .is_ok());
539 }
540
541 #[test]
542 fn amsterdam_post_execution_requires_computed_block_access_list_hash() {
543 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
544 let block = prague_recovered_block_with_bal_hash(B256::ZERO);
545 let result = BlockExecutionResult::<Receipt>::default();
546 let consensus = EthBeaconConsensus::new(chain_spec);
547
548 assert!(matches!(
549 FullConsensus::<EthPrimitives>::validate_block_post_execution(
550 &consensus, &block, &result, None, None,
551 )
552 .unwrap_err(),
553 ConsensusError::BlockAccessListHashMissing
554 ));
555 }
556
557 #[test]
558 fn skip_requests_hash_check_still_validates_block_access_list_hash() {
559 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
560 let mut header = valid_prague_header();
561 header.block_access_list_hash = Some(B256::ZERO);
562 header.requests_hash = Some(B256::with_last_byte(1));
563 let block =
564 RecoveredBlock::new_unhashed(EthBlock { header, body: Default::default() }, Vec::new());
565 let result = BlockExecutionResult::<Receipt>::default();
566 let computed_bal_hash = B256::with_last_byte(2);
567
568 let consensus = EthBeaconConsensus::new(chain_spec).with_skip_requests_hash_check(true);
569 assert!(matches!(
570 FullConsensus::<EthPrimitives>::validate_block_post_execution(
571 &consensus,
572 &block,
573 &result,
574 None,
575 Some(computed_bal_hash),
576 )
577 .unwrap_err(),
578 ConsensusError::BlockAccessListHashMismatch(_)
579 ));
580
581 assert!(FullConsensus::<EthPrimitives>::validate_block_post_execution(
583 &consensus,
584 &block,
585 &result,
586 None,
587 Some(B256::ZERO),
588 )
589 .is_ok());
590 }
591}