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}
704
705#[derive(Debug, thiserror::Error)]
706pub enum InvalidBlockBodyError {
707    #[error("Withdrawals root does not match")]
708    WithdrawalsRootNotMatch,
709    #[error("Transactions root does not match")]
710    TransactionsRootNotMatch,
711    #[error("Ommers is not empty")]
712    OmmersIsNotEmpty,
713}
714
715/// Validates that the header fields are correct in reference to the parent_header
716pub fn validate_block_header(
717    header: &BlockHeader,
718    parent_header: &BlockHeader,
719    elasticity_multiplier: u64,
720) -> Result<(), InvalidBlockHeaderError> {
721    if header.gas_used > header.gas_limit {
722        return Err(InvalidBlockHeaderError::GasUsedGreaterThanGasLimit);
723    }
724
725    let expected_base_fee_per_gas = if let Some(base_fee) = calculate_base_fee_per_gas(
726        header.gas_limit,
727        parent_header.gas_limit,
728        parent_header.gas_used,
729        parent_header.base_fee_per_gas.unwrap_or(INITIAL_BASE_FEE),
730        elasticity_multiplier,
731    ) {
732        base_fee
733    } else {
734        return Err(InvalidBlockHeaderError::GasLimitTooFarFromParent);
735    };
736
737    if expected_base_fee_per_gas != header.base_fee_per_gas.unwrap_or(INITIAL_BASE_FEE) {
738        return Err(InvalidBlockHeaderError::BaseFeePerGasIncorrect);
739    }
740
741    if header.timestamp <= parent_header.timestamp {
742        return Err(InvalidBlockHeaderError::TimestampNotGreaterThanParent);
743    }
744
745    if header.number != parent_header.number + 1 {
746        return Err(InvalidBlockHeaderError::BlockNumberNotOneGreater);
747    }
748
749    if header.extra_data.len() > 32 {
750        return Err(InvalidBlockHeaderError::ExtraDataTooLong);
751    }
752
753    if !header.difficulty.is_zero() {
754        return Err(InvalidBlockHeaderError::DifficultyNotZero);
755    }
756
757    if header.nonce != 0 {
758        return Err(InvalidBlockHeaderError::NonceNotZero);
759    }
760
761    if header.ommers_hash != *DEFAULT_OMMERS_HASH {
762        return Err(InvalidBlockHeaderError::OmmersHashNotDefault);
763    }
764
765    if header.parent_hash != parent_header.hash() {
766        return Err(InvalidBlockHeaderError::ParentHashIncorrect);
767    }
768
769    Ok(())
770}
771
772/// Validates that the body matches with the header
773pub fn validate_block_body(
774    block_header: &BlockHeader,
775    block_body: &BlockBody,
776    crypto: &dyn Crypto,
777) -> Result<(), InvalidBlockBodyError> {
778    // Validates that:
779    //  - Transactions root and withdrawals root matches with the header
780    //  - Ommers is empty -> https://eips.ethereum.org/EIPS/eip-3675
781    let computed_tx_root = compute_transactions_root(&block_body.transactions, crypto);
782
783    if block_header.transactions_root != computed_tx_root {
784        return Err(InvalidBlockBodyError::TransactionsRootNotMatch);
785    }
786
787    if !block_body.ommers.is_empty() {
788        return Err(InvalidBlockBodyError::OmmersIsNotEmpty);
789    }
790
791    match (block_header.withdrawals_root, &block_body.withdrawals) {
792        (Some(withdrawals_root), Some(withdrawals)) => {
793            let computed_withdrawals_root = compute_withdrawals_root(withdrawals, crypto);
794            if withdrawals_root != computed_withdrawals_root {
795                return Err(InvalidBlockBodyError::WithdrawalsRootNotMatch);
796            }
797        }
798        // Post-Shanghai, the withdrawals field must be present in the body even when
799        // empty. A body that omits it is malformed, regardless of the header's
800        // withdrawals_root — geth ("missing withdrawals in block body"), reth,
801        // nethermind, erigon and besu all reject this shape.
802        (None, None) => {}
803        _ => return Err(InvalidBlockBodyError::WithdrawalsRootNotMatch),
804    }
805
806    Ok(())
807}
808
809/// Normalizes a legacy post-Shanghai body shape produced by older ethrex versions,
810/// which omitted the `withdrawals` field while the header committed to the
811/// empty-withdrawals root. `validate_block_body` rejects that shape (reference
812/// clients treat it as malformed on the wire), but blocks already sitting in a
813/// node's store or in batch blobs published to L1 are immutable history. When the
814/// header's withdrawals_root is exactly the empty-list root, `Some(vec![])` is the
815/// provably-equivalent canonical body; any other root leaves the body untouched, and
816/// validation rejects it exactly as before.
817///
818/// Only call this on bodies read from trusted local history (store re-execution,
819/// blob reconstruction) — never on bodies received from the network.
820pub fn normalize_legacy_withdrawals(header: &BlockHeader, body: &mut BlockBody) {
821    if body.withdrawals.is_none() && header.withdrawals_root == Some(*EMPTY_WITHDRAWALS_HASH) {
822        tracing::debug!(
823            block = header.number,
824            "Normalizing legacy omitted-withdrawals block body from trusted history"
825        );
826        body.withdrawals = Some(Vec::new());
827    }
828}
829
830/// Validates that only the required field are present for a Prague block
831/// Also validates excess_blob_gas value against parent's header
832pub fn validate_prague_header_fields(
833    header: &BlockHeader,
834    parent_header: &BlockHeader,
835    chain_config: &ChainConfig,
836) -> Result<(), InvalidBlockHeaderError> {
837    if header.excess_blob_gas.is_none() {
838        return Err(InvalidBlockHeaderError::ExcessBlobGasNotPresent);
839    }
840    if header.blob_gas_used.is_none() {
841        return Err(InvalidBlockHeaderError::BlobGasUsedNotPresent);
842    }
843    validate_excess_blob_gas(header, parent_header, chain_config)?;
844
845    if header.parent_beacon_block_root.is_none() {
846        return Err(InvalidBlockHeaderError::ParentBeaconBlockRootNotPresent);
847    }
848    if header.requests_hash.is_none() {
849        return Err(InvalidBlockHeaderError::RequestsHashNotPresent);
850    }
851    if chain_config.is_amsterdam_activated(header.timestamp) {
852        // EIP-7928: BAL hash and EIP-7843: slot_number are both mandatory
853        // trailing header fields on Amsterdam. A header omitting either is
854        // schema-invalid and must be rejected to match conformant clients.
855        if header.block_access_list_hash.is_none() {
856            return Err(InvalidBlockHeaderError::BlockAccessListHashNotPresent);
857        }
858        if header.slot_number.is_none() {
859            return Err(InvalidBlockHeaderError::SlotNumberNotPresent);
860        }
861    } else {
862        if header.block_access_list_hash.is_some() {
863            return Err(InvalidBlockHeaderError::BlockAccessListHashPresent);
864        }
865        if header.slot_number.is_some() {
866            return Err(InvalidBlockHeaderError::SlotNumberPresent);
867        }
868    }
869    Ok(())
870}
871
872/// Validates that only the required field are present for a Cancun block
873/// Also validates excess_blob_gas value against parent's header
874pub fn validate_cancun_header_fields(
875    header: &BlockHeader,
876    parent_header: &BlockHeader,
877    chain_config: &ChainConfig,
878) -> Result<(), InvalidBlockHeaderError> {
879    if header.excess_blob_gas.is_none() {
880        return Err(InvalidBlockHeaderError::ExcessBlobGasNotPresent);
881    }
882    if header.blob_gas_used.is_none() {
883        return Err(InvalidBlockHeaderError::BlobGasUsedNotPresent);
884    }
885    validate_excess_blob_gas(header, parent_header, chain_config)?;
886    if header.parent_beacon_block_root.is_none() {
887        return Err(InvalidBlockHeaderError::ParentBeaconBlockRootNotPresent);
888    }
889    if header.requests_hash.is_some() {
890        return Err(InvalidBlockHeaderError::RequestsHashPresent);
891    }
892    if header.block_access_list_hash.is_some() {
893        return Err(InvalidBlockHeaderError::BlockAccessListHashPresent);
894    }
895    if header.slot_number.is_some() {
896        return Err(InvalidBlockHeaderError::SlotNumberPresent);
897    }
898    Ok(())
899}
900
901/// Validates that only the required field are present for a pre Cancun block
902/// Also validates excess_blob_gas value against parent's header
903pub fn validate_pre_cancun_header_fields(
904    header: &BlockHeader,
905) -> Result<(), InvalidBlockHeaderError> {
906    if header.excess_blob_gas.is_some() {
907        return Err(InvalidBlockHeaderError::ExcessBlobGasPresent);
908    }
909    if header.blob_gas_used.is_some() {
910        return Err(InvalidBlockHeaderError::BlobGasUsedPresent);
911    }
912    if header.parent_beacon_block_root.is_some() {
913        return Err(InvalidBlockHeaderError::ParentBeaconBlockRootPresent);
914    }
915    if header.requests_hash.is_some() {
916        return Err(InvalidBlockHeaderError::RequestsHashPresent);
917    }
918    if header.block_access_list_hash.is_some() {
919        return Err(InvalidBlockHeaderError::BlockAccessListHashPresent);
920    }
921    if header.slot_number.is_some() {
922        return Err(InvalidBlockHeaderError::SlotNumberPresent);
923    }
924    Ok(())
925}
926
927fn validate_excess_blob_gas(
928    header: &BlockHeader,
929    parent_header: &BlockHeader,
930    chain_config: &ChainConfig,
931) -> Result<(), InvalidBlockHeaderError> {
932    let expected_excess_blob_gas = chain_config
933        .get_fork_blob_schedule(header.timestamp)
934        .map(|schedule| {
935            calc_excess_blob_gas(parent_header, schedule, chain_config.fork(header.timestamp))
936        })
937        .unwrap_or_default();
938    if header
939        .excess_blob_gas
940        .is_none_or(|header_excess_blob_gas| header_excess_blob_gas != expected_excess_blob_gas)
941    {
942        return Err(InvalidBlockHeaderError::ExcessBlobGasIncorrect);
943    }
944    Ok(())
945}
946
947pub fn calc_excess_blob_gas(parent: &BlockHeader, schedule: ForkBlobSchedule, fork: Fork) -> u64 {
948    let parent_blob_gas_used = parent.blob_gas_used.unwrap_or_default();
949    let parent_base_fee_per_gas = parent.base_fee_per_gas.unwrap_or_default();
950    let parent_excess_blob_gas = parent.excess_blob_gas.unwrap_or_default();
951
952    let excess_blob_gas = parent_excess_blob_gas + parent_blob_gas_used;
953    let target_blob_gas_per_block = (schedule.target * GAS_PER_BLOB) as u64;
954    if excess_blob_gas < target_blob_gas_per_block {
955        return 0;
956    }
957
958    if fork >= Fork::Osaka
959        && U256::from(BLOB_BASE_COST) * U256::from(parent_base_fee_per_gas)
960            > (U256::from(GAS_PER_BLOB))
961                * calculate_base_fee_per_blob_gas(
962                    parent_excess_blob_gas,
963                    schedule.base_fee_update_fraction,
964                )
965    {
966        return parent_excess_blob_gas
967            + parent_blob_gas_used * (schedule.max as u64 - schedule.target as u64)
968                / schedule.max as u64;
969    }
970
971    excess_blob_gas - target_blob_gas_per_block
972}
973
974#[cfg(test)]
975mod test {
976    use super::*;
977    use crate::constants::EMPTY_KECCAK_HASH;
978    use crate::types::{BLOB_BASE_FEE_UPDATE_FRACTION, ELASTICITY_MULTIPLIER, INITIAL_BASE_FEE};
979    use ethereum_types::H160;
980    use hex_literal::hex;
981    use std::str::FromStr;
982
983    #[test]
984    fn test_compute_withdrawals_root() {
985        // Source: https://github.com/ethereum/tests/blob/9760400e667eba241265016b02644ef62ab55de2/BlockchainTests/EIPTests/bc4895-withdrawals/amountIs0.json
986        // "withdrawals" : [
987        //             {
988        //                 "address" : "0xc94f5374fce5edbc8e2a8697c15331677e6ebf0b",
989        //                 "amount" : "0x00",
990        //                 "index" : "0x00",
991        //                 "validatorIndex" : "0x00"
992        //             }
993        //         ]
994        // "withdrawalsRoot" : "0x48a703da164234812273ea083e4ec3d09d028300cd325b46a6a75402e5a7ab95"
995        let withdrawals = vec![Withdrawal {
996            index: 0x00,
997            validator_index: 0x00,
998            address: H160::from_slice(&hex!("c94f5374fce5edbc8e2a8697c15331677e6ebf0b")),
999            amount: 0x00_u64,
1000        }];
1001        let expected_root = H256::from_slice(&hex!(
1002            "48a703da164234812273ea083e4ec3d09d028300cd325b46a6a75402e5a7ab95"
1003        ));
1004        let root = compute_withdrawals_root(&withdrawals, &ethrex_crypto::NativeCrypto);
1005        assert_eq!(root, expected_root);
1006    }
1007
1008    #[test]
1009    fn test_validate_block_header() {
1010        let parent_block = BlockHeader {
1011            parent_hash: H256::from_str(
1012                "0x0000000000000000000000000000000000000000000000000000000000000000",
1013            )
1014            .unwrap(),
1015            ommers_hash: H256::from_str(
1016                "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
1017            )
1018            .unwrap(),
1019            coinbase: Address::zero(),
1020            state_root: H256::from_str(
1021                "0x590245a249decc317041b8dc7141cec0559c533efb82221e4e0a30a6456acf8b",
1022            )
1023            .unwrap(),
1024            transactions_root: H256::from_str(
1025                "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
1026            )
1027            .unwrap(),
1028            receipts_root: H256::from_str(
1029                "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
1030            )
1031            .unwrap(),
1032            logs_bloom: Bloom::from([0; 256]),
1033            difficulty: U256::zero(),
1034            number: 0,
1035            gas_limit: 0x016345785d8a0000,
1036            gas_used: 0,
1037            timestamp: 0,
1038            extra_data: Bytes::new(),
1039            prev_randao: H256::zero(),
1040            nonce: 0x0000000000000000,
1041            base_fee_per_gas: Some(0x07),
1042            withdrawals_root: Some(
1043                H256::from_str(
1044                    "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
1045                )
1046                .unwrap(),
1047            ),
1048            blob_gas_used: Some(0x00),
1049            excess_blob_gas: Some(0x00),
1050            parent_beacon_block_root: Some(H256::zero()),
1051            requests_hash: Some(*EMPTY_KECCAK_HASH),
1052            ..Default::default()
1053        };
1054        let block = BlockHeader {
1055            parent_hash: H256::from_str(
1056                "0x48e29e7357408113a4166e04e9f1aeff0680daa2b97ba93df6512a73ddf7a154",
1057            )
1058            .unwrap(),
1059            ommers_hash: H256::from_str(
1060                "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
1061            )
1062            .unwrap(),
1063            coinbase: Address::from_str("0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba").unwrap(),
1064            state_root: H256::from_str(
1065                "0x9de6f95cb4ff4ef22a73705d6ba38c4b927c7bca9887ef5d24a734bb863218d9",
1066            )
1067            .unwrap(),
1068            transactions_root: H256::from_str(
1069                "0x578602b2b7e3a3291c3eefca3a08bc13c0d194f9845a39b6f3bcf843d9fed79d",
1070            )
1071            .unwrap(),
1072            receipts_root: H256::from_str(
1073                "0x035d56bac3f47246c5eed0e6642ca40dc262f9144b582f058bc23ded72aa72fa",
1074            )
1075            .unwrap(),
1076            logs_bloom: Bloom::from([0; 256]),
1077            difficulty: U256::zero(),
1078            number: 1,
1079            gas_limit: 0x016345785d8a0000,
1080            gas_used: 0xa8de,
1081            timestamp: 0x03e8,
1082            extra_data: Bytes::new(),
1083            prev_randao: H256::zero(),
1084            nonce: 0x0000000000000000,
1085            base_fee_per_gas: Some(0x07),
1086            withdrawals_root: Some(
1087                H256::from_str(
1088                    "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
1089                )
1090                .unwrap(),
1091            ),
1092            blob_gas_used: Some(0x00),
1093            excess_blob_gas: Some(0x00),
1094            parent_beacon_block_root: Some(H256::zero()),
1095            requests_hash: Some(*EMPTY_KECCAK_HASH),
1096            ..Default::default()
1097        };
1098        assert!(validate_block_header(&block, &parent_block, ELASTICITY_MULTIPLIER).is_ok());
1099        assert_eq!(parent_block.encode_to_vec().len(), parent_block.length());
1100        assert_eq!(block.encode_to_vec().len(), block.length());
1101    }
1102
1103    #[test]
1104    fn test_compute_transactions_root() {
1105        let encoded_transactions = [
1106            "0x01f8d68330182404842daf517a830186a08080b880c1597f3c842558e64df52c3e0f0973067577c030c0c6578dbb2eef63155a21106fd4426057527f296b2ecdfabc81e34ffc82e89dec20f6b7c41fa1969d3c3bc44262c86f08b5b76077527fb7ece918787c50c878052c30a8b1d4abc07331e6d14b8ded52bbc58a6e9992b76097527f0110937c38cc13b914f201fc09dc6f7a80c001a09930cb92b4a27dce971c697a8c47fa34c98d076abc7b36e1239d6abcfc7c8403a041b35118447fe77c38c0b3a92a2dd3ecba4a9e4b35cc6534cd787f56c0cf2e21",
1107            "0xf86e81fa843127403882f61894db8d964741c53e55df9c2d4e9414c6c96482874e870aa87bee538000808360306ca03aa421df67a101c45ff9cb06ce28f518a5d8d8dbb76a79361280071909650a27a05a447ff053c4ae601cfe81859b58d5603f2d0a73481c50f348089032feb0b073",
1108            "0x02f8ef83301824048413f157f8842daf517a830186a094000000000000000000000000000000000000000080b8807a0a600060a0553db8600060c855c77fb29ecd7661d8aefe101a0db652a728af0fded622ff55d019b545d03a7532932a60ad52604260cd5360bf60ce53609460cf53603e60d05360f560d153bc596000609e55600060c6556000601f556000609155535660556057536055605853606e60595360e7605a5360d0605b5360eb60c080a03acb03b1fc20507bc66210f7e18ff5af65038fb22c626ae488ad9513d9b6debca05d38459e9d2a221eb345b0c2761b719b313d062ff1ea3d10cf5b8762c44385a6",
1109            "0x01f8ea8330182402842daf517a830186a094000000000000000000000000000000000000000080b880bdb30d976000604e557145600060a155d67fe7e473caf6e33cba341136268fc1189ba07837ef8a266570289ff53afc43436260c7527f333dfe837f4838f6053e5e46e4151aeec28f356ec39a2db9769f36ec92e3e3f660e7527f0b261608674300d4621eff679096a6ed786591aca69f2b22a3ea6949621daade610107527f3cc080a01f3f906540fb56b0576c51b3ffa86df213fd1f407378c9441cfdd9d5f3c1df3da035691b16c053b68ec74683ae020293cbc6a47ac773dc8defb96cb680c576e5a3",
1110        ];
1111        let transactions: Vec<Transaction> = encoded_transactions
1112            .iter()
1113            .map(|hex| {
1114                Transaction::decode_canonical(&hex::decode(hex.trim_start_matches("0x")).unwrap())
1115                    .unwrap()
1116            })
1117            .collect();
1118        let transactions_root =
1119            compute_transactions_root(&transactions, &ethrex_crypto::NativeCrypto);
1120        let expected_root = H256::from_slice(
1121            &hex::decode("adf0387d2303fe80aeca23bf6828c979b44d8a8fe4a1ba1d3511bc1567ca80de")
1122                .unwrap(),
1123        );
1124        assert_eq!(transactions_root, expected_root);
1125    }
1126
1127    #[test]
1128    // The values for this test were taken from sepolia testnet block number 6029872
1129    // Where a silent overflow within base fee calculations led to the wrong expected base fee
1130    fn test_calculate_base_fee_per_gas_big_numbers() {
1131        let expected_base_fee = Some(1317727380375);
1132        let block_gas_limit = 30000000;
1133        let parent_gas_limit = 30000000;
1134        let parent_gas_used = 1981764;
1135        let parent_base_fee_per_gas = 1478077008012;
1136        let calc_base_fee = calculate_base_fee_per_gas(
1137            block_gas_limit,
1138            parent_gas_limit,
1139            parent_gas_used,
1140            parent_base_fee_per_gas,
1141            ELASTICITY_MULTIPLIER,
1142        );
1143        assert_eq!(calc_base_fee, expected_base_fee)
1144    }
1145
1146    #[test]
1147    fn test_calc_blob_fee_post_osaka_bpo1() {
1148        let parent = BlockHeader {
1149            excess_blob_gas: Some(5149252),
1150            blob_gas_used: Some(1310720),
1151            base_fee_per_gas: Some(30),
1152            ..Default::default()
1153        };
1154        let schedule = ForkBlobSchedule {
1155            target: 9,
1156            max: 14,
1157            base_fee_update_fraction: 8832827,
1158        };
1159        let fork = Fork::Osaka;
1160
1161        let res = calc_excess_blob_gas(&parent, schedule, fork);
1162        assert_eq!(res, 5617366)
1163    }
1164
1165    #[test]
1166    fn test_calc_blob_fee_post_osaka_bpo3() {
1167        let parent = BlockHeader {
1168            excess_blob_gas: Some(19251039),
1169            blob_gas_used: Some(2490368),
1170            base_fee_per_gas: Some(50),
1171            ..Default::default()
1172        };
1173        let schedule = ForkBlobSchedule {
1174            target: 21,
1175            max: 32,
1176            base_fee_update_fraction: 20609697,
1177        };
1178        let fork = Fork::Osaka;
1179        let res = calc_excess_blob_gas(&parent, schedule, fork);
1180        assert_eq!(res, 20107103)
1181    }
1182
1183    #[test]
1184    fn test_calc_blob_fee_post_osaka_bpo1_ef() {
1185        let parent = BlockHeader {
1186            excess_blob_gas: Some(0x360000),
1187            blob_gas_used: Some(0),
1188            base_fee_per_gas: Some(0x11),
1189            ..Default::default()
1190        };
1191        let schedule = ForkBlobSchedule {
1192            target: 9,
1193            max: 14,
1194            base_fee_update_fraction: 0x86c73b,
1195        };
1196        let fork = Fork::Osaka;
1197
1198        let res = calc_excess_blob_gas(&parent, schedule, fork);
1199        assert_eq!(res, 3538944)
1200    }
1201
1202    #[test]
1203    fn test_calc_excess_blob_gas_at_amsterdam_inherits_bpo1_target() {
1204        // Amsterdam carries no blob params of its own, so a chain that scheduled BPO1
1205        // and never scheduled BPO2 keeps BPO1's target of 10 and max of 15 across the
1206        // Amsterdam boundary. A parent that spent 12 blobs is above that target, so the
1207        // EIP-7918 reserve-price branch raises the excess by `used * (max - target) / max`.
1208        // Resolving the schedule from an unscheduled BPO2 (target 14) instead would put
1209        // the parent below target and wrongly return 0.
1210        let parent = BlockHeader {
1211            excess_blob_gas: Some(0),
1212            blob_gas_used: Some(12 * GAS_PER_BLOB as u64),
1213            base_fee_per_gas: Some(INITIAL_BASE_FEE),
1214            ..Default::default()
1215        };
1216        let config = ChainConfig {
1217            osaka_time: Some(0),
1218            bpo1_time: Some(0),
1219            amsterdam_time: Some(100),
1220            ..Default::default()
1221        };
1222
1223        let schedule = config
1224            .get_fork_blob_schedule(100)
1225            .expect("Amsterdam must resolve a blob schedule");
1226        assert_eq!(schedule.target, 10);
1227        assert_eq!(schedule.max, 15);
1228
1229        let res = calc_excess_blob_gas(&parent, schedule, config.fork(100));
1230        assert_eq!(res, 4 * GAS_PER_BLOB as u64);
1231    }
1232
1233    #[test]
1234    fn test_fake_exponential_overflow() {
1235        // With u64 this overflows
1236        assert!(fake_exponential(57532635.into(), 3145728.into(), 3338477).is_ok());
1237    }
1238
1239    #[test]
1240    fn test_fake_exponential_bounds_overflow() {
1241        // Making sure the limit we state in the documentation of 400_000_000 works
1242        let thing = fake_exponential(
1243            MIN_BASE_FEE_PER_BLOB_GAS.into(),
1244            400_000_000.into(),
1245            BLOB_BASE_FEE_UPDATE_FRACTION,
1246        );
1247        // With u64 this overflows
1248        assert!(thing.is_ok());
1249    }
1250
1251    #[test]
1252    fn burned_fees_header_roundtrip_and_hash() {
1253        // For a correct round-trip, all preceding optional fields must be Some so the
1254        // positional/trailing RLP decoder can attribute burned_fees correctly.
1255        // This mirrors a real LStar-era block header.
1256        let h = BlockHeader {
1257            base_fee_per_gas: Some(7),
1258            withdrawals_root: Some(H256::zero()),
1259            blob_gas_used: Some(0),
1260            excess_blob_gas: Some(0),
1261            parent_beacon_block_root: Some(H256::zero()),
1262            requests_hash: Some(H256::zero()),
1263            block_access_list_hash: Some(H256::zero()),
1264            slot_number: Some(1),
1265            burned_fees: Some(12345),
1266            ..Default::default()
1267        };
1268        let encoded = h.encode_to_vec();
1269        let decoded = BlockHeader::decode(&encoded).expect("decode");
1270        assert_eq!(decoded.burned_fees, Some(12345));
1271        // None round-trips as None (pre-LStar).
1272        let h_none = BlockHeader {
1273            burned_fees: None,
1274            ..Default::default()
1275        };
1276        assert_eq!(
1277            BlockHeader::decode(&h_none.encode_to_vec())
1278                .unwrap()
1279                .burned_fees,
1280            None
1281        );
1282        // burned_fees participates in the block hash: same base state, only burned_fees differs.
1283        let h_with = BlockHeader {
1284            base_fee_per_gas: Some(7),
1285            withdrawals_root: Some(H256::zero()),
1286            blob_gas_used: Some(0),
1287            excess_blob_gas: Some(0),
1288            parent_beacon_block_root: Some(H256::zero()),
1289            requests_hash: Some(H256::zero()),
1290            block_access_list_hash: Some(H256::zero()),
1291            slot_number: Some(1),
1292            burned_fees: Some(12345),
1293            ..Default::default()
1294        };
1295        let h_without = BlockHeader {
1296            base_fee_per_gas: Some(7),
1297            withdrawals_root: Some(H256::zero()),
1298            blob_gas_used: Some(0),
1299            excess_blob_gas: Some(0),
1300            parent_beacon_block_root: Some(H256::zero()),
1301            requests_hash: Some(H256::zero()),
1302            block_access_list_hash: Some(H256::zero()),
1303            slot_number: Some(1),
1304            burned_fees: None,
1305            ..Default::default()
1306        };
1307        assert_ne!(h_with.hash(), h_without.hash());
1308    }
1309
1310    /// Verify that `into_with_burned_fees` clears the OnceCell so the resulting
1311    /// hash reflects the injected value and not any previously cached hash.
1312    ///
1313    /// This is the TDD anchor for the Task-4 verify-flow reorder: after
1314    /// `execute_blocks` caches the block hash (burned_fees=None), we must be
1315    /// able to inject the recomputed `burned_fees` and still get the correct hash.
1316    #[test]
1317    fn into_with_burned_fees_clears_stale_cache() {
1318        use crate::NativeCrypto;
1319
1320        // Build a default header (burned_fees = None).
1321        let header_none = BlockHeader::default();
1322
1323        // Force the hash cache to populate with burned_fees=None value.
1324        let hash_stale = header_none.hash();
1325
1326        // Build a reference header with burned_fees=Some(42) from scratch (fresh OnceCell).
1327        let header_some_fresh = BlockHeader {
1328            burned_fees: Some(42),
1329            ..BlockHeader::default()
1330        };
1331        let hash_expected = header_some_fresh.compute_block_hash(&NativeCrypto);
1332
1333        // The two hashes must differ — burned_fees is RLP-encoded in the header.
1334        assert_ne!(
1335            hash_stale, hash_expected,
1336            "burned_fees=None and burned_fees=Some(42) must produce different block hashes"
1337        );
1338
1339        // Now inject Some(42) via into_with_burned_fees, starting from the stale-cached header.
1340        let fresh_header = header_none.into_with_burned_fees(Some(42));
1341        let hash_fresh = fresh_header.hash();
1342
1343        // Must match the reference hash, NOT the stale one.
1344        assert_eq!(
1345            hash_fresh, hash_expected,
1346            "into_with_burned_fees must yield a hash identical to building a fresh header with the same burned_fees"
1347        );
1348        assert_ne!(
1349            hash_fresh, hash_stale,
1350            "OnceCell must have been cleared: fresh hash must differ from the stale cached hash"
1351        );
1352    }
1353
1354    /// Verify the Amsterdam (pre-LStar) no-op: injecting None into a header
1355    /// whose hash was cached with burned_fees=None yields the same hash.
1356    ///
1357    /// This is the primary correctness requirement for Task 4: the reordered
1358    /// verify-flow must not regress the current Amsterdam path.
1359    #[test]
1360    fn into_with_burned_fees_none_is_idempotent() {
1361        let header = BlockHeader::default();
1362        let hash_before = header.hash(); // populate cache with burned_fees=None
1363
1364        // Inject None (Amsterdam: burned_fees is None both before and after execution).
1365        let header_after = header.into_with_burned_fees(None);
1366        let hash_after = header_after.hash();
1367
1368        assert_eq!(
1369            hash_before, hash_after,
1370            "injecting None must not change the block hash (Amsterdam no-op)"
1371        );
1372    }
1373
1374    #[test]
1375    fn test_validate_block_body_rejects_missing_withdrawals_field() {
1376        use crate::constants::EMPTY_WITHDRAWALS_HASH;
1377
1378        let crypto = NativeCrypto;
1379        let header = BlockHeader {
1380            transactions_root: compute_transactions_root(&[], &crypto),
1381            withdrawals_root: Some(*EMPTY_WITHDRAWALS_HASH),
1382            ..Default::default()
1383        };
1384
1385        // A post-Shanghai body that OMITS the withdrawals field is malformed and
1386        // must be rejected even when the header commits to the empty-withdrawals
1387        // root (geth: "missing withdrawals in block body"; reth, nethermind,
1388        // erigon and besu reject this shape as well).
1389        let body_missing = BlockBody {
1390            withdrawals: None,
1391            ..BlockBody::empty()
1392        };
1393        assert!(matches!(
1394            validate_block_body(&header, &body_missing, &crypto),
1395            Err(InvalidBlockBodyError::WithdrawalsRootNotMatch)
1396        ));
1397
1398        // An explicit empty withdrawals list is valid for the same header.
1399        assert!(validate_block_body(&header, &BlockBody::empty(), &crypto).is_ok());
1400
1401        // A withdrawals field without a header root (pre-Shanghai shape) is rejected.
1402        let pre_shanghai_header = BlockHeader {
1403            transactions_root: compute_transactions_root(&[], &crypto),
1404            ..Default::default()
1405        };
1406        assert!(matches!(
1407            validate_block_body(&pre_shanghai_header, &BlockBody::empty(), &crypto),
1408            Err(InvalidBlockBodyError::WithdrawalsRootNotMatch)
1409        ));
1410        // Neither field present is valid.
1411        let body_no_withdrawals = BlockBody {
1412            withdrawals: None,
1413            ..BlockBody::empty()
1414        };
1415        assert!(validate_block_body(&pre_shanghai_header, &body_no_withdrawals, &crypto).is_ok());
1416    }
1417
1418    #[test]
1419    fn test_normalize_legacy_withdrawals() {
1420        use crate::constants::EMPTY_WITHDRAWALS_HASH;
1421
1422        let crypto = NativeCrypto;
1423
1424        // Legacy shape from trusted history: omitted field + empty-withdrawals
1425        // header root normalizes to the canonical Some(vec![]), and the
1426        // normalized body passes validation.
1427        let header = BlockHeader {
1428            transactions_root: compute_transactions_root(&[], &crypto),
1429            withdrawals_root: Some(*EMPTY_WITHDRAWALS_HASH),
1430            ..Default::default()
1431        };
1432        let mut body = BlockBody {
1433            withdrawals: None,
1434            ..BlockBody::empty()
1435        };
1436        normalize_legacy_withdrawals(&header, &mut body);
1437        assert_eq!(body.withdrawals, Some(Vec::new()));
1438        assert!(validate_block_body(&header, &body, &crypto).is_ok());
1439
1440        // An omitted field under a NON-empty withdrawals root is not the legacy
1441        // shape: the body stays untouched and validation still rejects it.
1442        let bad_header = BlockHeader {
1443            transactions_root: compute_transactions_root(&[], &crypto),
1444            withdrawals_root: Some(H256::repeat_byte(0xAB)),
1445            ..Default::default()
1446        };
1447        let mut bad_body = BlockBody {
1448            withdrawals: None,
1449            ..BlockBody::empty()
1450        };
1451        normalize_legacy_withdrawals(&bad_header, &mut bad_body);
1452        assert_eq!(bad_body.withdrawals, None);
1453        assert!(validate_block_body(&bad_header, &bad_body, &crypto).is_err());
1454
1455        // Pre-Shanghai shape (no header root, no field) stays untouched.
1456        let pre_shanghai_header = BlockHeader {
1457            transactions_root: compute_transactions_root(&[], &crypto),
1458            ..Default::default()
1459        };
1460        let mut pre_shanghai_body = BlockBody {
1461            withdrawals: None,
1462            ..BlockBody::empty()
1463        };
1464        normalize_legacy_withdrawals(&pre_shanghai_header, &mut pre_shanghai_body);
1465        assert_eq!(pre_shanghai_body.withdrawals, None);
1466
1467        // An already-canonical body is left as-is.
1468        let mut canonical = BlockBody::empty();
1469        let before = canonical.withdrawals.clone();
1470        normalize_legacy_withdrawals(&header, &mut canonical);
1471        assert_eq!(canonical.withdrawals, before);
1472    }
1473}