Skip to main content

ethrex_common/types/
block.rs

1use super::{
2    BASE_FEE_MAX_CHANGE_DENOMINATOR, ChainConfig, Fork, ForkBlobSchedule,
3    GAS_LIMIT_ADJUSTMENT_FACTOR, GAS_LIMIT_MINIMUM, INITIAL_BASE_FEE,
4};
5use crate::{
6    Address, H256, U256,
7    constants::{
8        BLOB_BASE_COST, DEFAULT_OMMERS_HASH, EMPTY_WITHDRAWALS_HASH, GAS_PER_BLOB,
9        MIN_BASE_FEE_PER_BLOB_GAS,
10    },
11    types::{Receipt, Transaction},
12};
13use bytes::Bytes;
14use ethereum_types::Bloom;
15use ethrex_crypto::{Crypto, CryptoError, NativeCrypto};
16use ethrex_rlp::{
17    decode::RLPDecode,
18    encode::RLPEncode,
19    error::RLPDecodeError,
20    structs::{Decoder, Encoder},
21};
22use ethrex_trie::Trie;
23#[cfg(feature = "rayon")]
24use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
25use rkyv::{Archive, Deserialize as RDeserialize, Serialize as RSerialize};
26use serde::{Deserialize, Serialize};
27
28use std::cmp::{Ordering, max};
29
30pub type BlockNumber = u64;
31pub type BlockHash = H256;
32
33#[cfg(all(feature = "zisk", target_arch = "riscv64"))]
34use super::unsync_cell::OnceCell;
35#[cfg(not(all(feature = "zisk", target_arch = "riscv64")))]
36use once_cell::sync::OnceCell;
37
38#[derive(
39    PartialEq, Eq, Debug, Clone, Deserialize, Serialize, Default, RSerialize, RDeserialize, Archive,
40)]
41pub struct Block {
42    pub header: BlockHeader,
43    pub body: BlockBody,
44}
45
46impl Block {
47    pub fn new(header: BlockHeader, body: BlockBody) -> Block {
48        Block { header, body }
49    }
50
51    pub fn hash(&self) -> BlockHash {
52        self.header.hash()
53    }
54}
55
56impl RLPEncode for Block {
57    fn encode(&self, buf: &mut dyn bytes::BufMut) {
58        Encoder::new(buf)
59            .encode_field(&self.header)
60            .encode_field(&self.body.transactions)
61            .encode_field(&self.body.ommers)
62            .encode_optional_field(&self.body.withdrawals)
63            .finish();
64    }
65}
66
67impl RLPDecode for Block {
68    fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
69        let decoder = Decoder::new(rlp)?;
70        let (header, decoder) = decoder.decode_field("header")?;
71        let (transactions, decoder) = decoder.decode_field("transactions")?;
72        let (ommers, decoder) = decoder.decode_field("ommers")?;
73        let (withdrawals, decoder) = decoder.decode_optional_field();
74        let remaining = decoder.finish()?;
75        let body = BlockBody {
76            transactions,
77            ommers,
78            withdrawals,
79        };
80        let block = Block::new(header, body);
81        Ok((block, remaining))
82    }
83}
84
85/// Header part of a block on the chain.
86#[derive(Clone, Debug, Serialize, Default, Deserialize, RSerialize, RDeserialize, Archive, Eq)]
87#[serde(rename_all = "camelCase")]
88pub struct BlockHeader {
89    #[serde(skip)]
90    #[rkyv(with=rkyv::with::Skip)]
91    pub hash: OnceCell<BlockHash>,
92    #[rkyv(with=crate::rkyv_utils::H256Wrapper)]
93    pub parent_hash: H256,
94    #[serde(rename = "sha3Uncles")]
95    #[rkyv(with=crate::rkyv_utils::H256Wrapper)]
96    pub ommers_hash: H256, // ommer = uncle
97    #[rkyv(with=crate::rkyv_utils::H160Wrapper)]
98    #[serde(rename = "miner")]
99    pub coinbase: Address,
100    #[rkyv(with=crate::rkyv_utils::H256Wrapper)]
101    pub state_root: H256,
102    #[rkyv(with=crate::rkyv_utils::H256Wrapper)]
103    pub transactions_root: H256,
104    #[rkyv(with=crate::rkyv_utils::H256Wrapper)]
105    pub receipts_root: H256,
106    #[rkyv(with=crate::rkyv_utils::BloomWrapper)]
107    pub logs_bloom: Bloom,
108    #[serde(default)]
109    #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
110    pub difficulty: U256,
111    #[serde(with = "crate::serde_utils::u64::hex_str")]
112    pub number: BlockNumber,
113    #[serde(with = "crate::serde_utils::u64::hex_str")]
114    pub gas_limit: u64,
115    #[serde(with = "crate::serde_utils::u64::hex_str")]
116    pub gas_used: u64,
117    #[serde(with = "crate::serde_utils::u64::hex_str")]
118    pub timestamp: u64,
119    #[serde(with = "crate::serde_utils::bytes")]
120    #[rkyv(with= crate::rkyv_utils::BytesWrapper)]
121    pub extra_data: Bytes,
122    #[serde(rename = "mixHash")]
123    #[rkyv(with=crate::rkyv_utils::H256Wrapper)]
124    pub prev_randao: H256,
125    #[serde(with = "crate::serde_utils::u64::hex_str_padding")]
126    pub nonce: u64,
127    #[serde(
128        skip_serializing_if = "Option::is_none",
129        with = "crate::serde_utils::u64::hex_str_opt",
130        default = "Option::default"
131    )]
132    pub base_fee_per_gas: Option<u64>,
133    #[serde(skip_serializing_if = "Option::is_none", default = "Option::default")]
134    #[rkyv(with=crate::rkyv_utils::OptionH256Wrapper)]
135    pub withdrawals_root: Option<H256>,
136    #[serde(
137        skip_serializing_if = "Option::is_none",
138        with = "crate::serde_utils::u64::hex_str_opt",
139        default = "Option::default"
140    )]
141    pub blob_gas_used: Option<u64>,
142    #[serde(
143        skip_serializing_if = "Option::is_none",
144        with = "crate::serde_utils::u64::hex_str_opt",
145        default = "Option::default"
146    )]
147    pub excess_blob_gas: Option<u64>,
148    #[serde(skip_serializing_if = "Option::is_none", default = "Option::default")]
149    #[rkyv(with=crate::rkyv_utils::OptionH256Wrapper)]
150    pub parent_beacon_block_root: Option<H256>,
151    #[serde(skip_serializing_if = "Option::is_none", default = "Option::default")]
152    #[rkyv(with=crate::rkyv_utils::OptionH256Wrapper)]
153    pub requests_hash: Option<H256>,
154    // Amsterdam fork fields (EIP-7928)
155    #[serde(skip_serializing_if = "Option::is_none", default = "Option::default")]
156    #[rkyv(with=crate::rkyv_utils::OptionH256Wrapper)]
157    pub block_access_list_hash: Option<H256>,
158    #[serde(
159        skip_serializing_if = "Option::is_none",
160        with = "crate::serde_utils::u64::hex_str_opt",
161        default = "Option::default"
162    )]
163    pub slot_number: Option<u64>,
164    // LStar fork fields (EIP-8079)
165    #[serde(
166        skip_serializing_if = "Option::is_none",
167        with = "crate::serde_utils::u64::hex_str_opt",
168        default = "Option::default"
169    )]
170    pub burned_fees: Option<u64>,
171}
172
173// Needs a explicit impl due to the hash OnceLock.
174impl PartialEq for BlockHeader {
175    fn eq(&self, other: &Self) -> bool {
176        let BlockHeader {
177            hash: _,
178            parent_hash,
179            ommers_hash,
180            coinbase,
181            state_root,
182            transactions_root,
183            receipts_root,
184            logs_bloom,
185            difficulty,
186            number,
187            gas_limit,
188            gas_used,
189            timestamp,
190            extra_data,
191            prev_randao,
192            nonce,
193            base_fee_per_gas,
194            withdrawals_root,
195            blob_gas_used,
196            excess_blob_gas,
197            parent_beacon_block_root,
198            requests_hash,
199            block_access_list_hash,
200            slot_number,
201            burned_fees,
202        } = self;
203
204        parent_hash == &other.parent_hash
205            && number == &other.number
206            && timestamp == &other.timestamp
207            && nonce == &other.nonce
208            && gas_used == &other.gas_used
209            && gas_limit == &other.gas_limit
210            && base_fee_per_gas == &other.base_fee_per_gas
211            && blob_gas_used == &other.blob_gas_used
212            && excess_blob_gas == &other.excess_blob_gas
213            && parent_beacon_block_root == &other.parent_beacon_block_root
214            && prev_randao == &other.prev_randao
215            && coinbase == &other.coinbase
216            && state_root == &other.state_root
217            && transactions_root == &other.transactions_root
218            && receipts_root == &other.receipts_root
219            && withdrawals_root == &other.withdrawals_root
220            && difficulty == &other.difficulty
221            && ommers_hash == &other.ommers_hash
222            && requests_hash == &other.requests_hash
223            && block_access_list_hash == &other.block_access_list_hash
224            && slot_number == &other.slot_number
225            && burned_fees == &other.burned_fees
226            && logs_bloom == &other.logs_bloom
227            && extra_data == &other.extra_data
228    }
229}
230
231impl RLPEncode for BlockHeader {
232    fn encode(&self, buf: &mut dyn bytes::BufMut) {
233        Encoder::new(buf)
234            .encode_field(&self.parent_hash)
235            .encode_field(&self.ommers_hash)
236            .encode_field(&self.coinbase)
237            .encode_field(&self.state_root)
238            .encode_field(&self.transactions_root)
239            .encode_field(&self.receipts_root)
240            .encode_field(&self.logs_bloom)
241            .encode_field(&self.difficulty)
242            .encode_field(&self.number)
243            .encode_field(&self.gas_limit)
244            .encode_field(&self.gas_used)
245            .encode_field(&self.timestamp)
246            .encode_field(&self.extra_data)
247            .encode_field(&self.prev_randao)
248            .encode_field(&self.nonce.to_be_bytes())
249            .encode_optional_field(&self.base_fee_per_gas)
250            .encode_optional_field(&self.withdrawals_root)
251            .encode_optional_field(&self.blob_gas_used)
252            .encode_optional_field(&self.excess_blob_gas)
253            .encode_optional_field(&self.parent_beacon_block_root)
254            .encode_optional_field(&self.requests_hash)
255            .encode_optional_field(&self.block_access_list_hash)
256            .encode_optional_field(&self.slot_number)
257            .encode_optional_field(&self.burned_fees)
258            .finish();
259    }
260}
261
262impl RLPDecode for BlockHeader {
263    fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
264        let decoder = Decoder::new(rlp)?;
265        let (parent_hash, decoder) = decoder.decode_field("parent_hash")?;
266        let (ommers_hash, decoder) = decoder.decode_field("ommers_hash")?;
267        let (coinbase, decoder) = decoder.decode_field("coinbase")?;
268        let (state_root, decoder) = decoder.decode_field("state_root")?;
269        let (transactions_root, decoder) = decoder.decode_field("transactions_root")?;
270        let (receipts_root, decoder) = decoder.decode_field("receipts_root")?;
271        let (logs_bloom, decoder) = decoder.decode_field("logs_bloom")?;
272        let (difficulty, decoder) = decoder.decode_field("difficulty")?;
273        let (number, decoder) = decoder.decode_field("number")?;
274        let (gas_limit, decoder) = decoder.decode_field("gas_limit")?;
275        let (gas_used, decoder) = decoder.decode_field("gas_used")?;
276        let (timestamp, decoder) = decoder.decode_field("timestamp")?;
277        let (extra_data, decoder) = decoder.decode_field("extra_data")?;
278        let (prev_randao, decoder) = decoder.decode_field("prev_randao")?;
279        let (nonce, decoder) = decoder.decode_field("nonce")?;
280        let nonce = u64::from_be_bytes(nonce);
281        let (base_fee_per_gas, decoder) = decoder.decode_optional_field();
282        let (withdrawals_root, decoder) = decoder.decode_optional_field();
283        let (blob_gas_used, decoder) = decoder.decode_optional_field();
284        let (excess_blob_gas, decoder) = decoder.decode_optional_field();
285        let (parent_beacon_block_root, decoder) = decoder.decode_optional_field();
286        let (requests_hash, decoder) = decoder.decode_optional_field();
287        let (block_access_list_hash, decoder) = decoder.decode_optional_field();
288        let (slot_number, decoder) = decoder.decode_optional_field();
289        let (burned_fees, decoder) = decoder.decode_optional_field();
290
291        Ok((
292            BlockHeader {
293                hash: OnceCell::new(),
294                parent_hash,
295                ommers_hash,
296                coinbase,
297                state_root,
298                transactions_root,
299                receipts_root,
300                logs_bloom,
301                difficulty,
302                number,
303                gas_limit,
304                gas_used,
305                timestamp,
306                extra_data,
307                prev_randao,
308                nonce,
309                base_fee_per_gas,
310                withdrawals_root,
311                blob_gas_used,
312                excess_blob_gas,
313                parent_beacon_block_root,
314                requests_hash,
315                block_access_list_hash,
316                slot_number,
317                burned_fees,
318            },
319            decoder.finish()?,
320        ))
321    }
322}
323
324// The body of a block on the chain
325#[derive(
326    Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default, RSerialize, RDeserialize, Archive,
327)]
328pub struct BlockBody {
329    pub transactions: Vec<Transaction>,
330    // TODO: ommers list is always empty, so we can remove it
331    #[serde(rename = "uncles")]
332    pub ommers: Vec<BlockHeader>,
333    pub withdrawals: Option<Vec<Withdrawal>>,
334}
335
336impl BlockBody {
337    pub const fn empty() -> Self {
338        Self {
339            transactions: Vec::new(),
340            ommers: Vec::new(),
341            withdrawals: Some(Vec::new()),
342        }
343    }
344
345    pub fn get_transactions_with_sender(
346        &self,
347        crypto: &dyn Crypto,
348    ) -> Result<Vec<(&Transaction, Address)>, CryptoError> {
349        // Recovering addresses is computationally expensive.
350        // Computing them in parallel greatly reduces execution time.
351        // Without rayon, use sequential iteration
352        #[cfg(feature = "rayon")]
353        return self
354            .transactions
355            .par_iter()
356            .map(|tx| Ok((tx, tx.sender(crypto)?)))
357            .collect::<Result<Vec<(&Transaction, Address)>, CryptoError>>();
358
359        #[cfg(not(feature = "rayon"))]
360        self.transactions
361            .iter()
362            .map(|tx| Ok((tx, tx.sender(crypto)?)))
363            .collect::<Result<Vec<(&Transaction, Address)>, CryptoError>>()
364    }
365}
366
367pub fn compute_transactions_root(transactions: &[Transaction], crypto: &dyn Crypto) -> H256 {
368    let iter = transactions.iter().enumerate().map(|(idx, tx)| {
369        // Key: RLP(tx_index)
370        // Value: tx_type || RLP(tx)  if tx_type != 0
371        //                   RLP(tx)  else
372        (idx.encode_to_vec(), tx.encode_canonical_to_vec())
373    });
374    Trie::compute_hash_from_unsorted_iter(iter, crypto)
375}
376
377pub fn compute_receipts_root(receipts: &[Receipt], crypto: &dyn Crypto) -> H256 {
378    let iter = receipts
379        .iter()
380        .enumerate()
381        .map(|(idx, receipt)| (idx.encode_to_vec(), receipt.encode_inner_with_bloom(crypto)));
382    Trie::compute_hash_from_unsorted_iter(iter, crypto)
383}
384
385/// Computes the receipts root and the aggregate header `logs_bloom` in a single pass,
386/// hashing each receipt's bloom only once (it feeds both the receipts trie and the
387/// OR-ed header bloom). Validation paths need both, so this avoids the duplicate
388/// `bloom_from_logs` keccak work — relevant in the zkVM guest where it is cycle-counted.
389pub fn compute_receipts_root_and_logs_bloom(
390    receipts: &[Receipt],
391    crypto: &dyn Crypto,
392) -> (H256, Bloom) {
393    let mut logs_bloom = Bloom::zero();
394    let iter = receipts.iter().enumerate().map(|(idx, receipt)| {
395        let bloom = crate::types::bloom_from_logs(&receipt.logs, crypto);
396        logs_bloom |= bloom;
397        (
398            idx.encode_to_vec(),
399            receipt.encode_inner_with_precomputed_bloom(bloom),
400        )
401    });
402    let receipts_root = Trie::compute_hash_from_unsorted_iter(iter, crypto);
403    (receipts_root, logs_bloom)
404}
405
406// See [EIP-4895](https://eips.ethereum.org/EIPS/eip-4895)
407pub fn compute_withdrawals_root(withdrawals: &[Withdrawal], crypto: &dyn Crypto) -> H256 {
408    let iter = withdrawals
409        .iter()
410        .enumerate()
411        .map(|(idx, withdrawal)| (idx.encode_to_vec(), withdrawal.encode_to_vec()));
412    Trie::compute_hash_from_unsorted_iter(iter, crypto)
413}
414
415impl RLPEncode for BlockBody {
416    fn encode(&self, buf: &mut dyn bytes::BufMut) {
417        Encoder::new(buf)
418            .encode_field(&self.transactions)
419            .encode_field(&self.ommers)
420            .encode_optional_field(&self.withdrawals)
421            .finish();
422    }
423}
424
425impl RLPDecode for BlockBody {
426    fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
427        let decoder = Decoder::new(rlp)?;
428        let (transactions, decoder) = decoder.decode_field("transactions")?;
429        let (ommers, decoder) = decoder.decode_field("ommers")?;
430        let (withdrawals, decoder) = decoder.decode_optional_field();
431        Ok((
432            BlockBody {
433                transactions,
434                ommers,
435                withdrawals,
436            },
437            decoder.finish()?,
438        ))
439    }
440}
441
442impl BlockHeader {
443    pub fn compute_block_hash(&self, crypto: &dyn Crypto) -> H256 {
444        let mut buf = vec![];
445        self.encode(&mut buf);
446        H256(crypto.keccak256(&buf))
447    }
448
449    pub fn hash(&self) -> H256 {
450        *self
451            .hash
452            .get_or_init(|| self.compute_block_hash(&NativeCrypto))
453    }
454
455    /// Returns `self` with `burned_fees` set and the hash cache cleared.
456    ///
457    /// After `execute_blocks`, the header's `OnceCell` may already hold a stale
458    /// hash that was computed before `burned_fees` was known (e.g. during
459    /// `initialize_block_header_hashes`).  Taking ownership and clearing the
460    /// cache guarantees that the next call to `hash()` reflects the injected
461    /// value — without any extra `once_cell` dependency at the call site.
462    pub fn into_with_burned_fees(mut self, burned_fees: Option<u64>) -> Self {
463        self.burned_fees = burned_fees;
464        let _ = self.hash.take(); // clear stale cached hash
465        self
466    }
467}
468
469#[derive(
470    Clone, Debug, PartialEq, Eq, Deserialize, Serialize, RSerialize, RDeserialize, Archive,
471)]
472#[serde(rename_all = "camelCase")]
473pub struct Withdrawal {
474    #[serde(with = "crate::serde_utils::u64::hex_str")]
475    pub index: u64,
476    #[serde(with = "crate::serde_utils::u64::hex_str")]
477    pub validator_index: u64,
478    #[rkyv(with=crate::rkyv_utils::H160Wrapper)]
479    pub address: Address,
480    #[serde(with = "crate::serde_utils::u64::hex_str")]
481    pub amount: u64,
482}
483
484impl RLPEncode for Withdrawal {
485    fn encode(&self, buf: &mut dyn bytes::BufMut) {
486        Encoder::new(buf)
487            .encode_field(&self.index)
488            .encode_field(&self.validator_index)
489            .encode_field(&self.address)
490            .encode_field(&self.amount)
491            .finish();
492    }
493}
494
495impl RLPDecode for Withdrawal {
496    fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
497        let decoder = Decoder::new(rlp)?;
498        let (index, decoder) = decoder.decode_field("index")?;
499        let (validator_index, decoder) = decoder.decode_field("validator_index")?;
500        let (address, decoder) = decoder.decode_field("address")?;
501        let (amount, decoder) = decoder.decode_field("amount")?;
502        Ok((
503            Withdrawal {
504                index,
505                validator_index,
506                address,
507                amount,
508            },
509            decoder.finish()?,
510        ))
511    }
512}
513
514// Checks that the gas_limit fits the gas bounds set by its parent block
515fn check_gas_limit(gas_limit: u64, parent_gas_limit: u64) -> bool {
516    let max_adjustment_delta = parent_gas_limit / GAS_LIMIT_ADJUSTMENT_FACTOR;
517
518    gas_limit < parent_gas_limit + max_adjustment_delta
519        && gas_limit > parent_gas_limit - max_adjustment_delta
520        && gas_limit >= GAS_LIMIT_MINIMUM
521}
522
523/// Calculates the base fee per blob gas for the current block based on
524/// it's parent excess blob gas and the update fraction, which depends on the fork.
525pub fn calculate_base_fee_per_blob_gas(parent_excess_blob_gas: u64, update_fraction: u64) -> U256 {
526    if update_fraction == 0 {
527        return U256::zero();
528    }
529
530    fake_exponential(
531        U256::from(MIN_BASE_FEE_PER_BLOB_GAS),
532        U256::from(parent_excess_blob_gas),
533        update_fraction,
534    )
535    .unwrap_or_default()
536}
537
538/// Approximates factor * e ** (numerator / denominator) using Taylor expansion
539/// https://eips.ethereum.org/EIPS/eip-4844#helpers
540/// 400_000_000 numerator is the limit for this operation to work with U256,
541/// it will overflow with a larger numerator
542pub fn fake_exponential(
543    factor: U256,
544    numerator: U256,
545    denominator: u64,
546) -> Result<U256, FakeExponentialError> {
547    if denominator == 0 {
548        return Err(FakeExponentialError::DenominatorIsZero);
549    }
550
551    if numerator.is_zero() {
552        return Ok(factor);
553    }
554
555    let mut output: U256 = U256::zero();
556    let denominator_u256: U256 = denominator.into();
557
558    // Initial multiplication: factor * denominator
559    let mut numerator_accum = factor
560        .checked_mul(denominator_u256)
561        .ok_or(FakeExponentialError::CheckedMul)?;
562
563    let mut denominator_by_i = denominator_u256;
564
565    #[expect(
566        clippy::arithmetic_side_effects,
567        reason = "division can't overflow since denominator is not 0"
568    )]
569    {
570        while !numerator_accum.is_zero() {
571            // Safe addition to output
572            output = output
573                .checked_add(numerator_accum)
574                .ok_or(FakeExponentialError::CheckedAdd)?;
575
576            // Safe multiplication and division within loop
577            numerator_accum = numerator_accum
578                .checked_mul(numerator)
579                .ok_or(FakeExponentialError::CheckedMul)?
580                / denominator_by_i;
581
582            // denominator comes from a u64 value, will never overflow before other variables.
583            denominator_by_i += denominator_u256;
584        }
585
586        output
587            .checked_div(denominator.into())
588            .ok_or(FakeExponentialError::CheckedDiv)
589    }
590}
591
592#[derive(Debug, thiserror::Error, Serialize, Clone, PartialEq, Deserialize, Eq)]
593pub enum FakeExponentialError {
594    #[error("FakeExponentialError: Denominator cannot be zero.")]
595    DenominatorIsZero,
596    #[error("FakeExponentialError: Checked div failed is None.")]
597    CheckedDiv,
598    #[error("FakeExponentialError: Checked mul failed is None.")]
599    CheckedMul,
600    #[error("FakeExponentialError: Checked add failed is None.")]
601    CheckedAdd,
602}
603
604// Calculates the base fee for the current block based on its gas_limit and parent's gas and fee
605// Returns None if the block gas limit is not valid in relation to its parent's gas limit
606pub fn calculate_base_fee_per_gas(
607    block_gas_limit: u64,
608    parent_gas_limit: u64,
609    parent_gas_used: u64,
610    parent_base_fee_per_gas: u64,
611    elasticity_multiplier: u64,
612) -> Option<u64> {
613    // Check gas limit, if the check passes we can also rest assured that none of the
614    // following divisions will have zero as a divider
615    if !check_gas_limit(block_gas_limit, parent_gas_limit) {
616        return None;
617    }
618
619    let parent_gas_target = parent_gas_limit / elasticity_multiplier;
620
621    match parent_gas_used.cmp(&parent_gas_target) {
622        Ordering::Equal => Some(parent_base_fee_per_gas),
623        Ordering::Greater => {
624            let gas_used_delta = parent_gas_used - parent_gas_target;
625
626            let parent_fee_gas_delta =
627                u128::from(parent_base_fee_per_gas) * u128::from(gas_used_delta);
628            let target_fee_gas_delta = parent_fee_gas_delta / u128::from(parent_gas_target);
629
630            let base_fee_per_gas_delta =
631                max(target_fee_gas_delta / BASE_FEE_MAX_CHANGE_DENOMINATOR, 1);
632
633            (u128::from(parent_base_fee_per_gas) + base_fee_per_gas_delta)
634                .try_into()
635                .ok()
636        }
637        Ordering::Less => {
638            let gas_used_delta = parent_gas_target - parent_gas_used;
639
640            let parent_fee_gas_delta =
641                u128::from(parent_base_fee_per_gas) * u128::from(gas_used_delta);
642            let target_fee_gas_delta = parent_fee_gas_delta / u128::from(parent_gas_target);
643
644            let base_fee_per_gas_delta = target_fee_gas_delta / BASE_FEE_MAX_CHANGE_DENOMINATOR;
645
646            (u128::from(parent_base_fee_per_gas) - base_fee_per_gas_delta)
647                .try_into()
648                .ok()
649        }
650    }
651}
652
653#[derive(Debug, thiserror::Error)]
654pub enum InvalidBlockHeaderError {
655    #[error("Gas used is greater than gas limit")]
656    GasUsedGreaterThanGasLimit,
657    #[error("Gas limit changed more than allowed from the parent")]
658    GasLimitTooFarFromParent,
659    #[error("Base fee per gas is incorrect")]
660    BaseFeePerGasIncorrect,
661    #[error("Timestamp is not greater than parent timestamp")]
662    TimestampNotGreaterThanParent,
663    #[error("Block number is not one greater than parent number")]
664    BlockNumberNotOneGreater,
665    #[error("Extra data is too long")]
666    ExtraDataTooLong,
667    #[error("Difficulty is not zero")]
668    DifficultyNotZero,
669    #[error("Nonce is not zero")]
670    NonceNotZero,
671    #[error("Ommers hash is not the default")]
672    OmmersHashNotDefault,
673    #[error("Parent hash is incorrect")]
674    ParentHashIncorrect,
675    // Cancun fork errors
676    #[error("Excess blob gas is not present")]
677    ExcessBlobGasNotPresent,
678    #[error("Blob gas used is not present")]
679    BlobGasUsedNotPresent,
680    #[error("Excess blob gas is incorrect")]
681    ExcessBlobGasIncorrect,
682    #[error("Parent beacon block root is not present")]
683    ParentBeaconBlockRootNotPresent,
684    #[error("Requests hash is not present")]
685    RequestsHashNotPresent,
686    // Other fork errors
687    #[error("Excess blob gas is present")]
688    ExcessBlobGasPresent,
689    #[error("Blob gas used is present")]
690    BlobGasUsedPresent,
691    #[error("Parent beacon block root is present")]
692    ParentBeaconBlockRootPresent,
693    #[error("Requests hash is present")]
694    RequestsHashPresent,
695    #[error("Block access list hash is not present")]
696    BlockAccessListHashNotPresent,
697    #[error("Block access list hash is present")]
698    BlockAccessListHashPresent,
699    #[error("Slot number is not present")]
700    SlotNumberNotPresent,
701    #[error("Slot number is present")]
702    SlotNumberPresent,
703    #[error("Burned fees is present")]
704    BurnedFeesPresent,
705}
706
707#[derive(Debug, thiserror::Error)]
708pub enum InvalidBlockBodyError {
709    #[error("Withdrawals root does not match")]
710    WithdrawalsRootNotMatch,
711    #[error("Transactions root does not match")]
712    TransactionsRootNotMatch,
713    #[error("Ommers is not empty")]
714    OmmersIsNotEmpty,
715}
716
717/// Validates that the header fields are correct in reference to the parent_header
718pub fn validate_block_header(
719    header: &BlockHeader,
720    parent_header: &BlockHeader,
721    elasticity_multiplier: u64,
722) -> Result<(), InvalidBlockHeaderError> {
723    if header.gas_used > header.gas_limit {
724        return Err(InvalidBlockHeaderError::GasUsedGreaterThanGasLimit);
725    }
726
727    let expected_base_fee_per_gas = if let Some(base_fee) = calculate_base_fee_per_gas(
728        header.gas_limit,
729        parent_header.gas_limit,
730        parent_header.gas_used,
731        parent_header.base_fee_per_gas.unwrap_or(INITIAL_BASE_FEE),
732        elasticity_multiplier,
733    ) {
734        base_fee
735    } else {
736        return Err(InvalidBlockHeaderError::GasLimitTooFarFromParent);
737    };
738
739    if expected_base_fee_per_gas != header.base_fee_per_gas.unwrap_or(INITIAL_BASE_FEE) {
740        return Err(InvalidBlockHeaderError::BaseFeePerGasIncorrect);
741    }
742
743    if header.timestamp <= parent_header.timestamp {
744        return Err(InvalidBlockHeaderError::TimestampNotGreaterThanParent);
745    }
746
747    if header.number != parent_header.number + 1 {
748        return Err(InvalidBlockHeaderError::BlockNumberNotOneGreater);
749    }
750
751    if header.extra_data.len() > 32 {
752        return Err(InvalidBlockHeaderError::ExtraDataTooLong);
753    }
754
755    if !header.difficulty.is_zero() {
756        return Err(InvalidBlockHeaderError::DifficultyNotZero);
757    }
758
759    if header.nonce != 0 {
760        return Err(InvalidBlockHeaderError::NonceNotZero);
761    }
762
763    if header.ommers_hash != *DEFAULT_OMMERS_HASH {
764        return Err(InvalidBlockHeaderError::OmmersHashNotDefault);
765    }
766
767    if header.parent_hash != parent_header.hash() {
768        return Err(InvalidBlockHeaderError::ParentHashIncorrect);
769    }
770
771    Ok(())
772}
773
774/// Validates that the body matches with the header
775pub fn validate_block_body(
776    block_header: &BlockHeader,
777    block_body: &BlockBody,
778    crypto: &dyn Crypto,
779) -> Result<(), InvalidBlockBodyError> {
780    // Validates that:
781    //  - Transactions root and withdrawals root matches with the header
782    //  - Ommers is empty -> https://eips.ethereum.org/EIPS/eip-3675
783    let computed_tx_root = compute_transactions_root(&block_body.transactions, crypto);
784
785    if block_header.transactions_root != computed_tx_root {
786        return Err(InvalidBlockBodyError::TransactionsRootNotMatch);
787    }
788
789    if !block_body.ommers.is_empty() {
790        return Err(InvalidBlockBodyError::OmmersIsNotEmpty);
791    }
792
793    match (block_header.withdrawals_root, &block_body.withdrawals) {
794        (Some(withdrawals_root), Some(withdrawals)) => {
795            let computed_withdrawals_root = compute_withdrawals_root(withdrawals, crypto);
796            if withdrawals_root != computed_withdrawals_root {
797                return Err(InvalidBlockBodyError::WithdrawalsRootNotMatch);
798            }
799        }
800        // Post-Shanghai, the withdrawals field must be present in the body even when
801        // empty. A body that omits it is malformed, regardless of the header's
802        // withdrawals_root — geth ("missing withdrawals in block body"), reth,
803        // nethermind, erigon and besu all reject this shape.
804        (None, None) => {}
805        _ => return Err(InvalidBlockBodyError::WithdrawalsRootNotMatch),
806    }
807
808    Ok(())
809}
810
811/// Normalizes a legacy post-Shanghai body shape produced by older ethrex versions,
812/// which omitted the `withdrawals` field while the header committed to the
813/// empty-withdrawals root. `validate_block_body` rejects that shape (reference
814/// clients treat it as malformed on the wire), but blocks already sitting in a
815/// node's store or in batch blobs published to L1 are immutable history. When the
816/// header's withdrawals_root is exactly the empty-list root, `Some(vec![])` is the
817/// provably-equivalent canonical body; any other root leaves the body untouched, and
818/// validation rejects it exactly as before.
819///
820/// Only call this on bodies read from trusted local history (store re-execution,
821/// blob reconstruction) — never on bodies received from the network.
822pub fn normalize_legacy_withdrawals(header: &BlockHeader, body: &mut BlockBody) {
823    if body.withdrawals.is_none() && header.withdrawals_root == Some(*EMPTY_WITHDRAWALS_HASH) {
824        tracing::debug!(
825            block = header.number,
826            "Normalizing legacy omitted-withdrawals block body from trusted history"
827        );
828        body.withdrawals = Some(Vec::new());
829    }
830}
831
832/// Validates that only the required field are present for a Prague block
833/// Also validates excess_blob_gas value against parent's header
834pub fn validate_prague_header_fields(
835    header: &BlockHeader,
836    parent_header: &BlockHeader,
837    chain_config: &ChainConfig,
838) -> Result<(), InvalidBlockHeaderError> {
839    if header.excess_blob_gas.is_none() {
840        return Err(InvalidBlockHeaderError::ExcessBlobGasNotPresent);
841    }
842    if header.blob_gas_used.is_none() {
843        return Err(InvalidBlockHeaderError::BlobGasUsedNotPresent);
844    }
845    validate_excess_blob_gas(header, parent_header, chain_config)?;
846
847    if header.parent_beacon_block_root.is_none() {
848        return Err(InvalidBlockHeaderError::ParentBeaconBlockRootNotPresent);
849    }
850    if header.requests_hash.is_none() {
851        return Err(InvalidBlockHeaderError::RequestsHashNotPresent);
852    }
853    if chain_config.is_amsterdam_activated(header.timestamp) {
854        // EIP-7928: BAL hash and EIP-7843: slot_number are both mandatory
855        // trailing header fields on Amsterdam. A header omitting either is
856        // schema-invalid and must be rejected to match conformant clients.
857        if header.block_access_list_hash.is_none() {
858            return Err(InvalidBlockHeaderError::BlockAccessListHashNotPresent);
859        }
860        if header.slot_number.is_none() {
861            return Err(InvalidBlockHeaderError::SlotNumberNotPresent);
862        }
863        // EIP-8079: burned_fees is an LStar header field. The RLP decoder takes any
864        // trailing item as it, so a header before LStar may not carry one. From LStar
865        // on, its value is checked against execution (`validate_burned_fees`), which
866        // also rejects a header without it; the stateless path only fills it in after
867        // executing, so its presence is not required here.
868        if !chain_config.is_lstar_activated(header.timestamp) && header.burned_fees.is_some() {
869            return Err(InvalidBlockHeaderError::BurnedFeesPresent);
870        }
871    } else {
872        if header.block_access_list_hash.is_some() {
873            return Err(InvalidBlockHeaderError::BlockAccessListHashPresent);
874        }
875        if header.slot_number.is_some() {
876            return Err(InvalidBlockHeaderError::SlotNumberPresent);
877        }
878        if header.burned_fees.is_some() {
879            return Err(InvalidBlockHeaderError::BurnedFeesPresent);
880        }
881    }
882    Ok(())
883}
884
885/// Validates that only the required field are present for a Cancun block
886/// Also validates excess_blob_gas value against parent's header
887pub fn validate_cancun_header_fields(
888    header: &BlockHeader,
889    parent_header: &BlockHeader,
890    chain_config: &ChainConfig,
891) -> Result<(), InvalidBlockHeaderError> {
892    if header.excess_blob_gas.is_none() {
893        return Err(InvalidBlockHeaderError::ExcessBlobGasNotPresent);
894    }
895    if header.blob_gas_used.is_none() {
896        return Err(InvalidBlockHeaderError::BlobGasUsedNotPresent);
897    }
898    validate_excess_blob_gas(header, parent_header, chain_config)?;
899    if header.parent_beacon_block_root.is_none() {
900        return Err(InvalidBlockHeaderError::ParentBeaconBlockRootNotPresent);
901    }
902    if header.requests_hash.is_some() {
903        return Err(InvalidBlockHeaderError::RequestsHashPresent);
904    }
905    if header.block_access_list_hash.is_some() {
906        return Err(InvalidBlockHeaderError::BlockAccessListHashPresent);
907    }
908    if header.slot_number.is_some() {
909        return Err(InvalidBlockHeaderError::SlotNumberPresent);
910    }
911    if header.burned_fees.is_some() {
912        return Err(InvalidBlockHeaderError::BurnedFeesPresent);
913    }
914    Ok(())
915}
916
917/// Validates that only the required field are present for a pre Cancun block
918/// Also validates excess_blob_gas value against parent's header
919pub fn validate_pre_cancun_header_fields(
920    header: &BlockHeader,
921) -> Result<(), InvalidBlockHeaderError> {
922    if header.excess_blob_gas.is_some() {
923        return Err(InvalidBlockHeaderError::ExcessBlobGasPresent);
924    }
925    if header.blob_gas_used.is_some() {
926        return Err(InvalidBlockHeaderError::BlobGasUsedPresent);
927    }
928    if header.parent_beacon_block_root.is_some() {
929        return Err(InvalidBlockHeaderError::ParentBeaconBlockRootPresent);
930    }
931    if header.requests_hash.is_some() {
932        return Err(InvalidBlockHeaderError::RequestsHashPresent);
933    }
934    if header.block_access_list_hash.is_some() {
935        return Err(InvalidBlockHeaderError::BlockAccessListHashPresent);
936    }
937    if header.slot_number.is_some() {
938        return Err(InvalidBlockHeaderError::SlotNumberPresent);
939    }
940    if header.burned_fees.is_some() {
941        return Err(InvalidBlockHeaderError::BurnedFeesPresent);
942    }
943    Ok(())
944}
945
946fn validate_excess_blob_gas(
947    header: &BlockHeader,
948    parent_header: &BlockHeader,
949    chain_config: &ChainConfig,
950) -> Result<(), InvalidBlockHeaderError> {
951    let expected_excess_blob_gas = chain_config
952        .get_fork_blob_schedule(header.timestamp)
953        .map(|schedule| {
954            calc_excess_blob_gas(parent_header, schedule, chain_config.fork(header.timestamp))
955        })
956        .unwrap_or_default();
957    if header
958        .excess_blob_gas
959        .is_none_or(|header_excess_blob_gas| header_excess_blob_gas != expected_excess_blob_gas)
960    {
961        return Err(InvalidBlockHeaderError::ExcessBlobGasIncorrect);
962    }
963    Ok(())
964}
965
966pub fn calc_excess_blob_gas(parent: &BlockHeader, schedule: ForkBlobSchedule, fork: Fork) -> u64 {
967    let parent_blob_gas_used = parent.blob_gas_used.unwrap_or_default();
968    let parent_base_fee_per_gas = parent.base_fee_per_gas.unwrap_or_default();
969    let parent_excess_blob_gas = parent.excess_blob_gas.unwrap_or_default();
970
971    let excess_blob_gas = parent_excess_blob_gas + parent_blob_gas_used;
972    let target_blob_gas_per_block = (schedule.target * GAS_PER_BLOB) as u64;
973    if excess_blob_gas < target_blob_gas_per_block {
974        return 0;
975    }
976
977    if fork >= Fork::Osaka
978        && U256::from(BLOB_BASE_COST) * U256::from(parent_base_fee_per_gas)
979            > (U256::from(GAS_PER_BLOB))
980                * calculate_base_fee_per_blob_gas(
981                    parent_excess_blob_gas,
982                    schedule.base_fee_update_fraction,
983                )
984    {
985        return parent_excess_blob_gas
986            + parent_blob_gas_used * (schedule.max as u64 - schedule.target as u64)
987                / schedule.max as u64;
988    }
989
990    excess_blob_gas - target_blob_gas_per_block
991}
992
993#[cfg(test)]
994mod test {
995    use super::*;
996    use crate::constants::EMPTY_KECCAK_HASH;
997    use crate::types::{BLOB_BASE_FEE_UPDATE_FRACTION, ELASTICITY_MULTIPLIER, INITIAL_BASE_FEE};
998    use ethereum_types::H160;
999    use hex_literal::hex;
1000    use std::str::FromStr;
1001
1002    #[test]
1003    fn test_compute_withdrawals_root() {
1004        // Source: https://github.com/ethereum/tests/blob/9760400e667eba241265016b02644ef62ab55de2/BlockchainTests/EIPTests/bc4895-withdrawals/amountIs0.json
1005        // "withdrawals" : [
1006        //             {
1007        //                 "address" : "0xc94f5374fce5edbc8e2a8697c15331677e6ebf0b",
1008        //                 "amount" : "0x00",
1009        //                 "index" : "0x00",
1010        //                 "validatorIndex" : "0x00"
1011        //             }
1012        //         ]
1013        // "withdrawalsRoot" : "0x48a703da164234812273ea083e4ec3d09d028300cd325b46a6a75402e5a7ab95"
1014        let withdrawals = vec![Withdrawal {
1015            index: 0x00,
1016            validator_index: 0x00,
1017            address: H160::from_slice(&hex!("c94f5374fce5edbc8e2a8697c15331677e6ebf0b")),
1018            amount: 0x00_u64,
1019        }];
1020        let expected_root = H256::from_slice(&hex!(
1021            "48a703da164234812273ea083e4ec3d09d028300cd325b46a6a75402e5a7ab95"
1022        ));
1023        let root = compute_withdrawals_root(&withdrawals, &ethrex_crypto::NativeCrypto);
1024        assert_eq!(root, expected_root);
1025    }
1026
1027    #[test]
1028    fn test_validate_block_header() {
1029        let parent_block = BlockHeader {
1030            parent_hash: H256::from_str(
1031                "0x0000000000000000000000000000000000000000000000000000000000000000",
1032            )
1033            .unwrap(),
1034            ommers_hash: H256::from_str(
1035                "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
1036            )
1037            .unwrap(),
1038            coinbase: Address::zero(),
1039            state_root: H256::from_str(
1040                "0x590245a249decc317041b8dc7141cec0559c533efb82221e4e0a30a6456acf8b",
1041            )
1042            .unwrap(),
1043            transactions_root: H256::from_str(
1044                "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
1045            )
1046            .unwrap(),
1047            receipts_root: H256::from_str(
1048                "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
1049            )
1050            .unwrap(),
1051            logs_bloom: Bloom::from([0; 256]),
1052            difficulty: U256::zero(),
1053            number: 0,
1054            gas_limit: 0x016345785d8a0000,
1055            gas_used: 0,
1056            timestamp: 0,
1057            extra_data: Bytes::new(),
1058            prev_randao: H256::zero(),
1059            nonce: 0x0000000000000000,
1060            base_fee_per_gas: Some(0x07),
1061            withdrawals_root: Some(
1062                H256::from_str(
1063                    "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
1064                )
1065                .unwrap(),
1066            ),
1067            blob_gas_used: Some(0x00),
1068            excess_blob_gas: Some(0x00),
1069            parent_beacon_block_root: Some(H256::zero()),
1070            requests_hash: Some(*EMPTY_KECCAK_HASH),
1071            ..Default::default()
1072        };
1073        let block = BlockHeader {
1074            parent_hash: H256::from_str(
1075                "0x48e29e7357408113a4166e04e9f1aeff0680daa2b97ba93df6512a73ddf7a154",
1076            )
1077            .unwrap(),
1078            ommers_hash: H256::from_str(
1079                "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
1080            )
1081            .unwrap(),
1082            coinbase: Address::from_str("0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba").unwrap(),
1083            state_root: H256::from_str(
1084                "0x9de6f95cb4ff4ef22a73705d6ba38c4b927c7bca9887ef5d24a734bb863218d9",
1085            )
1086            .unwrap(),
1087            transactions_root: H256::from_str(
1088                "0x578602b2b7e3a3291c3eefca3a08bc13c0d194f9845a39b6f3bcf843d9fed79d",
1089            )
1090            .unwrap(),
1091            receipts_root: H256::from_str(
1092                "0x035d56bac3f47246c5eed0e6642ca40dc262f9144b582f058bc23ded72aa72fa",
1093            )
1094            .unwrap(),
1095            logs_bloom: Bloom::from([0; 256]),
1096            difficulty: U256::zero(),
1097            number: 1,
1098            gas_limit: 0x016345785d8a0000,
1099            gas_used: 0xa8de,
1100            timestamp: 0x03e8,
1101            extra_data: Bytes::new(),
1102            prev_randao: H256::zero(),
1103            nonce: 0x0000000000000000,
1104            base_fee_per_gas: Some(0x07),
1105            withdrawals_root: Some(
1106                H256::from_str(
1107                    "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
1108                )
1109                .unwrap(),
1110            ),
1111            blob_gas_used: Some(0x00),
1112            excess_blob_gas: Some(0x00),
1113            parent_beacon_block_root: Some(H256::zero()),
1114            requests_hash: Some(*EMPTY_KECCAK_HASH),
1115            ..Default::default()
1116        };
1117        assert!(validate_block_header(&block, &parent_block, ELASTICITY_MULTIPLIER).is_ok());
1118        assert_eq!(parent_block.encode_to_vec().len(), parent_block.length());
1119        assert_eq!(block.encode_to_vec().len(), block.length());
1120    }
1121
1122    #[test]
1123    fn test_compute_transactions_root() {
1124        let encoded_transactions = [
1125            "0x01f8d68330182404842daf517a830186a08080b880c1597f3c842558e64df52c3e0f0973067577c030c0c6578dbb2eef63155a21106fd4426057527f296b2ecdfabc81e34ffc82e89dec20f6b7c41fa1969d3c3bc44262c86f08b5b76077527fb7ece918787c50c878052c30a8b1d4abc07331e6d14b8ded52bbc58a6e9992b76097527f0110937c38cc13b914f201fc09dc6f7a80c001a09930cb92b4a27dce971c697a8c47fa34c98d076abc7b36e1239d6abcfc7c8403a041b35118447fe77c38c0b3a92a2dd3ecba4a9e4b35cc6534cd787f56c0cf2e21",
1126            "0xf86e81fa843127403882f61894db8d964741c53e55df9c2d4e9414c6c96482874e870aa87bee538000808360306ca03aa421df67a101c45ff9cb06ce28f518a5d8d8dbb76a79361280071909650a27a05a447ff053c4ae601cfe81859b58d5603f2d0a73481c50f348089032feb0b073",
1127            "0x02f8ef83301824048413f157f8842daf517a830186a094000000000000000000000000000000000000000080b8807a0a600060a0553db8600060c855c77fb29ecd7661d8aefe101a0db652a728af0fded622ff55d019b545d03a7532932a60ad52604260cd5360bf60ce53609460cf53603e60d05360f560d153bc596000609e55600060c6556000601f556000609155535660556057536055605853606e60595360e7605a5360d0605b5360eb60c080a03acb03b1fc20507bc66210f7e18ff5af65038fb22c626ae488ad9513d9b6debca05d38459e9d2a221eb345b0c2761b719b313d062ff1ea3d10cf5b8762c44385a6",
1128            "0x01f8ea8330182402842daf517a830186a094000000000000000000000000000000000000000080b880bdb30d976000604e557145600060a155d67fe7e473caf6e33cba341136268fc1189ba07837ef8a266570289ff53afc43436260c7527f333dfe837f4838f6053e5e46e4151aeec28f356ec39a2db9769f36ec92e3e3f660e7527f0b261608674300d4621eff679096a6ed786591aca69f2b22a3ea6949621daade610107527f3cc080a01f3f906540fb56b0576c51b3ffa86df213fd1f407378c9441cfdd9d5f3c1df3da035691b16c053b68ec74683ae020293cbc6a47ac773dc8defb96cb680c576e5a3",
1129        ];
1130        let transactions: Vec<Transaction> = encoded_transactions
1131            .iter()
1132            .map(|hex| {
1133                Transaction::decode_canonical(&hex::decode(hex.trim_start_matches("0x")).unwrap())
1134                    .unwrap()
1135            })
1136            .collect();
1137        let transactions_root =
1138            compute_transactions_root(&transactions, &ethrex_crypto::NativeCrypto);
1139        let expected_root = H256::from_slice(
1140            &hex::decode("adf0387d2303fe80aeca23bf6828c979b44d8a8fe4a1ba1d3511bc1567ca80de")
1141                .unwrap(),
1142        );
1143        assert_eq!(transactions_root, expected_root);
1144    }
1145
1146    #[test]
1147    // The values for this test were taken from sepolia testnet block number 6029872
1148    // Where a silent overflow within base fee calculations led to the wrong expected base fee
1149    fn test_calculate_base_fee_per_gas_big_numbers() {
1150        let expected_base_fee = Some(1317727380375);
1151        let block_gas_limit = 30000000;
1152        let parent_gas_limit = 30000000;
1153        let parent_gas_used = 1981764;
1154        let parent_base_fee_per_gas = 1478077008012;
1155        let calc_base_fee = calculate_base_fee_per_gas(
1156            block_gas_limit,
1157            parent_gas_limit,
1158            parent_gas_used,
1159            parent_base_fee_per_gas,
1160            ELASTICITY_MULTIPLIER,
1161        );
1162        assert_eq!(calc_base_fee, expected_base_fee)
1163    }
1164
1165    #[test]
1166    fn test_calc_blob_fee_post_osaka_bpo1() {
1167        let parent = BlockHeader {
1168            excess_blob_gas: Some(5149252),
1169            blob_gas_used: Some(1310720),
1170            base_fee_per_gas: Some(30),
1171            ..Default::default()
1172        };
1173        let schedule = ForkBlobSchedule {
1174            target: 9,
1175            max: 14,
1176            base_fee_update_fraction: 8832827,
1177        };
1178        let fork = Fork::Osaka;
1179
1180        let res = calc_excess_blob_gas(&parent, schedule, fork);
1181        assert_eq!(res, 5617366)
1182    }
1183
1184    #[test]
1185    fn test_calc_blob_fee_post_osaka_bpo3() {
1186        let parent = BlockHeader {
1187            excess_blob_gas: Some(19251039),
1188            blob_gas_used: Some(2490368),
1189            base_fee_per_gas: Some(50),
1190            ..Default::default()
1191        };
1192        let schedule = ForkBlobSchedule {
1193            target: 21,
1194            max: 32,
1195            base_fee_update_fraction: 20609697,
1196        };
1197        let fork = Fork::Osaka;
1198        let res = calc_excess_blob_gas(&parent, schedule, fork);
1199        assert_eq!(res, 20107103)
1200    }
1201
1202    #[test]
1203    fn test_calc_blob_fee_post_osaka_bpo1_ef() {
1204        let parent = BlockHeader {
1205            excess_blob_gas: Some(0x360000),
1206            blob_gas_used: Some(0),
1207            base_fee_per_gas: Some(0x11),
1208            ..Default::default()
1209        };
1210        let schedule = ForkBlobSchedule {
1211            target: 9,
1212            max: 14,
1213            base_fee_update_fraction: 0x86c73b,
1214        };
1215        let fork = Fork::Osaka;
1216
1217        let res = calc_excess_blob_gas(&parent, schedule, fork);
1218        assert_eq!(res, 3538944)
1219    }
1220
1221    #[test]
1222    fn test_calc_excess_blob_gas_at_amsterdam_inherits_bpo1_target() {
1223        // Amsterdam carries no blob params of its own, so a chain that scheduled BPO1
1224        // and never scheduled BPO2 keeps BPO1's target of 10 and max of 15 across the
1225        // Amsterdam boundary. A parent that spent 12 blobs is above that target, so the
1226        // EIP-7918 reserve-price branch raises the excess by `used * (max - target) / max`.
1227        // Resolving the schedule from an unscheduled BPO2 (target 14) instead would put
1228        // the parent below target and wrongly return 0.
1229        let parent = BlockHeader {
1230            excess_blob_gas: Some(0),
1231            blob_gas_used: Some(12 * GAS_PER_BLOB as u64),
1232            base_fee_per_gas: Some(INITIAL_BASE_FEE),
1233            ..Default::default()
1234        };
1235        let config = ChainConfig {
1236            osaka_time: Some(0),
1237            bpo1_time: Some(0),
1238            amsterdam_time: Some(100),
1239            ..Default::default()
1240        };
1241
1242        let schedule = config
1243            .get_fork_blob_schedule(100)
1244            .expect("Amsterdam must resolve a blob schedule");
1245        assert_eq!(schedule.target, 10);
1246        assert_eq!(schedule.max, 15);
1247
1248        let res = calc_excess_blob_gas(&parent, schedule, config.fork(100));
1249        assert_eq!(res, 4 * GAS_PER_BLOB as u64);
1250    }
1251
1252    #[test]
1253    fn test_fake_exponential_overflow() {
1254        // With u64 this overflows
1255        assert!(fake_exponential(57532635.into(), 3145728.into(), 3338477).is_ok());
1256    }
1257
1258    #[test]
1259    fn test_fake_exponential_bounds_overflow() {
1260        // Making sure the limit we state in the documentation of 400_000_000 works
1261        let thing = fake_exponential(
1262            MIN_BASE_FEE_PER_BLOB_GAS.into(),
1263            400_000_000.into(),
1264            BLOB_BASE_FEE_UPDATE_FRACTION,
1265        );
1266        // With u64 this overflows
1267        assert!(thing.is_ok());
1268    }
1269
1270    #[test]
1271    fn burned_fees_header_roundtrip_and_hash() {
1272        // For a correct round-trip, all preceding optional fields must be Some so the
1273        // positional/trailing RLP decoder can attribute burned_fees correctly.
1274        // This mirrors a real LStar-era block header.
1275        let h = BlockHeader {
1276            base_fee_per_gas: Some(7),
1277            withdrawals_root: Some(H256::zero()),
1278            blob_gas_used: Some(0),
1279            excess_blob_gas: Some(0),
1280            parent_beacon_block_root: Some(H256::zero()),
1281            requests_hash: Some(H256::zero()),
1282            block_access_list_hash: Some(H256::zero()),
1283            slot_number: Some(1),
1284            burned_fees: Some(12345),
1285            ..Default::default()
1286        };
1287        let encoded = h.encode_to_vec();
1288        let decoded = BlockHeader::decode(&encoded).expect("decode");
1289        assert_eq!(decoded.burned_fees, Some(12345));
1290        // None round-trips as None (pre-LStar).
1291        let h_none = BlockHeader {
1292            burned_fees: None,
1293            ..Default::default()
1294        };
1295        assert_eq!(
1296            BlockHeader::decode(&h_none.encode_to_vec())
1297                .unwrap()
1298                .burned_fees,
1299            None
1300        );
1301        // burned_fees participates in the block hash: same base state, only burned_fees differs.
1302        let h_with = BlockHeader {
1303            base_fee_per_gas: Some(7),
1304            withdrawals_root: Some(H256::zero()),
1305            blob_gas_used: Some(0),
1306            excess_blob_gas: Some(0),
1307            parent_beacon_block_root: Some(H256::zero()),
1308            requests_hash: Some(H256::zero()),
1309            block_access_list_hash: Some(H256::zero()),
1310            slot_number: Some(1),
1311            burned_fees: Some(12345),
1312            ..Default::default()
1313        };
1314        let h_without = BlockHeader {
1315            base_fee_per_gas: Some(7),
1316            withdrawals_root: Some(H256::zero()),
1317            blob_gas_used: Some(0),
1318            excess_blob_gas: Some(0),
1319            parent_beacon_block_root: Some(H256::zero()),
1320            requests_hash: Some(H256::zero()),
1321            block_access_list_hash: Some(H256::zero()),
1322            slot_number: Some(1),
1323            burned_fees: None,
1324            ..Default::default()
1325        };
1326        assert_ne!(h_with.hash(), h_without.hash());
1327    }
1328
1329    /// Verify that `into_with_burned_fees` clears the OnceCell so the resulting
1330    /// hash reflects the injected value and not any previously cached hash.
1331    ///
1332    /// This is the TDD anchor for the Task-4 verify-flow reorder: after
1333    /// `execute_blocks` caches the block hash (burned_fees=None), we must be
1334    /// able to inject the recomputed `burned_fees` and still get the correct hash.
1335    #[test]
1336    fn into_with_burned_fees_clears_stale_cache() {
1337        use crate::NativeCrypto;
1338
1339        // Build a default header (burned_fees = None).
1340        let header_none = BlockHeader::default();
1341
1342        // Force the hash cache to populate with burned_fees=None value.
1343        let hash_stale = header_none.hash();
1344
1345        // Build a reference header with burned_fees=Some(42) from scratch (fresh OnceCell).
1346        let header_some_fresh = BlockHeader {
1347            burned_fees: Some(42),
1348            ..BlockHeader::default()
1349        };
1350        let hash_expected = header_some_fresh.compute_block_hash(&NativeCrypto);
1351
1352        // The two hashes must differ — burned_fees is RLP-encoded in the header.
1353        assert_ne!(
1354            hash_stale, hash_expected,
1355            "burned_fees=None and burned_fees=Some(42) must produce different block hashes"
1356        );
1357
1358        // Now inject Some(42) via into_with_burned_fees, starting from the stale-cached header.
1359        let fresh_header = header_none.into_with_burned_fees(Some(42));
1360        let hash_fresh = fresh_header.hash();
1361
1362        // Must match the reference hash, NOT the stale one.
1363        assert_eq!(
1364            hash_fresh, hash_expected,
1365            "into_with_burned_fees must yield a hash identical to building a fresh header with the same burned_fees"
1366        );
1367        assert_ne!(
1368            hash_fresh, hash_stale,
1369            "OnceCell must have been cleared: fresh hash must differ from the stale cached hash"
1370        );
1371    }
1372
1373    /// Verify the Amsterdam (pre-LStar) no-op: injecting None into a header
1374    /// whose hash was cached with burned_fees=None yields the same hash.
1375    ///
1376    /// This is the primary correctness requirement for Task 4: the reordered
1377    /// verify-flow must not regress the current Amsterdam path.
1378    #[test]
1379    fn into_with_burned_fees_none_is_idempotent() {
1380        let header = BlockHeader::default();
1381        let hash_before = header.hash(); // populate cache with burned_fees=None
1382
1383        // Inject None (Amsterdam: burned_fees is None both before and after execution).
1384        let header_after = header.into_with_burned_fees(None);
1385        let hash_after = header_after.hash();
1386
1387        assert_eq!(
1388            hash_before, hash_after,
1389            "injecting None must not change the block hash (Amsterdam no-op)"
1390        );
1391    }
1392
1393    #[test]
1394    fn test_validate_block_body_rejects_missing_withdrawals_field() {
1395        use crate::constants::EMPTY_WITHDRAWALS_HASH;
1396
1397        let crypto = NativeCrypto;
1398        let header = BlockHeader {
1399            transactions_root: compute_transactions_root(&[], &crypto),
1400            withdrawals_root: Some(*EMPTY_WITHDRAWALS_HASH),
1401            ..Default::default()
1402        };
1403
1404        // A post-Shanghai body that OMITS the withdrawals field is malformed and
1405        // must be rejected even when the header commits to the empty-withdrawals
1406        // root (geth: "missing withdrawals in block body"; reth, nethermind,
1407        // erigon and besu reject this shape as well).
1408        let body_missing = BlockBody {
1409            withdrawals: None,
1410            ..BlockBody::empty()
1411        };
1412        assert!(matches!(
1413            validate_block_body(&header, &body_missing, &crypto),
1414            Err(InvalidBlockBodyError::WithdrawalsRootNotMatch)
1415        ));
1416
1417        // An explicit empty withdrawals list is valid for the same header.
1418        assert!(validate_block_body(&header, &BlockBody::empty(), &crypto).is_ok());
1419
1420        // A withdrawals field without a header root (pre-Shanghai shape) is rejected.
1421        let pre_shanghai_header = BlockHeader {
1422            transactions_root: compute_transactions_root(&[], &crypto),
1423            ..Default::default()
1424        };
1425        assert!(matches!(
1426            validate_block_body(&pre_shanghai_header, &BlockBody::empty(), &crypto),
1427            Err(InvalidBlockBodyError::WithdrawalsRootNotMatch)
1428        ));
1429        // Neither field present is valid.
1430        let body_no_withdrawals = BlockBody {
1431            withdrawals: None,
1432            ..BlockBody::empty()
1433        };
1434        assert!(validate_block_body(&pre_shanghai_header, &body_no_withdrawals, &crypto).is_ok());
1435    }
1436
1437    #[test]
1438    fn test_normalize_legacy_withdrawals() {
1439        use crate::constants::EMPTY_WITHDRAWALS_HASH;
1440
1441        let crypto = NativeCrypto;
1442
1443        // Legacy shape from trusted history: omitted field + empty-withdrawals
1444        // header root normalizes to the canonical Some(vec![]), and the
1445        // normalized body passes validation.
1446        let header = BlockHeader {
1447            transactions_root: compute_transactions_root(&[], &crypto),
1448            withdrawals_root: Some(*EMPTY_WITHDRAWALS_HASH),
1449            ..Default::default()
1450        };
1451        let mut body = BlockBody {
1452            withdrawals: None,
1453            ..BlockBody::empty()
1454        };
1455        normalize_legacy_withdrawals(&header, &mut body);
1456        assert_eq!(body.withdrawals, Some(Vec::new()));
1457        assert!(validate_block_body(&header, &body, &crypto).is_ok());
1458
1459        // An omitted field under a NON-empty withdrawals root is not the legacy
1460        // shape: the body stays untouched and validation still rejects it.
1461        let bad_header = BlockHeader {
1462            transactions_root: compute_transactions_root(&[], &crypto),
1463            withdrawals_root: Some(H256::repeat_byte(0xAB)),
1464            ..Default::default()
1465        };
1466        let mut bad_body = BlockBody {
1467            withdrawals: None,
1468            ..BlockBody::empty()
1469        };
1470        normalize_legacy_withdrawals(&bad_header, &mut bad_body);
1471        assert_eq!(bad_body.withdrawals, None);
1472        assert!(validate_block_body(&bad_header, &bad_body, &crypto).is_err());
1473
1474        // Pre-Shanghai shape (no header root, no field) stays untouched.
1475        let pre_shanghai_header = BlockHeader {
1476            transactions_root: compute_transactions_root(&[], &crypto),
1477            ..Default::default()
1478        };
1479        let mut pre_shanghai_body = BlockBody {
1480            withdrawals: None,
1481            ..BlockBody::empty()
1482        };
1483        normalize_legacy_withdrawals(&pre_shanghai_header, &mut pre_shanghai_body);
1484        assert_eq!(pre_shanghai_body.withdrawals, None);
1485
1486        // An already-canonical body is left as-is.
1487        let mut canonical = BlockBody::empty();
1488        let before = canonical.withdrawals.clone();
1489        normalize_legacy_withdrawals(&header, &mut canonical);
1490        assert_eq!(canonical.withdrawals, before);
1491    }
1492}