Skip to main content

ethrex_common/types/
genesis.rs

1use bytes::Bytes;
2use ethereum_types::{Address, Bloom, H256, U256};
3use ethrex_crypto::{NativeCrypto, keccak::keccak_hash};
4use ethrex_rlp::encode::RLPEncode;
5use ethrex_trie::Trie;
6use rkyv::{Archive, Deserialize as RDeserialize, Serialize as RSerialize};
7use serde::{Deserialize, Serialize};
8use std::{
9    collections::{BTreeMap, HashMap},
10    io::{BufReader, Error},
11    path::Path,
12};
13use tracing::warn;
14
15use super::{
16    AccountState, Block, BlockBody, BlockHeader, BlockNumber, INITIAL_BASE_FEE,
17    compute_receipts_root, compute_transactions_root, compute_withdrawals_root,
18};
19use crate::{
20    constants::{DEFAULT_OMMERS_HASH, DEFAULT_REQUESTS_HASH, EMPTY_BLOCK_ACCESS_LIST_HASH},
21    rkyv_utils,
22};
23
24#[allow(unused)]
25#[derive(Debug, Deserialize, Serialize, Clone, Default)]
26#[serde(rename_all = "camelCase")]
27pub struct Genesis {
28    /// Chain configuration
29    pub config: ChainConfig,
30    /// The initial state of the accounts in the genesis block.
31    /// This is a BTreeMap because: https://github.com/lambdaclass/ethrex/issues/2070
32    pub alloc: BTreeMap<Address, GenesisAccount>,
33    /// Genesis header values
34    pub coinbase: Address,
35    pub difficulty: U256,
36    #[serde(default, with = "crate::serde_utils::bytes")]
37    pub extra_data: Bytes,
38    #[serde(with = "crate::serde_utils::u64::hex_or_dec")]
39    pub gas_limit: u64,
40    #[serde(with = "crate::serde_utils::u64::hex_or_dec")]
41    pub nonce: u64,
42    #[serde(alias = "mixHash", alias = "mixhash")]
43    pub mix_hash: H256,
44    #[serde(deserialize_with = "crate::serde_utils::u64::hex_or_dec::deserialize")]
45    #[serde(serialize_with = "crate::serde_utils::u256::serialize_number")]
46    pub timestamp: u64,
47    #[serde(default, with = "crate::serde_utils::u64::hex_or_dec_opt")]
48    pub base_fee_per_gas: Option<u64>,
49    #[serde(default, with = "crate::serde_utils::u64::hex_or_dec_opt")]
50    pub blob_gas_used: Option<u64>,
51    #[serde(default, with = "crate::serde_utils::u64::hex_or_dec_opt")]
52    pub excess_blob_gas: Option<u64>,
53    pub requests_hash: Option<H256>,
54    // Amsterdam fork fields (EIP-7928)
55    pub block_access_list_hash: Option<H256>,
56    #[serde(default, with = "crate::serde_utils::u64::hex_or_dec_opt")]
57    pub slot_number: Option<u64>,
58}
59
60#[derive(Debug, thiserror::Error)]
61pub enum GenesisError {
62    #[error("Failed to decode genesis file: {0}")]
63    Decode(#[from] serde_json::Error),
64    #[error("Fork not supported. Only post-merge networks are supported.")]
65    InvalidFork(),
66    #[error("Failed to open genesis file: {0}")]
67    File(#[from] Error),
68}
69
70impl TryFrom<&Path> for Genesis {
71    type Error = GenesisError;
72
73    fn try_from(genesis_file_path: &Path) -> Result<Self, Self::Error> {
74        let genesis_file = std::fs::File::open(genesis_file_path)?;
75        let genesis_reader = BufReader::new(genesis_file);
76        let genesis: Genesis = serde_json::from_reader(genesis_reader)?;
77
78        // ethrex only supports post-merge (PoS) networks. PoW execution is not planned.
79        if is_unsupported_pow_genesis(&genesis) {
80            warn!("Genesis has no merge configuration; ethrex only supports post-merge networks.");
81        }
82
83        if genesis.config.bpo3_time.is_some() && genesis.config.blob_schedule.bpo3.is_none()
84            || genesis.config.bpo4_time.is_some() && genesis.config.blob_schedule.bpo4.is_none()
85            || genesis.config.bpo5_time.is_some() && genesis.config.blob_schedule.bpo5.is_none()
86        {
87            warn!("BPO time set but no BPO BlobSchedule found in ChainConfig")
88        }
89
90        Ok(genesis)
91    }
92}
93
94/// Returns true for a genesis that describes a pre-merge PoW chain with no
95/// merge configured. A real post-merge genesis either configures the merge
96/// (terminal total difficulty or merge-netsplit block) or starts post-merge
97/// (genesis difficulty 0). The previous heuristic warned whenever the
98/// post-merge forks were scheduled at non-zero timestamps, which false-fired
99/// on every mainnet-style genesis.
100///
101/// Note: `terminal_total_difficulty = Some(0)` is the sentinel for "PoS active
102/// from genesis" and counts as merge-configured here, as does the
103/// `terminal_total_difficulty_passed` flag (the post-merge signal used by the
104/// sync manager).
105fn is_unsupported_pow_genesis(genesis: &Genesis) -> bool {
106    let merge_configured = genesis.config.terminal_total_difficulty.is_some()
107        || genesis.config.merge_netsplit_block.is_some()
108        || genesis.config.terminal_total_difficulty_passed;
109    let post_merge_at_genesis = genesis.difficulty.is_zero();
110    !merge_configured && !post_merge_at_genesis
111}
112
113#[allow(unused)]
114#[derive(
115    Clone,
116    Copy,
117    Debug,
118    Serialize,
119    Deserialize,
120    PartialEq,
121    RSerialize,
122    RDeserialize,
123    Archive,
124    Default,
125)]
126#[serde(rename_all = "camelCase")]
127pub struct ForkBlobSchedule {
128    pub base_fee_update_fraction: u64,
129    pub max: u32,
130    pub target: u32,
131}
132
133#[allow(unused)]
134#[derive(
135    Clone, Copy, Debug, Serialize, Deserialize, PartialEq, RSerialize, RDeserialize, Archive,
136)]
137#[serde(rename_all = "camelCase")]
138pub struct BlobSchedule {
139    #[serde(default = "default_cancun_schedule")]
140    pub cancun: ForkBlobSchedule,
141    #[serde(default = "default_prague_schedule")]
142    pub prague: ForkBlobSchedule,
143    #[serde(default = "default_osaka_schedule")]
144    pub osaka: ForkBlobSchedule,
145    #[serde(default = "default_bpo1_schedule")]
146    pub bpo1: ForkBlobSchedule,
147    #[serde(default = "default_bpo2_schedule")]
148    pub bpo2: ForkBlobSchedule,
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub bpo3: Option<ForkBlobSchedule>,
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub bpo4: Option<ForkBlobSchedule>,
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub bpo5: Option<ForkBlobSchedule>,
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub amsterdam: Option<ForkBlobSchedule>,
157}
158
159impl Default for BlobSchedule {
160    fn default() -> Self {
161        BlobSchedule {
162            cancun: default_cancun_schedule(),
163            prague: default_prague_schedule(),
164            osaka: default_osaka_schedule(),
165            bpo1: default_bpo1_schedule(),
166            bpo2: default_bpo2_schedule(),
167            bpo3: None,
168            bpo4: None,
169            bpo5: None,
170            amsterdam: None,
171        }
172    }
173}
174
175fn default_cancun_schedule() -> ForkBlobSchedule {
176    ForkBlobSchedule {
177        target: 3,
178        max: 6,
179        base_fee_update_fraction: 3338477,
180    }
181}
182
183fn default_prague_schedule() -> ForkBlobSchedule {
184    ForkBlobSchedule {
185        target: 6,
186        max: 9,
187        base_fee_update_fraction: 5007716,
188    }
189}
190
191fn default_osaka_schedule() -> ForkBlobSchedule {
192    ForkBlobSchedule {
193        target: 6,
194        max: 9,
195        base_fee_update_fraction: 5007716,
196    }
197}
198
199fn default_bpo1_schedule() -> ForkBlobSchedule {
200    ForkBlobSchedule {
201        target: 10,
202        max: 15,
203        base_fee_update_fraction: 8346193,
204    }
205}
206
207fn default_bpo2_schedule() -> ForkBlobSchedule {
208    ForkBlobSchedule {
209        target: 14,
210        max: 21,
211        base_fee_update_fraction: 11684671,
212    }
213}
214/// Blockchain settings defined per block
215#[allow(unused)]
216#[derive(
217    Clone,
218    Copy,
219    Debug,
220    Serialize,
221    Deserialize,
222    Default,
223    PartialEq,
224    RSerialize,
225    RDeserialize,
226    Archive,
227)]
228#[serde(rename_all = "camelCase")]
229pub struct ChainConfig {
230    /// Current chain identifier
231    pub chain_id: u64,
232
233    /// Block numbers for the block where each fork was activated
234    /// (None = no fork, 0 = fork is already active)
235    pub homestead_block: Option<u64>,
236
237    pub dao_fork_block: Option<u64>,
238    /// Whether the node supports or opposes the DAO hard-fork
239    #[serde(default)]
240    pub dao_fork_support: bool,
241
242    pub eip150_block: Option<u64>,
243    pub eip155_block: Option<u64>,
244    pub eip158_block: Option<u64>,
245
246    pub byzantium_block: Option<u64>,
247    pub constantinople_block: Option<u64>,
248    pub petersburg_block: Option<u64>,
249    pub istanbul_block: Option<u64>,
250    pub muir_glacier_block: Option<u64>,
251    pub berlin_block: Option<u64>,
252    pub london_block: Option<u64>,
253    pub arrow_glacier_block: Option<u64>,
254    pub gray_glacier_block: Option<u64>,
255    pub merge_netsplit_block: Option<u64>,
256
257    /// Timestamp at which each fork was activated
258    /// (None = no fork, 0 = fork is already active)
259    pub shanghai_time: Option<u64>,
260    pub cancun_time: Option<u64>,
261    pub prague_time: Option<u64>,
262    pub verkle_time: Option<u64>,
263    pub osaka_time: Option<u64>,
264
265    pub bpo1_time: Option<u64>,
266    pub bpo2_time: Option<u64>,
267    pub bpo3_time: Option<u64>,
268    pub bpo4_time: Option<u64>,
269    pub bpo5_time: Option<u64>,
270    pub amsterdam_time: Option<u64>,
271    /// `hezeTime`/`heze_time`, and `bogotaTime`/`bogota_time` in genesis JSON
272    /// to track upstream rename of the post-Glamsterdam fork
273    /// (Bogotá → Hegotá → Hezé). The ethereum-genesis-generator (6.0.5)
274    /// currently emits `bogotaTime` regardless of which name kurtosis args
275    /// use. Internal name stays `hegota_time` until upstream picks a final
276    /// name; this is purely a parsing alias.
277    #[serde(
278        alias = "hezeTime",
279        alias = "heze_time",
280        alias = "bogotaTime",
281        alias = "bogota_time"
282    )]
283    pub hegota_time: Option<u64>,
284    pub lstar_time: Option<u64>,
285
286    /// Amount of total difficulty reached by the network that triggers the consensus upgrade.
287    #[serde(default, with = "crate::serde_utils::u128::hex_str_opt")]
288    pub terminal_total_difficulty: Option<u128>,
289    /// Network has already passed the terminal total difficult
290    #[serde(default)]
291    pub terminal_total_difficulty_passed: bool,
292    #[serde(default)]
293    pub blob_schedule: BlobSchedule,
294    #[rkyv(with = rkyv_utils::H160Wrapper)]
295    // Deposits system contract address
296    pub deposit_contract_address: Address,
297
298    #[serde(default)]
299    pub enable_verkle_at_genesis: bool,
300}
301
302lazy_static::lazy_static! {
303    pub static ref NETWORK_NAMES: HashMap<u64, &'static str> = {
304        HashMap::from([
305            (1, "mainnet"),
306            (11155111, "sepolia"),
307            (560048, "hoodi"),
308            (7091047534, "plataberget"),
309            (9, "L1 local devnet"),
310            (65536999, "L2 local devnet"),
311        ])
312    };
313}
314
315#[repr(u8)]
316#[derive(Debug, PartialEq, Eq, PartialOrd, Default, Hash, Clone, Copy, Serialize, Deserialize)]
317pub enum Fork {
318    Frontier = 0,
319    FrontierThawing = 1,
320    Homestead = 2,
321    DaoFork = 3,
322    Tangerine = 4,
323    SpuriousDragon = 5,
324    Byzantium = 6,
325    Constantinople = 7,
326    Petersburg = 8,
327    Istanbul = 9,
328    MuirGlacier = 10,
329    Berlin = 11,
330    London = 12,
331    ArrowGlacier = 13,
332    GrayGlacier = 14,
333    Paris = 15,
334    Shanghai = 16,
335    #[default]
336    Cancun = 17,
337    Prague = 18,
338    Osaka = 19,
339    BPO1 = 20,
340    BPO2 = 21,
341    BPO3 = 22,
342    BPO4 = 23,
343    BPO5 = 24,
344    Amsterdam = 25,
345    Hegota = 26,
346    LStar = 27,
347}
348
349impl From<Fork> for &str {
350    fn from(fork: Fork) -> Self {
351        match fork {
352            Fork::Frontier => "Frontier",
353            Fork::FrontierThawing => "FrontierThawing",
354            Fork::Homestead => "Homestead",
355            Fork::DaoFork => "DaoFork",
356            Fork::Tangerine => "Tangerine",
357            Fork::SpuriousDragon => "SpuriousDragon",
358            Fork::Byzantium => "Byzantium",
359            Fork::Constantinople => "Constantinople",
360            Fork::Petersburg => "Petersburg",
361            Fork::Istanbul => "Istanbul",
362            Fork::MuirGlacier => "MuirGlacier",
363            Fork::Berlin => "Berlin",
364            Fork::London => "London",
365            Fork::ArrowGlacier => "ArrowGlacier",
366            Fork::GrayGlacier => "GrayGlacier",
367            Fork::Paris => "Paris",
368            Fork::Shanghai => "Shanghai",
369            Fork::Cancun => "Cancun",
370            Fork::Prague => "Prague",
371            Fork::Osaka => "Osaka",
372            Fork::BPO1 => "BPO1",
373            Fork::BPO2 => "BPO2",
374            Fork::BPO3 => "BPO3",
375            Fork::BPO4 => "BPO4",
376            Fork::BPO5 => "BPO5",
377            Fork::Amsterdam => "Amsterdam",
378            Fork::Hegota => "Hegota",
379            Fork::LStar => "LStar",
380        }
381    }
382}
383
384impl ChainConfig {
385    pub fn is_hegota_activated(&self, block_timestamp: u64) -> bool {
386        self.hegota_time.is_some_and(|time| time <= block_timestamp)
387    }
388
389    pub fn is_lstar_activated(&self, block_timestamp: u64) -> bool {
390        self.lstar_time.is_some_and(|time| time <= block_timestamp)
391    }
392
393    pub fn is_amsterdam_activated(&self, block_timestamp: u64) -> bool {
394        self.amsterdam_time
395            .is_some_and(|time| time <= block_timestamp)
396    }
397
398    pub fn is_bpo5_activated(&self, block_timestamp: u64) -> bool {
399        self.bpo5_time.is_some_and(|time| time <= block_timestamp)
400    }
401
402    pub fn is_bpo4_activated(&self, block_timestamp: u64) -> bool {
403        self.bpo4_time.is_some_and(|time| time <= block_timestamp)
404    }
405
406    pub fn is_bpo3_activated(&self, block_timestamp: u64) -> bool {
407        self.bpo3_time.is_some_and(|time| time <= block_timestamp)
408    }
409
410    pub fn is_bpo2_activated(&self, block_timestamp: u64) -> bool {
411        self.bpo2_time.is_some_and(|time| time <= block_timestamp)
412    }
413
414    pub fn is_bpo1_activated(&self, block_timestamp: u64) -> bool {
415        self.bpo1_time.is_some_and(|time| time <= block_timestamp)
416    }
417
418    pub fn is_osaka_activated(&self, block_timestamp: u64) -> bool {
419        self.osaka_time.is_some_and(|time| time <= block_timestamp)
420    }
421
422    pub fn is_prague_activated(&self, block_timestamp: u64) -> bool {
423        self.prague_time.is_some_and(|time| time <= block_timestamp)
424    }
425
426    pub fn is_shanghai_activated(&self, block_timestamp: u64) -> bool {
427        self.shanghai_time
428            .is_some_and(|time| time <= block_timestamp)
429    }
430
431    pub fn is_cancun_activated(&self, block_timestamp: u64) -> bool {
432        self.cancun_time.is_some_and(|time| time <= block_timestamp)
433    }
434
435    pub fn is_istanbul_activated(&self, block_number: BlockNumber) -> bool {
436        self.istanbul_block.is_some_and(|num| num <= block_number)
437    }
438
439    pub fn is_london_activated(&self, block_number: BlockNumber) -> bool {
440        self.london_block.is_some_and(|num| num <= block_number)
441    }
442
443    pub fn is_eip155_activated(&self, block_number: BlockNumber) -> bool {
444        self.eip155_block.is_some_and(|num| num <= block_number)
445    }
446
447    pub fn display_config(&self) -> String {
448        let network = NETWORK_NAMES.get(&self.chain_id).unwrap_or(&"unknown");
449        let mut output = format!("Chain ID: {} ({})\n\n", self.chain_id, network);
450
451        let post_merge_forks = [
452            ("Shanghai", self.shanghai_time),
453            ("Cancun", self.cancun_time),
454            ("Prague", self.prague_time),
455            ("Verkle", self.verkle_time),
456            ("Osaka", self.osaka_time),
457            ("Amsterdam", self.amsterdam_time),
458            ("Hegota", self.hegota_time),
459        ];
460
461        let active_forks: Vec<_> = post_merge_forks
462            .iter()
463            .filter_map(|(name, t)| t.map(|time| format!("- {}: @{:<10}", name, time)))
464            .collect();
465
466        if !active_forks.is_empty() {
467            output.push_str("Network is post-merge\n\n");
468            output.push_str("Post-Merge hard forks (timestamp based):\n");
469            output.push_str(&active_forks.join("\n"));
470        } else {
471            output.push_str("Network is at Paris\n\n");
472        }
473
474        output
475    }
476
477    pub fn get_fork(&self, block_timestamp: u64) -> Fork {
478        if self.is_lstar_activated(block_timestamp) {
479            Fork::LStar
480        } else if self.is_hegota_activated(block_timestamp) {
481            Fork::Hegota
482        } else if self.is_amsterdam_activated(block_timestamp) {
483            Fork::Amsterdam
484        } else if self.is_bpo5_activated(block_timestamp) {
485            Fork::BPO5
486        } else if self.is_bpo4_activated(block_timestamp) {
487            Fork::BPO4
488        } else if self.is_bpo3_activated(block_timestamp) {
489            Fork::BPO3
490        } else if self.is_bpo2_activated(block_timestamp) {
491            Fork::BPO2
492        } else if self.is_bpo1_activated(block_timestamp) {
493            Fork::BPO1
494        } else if self.is_osaka_activated(block_timestamp) {
495            Fork::Osaka
496        } else if self.is_prague_activated(block_timestamp) {
497            Fork::Prague
498        } else if self.is_cancun_activated(block_timestamp) {
499            Fork::Cancun
500        } else if self.is_shanghai_activated(block_timestamp) {
501            Fork::Shanghai
502        } else {
503            Fork::Paris
504        }
505    }
506
507    pub fn get_fork_blob_schedule(&self, block_timestamp: u64) -> Option<ForkBlobSchedule> {
508        // EIP-7892: from Prague onward the blob schedule only changes at BPO forks.
509        // Named forks (Osaka, Amsterdam, Hegotá, LStar) carry no blob params of their own
510        // and inherit the highest activated BPO entry, so resolution falls through the BPO
511        // chain. A genesis that pins an entry for the named fork anyway takes precedence.
512        if (self.is_lstar_activated(block_timestamp)
513            || self.is_hegota_activated(block_timestamp)
514            || self.is_amsterdam_activated(block_timestamp))
515            && let Some(schedule) = self.blob_schedule.amsterdam
516        {
517            return Some(schedule);
518        }
519        if self.is_bpo5_activated(block_timestamp)
520            && let Some(schedule) = self.blob_schedule.bpo5
521        {
522            return Some(schedule);
523        }
524        if self.is_bpo4_activated(block_timestamp)
525            && let Some(schedule) = self.blob_schedule.bpo4
526        {
527            return Some(schedule);
528        }
529        if self.is_bpo3_activated(block_timestamp)
530            && let Some(schedule) = self.blob_schedule.bpo3
531        {
532            return Some(schedule);
533        }
534        if self.is_bpo2_activated(block_timestamp) {
535            Some(self.blob_schedule.bpo2)
536        } else if self.is_bpo1_activated(block_timestamp) {
537            Some(self.blob_schedule.bpo1)
538        } else if self.is_osaka_activated(block_timestamp) {
539            Some(self.blob_schedule.osaka)
540        } else if self.is_prague_activated(block_timestamp) {
541            Some(self.blob_schedule.prague)
542        } else if self.is_cancun_activated(block_timestamp) {
543            Some(self.blob_schedule.cancun)
544        } else {
545            None
546        }
547    }
548
549    pub fn fork(&self, block_timestamp: u64) -> Fork {
550        self.get_fork(block_timestamp)
551    }
552
553    pub fn next_fork(&self, block_timestamp: u64) -> Option<Fork> {
554        // Pick the scheduled fork with the smallest activation timestamp strictly
555        // greater than `block_timestamp`. Iterating all timestamp-based forks avoids
556        // bugs when intermediate forks (e.g. BPOs) are skipped in a network's schedule.
557        //
558        // NOTE: every timestamp-based fork MUST appear here in chronological order.
559        // Omitting a fork will silently cause `next_fork` to skip it; ties are
560        // broken by array position, so the order also encodes the canonical
561        // schedule independent of the `Fork` enum's discriminants.
562        [
563            Fork::Shanghai,
564            Fork::Cancun,
565            Fork::Prague,
566            Fork::Osaka,
567            Fork::BPO1,
568            Fork::BPO2,
569            Fork::BPO3,
570            Fork::BPO4,
571            Fork::BPO5,
572            Fork::Amsterdam,
573            Fork::Hegota,
574            Fork::LStar,
575        ]
576        .into_iter()
577        .enumerate()
578        .filter_map(|(pos, fork)| {
579            self.get_activation_timestamp_for_fork(fork)
580                .filter(|&t| t > block_timestamp)
581                .map(|t| (fork, t, pos))
582        })
583        .min_by(|a, b| a.1.cmp(&b.1).then_with(|| a.2.cmp(&b.2)))
584        .map(|(fork, _, _)| fork)
585    }
586
587    pub fn get_last_scheduled_fork(&self) -> Fork {
588        if self.lstar_time.is_some() {
589            Fork::LStar
590        } else if self.hegota_time.is_some() {
591            Fork::Hegota
592        } else if self.amsterdam_time.is_some() {
593            Fork::Amsterdam
594        } else if self.bpo5_time.is_some() {
595            Fork::BPO5
596        } else if self.bpo4_time.is_some() {
597            Fork::BPO4
598        } else if self.bpo3_time.is_some() {
599            Fork::BPO3
600        } else if self.bpo2_time.is_some() {
601            Fork::BPO2
602        } else if self.bpo1_time.is_some() {
603            Fork::BPO1
604        } else if self.osaka_time.is_some() {
605            Fork::Osaka
606        } else if self.prague_time.is_some() {
607            Fork::Prague
608        } else if self.cancun_time.is_some() {
609            Fork::Cancun
610        } else {
611            Fork::Paris
612        }
613    }
614
615    pub fn get_activation_timestamp_for_fork(&self, fork: Fork) -> Option<u64> {
616        match fork {
617            Fork::Cancun => self.cancun_time,
618            Fork::Prague => self.prague_time,
619            Fork::Osaka => self.osaka_time,
620            Fork::BPO1 => self.bpo1_time,
621            Fork::BPO2 => self.bpo2_time,
622            Fork::BPO3 => self.bpo3_time,
623            Fork::BPO4 => self.bpo4_time,
624            Fork::BPO5 => self.bpo5_time,
625            Fork::Amsterdam => self.amsterdam_time,
626            Fork::Hegota => self.hegota_time,
627            Fork::LStar => self.lstar_time,
628            Fork::Homestead => self.homestead_block,
629            Fork::DaoFork => self.dao_fork_block,
630            Fork::Byzantium => self.byzantium_block,
631            Fork::Constantinople => self.constantinople_block,
632            Fork::Petersburg => self.petersburg_block,
633            Fork::Istanbul => self.istanbul_block,
634            Fork::MuirGlacier => self.muir_glacier_block,
635            Fork::Berlin => self.berlin_block,
636            Fork::London => self.london_block,
637            Fork::ArrowGlacier => self.arrow_glacier_block,
638            Fork::GrayGlacier => self.gray_glacier_block,
639            Fork::Paris => self.merge_netsplit_block,
640            Fork::Shanghai => self.shanghai_time,
641            _ => None,
642        }
643    }
644
645    pub fn get_blob_schedule_for_fork(&self, fork: Fork) -> Option<ForkBlobSchedule> {
646        // Blob params are timestamp-scheduled from Cancun onward; earlier forks are
647        // activated by block number and have no blob schedule. Resolving through the
648        // fork's activation timestamp keeps this in step with the inheritance rules in
649        // `get_fork_blob_schedule`, so a named fork that declares no entry of its own
650        // reports the entry actually in force at its activation.
651        if fork < Fork::Cancun {
652            return None;
653        }
654        self.get_activation_timestamp_for_fork(fork)
655            .and_then(|timestamp| self.get_fork_blob_schedule(timestamp))
656    }
657
658    pub fn gather_forks(&self, genesis_header: BlockHeader) -> (Vec<u64>, Vec<u64>) {
659        let mut block_number_based_forks: Vec<u64> = vec![
660            self.homestead_block,
661            if self.dao_fork_support {
662                self.dao_fork_block
663            } else {
664                None
665            },
666            self.eip150_block,
667            self.eip155_block,
668            self.eip158_block,
669            self.byzantium_block,
670            self.constantinople_block,
671            self.petersburg_block,
672            self.istanbul_block,
673            self.muir_glacier_block,
674            self.berlin_block,
675            self.london_block,
676            self.arrow_glacier_block,
677            self.gray_glacier_block,
678            self.merge_netsplit_block,
679        ]
680        .into_iter()
681        .flatten()
682        .collect();
683
684        // Remove repeated values
685        block_number_based_forks.sort();
686        block_number_based_forks.dedup();
687
688        let mut timestamp_based_forks: Vec<u64> = vec![
689            self.shanghai_time,
690            self.cancun_time,
691            self.prague_time,
692            self.osaka_time,
693            self.bpo1_time,
694            self.bpo2_time,
695            self.bpo3_time,
696            self.bpo4_time,
697            self.bpo5_time,
698            self.amsterdam_time,
699            self.hegota_time,
700            self.verkle_time,
701        ]
702        .into_iter()
703        .flatten()
704        .collect();
705
706        // Remove repeated values
707        timestamp_based_forks.sort();
708        timestamp_based_forks.dedup();
709
710        // Filter forks before genesis
711        block_number_based_forks.retain(|block_number| *block_number != 0);
712        timestamp_based_forks.retain(|block_timestamp| *block_timestamp > genesis_header.timestamp);
713
714        (block_number_based_forks, timestamp_based_forks)
715    }
716}
717
718#[allow(unused)]
719#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
720pub struct GenesisAccount {
721    #[serde(default, with = "crate::serde_utils::bytes")]
722    pub code: Bytes,
723    #[serde(default)]
724    pub storage: BTreeMap<U256, U256>,
725    #[serde(deserialize_with = "crate::serde_utils::u256::hex_or_dec::deserialize")]
726    pub balance: U256,
727    #[serde(default, with = "crate::serde_utils::u64::hex_or_dec")]
728    pub nonce: u64,
729}
730
731impl Genesis {
732    pub fn get_block(&self) -> Block {
733        Block::new(self.get_block_header(), self.get_block_body())
734    }
735
736    fn get_block_header(&self) -> BlockHeader {
737        let mut blob_gas_used: Option<u64> = None;
738        let mut excess_blob_gas: Option<u64> = None;
739
740        if let Some(cancun_time) = self.config.cancun_time
741            && cancun_time <= self.timestamp
742        {
743            blob_gas_used = Some(self.blob_gas_used.unwrap_or(0));
744            excess_blob_gas = Some(self.excess_blob_gas.unwrap_or(0));
745        }
746        let base_fee_per_gas = self.base_fee_per_gas.or_else(|| {
747            self.config
748                .is_london_activated(0)
749                .then_some(INITIAL_BASE_FEE)
750        });
751
752        let withdrawals_root = self
753            .config
754            .is_shanghai_activated(self.timestamp)
755            .then_some(compute_withdrawals_root(&[], &NativeCrypto));
756
757        let parent_beacon_block_root = self
758            .config
759            .is_cancun_activated(self.timestamp)
760            .then_some(H256::zero());
761
762        let requests_hash = self
763            .config
764            .is_prague_activated(self.timestamp)
765            .then_some(self.requests_hash.unwrap_or(*DEFAULT_REQUESTS_HASH));
766
767        let block_access_list_hash = self
768            .config
769            .is_amsterdam_activated(self.timestamp)
770            .then_some(
771                self.block_access_list_hash
772                    .unwrap_or(*EMPTY_BLOCK_ACCESS_LIST_HASH),
773            );
774
775        let slot_number = self
776            .config
777            .is_amsterdam_activated(self.timestamp)
778            .then_some(self.slot_number.unwrap_or(0));
779
780        BlockHeader {
781            parent_hash: H256::zero(),
782            ommers_hash: *DEFAULT_OMMERS_HASH,
783            coinbase: self.coinbase,
784            state_root: self.compute_state_root(),
785            transactions_root: compute_transactions_root(&[], &NativeCrypto),
786            receipts_root: compute_receipts_root(&[], &NativeCrypto),
787            logs_bloom: Bloom::zero(),
788            difficulty: self.difficulty,
789            number: 0,
790            gas_limit: self.gas_limit,
791            gas_used: 0,
792            timestamp: self.timestamp,
793            extra_data: self.extra_data.clone(),
794            prev_randao: self.mix_hash,
795            nonce: self.nonce,
796            base_fee_per_gas,
797            withdrawals_root,
798            blob_gas_used,
799            excess_blob_gas,
800            parent_beacon_block_root,
801            requests_hash,
802            block_access_list_hash,
803            slot_number,
804            ..Default::default()
805        }
806    }
807
808    fn get_block_body(&self) -> BlockBody {
809        BlockBody {
810            transactions: vec![],
811            ommers: vec![],
812            withdrawals: Some(vec![]),
813        }
814    }
815
816    pub fn compute_state_root(&self) -> H256 {
817        let iter = self.alloc.iter().map(|(addr, account)| {
818            (
819                keccak_hash(addr).to_vec(),
820                AccountState::from(account).encode_to_vec(),
821            )
822        });
823        Trie::compute_hash_from_unsorted_iter(iter, &NativeCrypto)
824    }
825}
826#[cfg(test)]
827mod tests {
828    use std::str::FromStr;
829    use std::{fs::File, io::BufReader};
830
831    use ethereum_types::H160;
832
833    use crate::types::INITIAL_BASE_FEE;
834
835    use super::*;
836
837    #[test]
838    fn terminal_total_difficulty_accepts_number_or_hex_string() {
839        // geth/reth-style genesis files encode terminalTotalDifficulty as a
840        // bare decimal number that exceeds u64::MAX; ethrex must accept it as
841        // well as the 0x-hex-string form.
842        let dca = r#""depositContractAddress":"0x00000000219ab540356cbb839cbe05303d7705fa""#;
843
844        let from_number: ChainConfig = serde_json::from_str(&format!(
845            r#"{{"chainId":1,"terminalTotalDifficulty":58750000000000000000000,{dca}}}"#
846        ))
847        .expect("number-encoded TTD should parse");
848        // f64 cast is lossy above u64::MAX; assert the known, stable
849        // approximation so a regression to Some(0) can't silently pass.
850        assert_eq!(
851            from_number.terminal_total_difficulty,
852            Some(58749999999999996329984u128)
853        );
854
855        let from_hex: ChainConfig = serde_json::from_str(&format!(
856            r#"{{"chainId":1,"terminalTotalDifficulty":"0xc70d808a128d7380000",{dca}}}"#
857        ))
858        .expect("hex-string TTD should parse");
859        assert_eq!(
860            from_hex.terminal_total_difficulty,
861            Some(58750000000000000000000u128)
862        );
863
864        let small: ChainConfig = serde_json::from_str(&format!(
865            r#"{{"chainId":1,"terminalTotalDifficulty":17000000000000000,{dca}}}"#
866        ))
867        .expect("small number TTD should parse");
868        assert_eq!(small.terminal_total_difficulty, Some(17000000000000000u128));
869
870        // A negative bare number must error, not silently saturate to Some(0).
871        let negative = serde_json::from_str::<ChainConfig>(&format!(
872            r#"{{"chainId":1,"terminalTotalDifficulty":-1,{dca}}}"#
873        ));
874        let err = negative.expect_err("negative TTD must be rejected");
875        assert!(
876            err.to_string().contains("finite, non-negative"),
877            "error should name the sign/finiteness cause, got: {err}"
878        );
879    }
880
881    #[test]
882    fn genesis_quantities_accept_numbers_and_hex_or_decimal_strings() {
883        // geth reads these fields as a JSON number, a 0x-hex string or a decimal
884        // string, and genesis files written by other tooling use all three. An
885        // unprefixed string is decimal, so "10" must not be read as 0x10.
886        let fixture: serde_json::Value = serde_json::from_reader(BufReader::new(
887            File::open("../../fixtures/genesis/l1.json").expect("Failed to open genesis file"),
888        ))
889        .expect("Failed to deserialize genesis file");
890        for encoded in [
891            serde_json::json!(10),
892            serde_json::json!("0xa"),
893            serde_json::json!("0XA"),
894            serde_json::json!("10"),
895        ] {
896            let account: GenesisAccount =
897                serde_json::from_value(serde_json::json!({"balance": encoded, "nonce": encoded}))
898                    .expect("account quantities should parse");
899            assert_eq!(
900                (account.balance, account.nonce),
901                (U256::from(10), 10),
902                "account quantities {encoded}"
903            );
904
905            let mut genesis = fixture.clone();
906            for field in [
907                "gasLimit",
908                "nonce",
909                "timestamp",
910                "baseFeePerGas",
911                "blobGasUsed",
912                "excessBlobGas",
913                "slotNumber",
914            ] {
915                genesis[field] = encoded.clone();
916            }
917            let genesis: Genesis =
918                serde_json::from_value(genesis).expect("genesis header fields should parse");
919            assert_eq!(
920                (genesis.gas_limit, genesis.nonce, genesis.timestamp),
921                (10, 10, 10),
922                "genesis header fields {encoded}"
923            );
924            assert_eq!(
925                (
926                    genesis.base_fee_per_gas,
927                    genesis.blob_gas_used,
928                    genesis.excess_blob_gas,
929                    genesis.slot_number
930                ),
931                (Some(10), Some(10), Some(10), Some(10)),
932                "optional genesis header fields {encoded}"
933            );
934        }
935
936        // As in geth, an empty string is 0.
937        let account: GenesisAccount =
938            serde_json::from_value(serde_json::json!({"balance": "", "nonce": ""}))
939                .expect("empty account quantities should parse");
940        assert_eq!((account.balance, account.nonce), (U256::zero(), 0));
941
942        for invalid in [
943            serde_json::json!(-1),
944            serde_json::json!("0xzz"),
945            serde_json::json!("0x"),
946            serde_json::json!("0x0x10"),
947            serde_json::json!("+10"),
948            serde_json::json!(true),
949        ] {
950            assert!(
951                serde_json::from_value::<GenesisAccount>(
952                    serde_json::json!({"balance": "0", "nonce": invalid})
953                )
954                .is_err(),
955                "account nonce {invalid} must be rejected"
956            );
957            assert!(
958                serde_json::from_value::<GenesisAccount>(serde_json::json!({"balance": invalid}))
959                    .is_err(),
960                "account balance {invalid} must be rejected"
961            );
962        }
963        // serde_json holds an integer this large as a float, so it must be rejected
964        // rather than rounded.
965        assert!(
966            serde_json::from_str::<GenesisAccount>(r#"{"balance": 1000000000000000000000000}"#)
967                .is_err(),
968            "a balance above u64::MAX given as a JSON number must be rejected"
969        );
970    }
971
972    #[test]
973    fn pow_genesis_detection() {
974        // Default genesis: difficulty 0 (post-merge at genesis) -> supported.
975        let mut g = Genesis::default();
976        assert!(!is_unsupported_pow_genesis(&g));
977
978        // PoW genesis: non-zero difficulty, no merge configured -> unsupported.
979        g.difficulty = U256::from(0x4000_0000u64);
980        assert!(is_unsupported_pow_genesis(&g));
981
982        // Mainnet-style: non-zero difficulty but TTD configured -> supported.
983        g.config.terminal_total_difficulty = Some(58750000000000000000000);
984        assert!(!is_unsupported_pow_genesis(&g));
985
986        // Merge-netsplit block configured (no TTD) -> supported.
987        g.config.terminal_total_difficulty = None;
988        g.config.merge_netsplit_block = Some(15537394);
989        assert!(!is_unsupported_pow_genesis(&g));
990
991        // TTD = Some(0) sentinel (PoS from genesis), non-zero difficulty -> supported.
992        g.config.merge_netsplit_block = None;
993        g.config.terminal_total_difficulty = Some(0);
994        assert!(!is_unsupported_pow_genesis(&g));
995
996        // terminal_total_difficulty_passed with no TTD value (post-merge snapshot
997        // that dropped the redundant field), non-zero difficulty -> supported.
998        g.config.terminal_total_difficulty = None;
999        g.config.terminal_total_difficulty_passed = true;
1000        assert!(!is_unsupported_pow_genesis(&g));
1001    }
1002
1003    #[test]
1004    fn deserialize_genesis_file() {
1005        // Deserialize genesis file
1006        let file = File::open("../../fixtures/genesis/kurtosis.json")
1007            .expect("Failed to open genesis file");
1008        let reader = BufReader::new(file);
1009        let genesis: Genesis =
1010            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1011        // Check Genesis fields
1012        // Chain config
1013        let expected_chain_config = ChainConfig {
1014            chain_id: 3151908_u64,
1015            homestead_block: Some(0),
1016            eip150_block: Some(0),
1017            eip155_block: Some(0),
1018            eip158_block: Some(0),
1019            byzantium_block: Some(0),
1020            constantinople_block: Some(0),
1021            petersburg_block: Some(0),
1022            istanbul_block: Some(0),
1023            berlin_block: Some(0),
1024            london_block: Some(0),
1025            merge_netsplit_block: Some(0),
1026            shanghai_time: Some(0),
1027            cancun_time: Some(0),
1028            prague_time: Some(1718232101),
1029            terminal_total_difficulty: Some(0),
1030            terminal_total_difficulty_passed: true,
1031            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1032                .unwrap(),
1033            // Note this BlobSchedule config is not the default
1034            blob_schedule: BlobSchedule {
1035                cancun: ForkBlobSchedule {
1036                    target: 2,
1037                    max: 3,
1038                    base_fee_update_fraction: 6676954,
1039                },
1040                prague: ForkBlobSchedule {
1041                    target: 3,
1042                    max: 4,
1043                    base_fee_update_fraction: 13353908,
1044                },
1045                ..Default::default()
1046            },
1047            ..Default::default()
1048        };
1049        assert_eq!(&genesis.config, &expected_chain_config);
1050        // Genesis header fields
1051        assert_eq!(genesis.coinbase, Address::from([0; 20]));
1052        assert_eq!(genesis.difficulty, U256::from(1));
1053        assert!(genesis.extra_data.is_empty());
1054        assert_eq!(genesis.gas_limit, 0x17d7840);
1055        assert_eq!(genesis.nonce, 0x1234);
1056        assert_eq!(genesis.mix_hash, H256::from([0; 32]));
1057        assert_eq!(genesis.timestamp, 1718040081);
1058        // Check alloc field
1059        // We will only check a couple of the hashmap's values as it is quite large
1060        let addr_a = Address::from_str("0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02").unwrap();
1061        assert!(genesis.alloc.contains_key(&addr_a));
1062        let expected_account_a = GenesisAccount {
1063        code: Bytes::from(hex::decode("3373fffffffffffffffffffffffffffffffffffffffe14604d57602036146024575f5ffd5b5f35801560495762001fff810690815414603c575f5ffd5b62001fff01545f5260205ff35b5f5ffd5b62001fff42064281555f359062001fff015500").unwrap()),
1064        balance: 0.into(),
1065        nonce: 1,
1066        storage: Default::default(),
1067    };
1068        assert_eq!(genesis.alloc[&addr_a], expected_account_a);
1069        // Check some storage values from another account
1070        let addr_b = Address::from_str("0x4242424242424242424242424242424242424242").unwrap();
1071        assert!(genesis.alloc.contains_key(&addr_b));
1072        let addr_b_storage = &genesis.alloc[&addr_b].storage;
1073        assert_eq!(
1074            addr_b_storage.get(
1075                &U256::from_str(
1076                    "0x0000000000000000000000000000000000000000000000000000000000000022"
1077                )
1078                .unwrap()
1079            ),
1080            Some(
1081                &U256::from_str(
1082                    "0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b"
1083                )
1084                .unwrap()
1085            )
1086        );
1087        assert_eq!(
1088            addr_b_storage.get(
1089                &U256::from_str(
1090                    "0x0000000000000000000000000000000000000000000000000000000000000038"
1091                )
1092                .unwrap()
1093            ),
1094            Some(
1095                &U256::from_str(
1096                    "0xe71f0aa83cc32edfbefa9f4d3e0174ca85182eec9f3a09f6a6c0df6377a510d7"
1097                )
1098                .unwrap()
1099            )
1100        );
1101    }
1102
1103    #[test]
1104    fn genesis_block() {
1105        // Deserialize genesis file
1106        let file = File::open("../../fixtures/genesis/kurtosis.json")
1107            .expect("Failed to open genesis file");
1108        let reader = BufReader::new(file);
1109        let genesis: Genesis =
1110            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1111        let genesis_block = genesis.get_block();
1112        let header = genesis_block.header;
1113        let body = genesis_block.body;
1114        assert_eq!(header.parent_hash, H256::from([0; 32]));
1115        assert_eq!(header.ommers_hash, *DEFAULT_OMMERS_HASH);
1116        assert_eq!(header.coinbase, Address::default());
1117        assert_eq!(
1118            header.state_root,
1119            H256::from_str("0x2dab6a1d6d638955507777aecea699e6728825524facbd446bd4e86d44fa5ecd")
1120                .unwrap()
1121        );
1122        assert_eq!(
1123            header.transactions_root,
1124            compute_transactions_root(&[], &NativeCrypto)
1125        );
1126        assert_eq!(
1127            header.receipts_root,
1128            compute_receipts_root(&[], &NativeCrypto)
1129        );
1130        assert_eq!(header.logs_bloom, Bloom::default());
1131        assert_eq!(header.difficulty, U256::from(1));
1132        assert_eq!(header.gas_limit, 25_000_000);
1133        assert_eq!(header.gas_used, 0);
1134        assert_eq!(header.timestamp, 1_718_040_081);
1135        assert_eq!(header.extra_data, Bytes::default());
1136        assert_eq!(header.prev_randao, H256::from([0; 32]));
1137        assert_eq!(header.nonce, 4660);
1138        assert_eq!(
1139            header.base_fee_per_gas.unwrap_or(INITIAL_BASE_FEE),
1140            INITIAL_BASE_FEE
1141        );
1142        assert_eq!(
1143            header.withdrawals_root,
1144            Some(compute_withdrawals_root(&[], &NativeCrypto))
1145        );
1146        assert_eq!(header.blob_gas_used, Some(0));
1147        assert_eq!(header.excess_blob_gas, Some(0));
1148        assert_eq!(header.parent_beacon_block_root, Some(H256::zero()));
1149        assert!(body.transactions.is_empty());
1150        assert!(body.ommers.is_empty());
1151        assert!(body.withdrawals.is_some_and(|w| w.is_empty()));
1152    }
1153
1154    #[test]
1155    // Parses genesis received by kurtosis and checks that the hash matches the next block's parent hash
1156    fn read_and_compute_kurtosis_hash() {
1157        let file = File::open("../../fixtures/genesis/kurtosis.json")
1158            .expect("Failed to open genesis file");
1159        let reader = BufReader::new(file);
1160        let genesis: Genesis =
1161            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1162        let genesis_block_hash = genesis.get_block().hash();
1163        assert_eq!(
1164            genesis_block_hash,
1165            H256::from_str("0xcb5306dd861d0f2c1f9952fbfbc75a46d0b6ce4f37bea370c3471fe8410bf40b")
1166                .unwrap()
1167        )
1168    }
1169
1170    #[test]
1171    fn parse_hive_genesis_file() {
1172        let file =
1173            File::open("../../fixtures/genesis/hive.json").expect("Failed to open genesis file");
1174        let reader = BufReader::new(file);
1175        let _genesis: Genesis =
1176            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1177    }
1178
1179    #[test]
1180    fn read_and_compute_hive_hash() {
1181        let file =
1182            File::open("../../fixtures/genesis/hive.json").expect("Failed to open genesis file");
1183        let reader = BufReader::new(file);
1184        let genesis: Genesis =
1185            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1186        let computed_block_hash = genesis.get_block().hash();
1187        let genesis_block_hash =
1188            H256::from_str("0x30f516e34fc173bb5fc4daddcc7532c4aca10b702c7228f3c806b4df2646fb7e")
1189                .unwrap();
1190        assert_eq!(genesis_block_hash, computed_block_hash)
1191    }
1192
1193    #[test]
1194    fn deserialize_chain_config_blob_schedule() {
1195        let json = r#"
1196
1197            {
1198                "chainId": 123,
1199                "blobSchedule": {
1200                  "cancun": {
1201                    "target": 1,
1202                    "max": 2,
1203                    "baseFeeUpdateFraction": 10000
1204                  },
1205                  "prague": {
1206                    "target": 3,
1207                    "max": 4,
1208                    "baseFeeUpdateFraction": 20000
1209                  }
1210                },
1211                "depositContractAddress": "0x4242424242424242424242424242424242424242"
1212            }
1213            "#;
1214
1215        let config: ChainConfig =
1216            serde_json::from_str(json).expect("Failed to deserialize ChainConfig");
1217        let expected_chain_config = ChainConfig {
1218            chain_id: 123,
1219            blob_schedule: BlobSchedule {
1220                cancun: ForkBlobSchedule {
1221                    target: 1,
1222                    max: 2,
1223                    base_fee_update_fraction: 10000,
1224                },
1225                prague: ForkBlobSchedule {
1226                    target: 3,
1227                    max: 4,
1228                    base_fee_update_fraction: 20000,
1229                },
1230                ..Default::default()
1231            },
1232            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1233                .unwrap(),
1234            ..Default::default()
1235        };
1236        assert_eq!(&config, &expected_chain_config);
1237    }
1238
1239    #[test]
1240    fn deserialize_chain_config_missing_entire_blob_schedule() {
1241        let json = r#"
1242            {
1243                "chainId": 123,
1244                "depositContractAddress": "0x4242424242424242424242424242424242424242"
1245            }
1246            "#;
1247
1248        let config: ChainConfig =
1249            serde_json::from_str(json).expect("Failed to deserialize ChainConfig");
1250        let expected_chain_config = ChainConfig {
1251            chain_id: 123,
1252            blob_schedule: BlobSchedule {
1253                cancun: ForkBlobSchedule {
1254                    target: 3,
1255                    max: 6,
1256                    base_fee_update_fraction: 3338477,
1257                },
1258                prague: ForkBlobSchedule {
1259                    target: 6,
1260                    max: 9,
1261                    base_fee_update_fraction: 5007716,
1262                },
1263                ..Default::default()
1264            },
1265            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1266                .unwrap(),
1267            ..Default::default()
1268        };
1269        assert_eq!(&config, &expected_chain_config);
1270    }
1271
1272    #[test]
1273    fn deserialize_chain_config_missing_cancun_blob_schedule() {
1274        let json = r#"
1275            {
1276                "chainId": 123,
1277                "blobSchedule": {
1278                    "prague": {
1279                      "target": 3,
1280                      "max": 4,
1281                      "baseFeeUpdateFraction": 20000
1282                    }
1283                },
1284                "depositContractAddress": "0x4242424242424242424242424242424242424242"
1285            }
1286            "#;
1287
1288        let config: ChainConfig =
1289            serde_json::from_str(json).expect("Failed to deserialize ChainConfig");
1290        let expected_chain_config = ChainConfig {
1291            chain_id: 123,
1292            blob_schedule: BlobSchedule {
1293                cancun: ForkBlobSchedule {
1294                    target: 3,
1295                    max: 6,
1296                    base_fee_update_fraction: 3338477,
1297                },
1298                prague: ForkBlobSchedule {
1299                    target: 3,
1300                    max: 4,
1301                    base_fee_update_fraction: 20000,
1302                },
1303                ..Default::default()
1304            },
1305            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1306                .unwrap(),
1307            ..Default::default()
1308        };
1309        assert_eq!(&config, &expected_chain_config);
1310    }
1311
1312    #[test]
1313    fn deserialize_chain_config_missing_prague_blob_schedule() {
1314        let json = r#"
1315            {
1316                "chainId": 123,
1317                "blobSchedule": {
1318                  "cancun": {
1319                    "target": 1,
1320                    "max": 2,
1321                    "baseFeeUpdateFraction": 10000
1322                  }
1323                },
1324                "depositContractAddress": "0x4242424242424242424242424242424242424242"
1325            }
1326            "#;
1327
1328        let config: ChainConfig =
1329            serde_json::from_str(json).expect("Failed to deserialize ChainConfig");
1330        let expected_chain_config = ChainConfig {
1331            chain_id: 123,
1332            blob_schedule: BlobSchedule {
1333                cancun: ForkBlobSchedule {
1334                    target: 1,
1335                    max: 2,
1336                    base_fee_update_fraction: 10000,
1337                },
1338                prague: ForkBlobSchedule {
1339                    target: 6,
1340                    max: 9,
1341                    base_fee_update_fraction: 5007716,
1342                },
1343                ..Default::default()
1344            },
1345            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1346                .unwrap(),
1347            ..Default::default()
1348        };
1349        assert_eq!(&config, &expected_chain_config);
1350    }
1351
1352    #[test]
1353    fn deserialize_chain_config_missing_deposit_contract_address() {
1354        let json = r#"
1355            {
1356                "chainId": 123
1357            }
1358            "#;
1359
1360        let result: Result<ChainConfig, _> = serde_json::from_str(json);
1361
1362        assert!(result.is_err());
1363
1364        let error_message = result.unwrap_err().to_string();
1365        assert!(error_message.contains("missing field `depositContractAddress`"),);
1366    }
1367
1368    #[test]
1369    fn lstar_fork_ordering_and_activation() {
1370        // LStar is the highest fork and strictly greater than Amsterdam.
1371        assert!(Fork::LStar > Fork::Amsterdam);
1372        assert_eq!(<&str>::from(Fork::LStar), "LStar");
1373
1374        let mut cfg = ChainConfig {
1375            lstar_time: Some(100),
1376            ..Default::default()
1377        };
1378        assert!(!cfg.is_lstar_activated(99));
1379        assert!(cfg.is_lstar_activated(100));
1380        assert!(cfg.is_lstar_activated(101));
1381
1382        cfg.lstar_time = None;
1383        assert!(!cfg.is_lstar_activated(u64::MAX));
1384    }
1385
1386    #[test]
1387    fn native_l2_genesis_activates_amsterdam() {
1388        let file = File::open("../../fixtures/genesis/native_l2.json")
1389            .expect("Failed to open native_l2.json");
1390        let reader = BufReader::new(file);
1391        let genesis: Genesis =
1392            serde_json::from_reader(reader).expect("Failed to deserialize native_l2.json");
1393        assert_eq!(
1394            genesis.config.get_fork(0),
1395            Fork::Amsterdam,
1396            "native_l2.json genesis should activate Amsterdam at timestamp 0"
1397        );
1398        // Confirm blobSchedule falls back to bpo2 (no explicit amsterdam entry).
1399        let bs = genesis
1400            .config
1401            .get_fork_blob_schedule(0)
1402            .expect("Amsterdam implies bpo2 blob schedule");
1403        assert_eq!(bs.max, 21, "Amsterdam should inherit bpo2 max=21");
1404    }
1405
1406    #[test]
1407    fn lstar_fork_resolution() {
1408        // Genesis-activated Amsterdam + LStar (LStar at a later time).
1409        let cfg = ChainConfig {
1410            cancun_time: Some(0),
1411            prague_time: Some(0),
1412            amsterdam_time: Some(0),
1413            lstar_time: Some(1000),
1414            ..Default::default()
1415        };
1416
1417        // Before LStar: highest active fork is Amsterdam.
1418        assert_eq!(cfg.get_fork(999), Fork::Amsterdam);
1419        // At/after LStar: highest active fork is LStar.
1420        assert_eq!(cfg.get_fork(1000), Fork::LStar);
1421
1422        // next_fork: at Amsterdam (pre-LStar) the next scheduled fork is LStar; at LStar there is none.
1423        assert_eq!(cfg.next_fork(999), Some(Fork::LStar));
1424        assert_eq!(cfg.next_fork(1000), None);
1425
1426        // get_last_scheduled_fork reflects LStar once scheduled.
1427        assert_eq!(cfg.get_last_scheduled_fork(), Fork::LStar);
1428
1429        // Activation timestamp round-trips.
1430        assert_eq!(
1431            cfg.get_activation_timestamp_for_fork(Fork::LStar),
1432            Some(1000)
1433        );
1434
1435        // Blob schedule at LStar inherits Amsterdam's (which inherits bpo2, max=9 default).
1436        let sched_lstar = cfg
1437            .get_fork_blob_schedule(1000)
1438            .expect("lstar blob schedule");
1439        let sched_amsterdam = cfg
1440            .get_fork_blob_schedule(999)
1441            .expect("amsterdam blob schedule");
1442        assert_eq!(sched_lstar.max, sched_amsterdam.max);
1443    }
1444
1445    #[test]
1446    fn test_hegota_after_amsterdam() {
1447        // Discriminant ordering: Hegota strictly follows Amsterdam.
1448        assert!(Fork::Hegota > Fork::Amsterdam);
1449        assert_eq!(Fork::Hegota as u8, 26);
1450        assert_eq!(Fork::Amsterdam as u8, 25);
1451
1452        // String conversion.
1453        let hegota_str: &str = Fork::Hegota.into();
1454        assert_eq!(hegota_str, "Hegota");
1455
1456        // Activation predicate boundary behavior.
1457        let mut config = ChainConfig {
1458            chain_id: 1,
1459            deposit_contract_address: Address::default(),
1460            ..Default::default()
1461        };
1462        config.hegota_time = Some(1000);
1463        assert!(!config.is_hegota_activated(999));
1464        assert!(config.is_hegota_activated(1000));
1465        assert!(config.is_hegota_activated(1001));
1466
1467        // None means inactive.
1468        config.hegota_time = None;
1469        assert!(!config.is_hegota_activated(0));
1470        assert!(!config.is_hegota_activated(u64::MAX));
1471
1472        // get_fork returns Hegota when both Amsterdam and Hegota are active.
1473        let mut config = ChainConfig {
1474            chain_id: 1,
1475            deposit_contract_address: Address::default(),
1476            ..Default::default()
1477        };
1478        config.amsterdam_time = Some(500);
1479        config.hegota_time = Some(1000);
1480        assert_eq!(config.get_fork(499), Fork::Paris);
1481        assert_eq!(config.get_fork(500), Fork::Amsterdam);
1482        assert_eq!(config.get_fork(999), Fork::Amsterdam);
1483        assert_eq!(config.get_fork(1000), Fork::Hegota);
1484        assert_eq!(config.get_fork(2000), Fork::Hegota);
1485
1486        // next_fork transitions correctly.
1487        assert_eq!(config.next_fork(500), Some(Fork::Hegota));
1488        assert_eq!(config.next_fork(1000), None);
1489
1490        // get_last_scheduled_fork picks Hegota when scheduled.
1491        assert_eq!(config.get_last_scheduled_fork(), Fork::Hegota);
1492
1493        // get_activation_timestamp_for_fork returns the right value.
1494        assert_eq!(
1495            config.get_activation_timestamp_for_fork(Fork::Hegota),
1496            Some(1000)
1497        );
1498    }
1499
1500    #[test]
1501    fn chain_config_accepts_heze_and_bogota_aliases_for_hegota_time() {
1502        for key in [
1503            "hegotaTime",
1504            "hezeTime",
1505            "heze_time",
1506            "bogotaTime",
1507            "bogota_time",
1508        ] {
1509            let json = format!(
1510                r#"{{
1511                    "chainId": 1,
1512                    "depositContractAddress": "0x0000000000000000000000000000000000000000",
1513                    "{key}": 1700000000
1514                }}"#
1515            );
1516            let cfg: ChainConfig = serde_json::from_str(&json)
1517                .unwrap_or_else(|e| panic!("alias {key} must deserialize: {e}"));
1518            assert_eq!(cfg.hegota_time, Some(1_700_000_000), "alias {key}");
1519        }
1520    }
1521
1522    #[test]
1523    fn next_fork_skips_unscheduled_intermediate_forks() {
1524        // bal-devnet-7 layout: every post-merge fork up to Osaka at t=0, Amsterdam
1525        // scheduled later, no BPOs scheduled. `next_fork` must return Amsterdam
1526        // even though the BPO chain between Osaka and Amsterdam is empty.
1527        let config = ChainConfig {
1528            shanghai_time: Some(0),
1529            cancun_time: Some(0),
1530            prague_time: Some(0),
1531            osaka_time: Some(0),
1532            amsterdam_time: Some(1_779_098_127),
1533            ..Default::default()
1534        };
1535        assert_eq!(config.next_fork(0), Some(Fork::Amsterdam));
1536        assert_eq!(config.next_fork(1_779_098_126), Some(Fork::Amsterdam));
1537        assert_eq!(config.next_fork(1_779_098_127), None);
1538    }
1539
1540    #[test]
1541    fn next_fork_picks_earliest_scheduled() {
1542        // Contiguous schedule: at Cancun, next should be Prague (not Osaka).
1543        let config = ChainConfig {
1544            shanghai_time: Some(0),
1545            cancun_time: Some(100),
1546            prague_time: Some(200),
1547            osaka_time: Some(300),
1548            ..Default::default()
1549        };
1550        assert_eq!(config.next_fork(150), Some(Fork::Prague));
1551        assert_eq!(config.next_fork(250), Some(Fork::Osaka));
1552        assert_eq!(config.next_fork(300), None);
1553    }
1554
1555    #[test]
1556    fn next_fork_returns_none_when_at_last_scheduled() {
1557        let config = ChainConfig {
1558            shanghai_time: Some(0),
1559            cancun_time: Some(0),
1560            ..Default::default()
1561        };
1562        assert_eq!(config.next_fork(0), None);
1563    }
1564
1565    #[test]
1566    fn amsterdam_inherits_highest_activated_bpo_schedule() {
1567        // EIP-7892: Amsterdam declares no blob params of its own, so a genesis that
1568        // schedules BPO1 and then Amsterdam keeps BPO1's target and max across the
1569        // Amsterdam boundary. An unscheduled BPO2 must never contribute its schedule.
1570        let config: ChainConfig = serde_json::from_str(
1571            r#"{
1572                "chainId": 1,
1573                "depositContractAddress": "0x00000000219ab540356cbb839cbe05303d7705fa",
1574                "osakaTime": 0,
1575                "bpo1Time": 0,
1576                "amsterdamTime": 100,
1577                "blobSchedule": {
1578                    "cancun": {"target": 3, "max": 6, "baseFeeUpdateFraction": 3338477},
1579                    "prague": {"target": 6, "max": 9, "baseFeeUpdateFraction": 5007716},
1580                    "bpo1": {"target": 10, "max": 15, "baseFeeUpdateFraction": 8346193}
1581                }
1582            }"#,
1583        )
1584        .expect("genesis should parse");
1585
1586        let bpo1 = ForkBlobSchedule {
1587            target: 10,
1588            max: 15,
1589            base_fee_update_fraction: 8346193,
1590        };
1591        assert_eq!(config.get_fork_blob_schedule(99), Some(bpo1));
1592        assert_eq!(config.get_fork_blob_schedule(100), Some(bpo1));
1593    }
1594
1595    #[test]
1596    fn blob_schedule_for_fork_reports_the_inherited_entry() {
1597        // `eth_config` (EIP-7910) must report the blob params actually in force at a
1598        // fork's activation, which for Amsterdam is the highest activated BPO entry.
1599        let config = ChainConfig {
1600            osaka_time: Some(0),
1601            bpo1_time: Some(0),
1602            amsterdam_time: Some(100),
1603            ..Default::default()
1604        };
1605
1606        let schedule = config
1607            .get_blob_schedule_for_fork(Fork::Amsterdam)
1608            .expect("Amsterdam must report a blob schedule");
1609        assert_eq!((schedule.target, schedule.max), (10, 15));
1610
1611        // Forks that were never scheduled have nothing to report, and pre-Cancun forks
1612        // are activated by block number rather than timestamp.
1613        assert_eq!(config.get_blob_schedule_for_fork(Fork::BPO2), None);
1614        assert_eq!(config.get_blob_schedule_for_fork(Fork::London), None);
1615    }
1616
1617    #[test]
1618    fn amsterdam_prefers_explicitly_pinned_schedule() {
1619        let mut config = ChainConfig {
1620            osaka_time: Some(0),
1621            bpo1_time: Some(0),
1622            bpo2_time: Some(50),
1623            amsterdam_time: Some(100),
1624            ..Default::default()
1625        };
1626        assert_eq!(
1627            config.get_fork_blob_schedule(100),
1628            Some(default_bpo2_schedule())
1629        );
1630
1631        let pinned = ForkBlobSchedule {
1632            target: 16,
1633            max: 24,
1634            base_fee_update_fraction: 13353910,
1635        };
1636        config.blob_schedule.amsterdam = Some(pinned);
1637        assert_eq!(config.get_fork_blob_schedule(100), Some(pinned));
1638    }
1639}