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 reth_chainspec::{EthChainSpec, EthereumHardforks};
18use reth_consensus::{
19 Consensus, ConsensusError, FullConsensus, HeaderValidator, ReceiptRootBloom, TransactionRoot,
20};
21use reth_consensus_common::validation::{
22 validate_4844_header_standalone, validate_against_parent_4844,
23 validate_against_parent_eip1559_base_fee, validate_against_parent_gas_limit,
24 validate_against_parent_hash_number, validate_against_parent_timestamp,
25 validate_block_pre_execution, validate_block_pre_execution_with_tx_root,
26 validate_body_against_header, validate_header_base_fee, validate_header_extra_data,
27 validate_header_gas,
28};
29use reth_execution_types::BlockExecutionResult;
30use reth_primitives_traits::{
31 Block, BlockHeader, NodePrimitives, RecoveredBlock, SealedBlock, SealedHeader,
32};
33
34mod validation;
35pub use validation::validate_block_post_execution;
36
37#[derive(Debug, Clone)]
41pub struct EthBeaconConsensus<ChainSpec> {
42 chain_spec: Arc<ChainSpec>,
44 max_extra_data_size: usize,
46}
47
48impl<ChainSpec: EthChainSpec + EthereumHardforks> EthBeaconConsensus<ChainSpec> {
49 pub const fn new(chain_spec: Arc<ChainSpec>) -> Self {
51 Self { chain_spec, max_extra_data_size: MAXIMUM_EXTRA_DATA_SIZE }
52 }
53
54 pub const fn max_extra_data_size(&self) -> usize {
56 self.max_extra_data_size
57 }
58
59 pub const fn with_max_extra_data_size(mut self, size: usize) -> Self {
61 self.max_extra_data_size = size;
62 self
63 }
64
65 pub const fn chain_spec(&self) -> &Arc<ChainSpec> {
67 &self.chain_spec
68 }
69}
70
71impl<ChainSpec, N> FullConsensus<N> for EthBeaconConsensus<ChainSpec>
72where
73 ChainSpec: Send + Sync + EthChainSpec<Header = N::BlockHeader> + EthereumHardforks + Debug,
74 N: NodePrimitives,
75{
76 fn validate_block_post_execution(
77 &self,
78 block: &RecoveredBlock<N::Block>,
79 result: &BlockExecutionResult<N::Receipt>,
80 receipt_root_bloom: Option<ReceiptRootBloom>,
81 ) -> Result<(), ConsensusError> {
82 validate_block_post_execution(
83 block,
84 &self.chain_spec,
85 &result.receipts,
86 &result.requests,
87 receipt_root_bloom,
88 )
89 }
90}
91
92impl<B, ChainSpec> Consensus<B> for EthBeaconConsensus<ChainSpec>
93where
94 B: Block,
95 ChainSpec: EthChainSpec<Header = B::Header> + EthereumHardforks + Debug + Send + Sync,
96{
97 fn validate_body_against_header(
98 &self,
99 body: &B::Body,
100 header: &SealedHeader<B::Header>,
101 ) -> Result<(), ConsensusError> {
102 validate_body_against_header(body, header.header())
103 }
104
105 fn validate_block_pre_execution(&self, block: &SealedBlock<B>) -> Result<(), ConsensusError> {
106 validate_block_pre_execution(block, &self.chain_spec)
107 }
108
109 fn validate_block_pre_execution_with_tx_root(
110 &self,
111 block: &SealedBlock<B>,
112 transaction_root: Option<TransactionRoot>,
113 ) -> Result<(), ConsensusError> {
114 validate_block_pre_execution_with_tx_root(block, &self.chain_spec, transaction_root)
115 }
116}
117
118impl<H, ChainSpec> HeaderValidator<H> for EthBeaconConsensus<ChainSpec>
119where
120 H: BlockHeader,
121 ChainSpec: EthChainSpec<Header = H> + EthereumHardforks + Debug + Send + Sync,
122{
123 fn validate_header(&self, header: &SealedHeader<H>) -> Result<(), ConsensusError> {
124 let header = header.header();
125 let is_post_merge = self.chain_spec.is_paris_active_at_block(header.number());
126
127 if is_post_merge {
128 if !header.difficulty().is_zero() {
129 return Err(ConsensusError::TheMergeDifficultyIsNotZero);
130 }
131
132 if !header.nonce().is_some_and(|nonce| nonce.is_zero()) {
133 return Err(ConsensusError::TheMergeNonceIsNotZero);
134 }
135
136 if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH {
137 return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty);
138 }
139 } else {
140 #[cfg(feature = "std")]
141 {
142 let present_timestamp = std::time::SystemTime::now()
143 .duration_since(std::time::SystemTime::UNIX_EPOCH)
144 .unwrap()
145 .as_secs();
146
147 if header.timestamp() >
148 present_timestamp + alloy_eips::merge::ALLOWED_FUTURE_BLOCK_TIME_SECONDS
149 {
150 return Err(ConsensusError::TimestampIsInFuture {
151 timestamp: header.timestamp(),
152 present_timestamp,
153 });
154 }
155 }
156 }
157 validate_header_extra_data(header, self.max_extra_data_size)?;
158 validate_header_gas(header)?;
159 validate_header_base_fee(header, &self.chain_spec)?;
160
161 if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) &&
163 header.withdrawals_root().is_none()
164 {
165 return Err(ConsensusError::WithdrawalsRootMissing)
166 } else if !self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) &&
167 header.withdrawals_root().is_some()
168 {
169 return Err(ConsensusError::WithdrawalsRootUnexpected)
170 }
171
172 if self.chain_spec.is_cancun_active_at_timestamp(header.timestamp()) {
174 validate_4844_header_standalone(
175 header,
176 self.chain_spec
177 .blob_params_at_timestamp(header.timestamp())
178 .unwrap_or_else(BlobParams::cancun),
179 )?;
180 } else if header.blob_gas_used().is_some() {
181 return Err(ConsensusError::BlobGasUsedUnexpected)
182 } else if header.excess_blob_gas().is_some() {
183 return Err(ConsensusError::ExcessBlobGasUnexpected)
184 } else if header.parent_beacon_block_root().is_some() {
185 return Err(ConsensusError::ParentBeaconBlockRootUnexpected)
186 }
187
188 if self.chain_spec.is_prague_active_at_timestamp(header.timestamp()) {
189 if header.requests_hash().is_none() {
190 return Err(ConsensusError::RequestsHashMissing)
191 }
192 } else if header.requests_hash().is_some() {
193 return Err(ConsensusError::RequestsHashUnexpected)
194 }
195
196 Ok(())
197 }
198
199 fn validate_header_against_parent(
200 &self,
201 header: &SealedHeader<H>,
202 parent: &SealedHeader<H>,
203 ) -> Result<(), ConsensusError> {
204 validate_against_parent_hash_number(header.header(), parent)?;
205
206 validate_against_parent_timestamp(header.header(), parent.header())?;
207
208 validate_against_parent_gas_limit(header, parent, &self.chain_spec)?;
209
210 validate_against_parent_eip1559_base_fee(
211 header.header(),
212 parent.header(),
213 &self.chain_spec,
214 )?;
215
216 if let Some(blob_params) = self.chain_spec.blob_params_at_timestamp(header.timestamp()) {
218 validate_against_parent_4844(header.header(), parent.header(), blob_params)?;
219 }
220
221 Ok(())
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228 use alloy_consensus::Header;
229 use alloy_primitives::B256;
230 use reth_chainspec::{ChainSpec, ChainSpecBuilder};
231 use reth_consensus_common::validation::validate_against_parent_gas_limit;
232 use reth_primitives_traits::{
233 constants::{GAS_LIMIT_BOUND_DIVISOR, MINIMUM_GAS_LIMIT},
234 proofs,
235 };
236
237 fn header_with_gas_limit(gas_limit: u64) -> SealedHeader {
238 let header = reth_primitives_traits::Header { gas_limit, ..Default::default() };
239 SealedHeader::new(header, B256::ZERO)
240 }
241
242 #[test]
243 fn test_valid_gas_limit_increase() {
244 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
245 let child = header_with_gas_limit(parent.gas_limit + 5);
246
247 assert!(validate_against_parent_gas_limit(
248 &child,
249 &parent,
250 &ChainSpec::<Header>::default()
251 )
252 .is_ok());
253 }
254
255 #[test]
256 fn test_gas_limit_below_minimum() {
257 let parent = header_with_gas_limit(MINIMUM_GAS_LIMIT);
258 let child = header_with_gas_limit(MINIMUM_GAS_LIMIT - 1);
259
260 assert!(matches!(
261 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
262 ConsensusError::GasLimitInvalidMinimum { child_gas_limit }
263 if child_gas_limit == child.gas_limit
264 ));
265 }
266
267 #[test]
268 fn test_invalid_gas_limit_increase_exceeding_limit() {
269 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
270 let child = header_with_gas_limit(
271 parent.gas_limit + parent.gas_limit / GAS_LIMIT_BOUND_DIVISOR + 1,
272 );
273
274 assert!(matches!(
275 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
276 ConsensusError::GasLimitInvalidIncrease { parent_gas_limit, child_gas_limit }
277 if parent_gas_limit == parent.gas_limit && child_gas_limit == child.gas_limit
278 ));
279 }
280
281 #[test]
282 fn test_valid_gas_limit_decrease_within_limit() {
283 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
284 let child = header_with_gas_limit(parent.gas_limit - 5);
285
286 assert!(validate_against_parent_gas_limit(
287 &child,
288 &parent,
289 &ChainSpec::<Header>::default()
290 )
291 .is_ok());
292 }
293
294 #[test]
295 fn test_invalid_gas_limit_decrease_exceeding_limit() {
296 let parent = header_with_gas_limit(GAS_LIMIT_BOUND_DIVISOR * 10);
297 let child = header_with_gas_limit(
298 parent.gas_limit - parent.gas_limit / GAS_LIMIT_BOUND_DIVISOR - 1,
299 );
300
301 assert!(matches!(
302 validate_against_parent_gas_limit(&child, &parent, &ChainSpec::<Header>::default()).unwrap_err(),
303 ConsensusError::GasLimitInvalidDecrease { parent_gas_limit, child_gas_limit }
304 if parent_gas_limit == parent.gas_limit && child_gas_limit == child.gas_limit
305 ));
306 }
307
308 #[test]
309 fn shanghai_block_zero_withdrawals() {
310 let chain_spec = Arc::new(ChainSpecBuilder::mainnet().shanghai_activated().build());
313
314 let header = reth_primitives_traits::Header {
315 base_fee_per_gas: Some(1337),
316 withdrawals_root: Some(proofs::calculate_withdrawals_root(&[])),
317 ..Default::default()
318 };
319
320 assert!(EthBeaconConsensus::new(chain_spec)
321 .validate_header(&SealedHeader::seal_slow(header,))
322 .is_ok());
323 }
324}