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_blob_gas_used_check,
133 self.skip_requests_hash_check,
134 )
135 }
136}
137
138impl<B, ChainSpec> Consensus<B> for EthBeaconConsensus<ChainSpec>
139where
140 B: Block,
141 ChainSpec: EthChainSpec<Header = B::Header> + EthereumHardforks,
142{
143 fn validate_body_against_header(
144 &self,
145 body: &B::Body,
146 header: &SealedHeader<B::Header>,
147 ) -> Result<(), ConsensusError> {
148 validate_body_against_header(body, header.header())
149 }
150
151 fn validate_block_pre_execution(&self, block: &SealedBlock<B>) -> Result<(), ConsensusError> {
152 validate_block_pre_execution(block, &self.chain_spec)
153 }
154
155 fn validate_block_pre_execution_with_tx_root(
156 &self,
157 block: &SealedBlock<B>,
158 transaction_root: Option<TransactionRoot>,
159 ) -> Result<(), ConsensusError> {
160 validate_block_pre_execution_with_tx_root(block, &self.chain_spec, transaction_root)
161 }
162}
163
164impl<H, ChainSpec> HeaderValidator<H> for EthBeaconConsensus<ChainSpec>
165where
166 H: BlockHeader,
167 ChainSpec: EthChainSpec<Header = H> + EthereumHardforks,
168{
169 fn validate_header(&self, header: &SealedHeader<H>) -> Result<(), ConsensusError> {
170 let header = header.header();
171 let is_post_merge = self.chain_spec.is_paris_active_at_block(header.number());
172
173 if is_post_merge {
174 if !header.difficulty().is_zero() {
175 return Err(ConsensusError::TheMergeDifficultyIsNotZero);
176 }
177
178 if !header.nonce().is_some_and(|nonce| nonce.is_zero()) {
179 return Err(ConsensusError::TheMergeNonceIsNotZero);
180 }
181
182 if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH {
183 return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty);
184 }
185 } else {
186 #[cfg(feature = "std")]
187 {
188 let present_timestamp = std::time::SystemTime::now()
189 .duration_since(std::time::SystemTime::UNIX_EPOCH)
190 .unwrap()
191 .as_secs();
192
193 if header.timestamp() >
194 present_timestamp + alloy_eips::merge::ALLOWED_FUTURE_BLOCK_TIME_SECONDS
195 {
196 return Err(ConsensusError::TimestampIsInFuture {
197 timestamp: header.timestamp(),
198 present_timestamp,
199 });
200 }
201 }
202 }
203 validate_header_extra_data(header, self.max_extra_data_size)?;
204 validate_header_gas(header)?;
205 validate_header_base_fee(header, &self.chain_spec)?;
206
207 if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) &&
209 header.withdrawals_root().is_none()
210 {
211 return Err(ConsensusError::WithdrawalsRootMissing)
212 } else if !self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) &&
213 header.withdrawals_root().is_some()
214 {
215 return Err(ConsensusError::WithdrawalsRootUnexpected)
216 }
217
218 if self.chain_spec.is_cancun_active_at_timestamp(header.timestamp()) {
220 if !self.skip_blob_gas_used_check {
221 validate_4844_header_standalone(
222 header,
223 self.chain_spec
224 .blob_params_at_timestamp(header.timestamp())
225 .unwrap_or_else(BlobParams::cancun),
226 )?;
227 }
228 } else if header.blob_gas_used().is_some() {
229 return Err(ConsensusError::BlobGasUsedUnexpected)
230 } else if header.excess_blob_gas().is_some() {
231 return Err(ConsensusError::ExcessBlobGasUnexpected)
232 } else if header.parent_beacon_block_root().is_some() {
233 return Err(ConsensusError::ParentBeaconBlockRootUnexpected)
234 }
235
236 if self.chain_spec.is_prague_active_at_timestamp(header.timestamp()) {
237 if header.requests_hash().is_none() {
238 return Err(ConsensusError::RequestsHashMissing)
239 }
240 } else if header.requests_hash().is_some() {
241 return Err(ConsensusError::RequestsHashUnexpected)
242 }
243
244 if self.chain_spec.is_amsterdam_active_at_timestamp(header.timestamp()) {
245 if header.block_access_list_hash().is_none() {
246 return Err(ConsensusError::BlockAccessListHashMissing)
247 }
248 if header.slot_number().is_none() {
249 return Err(ConsensusError::SlotNumberMissing)
250 }
251 } else {
252 if header.block_access_list_hash().is_some() && !self.allow_bal_hashes {
253 return Err(ConsensusError::BlockAccessListHashUnexpected)
254 }
255 if header.slot_number().is_some() {
256 return Err(ConsensusError::SlotNumberUnexpected)
257 }
258 }
259
260 Ok(())
261 }
262
263 fn validate_header_against_parent(
264 &self,
265 header: &SealedHeader<H>,
266 parent: &SealedHeader<H>,
267 ) -> Result<(), ConsensusError> {
268 validate_against_parent_hash_number(header.header(), parent)?;
269
270 validate_against_parent_timestamp(header.header(), parent.header())?;
271
272 if !self.skip_gas_limit_ramp_check {
273 validate_against_parent_gas_limit(header, parent, &self.chain_spec)?;
274 }
275
276 validate_against_parent_eip1559_base_fee(
277 header.header(),
278 parent.header(),
279 &self.chain_spec,
280 )?;
281
282 if let Some(blob_params) = self.chain_spec.blob_params_at_timestamp(header.timestamp()) {
284 validate_against_parent_4844(header.header(), parent.header(), blob_params)?;
285 }
286
287 Ok(())
288 }
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294 use alloy_consensus::Header;
295 use alloy_eips::{eip4844::DATA_GAS_PER_BLOB, eip7685::EMPTY_REQUESTS_HASH};
296 use alloy_primitives::B256;
297 use reth_chainspec::{ChainSpec, ChainSpecBuilder};
298 use reth_consensus_common::validation::validate_against_parent_gas_limit;
299 use reth_ethereum_primitives::{Block as EthBlock, EthPrimitives, Receipt};
300 use reth_primitives_traits::{
301 constants::{GAS_LIMIT_BOUND_DIVISOR, MINIMUM_GAS_LIMIT},
302 proofs, GotExpected,
303 };
304
305 fn header_with_gas_limit(gas_limit: u64) -> SealedHeader {
306 let header = reth_primitives_traits::Header { gas_limit, ..Default::default() };
307 SealedHeader::new(header, B256::ZERO)
308 }
309
310 fn valid_prague_header() -> reth_primitives_traits::Header {
311 reth_primitives_traits::Header {
312 base_fee_per_gas: Some(1337),
313 withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])),
314 blob_gas_used: Some(0),
315 excess_blob_gas: Some(0),
316 parent_beacon_block_root: Some(B256::ZERO),
317 requests_hash: Some(EMPTY_REQUESTS_HASH),
318 ..Default::default()
319 }
320 }
321
322 fn prague_recovered_block_with_bal_hash(hash: B256) -> RecoveredBlock<EthBlock> {
323 let mut header = valid_prague_header();
324 header.block_access_list_hash = Some(hash);
325 RecoveredBlock::new_unhashed(EthBlock { header, body: Default::default() }, Vec::new())
326 }
327
328 #[test]
329 fn test_valid_gas_limit_increase() {
330 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
331 let child = header_with_gas_limit(parent.gas_limit + 5);
332
333 assert!(validate_against_parent_gas_limit(
334 &child,
335 &parent,
336 &ChainSpec::<Header>::default()
337 )
338 .is_ok());
339 }
340
341 #[test]
342 fn test_gas_limit_below_minimum() {
343 let parent = header_with_gas_limit(MINIMUM_GAS_LIMIT);
344 let child = header_with_gas_limit(MINIMUM_GAS_LIMIT - 1);
345
346 assert!(matches!(
347 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
348 ConsensusError::GasLimitInvalidMinimum { child_gas_limit }
349 if child_gas_limit == child.gas_limit
350 ));
351 }
352
353 #[test]
354 fn test_invalid_gas_limit_increase_exceeding_limit() {
355 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
356 let child = header_with_gas_limit(
357 parent.gas_limit + parent.gas_limit / GAS_LIMIT_BOUND_DIVISOR + 1,
358 );
359
360 assert!(matches!(
361 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
362 ConsensusError::GasLimitInvalidIncrease { parent_gas_limit, child_gas_limit }
363 if parent_gas_limit == parent.gas_limit && child_gas_limit == child.gas_limit
364 ));
365 }
366
367 #[test]
368 fn test_valid_gas_limit_decrease_within_limit() {
369 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
370 let child = header_with_gas_limit(parent.gas_limit - 5);
371
372 assert!(validate_against_parent_gas_limit(
373 &child,
374 &parent,
375 &ChainSpec::<Header>::default()
376 )
377 .is_ok());
378 }
379
380 #[test]
381 fn test_invalid_gas_limit_decrease_exceeding_limit() {
382 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
383 let child = header_with_gas_limit(
384 parent.gas_limit - parent.gas_limit / GAS_LIMIT_BOUND_DIVISOR - 1,
385 );
386
387 assert!(matches!(
388 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
389 ConsensusError::GasLimitInvalidDecrease { parent_gas_limit, child_gas_limit }
390 if parent_gas_limit == parent.gas_limit && child_gas_limit == child.gas_limit
391 ));
392 }
393
394 #[test]
395 fn shanghai_block_zero_withdrawals() {
396 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().shanghai_activated().build());
399
400 let header = reth_primitives_traits::Header {
401 base_fee_per_gas: Some(1337),
402 withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])),
403 ..Default::default()
404 };
405
406 assert!(EthBeaconConsensus::new(chain_spec)
407 .validate_header(&SealedHeader::seal_slow(header,))
408 .is_ok());
409 }
410
411 #[test]
412 fn prague_header_rejects_block_access_list_hash_before_amsterdam() {
413 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
414 let mut header = valid_prague_header();
415 header.block_access_list_hash = Some(B256::ZERO);
416
417 assert!(matches!(
418 EthBeaconConsensus::new(chain_spec)
419 .validate_header(&SealedHeader::seal_slow(header,))
420 .unwrap_err(),
421 ConsensusError::BlockAccessListHashUnexpected
422 ));
423 }
424
425 #[test]
426 fn prague_header_allows_block_access_list_hash_before_amsterdam() {
427 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
428 let mut header = valid_prague_header();
429 header.block_access_list_hash = Some(B256::ZERO);
430
431 assert!(EthBeaconConsensus::new(chain_spec)
432 .with_allow_bal_hashes(true)
433 .validate_header(&SealedHeader::seal_slow(header,))
434 .is_ok());
435 }
436
437 #[test]
438 fn prague_header_rejects_slot_number_before_amsterdam() {
439 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
440 let mut header = valid_prague_header();
441 header.slot_number = Some(0);
442
443 assert!(matches!(
444 EthBeaconConsensus::new(chain_spec)
445 .validate_header(&SealedHeader::seal_slow(header,))
446 .unwrap_err(),
447 ConsensusError::SlotNumberUnexpected
448 ));
449 }
450
451 #[test]
452 fn prague_header_rejects_slot_number_with_allowed_bal_hashes_before_amsterdam() {
453 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
454 let mut header = valid_prague_header();
455 header.block_access_list_hash = Some(B256::ZERO);
456 header.slot_number = Some(0);
457
458 assert!(matches!(
459 EthBeaconConsensus::new(chain_spec)
460 .with_allow_bal_hashes(true)
461 .validate_header(&SealedHeader::seal_slow(header,))
462 .unwrap_err(),
463 ConsensusError::SlotNumberUnexpected
464 ));
465 }
466
467 #[test]
468 fn prague_post_execution_allows_block_access_list_hash_before_amsterdam() {
469 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
470 let expected_hash = B256::repeat_byte(0x42);
471 let block = prague_recovered_block_with_bal_hash(expected_hash);
472 let result = BlockExecutionResult::<Receipt>::default();
473 let consensus = EthBeaconConsensus::new(chain_spec).with_allow_bal_hashes(true);
474
475 assert!(FullConsensus::<EthPrimitives>::validate_block_post_execution(
476 &consensus,
477 &block,
478 &result,
479 None,
480 Some(expected_hash),
481 )
482 .is_ok());
483
484 assert!(FullConsensus::<EthPrimitives>::validate_block_post_execution(
485 &consensus, &block, &result, None, None,
486 )
487 .is_ok());
488
489 assert!(matches!(
490 FullConsensus::<EthPrimitives>::validate_block_post_execution(
491 &consensus,
492 &block,
493 &result,
494 None,
495 Some(B256::repeat_byte(0x24)),
496 )
497 .unwrap_err(),
498 ConsensusError::BlockAccessListHashMismatch(_)
499 ));
500 }
501
502 #[test]
503 fn amsterdam_header_requires_block_access_list_hash() {
504 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
505 let mut header = valid_prague_header();
506 header.slot_number = Some(0);
507
508 assert!(matches!(
509 EthBeaconConsensus::new(chain_spec)
510 .validate_header(&SealedHeader::seal_slow(header,))
511 .unwrap_err(),
512 ConsensusError::BlockAccessListHashMissing
513 ));
514 }
515
516 #[test]
517 fn amsterdam_header_requires_slot_number() {
518 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
519 let mut header = valid_prague_header();
520 header.block_access_list_hash = Some(B256::ZERO);
521
522 assert!(matches!(
523 EthBeaconConsensus::new(chain_spec)
524 .validate_header(&SealedHeader::seal_slow(header,))
525 .unwrap_err(),
526 ConsensusError::SlotNumberMissing
527 ));
528 }
529
530 #[test]
531 fn amsterdam_header_accepts_block_access_list_hash_and_slot_number() {
532 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
533 let mut header = valid_prague_header();
534 header.block_access_list_hash = Some(B256::ZERO);
535 header.slot_number = Some(0);
536
537 assert!(EthBeaconConsensus::new(chain_spec)
538 .validate_header(&SealedHeader::seal_slow(header,))
539 .is_ok());
540 }
541
542 #[test]
543 fn amsterdam_post_execution_requires_computed_block_access_list_hash() {
544 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
545 let block = prague_recovered_block_with_bal_hash(B256::ZERO);
546 let result = BlockExecutionResult::<Receipt>::default();
547 let consensus = EthBeaconConsensus::new(chain_spec);
548
549 assert!(matches!(
550 FullConsensus::<EthPrimitives>::validate_block_post_execution(
551 &consensus, &block, &result, None, None,
552 )
553 .unwrap_err(),
554 ConsensusError::BlockAccessListHashMissing
555 ));
556 }
557
558 #[test]
559 fn skip_requests_hash_check_still_validates_block_access_list_hash() {
560 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build());
561 let mut header = valid_prague_header();
562 header.block_access_list_hash = Some(B256::ZERO);
563 header.requests_hash = Some(B256::with_last_byte(1));
564 let block =
565 RecoveredBlock::new_unhashed(EthBlock { header, body: Default::default() }, Vec::new());
566 let result = BlockExecutionResult::<Receipt>::default();
567 let computed_bal_hash = B256::with_last_byte(2);
568
569 let consensus = EthBeaconConsensus::new(chain_spec).with_skip_requests_hash_check(true);
570 assert!(matches!(
571 FullConsensus::<EthPrimitives>::validate_block_post_execution(
572 &consensus,
573 &block,
574 &result,
575 None,
576 Some(computed_bal_hash),
577 )
578 .unwrap_err(),
579 ConsensusError::BlockAccessListHashMismatch(_)
580 ));
581
582 assert!(FullConsensus::<EthPrimitives>::validate_block_post_execution(
584 &consensus,
585 &block,
586 &result,
587 None,
588 Some(B256::ZERO),
589 )
590 .is_ok());
591 }
592
593 #[test]
594 fn prague_post_execution_rejects_blob_gas_used_diff_for_empty_block() {
595 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
596 let mut header = valid_prague_header();
597 header.blob_gas_used = Some(DATA_GAS_PER_BLOB);
598 let block =
599 RecoveredBlock::new_unhashed(EthBlock { header, body: Default::default() }, Vec::new());
600 let result = BlockExecutionResult::<Receipt>::default();
601
602 let consensus = EthBeaconConsensus::new(chain_spec.clone());
603 assert!(matches!(
604 FullConsensus::<EthPrimitives>::validate_block_post_execution(
605 &consensus, &block, &result, None, None,
606 )
607 .unwrap_err(),
608 ConsensusError::BlobGasUsedDiff(GotExpected { got: 0, expected: DATA_GAS_PER_BLOB })
609 ));
610
611 let consensus = EthBeaconConsensus::new(chain_spec).with_skip_blob_gas_used_check(true);
612 assert!(FullConsensus::<EthPrimitives>::validate_block_post_execution(
613 &consensus, &block, &result, None, None,
614 )
615 .is_ok());
616 }
617
618 #[test]
619 fn prague_post_execution_requires_blob_gas_used() {
620 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().prague_activated().build());
621 let mut header = valid_prague_header();
622 header.blob_gas_used = None;
623 let block =
624 RecoveredBlock::new_unhashed(EthBlock { header, body: Default::default() }, Vec::new());
625 let result = BlockExecutionResult::<Receipt>::default();
626 let consensus = EthBeaconConsensus::new(chain_spec);
627
628 assert!(matches!(
629 FullConsensus::<EthPrimitives>::validate_block_post_execution(
630 &consensus, &block, &result, None, None,
631 )
632 .unwrap_err(),
633 ConsensusError::BlobGasUsedMissing
634 ));
635 }
636}