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 latest activated BPO entry. A genesis that pins an entry for
511        // Amsterdam anyway applies from the first of Amsterdam, Hegotá and LStar to
512        // activate.
513        //
514        // The entry in force is the one activated last. BPO3 and later may come after
515        // Amsterdam, as they do on the test forks since tests@v21.0.2, so a fixed
516        // precedence between the two cannot work. Entries that activate at the same
517        // timestamp resolve in the order below, where BPO3 and later follow Amsterdam.
518        let amsterdam_time = [self.amsterdam_time, self.hegota_time, self.lstar_time]
519            .into_iter()
520            .flatten()
521            .min();
522        [
523            (self.cancun_time, Some(self.blob_schedule.cancun)),
524            (self.prague_time, Some(self.blob_schedule.prague)),
525            (self.osaka_time, Some(self.blob_schedule.osaka)),
526            (self.bpo1_time, Some(self.blob_schedule.bpo1)),
527            (self.bpo2_time, Some(self.blob_schedule.bpo2)),
528            (amsterdam_time, self.blob_schedule.amsterdam),
529            (self.bpo3_time, self.blob_schedule.bpo3),
530            (self.bpo4_time, self.blob_schedule.bpo4),
531            (self.bpo5_time, self.blob_schedule.bpo5),
532        ]
533        .into_iter()
534        .enumerate()
535        .filter_map(|(pos, (time, schedule))| {
536            let time = time.filter(|&time| time <= block_timestamp)?;
537            Some((time, pos, schedule?))
538        })
539        .max_by_key(|&(time, pos, _)| (time, pos))
540        .map(|(_, _, schedule)| schedule)
541    }
542
543    pub fn fork(&self, block_timestamp: u64) -> Fork {
544        self.get_fork(block_timestamp)
545    }
546
547    pub fn next_fork(&self, block_timestamp: u64) -> Option<Fork> {
548        // Pick the scheduled fork with the smallest activation timestamp strictly
549        // greater than `block_timestamp`. Iterating all timestamp-based forks avoids
550        // bugs when intermediate forks (e.g. BPOs) are skipped in a network's schedule.
551        //
552        // NOTE: every timestamp-based fork MUST appear here in chronological order.
553        // Omitting a fork will silently cause `next_fork` to skip it; ties are
554        // broken by array position, so the order also encodes the canonical
555        // schedule independent of the `Fork` enum's discriminants.
556        [
557            Fork::Shanghai,
558            Fork::Cancun,
559            Fork::Prague,
560            Fork::Osaka,
561            Fork::BPO1,
562            Fork::BPO2,
563            Fork::BPO3,
564            Fork::BPO4,
565            Fork::BPO5,
566            Fork::Amsterdam,
567            Fork::Hegota,
568            Fork::LStar,
569        ]
570        .into_iter()
571        .enumerate()
572        .filter_map(|(pos, fork)| {
573            self.get_activation_timestamp_for_fork(fork)
574                .filter(|&t| t > block_timestamp)
575                .map(|t| (fork, t, pos))
576        })
577        .min_by(|a, b| a.1.cmp(&b.1).then_with(|| a.2.cmp(&b.2)))
578        .map(|(fork, _, _)| fork)
579    }
580
581    pub fn get_last_scheduled_fork(&self) -> Fork {
582        if self.lstar_time.is_some() {
583            Fork::LStar
584        } else if self.hegota_time.is_some() {
585            Fork::Hegota
586        } else if self.amsterdam_time.is_some() {
587            Fork::Amsterdam
588        } else if self.bpo5_time.is_some() {
589            Fork::BPO5
590        } else if self.bpo4_time.is_some() {
591            Fork::BPO4
592        } else if self.bpo3_time.is_some() {
593            Fork::BPO3
594        } else if self.bpo2_time.is_some() {
595            Fork::BPO2
596        } else if self.bpo1_time.is_some() {
597            Fork::BPO1
598        } else if self.osaka_time.is_some() {
599            Fork::Osaka
600        } else if self.prague_time.is_some() {
601            Fork::Prague
602        } else if self.cancun_time.is_some() {
603            Fork::Cancun
604        } else {
605            Fork::Paris
606        }
607    }
608
609    pub fn get_activation_timestamp_for_fork(&self, fork: Fork) -> Option<u64> {
610        match fork {
611            Fork::Cancun => self.cancun_time,
612            Fork::Prague => self.prague_time,
613            Fork::Osaka => self.osaka_time,
614            Fork::BPO1 => self.bpo1_time,
615            Fork::BPO2 => self.bpo2_time,
616            Fork::BPO3 => self.bpo3_time,
617            Fork::BPO4 => self.bpo4_time,
618            Fork::BPO5 => self.bpo5_time,
619            Fork::Amsterdam => self.amsterdam_time,
620            Fork::Hegota => self.hegota_time,
621            Fork::LStar => self.lstar_time,
622            Fork::Homestead => self.homestead_block,
623            Fork::DaoFork => self.dao_fork_block,
624            Fork::Byzantium => self.byzantium_block,
625            Fork::Constantinople => self.constantinople_block,
626            Fork::Petersburg => self.petersburg_block,
627            Fork::Istanbul => self.istanbul_block,
628            Fork::MuirGlacier => self.muir_glacier_block,
629            Fork::Berlin => self.berlin_block,
630            Fork::London => self.london_block,
631            Fork::ArrowGlacier => self.arrow_glacier_block,
632            Fork::GrayGlacier => self.gray_glacier_block,
633            Fork::Paris => self.merge_netsplit_block,
634            Fork::Shanghai => self.shanghai_time,
635            _ => None,
636        }
637    }
638
639    pub fn get_blob_schedule_for_fork(&self, fork: Fork) -> Option<ForkBlobSchedule> {
640        // Blob params are timestamp-scheduled from Cancun onward; earlier forks are
641        // activated by block number and have no blob schedule. Resolving through the
642        // fork's activation timestamp keeps this in step with the inheritance rules in
643        // `get_fork_blob_schedule`, so a named fork that declares no entry of its own
644        // reports the entry actually in force at its activation.
645        if fork < Fork::Cancun {
646            return None;
647        }
648        self.get_activation_timestamp_for_fork(fork)
649            .and_then(|timestamp| self.get_fork_blob_schedule(timestamp))
650    }
651
652    pub fn gather_forks(&self, genesis_header: BlockHeader) -> (Vec<u64>, Vec<u64>) {
653        let mut block_number_based_forks: Vec<u64> = vec![
654            self.homestead_block,
655            if self.dao_fork_support {
656                self.dao_fork_block
657            } else {
658                None
659            },
660            self.eip150_block,
661            self.eip155_block,
662            self.eip158_block,
663            self.byzantium_block,
664            self.constantinople_block,
665            self.petersburg_block,
666            self.istanbul_block,
667            self.muir_glacier_block,
668            self.berlin_block,
669            self.london_block,
670            self.arrow_glacier_block,
671            self.gray_glacier_block,
672            self.merge_netsplit_block,
673        ]
674        .into_iter()
675        .flatten()
676        .collect();
677
678        // Remove repeated values
679        block_number_based_forks.sort();
680        block_number_based_forks.dedup();
681
682        let mut timestamp_based_forks: Vec<u64> = vec![
683            self.shanghai_time,
684            self.cancun_time,
685            self.prague_time,
686            self.osaka_time,
687            self.bpo1_time,
688            self.bpo2_time,
689            self.bpo3_time,
690            self.bpo4_time,
691            self.bpo5_time,
692            self.amsterdam_time,
693            self.hegota_time,
694            self.verkle_time,
695        ]
696        .into_iter()
697        .flatten()
698        .collect();
699
700        // Remove repeated values
701        timestamp_based_forks.sort();
702        timestamp_based_forks.dedup();
703
704        // Filter forks before genesis
705        block_number_based_forks.retain(|block_number| *block_number != 0);
706        timestamp_based_forks.retain(|block_timestamp| *block_timestamp > genesis_header.timestamp);
707
708        (block_number_based_forks, timestamp_based_forks)
709    }
710}
711
712#[allow(unused)]
713#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
714pub struct GenesisAccount {
715    #[serde(default, with = "crate::serde_utils::bytes")]
716    pub code: Bytes,
717    #[serde(default)]
718    pub storage: BTreeMap<U256, U256>,
719    #[serde(deserialize_with = "crate::serde_utils::u256::hex_or_dec::deserialize")]
720    pub balance: U256,
721    #[serde(default, with = "crate::serde_utils::u64::hex_or_dec")]
722    pub nonce: u64,
723}
724
725impl Genesis {
726    pub fn get_block(&self) -> Block {
727        Block::new(self.get_block_header(), self.get_block_body())
728    }
729
730    fn get_block_header(&self) -> BlockHeader {
731        let mut blob_gas_used: Option<u64> = None;
732        let mut excess_blob_gas: Option<u64> = None;
733
734        if let Some(cancun_time) = self.config.cancun_time
735            && cancun_time <= self.timestamp
736        {
737            blob_gas_used = Some(self.blob_gas_used.unwrap_or(0));
738            excess_blob_gas = Some(self.excess_blob_gas.unwrap_or(0));
739        }
740        let base_fee_per_gas = self.base_fee_per_gas.or_else(|| {
741            self.config
742                .is_london_activated(0)
743                .then_some(INITIAL_BASE_FEE)
744        });
745
746        let withdrawals_root = self
747            .config
748            .is_shanghai_activated(self.timestamp)
749            .then_some(compute_withdrawals_root(&[], &NativeCrypto));
750
751        let parent_beacon_block_root = self
752            .config
753            .is_cancun_activated(self.timestamp)
754            .then_some(H256::zero());
755
756        let requests_hash = self
757            .config
758            .is_prague_activated(self.timestamp)
759            .then_some(self.requests_hash.unwrap_or(*DEFAULT_REQUESTS_HASH));
760
761        let block_access_list_hash = self
762            .config
763            .is_amsterdam_activated(self.timestamp)
764            .then_some(
765                self.block_access_list_hash
766                    .unwrap_or(*EMPTY_BLOCK_ACCESS_LIST_HASH),
767            );
768
769        let slot_number = self
770            .config
771            .is_amsterdam_activated(self.timestamp)
772            .then_some(self.slot_number.unwrap_or(0));
773
774        BlockHeader {
775            parent_hash: H256::zero(),
776            ommers_hash: *DEFAULT_OMMERS_HASH,
777            coinbase: self.coinbase,
778            state_root: self.compute_state_root(),
779            transactions_root: compute_transactions_root(&[], &NativeCrypto),
780            receipts_root: compute_receipts_root(&[], &NativeCrypto),
781            logs_bloom: Bloom::zero(),
782            difficulty: self.difficulty,
783            number: 0,
784            gas_limit: self.gas_limit,
785            gas_used: 0,
786            timestamp: self.timestamp,
787            extra_data: self.extra_data.clone(),
788            prev_randao: self.mix_hash,
789            nonce: self.nonce,
790            base_fee_per_gas,
791            withdrawals_root,
792            blob_gas_used,
793            excess_blob_gas,
794            parent_beacon_block_root,
795            requests_hash,
796            block_access_list_hash,
797            slot_number,
798            ..Default::default()
799        }
800    }
801
802    fn get_block_body(&self) -> BlockBody {
803        BlockBody {
804            transactions: vec![],
805            ommers: vec![],
806            withdrawals: Some(vec![]),
807        }
808    }
809
810    pub fn compute_state_root(&self) -> H256 {
811        let iter = self.alloc.iter().map(|(addr, account)| {
812            (
813                keccak_hash(addr).to_vec(),
814                AccountState::from(account).encode_to_vec(),
815            )
816        });
817        Trie::compute_hash_from_unsorted_iter(iter, &NativeCrypto)
818    }
819}
820#[cfg(test)]
821mod tests {
822    use std::str::FromStr;
823    use std::{fs::File, io::BufReader};
824
825    use ethereum_types::H160;
826
827    use crate::types::INITIAL_BASE_FEE;
828
829    use super::*;
830
831    #[test]
832    fn terminal_total_difficulty_accepts_number_or_hex_string() {
833        // geth/reth-style genesis files encode terminalTotalDifficulty as a
834        // bare decimal number that exceeds u64::MAX; ethrex must accept it as
835        // well as the 0x-hex-string form.
836        let dca = r#""depositContractAddress":"0x00000000219ab540356cbb839cbe05303d7705fa""#;
837
838        let from_number: ChainConfig = serde_json::from_str(&format!(
839            r#"{{"chainId":1,"terminalTotalDifficulty":58750000000000000000000,{dca}}}"#
840        ))
841        .expect("number-encoded TTD should parse");
842        // f64 cast is lossy above u64::MAX; assert the known, stable
843        // approximation so a regression to Some(0) can't silently pass.
844        assert_eq!(
845            from_number.terminal_total_difficulty,
846            Some(58749999999999996329984u128)
847        );
848
849        let from_hex: ChainConfig = serde_json::from_str(&format!(
850            r#"{{"chainId":1,"terminalTotalDifficulty":"0xc70d808a128d7380000",{dca}}}"#
851        ))
852        .expect("hex-string TTD should parse");
853        assert_eq!(
854            from_hex.terminal_total_difficulty,
855            Some(58750000000000000000000u128)
856        );
857
858        let small: ChainConfig = serde_json::from_str(&format!(
859            r#"{{"chainId":1,"terminalTotalDifficulty":17000000000000000,{dca}}}"#
860        ))
861        .expect("small number TTD should parse");
862        assert_eq!(small.terminal_total_difficulty, Some(17000000000000000u128));
863
864        // A negative bare number must error, not silently saturate to Some(0).
865        let negative = serde_json::from_str::<ChainConfig>(&format!(
866            r#"{{"chainId":1,"terminalTotalDifficulty":-1,{dca}}}"#
867        ));
868        let err = negative.expect_err("negative TTD must be rejected");
869        assert!(
870            err.to_string().contains("finite, non-negative"),
871            "error should name the sign/finiteness cause, got: {err}"
872        );
873    }
874
875    #[test]
876    fn genesis_quantities_accept_numbers_and_hex_or_decimal_strings() {
877        // geth reads these fields as a JSON number, a 0x-hex string or a decimal
878        // string, and genesis files written by other tooling use all three. An
879        // unprefixed string is decimal, so "10" must not be read as 0x10.
880        let fixture: serde_json::Value = serde_json::from_reader(BufReader::new(
881            File::open("../../fixtures/genesis/l1.json").expect("Failed to open genesis file"),
882        ))
883        .expect("Failed to deserialize genesis file");
884        for encoded in [
885            serde_json::json!(10),
886            serde_json::json!("0xa"),
887            serde_json::json!("0XA"),
888            serde_json::json!("10"),
889        ] {
890            let account: GenesisAccount =
891                serde_json::from_value(serde_json::json!({"balance": encoded, "nonce": encoded}))
892                    .expect("account quantities should parse");
893            assert_eq!(
894                (account.balance, account.nonce),
895                (U256::from(10), 10),
896                "account quantities {encoded}"
897            );
898
899            let mut genesis = fixture.clone();
900            for field in [
901                "gasLimit",
902                "nonce",
903                "timestamp",
904                "baseFeePerGas",
905                "blobGasUsed",
906                "excessBlobGas",
907                "slotNumber",
908            ] {
909                genesis[field] = encoded.clone();
910            }
911            let genesis: Genesis =
912                serde_json::from_value(genesis).expect("genesis header fields should parse");
913            assert_eq!(
914                (genesis.gas_limit, genesis.nonce, genesis.timestamp),
915                (10, 10, 10),
916                "genesis header fields {encoded}"
917            );
918            assert_eq!(
919                (
920                    genesis.base_fee_per_gas,
921                    genesis.blob_gas_used,
922                    genesis.excess_blob_gas,
923                    genesis.slot_number
924                ),
925                (Some(10), Some(10), Some(10), Some(10)),
926                "optional genesis header fields {encoded}"
927            );
928        }
929
930        // As in geth, an empty string is 0.
931        let account: GenesisAccount =
932            serde_json::from_value(serde_json::json!({"balance": "", "nonce": ""}))
933                .expect("empty account quantities should parse");
934        assert_eq!((account.balance, account.nonce), (U256::zero(), 0));
935
936        for invalid in [
937            serde_json::json!(-1),
938            serde_json::json!("0xzz"),
939            serde_json::json!("0x"),
940            serde_json::json!("0x0x10"),
941            serde_json::json!("+10"),
942            serde_json::json!(true),
943        ] {
944            assert!(
945                serde_json::from_value::<GenesisAccount>(
946                    serde_json::json!({"balance": "0", "nonce": invalid})
947                )
948                .is_err(),
949                "account nonce {invalid} must be rejected"
950            );
951            assert!(
952                serde_json::from_value::<GenesisAccount>(serde_json::json!({"balance": invalid}))
953                    .is_err(),
954                "account balance {invalid} must be rejected"
955            );
956        }
957        // serde_json holds an integer this large as a float, so it must be rejected
958        // rather than rounded.
959        assert!(
960            serde_json::from_str::<GenesisAccount>(r#"{"balance": 1000000000000000000000000}"#)
961                .is_err(),
962            "a balance above u64::MAX given as a JSON number must be rejected"
963        );
964    }
965
966    #[test]
967    fn pow_genesis_detection() {
968        // Default genesis: difficulty 0 (post-merge at genesis) -> supported.
969        let mut g = Genesis::default();
970        assert!(!is_unsupported_pow_genesis(&g));
971
972        // PoW genesis: non-zero difficulty, no merge configured -> unsupported.
973        g.difficulty = U256::from(0x4000_0000u64);
974        assert!(is_unsupported_pow_genesis(&g));
975
976        // Mainnet-style: non-zero difficulty but TTD configured -> supported.
977        g.config.terminal_total_difficulty = Some(58750000000000000000000);
978        assert!(!is_unsupported_pow_genesis(&g));
979
980        // Merge-netsplit block configured (no TTD) -> supported.
981        g.config.terminal_total_difficulty = None;
982        g.config.merge_netsplit_block = Some(15537394);
983        assert!(!is_unsupported_pow_genesis(&g));
984
985        // TTD = Some(0) sentinel (PoS from genesis), non-zero difficulty -> supported.
986        g.config.merge_netsplit_block = None;
987        g.config.terminal_total_difficulty = Some(0);
988        assert!(!is_unsupported_pow_genesis(&g));
989
990        // terminal_total_difficulty_passed with no TTD value (post-merge snapshot
991        // that dropped the redundant field), non-zero difficulty -> supported.
992        g.config.terminal_total_difficulty = None;
993        g.config.terminal_total_difficulty_passed = true;
994        assert!(!is_unsupported_pow_genesis(&g));
995    }
996
997    #[test]
998    fn deserialize_genesis_file() {
999        // Deserialize genesis file
1000        let file = File::open("../../fixtures/genesis/kurtosis.json")
1001            .expect("Failed to open genesis file");
1002        let reader = BufReader::new(file);
1003        let genesis: Genesis =
1004            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1005        // Check Genesis fields
1006        // Chain config
1007        let expected_chain_config = ChainConfig {
1008            chain_id: 3151908_u64,
1009            homestead_block: Some(0),
1010            eip150_block: Some(0),
1011            eip155_block: Some(0),
1012            eip158_block: Some(0),
1013            byzantium_block: Some(0),
1014            constantinople_block: Some(0),
1015            petersburg_block: Some(0),
1016            istanbul_block: Some(0),
1017            berlin_block: Some(0),
1018            london_block: Some(0),
1019            merge_netsplit_block: Some(0),
1020            shanghai_time: Some(0),
1021            cancun_time: Some(0),
1022            prague_time: Some(1718232101),
1023            terminal_total_difficulty: Some(0),
1024            terminal_total_difficulty_passed: true,
1025            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1026                .unwrap(),
1027            // Note this BlobSchedule config is not the default
1028            blob_schedule: BlobSchedule {
1029                cancun: ForkBlobSchedule {
1030                    target: 2,
1031                    max: 3,
1032                    base_fee_update_fraction: 6676954,
1033                },
1034                prague: ForkBlobSchedule {
1035                    target: 3,
1036                    max: 4,
1037                    base_fee_update_fraction: 13353908,
1038                },
1039                ..Default::default()
1040            },
1041            ..Default::default()
1042        };
1043        assert_eq!(&genesis.config, &expected_chain_config);
1044        // Genesis header fields
1045        assert_eq!(genesis.coinbase, Address::from([0; 20]));
1046        assert_eq!(genesis.difficulty, U256::from(1));
1047        assert!(genesis.extra_data.is_empty());
1048        assert_eq!(genesis.gas_limit, 0x17d7840);
1049        assert_eq!(genesis.nonce, 0x1234);
1050        assert_eq!(genesis.mix_hash, H256::from([0; 32]));
1051        assert_eq!(genesis.timestamp, 1718040081);
1052        // Check alloc field
1053        // We will only check a couple of the hashmap's values as it is quite large
1054        let addr_a = Address::from_str("0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02").unwrap();
1055        assert!(genesis.alloc.contains_key(&addr_a));
1056        let expected_account_a = GenesisAccount {
1057        code: Bytes::from(hex::decode("3373fffffffffffffffffffffffffffffffffffffffe14604d57602036146024575f5ffd5b5f35801560495762001fff810690815414603c575f5ffd5b62001fff01545f5260205ff35b5f5ffd5b62001fff42064281555f359062001fff015500").unwrap()),
1058        balance: 0.into(),
1059        nonce: 1,
1060        storage: Default::default(),
1061    };
1062        assert_eq!(genesis.alloc[&addr_a], expected_account_a);
1063        // Check some storage values from another account
1064        let addr_b = Address::from_str("0x4242424242424242424242424242424242424242").unwrap();
1065        assert!(genesis.alloc.contains_key(&addr_b));
1066        let addr_b_storage = &genesis.alloc[&addr_b].storage;
1067        assert_eq!(
1068            addr_b_storage.get(
1069                &U256::from_str(
1070                    "0x0000000000000000000000000000000000000000000000000000000000000022"
1071                )
1072                .unwrap()
1073            ),
1074            Some(
1075                &U256::from_str(
1076                    "0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b"
1077                )
1078                .unwrap()
1079            )
1080        );
1081        assert_eq!(
1082            addr_b_storage.get(
1083                &U256::from_str(
1084                    "0x0000000000000000000000000000000000000000000000000000000000000038"
1085                )
1086                .unwrap()
1087            ),
1088            Some(
1089                &U256::from_str(
1090                    "0xe71f0aa83cc32edfbefa9f4d3e0174ca85182eec9f3a09f6a6c0df6377a510d7"
1091                )
1092                .unwrap()
1093            )
1094        );
1095    }
1096
1097    #[test]
1098    fn genesis_block() {
1099        // Deserialize genesis file
1100        let file = File::open("../../fixtures/genesis/kurtosis.json")
1101            .expect("Failed to open genesis file");
1102        let reader = BufReader::new(file);
1103        let genesis: Genesis =
1104            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1105        let genesis_block = genesis.get_block();
1106        let header = genesis_block.header;
1107        let body = genesis_block.body;
1108        assert_eq!(header.parent_hash, H256::from([0; 32]));
1109        assert_eq!(header.ommers_hash, *DEFAULT_OMMERS_HASH);
1110        assert_eq!(header.coinbase, Address::default());
1111        assert_eq!(
1112            header.state_root,
1113            H256::from_str("0x2dab6a1d6d638955507777aecea699e6728825524facbd446bd4e86d44fa5ecd")
1114                .unwrap()
1115        );
1116        assert_eq!(
1117            header.transactions_root,
1118            compute_transactions_root(&[], &NativeCrypto)
1119        );
1120        assert_eq!(
1121            header.receipts_root,
1122            compute_receipts_root(&[], &NativeCrypto)
1123        );
1124        assert_eq!(header.logs_bloom, Bloom::default());
1125        assert_eq!(header.difficulty, U256::from(1));
1126        assert_eq!(header.gas_limit, 25_000_000);
1127        assert_eq!(header.gas_used, 0);
1128        assert_eq!(header.timestamp, 1_718_040_081);
1129        assert_eq!(header.extra_data, Bytes::default());
1130        assert_eq!(header.prev_randao, H256::from([0; 32]));
1131        assert_eq!(header.nonce, 4660);
1132        assert_eq!(
1133            header.base_fee_per_gas.unwrap_or(INITIAL_BASE_FEE),
1134            INITIAL_BASE_FEE
1135        );
1136        assert_eq!(
1137            header.withdrawals_root,
1138            Some(compute_withdrawals_root(&[], &NativeCrypto))
1139        );
1140        assert_eq!(header.blob_gas_used, Some(0));
1141        assert_eq!(header.excess_blob_gas, Some(0));
1142        assert_eq!(header.parent_beacon_block_root, Some(H256::zero()));
1143        assert!(body.transactions.is_empty());
1144        assert!(body.ommers.is_empty());
1145        assert!(body.withdrawals.is_some_and(|w| w.is_empty()));
1146    }
1147
1148    #[test]
1149    // Parses genesis received by kurtosis and checks that the hash matches the next block's parent hash
1150    fn read_and_compute_kurtosis_hash() {
1151        let file = File::open("../../fixtures/genesis/kurtosis.json")
1152            .expect("Failed to open genesis file");
1153        let reader = BufReader::new(file);
1154        let genesis: Genesis =
1155            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1156        let genesis_block_hash = genesis.get_block().hash();
1157        assert_eq!(
1158            genesis_block_hash,
1159            H256::from_str("0xcb5306dd861d0f2c1f9952fbfbc75a46d0b6ce4f37bea370c3471fe8410bf40b")
1160                .unwrap()
1161        )
1162    }
1163
1164    #[test]
1165    fn parse_hive_genesis_file() {
1166        let file =
1167            File::open("../../fixtures/genesis/hive.json").expect("Failed to open genesis file");
1168        let reader = BufReader::new(file);
1169        let _genesis: Genesis =
1170            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1171    }
1172
1173    #[test]
1174    fn read_and_compute_hive_hash() {
1175        let file =
1176            File::open("../../fixtures/genesis/hive.json").expect("Failed to open genesis file");
1177        let reader = BufReader::new(file);
1178        let genesis: Genesis =
1179            serde_json::from_reader(reader).expect("Failed to deserialize genesis file");
1180        let computed_block_hash = genesis.get_block().hash();
1181        let genesis_block_hash =
1182            H256::from_str("0x30f516e34fc173bb5fc4daddcc7532c4aca10b702c7228f3c806b4df2646fb7e")
1183                .unwrap();
1184        assert_eq!(genesis_block_hash, computed_block_hash)
1185    }
1186
1187    #[test]
1188    fn deserialize_chain_config_blob_schedule() {
1189        let json = r#"
1190
1191            {
1192                "chainId": 123,
1193                "blobSchedule": {
1194                  "cancun": {
1195                    "target": 1,
1196                    "max": 2,
1197                    "baseFeeUpdateFraction": 10000
1198                  },
1199                  "prague": {
1200                    "target": 3,
1201                    "max": 4,
1202                    "baseFeeUpdateFraction": 20000
1203                  }
1204                },
1205                "depositContractAddress": "0x4242424242424242424242424242424242424242"
1206            }
1207            "#;
1208
1209        let config: ChainConfig =
1210            serde_json::from_str(json).expect("Failed to deserialize ChainConfig");
1211        let expected_chain_config = ChainConfig {
1212            chain_id: 123,
1213            blob_schedule: BlobSchedule {
1214                cancun: ForkBlobSchedule {
1215                    target: 1,
1216                    max: 2,
1217                    base_fee_update_fraction: 10000,
1218                },
1219                prague: ForkBlobSchedule {
1220                    target: 3,
1221                    max: 4,
1222                    base_fee_update_fraction: 20000,
1223                },
1224                ..Default::default()
1225            },
1226            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1227                .unwrap(),
1228            ..Default::default()
1229        };
1230        assert_eq!(&config, &expected_chain_config);
1231    }
1232
1233    #[test]
1234    fn deserialize_chain_config_missing_entire_blob_schedule() {
1235        let json = r#"
1236            {
1237                "chainId": 123,
1238                "depositContractAddress": "0x4242424242424242424242424242424242424242"
1239            }
1240            "#;
1241
1242        let config: ChainConfig =
1243            serde_json::from_str(json).expect("Failed to deserialize ChainConfig");
1244        let expected_chain_config = ChainConfig {
1245            chain_id: 123,
1246            blob_schedule: BlobSchedule {
1247                cancun: ForkBlobSchedule {
1248                    target: 3,
1249                    max: 6,
1250                    base_fee_update_fraction: 3338477,
1251                },
1252                prague: ForkBlobSchedule {
1253                    target: 6,
1254                    max: 9,
1255                    base_fee_update_fraction: 5007716,
1256                },
1257                ..Default::default()
1258            },
1259            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1260                .unwrap(),
1261            ..Default::default()
1262        };
1263        assert_eq!(&config, &expected_chain_config);
1264    }
1265
1266    #[test]
1267    fn deserialize_chain_config_missing_cancun_blob_schedule() {
1268        let json = r#"
1269            {
1270                "chainId": 123,
1271                "blobSchedule": {
1272                    "prague": {
1273                      "target": 3,
1274                      "max": 4,
1275                      "baseFeeUpdateFraction": 20000
1276                    }
1277                },
1278                "depositContractAddress": "0x4242424242424242424242424242424242424242"
1279            }
1280            "#;
1281
1282        let config: ChainConfig =
1283            serde_json::from_str(json).expect("Failed to deserialize ChainConfig");
1284        let expected_chain_config = ChainConfig {
1285            chain_id: 123,
1286            blob_schedule: BlobSchedule {
1287                cancun: ForkBlobSchedule {
1288                    target: 3,
1289                    max: 6,
1290                    base_fee_update_fraction: 3338477,
1291                },
1292                prague: ForkBlobSchedule {
1293                    target: 3,
1294                    max: 4,
1295                    base_fee_update_fraction: 20000,
1296                },
1297                ..Default::default()
1298            },
1299            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1300                .unwrap(),
1301            ..Default::default()
1302        };
1303        assert_eq!(&config, &expected_chain_config);
1304    }
1305
1306    #[test]
1307    fn deserialize_chain_config_missing_prague_blob_schedule() {
1308        let json = r#"
1309            {
1310                "chainId": 123,
1311                "blobSchedule": {
1312                  "cancun": {
1313                    "target": 1,
1314                    "max": 2,
1315                    "baseFeeUpdateFraction": 10000
1316                  }
1317                },
1318                "depositContractAddress": "0x4242424242424242424242424242424242424242"
1319            }
1320            "#;
1321
1322        let config: ChainConfig =
1323            serde_json::from_str(json).expect("Failed to deserialize ChainConfig");
1324        let expected_chain_config = ChainConfig {
1325            chain_id: 123,
1326            blob_schedule: BlobSchedule {
1327                cancun: ForkBlobSchedule {
1328                    target: 1,
1329                    max: 2,
1330                    base_fee_update_fraction: 10000,
1331                },
1332                prague: ForkBlobSchedule {
1333                    target: 6,
1334                    max: 9,
1335                    base_fee_update_fraction: 5007716,
1336                },
1337                ..Default::default()
1338            },
1339            deposit_contract_address: H160::from_str("0x4242424242424242424242424242424242424242")
1340                .unwrap(),
1341            ..Default::default()
1342        };
1343        assert_eq!(&config, &expected_chain_config);
1344    }
1345
1346    #[test]
1347    fn deserialize_chain_config_missing_deposit_contract_address() {
1348        let json = r#"
1349            {
1350                "chainId": 123
1351            }
1352            "#;
1353
1354        let result: Result<ChainConfig, _> = serde_json::from_str(json);
1355
1356        assert!(result.is_err());
1357
1358        let error_message = result.unwrap_err().to_string();
1359        assert!(error_message.contains("missing field `depositContractAddress`"),);
1360    }
1361
1362    #[test]
1363    fn lstar_fork_ordering_and_activation() {
1364        // LStar is the highest fork and strictly greater than Amsterdam.
1365        assert!(Fork::LStar > Fork::Amsterdam);
1366        assert_eq!(<&str>::from(Fork::LStar), "LStar");
1367
1368        let mut cfg = ChainConfig {
1369            lstar_time: Some(100),
1370            ..Default::default()
1371        };
1372        assert!(!cfg.is_lstar_activated(99));
1373        assert!(cfg.is_lstar_activated(100));
1374        assert!(cfg.is_lstar_activated(101));
1375
1376        cfg.lstar_time = None;
1377        assert!(!cfg.is_lstar_activated(u64::MAX));
1378    }
1379
1380    #[test]
1381    fn native_l2_genesis_activates_amsterdam() {
1382        let file = File::open("../../fixtures/genesis/native_l2.json")
1383            .expect("Failed to open native_l2.json");
1384        let reader = BufReader::new(file);
1385        let genesis: Genesis =
1386            serde_json::from_reader(reader).expect("Failed to deserialize native_l2.json");
1387        assert_eq!(
1388            genesis.config.get_fork(0),
1389            Fork::Amsterdam,
1390            "native_l2.json genesis should activate Amsterdam at timestamp 0"
1391        );
1392        // Confirm blobSchedule falls back to bpo2 (no explicit amsterdam entry).
1393        let bs = genesis
1394            .config
1395            .get_fork_blob_schedule(0)
1396            .expect("Amsterdam implies bpo2 blob schedule");
1397        assert_eq!(bs.max, 21, "Amsterdam should inherit bpo2 max=21");
1398    }
1399
1400    #[test]
1401    fn lstar_fork_resolution() {
1402        // Genesis-activated Amsterdam + LStar (LStar at a later time).
1403        let cfg = ChainConfig {
1404            cancun_time: Some(0),
1405            prague_time: Some(0),
1406            amsterdam_time: Some(0),
1407            lstar_time: Some(1000),
1408            ..Default::default()
1409        };
1410
1411        // Before LStar: highest active fork is Amsterdam.
1412        assert_eq!(cfg.get_fork(999), Fork::Amsterdam);
1413        // At/after LStar: highest active fork is LStar.
1414        assert_eq!(cfg.get_fork(1000), Fork::LStar);
1415
1416        // next_fork: at Amsterdam (pre-LStar) the next scheduled fork is LStar; at LStar there is none.
1417        assert_eq!(cfg.next_fork(999), Some(Fork::LStar));
1418        assert_eq!(cfg.next_fork(1000), None);
1419
1420        // get_last_scheduled_fork reflects LStar once scheduled.
1421        assert_eq!(cfg.get_last_scheduled_fork(), Fork::LStar);
1422
1423        // Activation timestamp round-trips.
1424        assert_eq!(
1425            cfg.get_activation_timestamp_for_fork(Fork::LStar),
1426            Some(1000)
1427        );
1428
1429        // Blob schedule at LStar inherits Amsterdam's (which inherits bpo2, max=9 default).
1430        let sched_lstar = cfg
1431            .get_fork_blob_schedule(1000)
1432            .expect("lstar blob schedule");
1433        let sched_amsterdam = cfg
1434            .get_fork_blob_schedule(999)
1435            .expect("amsterdam blob schedule");
1436        assert_eq!(sched_lstar.max, sched_amsterdam.max);
1437    }
1438
1439    #[test]
1440    fn test_hegota_after_amsterdam() {
1441        // Discriminant ordering: Hegota strictly follows Amsterdam.
1442        assert!(Fork::Hegota > Fork::Amsterdam);
1443        assert_eq!(Fork::Hegota as u8, 26);
1444        assert_eq!(Fork::Amsterdam as u8, 25);
1445
1446        // String conversion.
1447        let hegota_str: &str = Fork::Hegota.into();
1448        assert_eq!(hegota_str, "Hegota");
1449
1450        // Activation predicate boundary behavior.
1451        let mut config = ChainConfig {
1452            chain_id: 1,
1453            deposit_contract_address: Address::default(),
1454            ..Default::default()
1455        };
1456        config.hegota_time = Some(1000);
1457        assert!(!config.is_hegota_activated(999));
1458        assert!(config.is_hegota_activated(1000));
1459        assert!(config.is_hegota_activated(1001));
1460
1461        // None means inactive.
1462        config.hegota_time = None;
1463        assert!(!config.is_hegota_activated(0));
1464        assert!(!config.is_hegota_activated(u64::MAX));
1465
1466        // get_fork returns Hegota when both Amsterdam and Hegota are active.
1467        let mut config = ChainConfig {
1468            chain_id: 1,
1469            deposit_contract_address: Address::default(),
1470            ..Default::default()
1471        };
1472        config.amsterdam_time = Some(500);
1473        config.hegota_time = Some(1000);
1474        assert_eq!(config.get_fork(499), Fork::Paris);
1475        assert_eq!(config.get_fork(500), Fork::Amsterdam);
1476        assert_eq!(config.get_fork(999), Fork::Amsterdam);
1477        assert_eq!(config.get_fork(1000), Fork::Hegota);
1478        assert_eq!(config.get_fork(2000), Fork::Hegota);
1479
1480        // next_fork transitions correctly.
1481        assert_eq!(config.next_fork(500), Some(Fork::Hegota));
1482        assert_eq!(config.next_fork(1000), None);
1483
1484        // get_last_scheduled_fork picks Hegota when scheduled.
1485        assert_eq!(config.get_last_scheduled_fork(), Fork::Hegota);
1486
1487        // get_activation_timestamp_for_fork returns the right value.
1488        assert_eq!(
1489            config.get_activation_timestamp_for_fork(Fork::Hegota),
1490            Some(1000)
1491        );
1492    }
1493
1494    #[test]
1495    fn chain_config_accepts_heze_and_bogota_aliases_for_hegota_time() {
1496        for key in [
1497            "hegotaTime",
1498            "hezeTime",
1499            "heze_time",
1500            "bogotaTime",
1501            "bogota_time",
1502        ] {
1503            let json = format!(
1504                r#"{{
1505                    "chainId": 1,
1506                    "depositContractAddress": "0x0000000000000000000000000000000000000000",
1507                    "{key}": 1700000000
1508                }}"#
1509            );
1510            let cfg: ChainConfig = serde_json::from_str(&json)
1511                .unwrap_or_else(|e| panic!("alias {key} must deserialize: {e}"));
1512            assert_eq!(cfg.hegota_time, Some(1_700_000_000), "alias {key}");
1513        }
1514    }
1515
1516    #[test]
1517    fn next_fork_skips_unscheduled_intermediate_forks() {
1518        // bal-devnet-7 layout: every post-merge fork up to Osaka at t=0, Amsterdam
1519        // scheduled later, no BPOs scheduled. `next_fork` must return Amsterdam
1520        // even though the BPO chain between Osaka and Amsterdam is empty.
1521        let config = ChainConfig {
1522            shanghai_time: Some(0),
1523            cancun_time: Some(0),
1524            prague_time: Some(0),
1525            osaka_time: Some(0),
1526            amsterdam_time: Some(1_779_098_127),
1527            ..Default::default()
1528        };
1529        assert_eq!(config.next_fork(0), Some(Fork::Amsterdam));
1530        assert_eq!(config.next_fork(1_779_098_126), Some(Fork::Amsterdam));
1531        assert_eq!(config.next_fork(1_779_098_127), None);
1532    }
1533
1534    #[test]
1535    fn next_fork_picks_earliest_scheduled() {
1536        // Contiguous schedule: at Cancun, next should be Prague (not Osaka).
1537        let config = ChainConfig {
1538            shanghai_time: Some(0),
1539            cancun_time: Some(100),
1540            prague_time: Some(200),
1541            osaka_time: Some(300),
1542            ..Default::default()
1543        };
1544        assert_eq!(config.next_fork(150), Some(Fork::Prague));
1545        assert_eq!(config.next_fork(250), Some(Fork::Osaka));
1546        assert_eq!(config.next_fork(300), None);
1547    }
1548
1549    #[test]
1550    fn next_fork_returns_none_when_at_last_scheduled() {
1551        let config = ChainConfig {
1552            shanghai_time: Some(0),
1553            cancun_time: Some(0),
1554            ..Default::default()
1555        };
1556        assert_eq!(config.next_fork(0), None);
1557    }
1558
1559    #[test]
1560    fn amsterdam_inherits_highest_activated_bpo_schedule() {
1561        // EIP-7892: Amsterdam declares no blob params of its own, so a genesis that
1562        // schedules BPO1 and then Amsterdam keeps BPO1's target and max across the
1563        // Amsterdam boundary. An unscheduled BPO2 must never contribute its schedule.
1564        let config: ChainConfig = serde_json::from_str(
1565            r#"{
1566                "chainId": 1,
1567                "depositContractAddress": "0x00000000219ab540356cbb839cbe05303d7705fa",
1568                "osakaTime": 0,
1569                "bpo1Time": 0,
1570                "amsterdamTime": 100,
1571                "blobSchedule": {
1572                    "cancun": {"target": 3, "max": 6, "baseFeeUpdateFraction": 3338477},
1573                    "prague": {"target": 6, "max": 9, "baseFeeUpdateFraction": 5007716},
1574                    "bpo1": {"target": 10, "max": 15, "baseFeeUpdateFraction": 8346193}
1575                }
1576            }"#,
1577        )
1578        .expect("genesis should parse");
1579
1580        let bpo1 = ForkBlobSchedule {
1581            target: 10,
1582            max: 15,
1583            base_fee_update_fraction: 8346193,
1584        };
1585        assert_eq!(config.get_fork_blob_schedule(99), Some(bpo1));
1586        assert_eq!(config.get_fork_blob_schedule(100), Some(bpo1));
1587    }
1588
1589    #[test]
1590    fn blob_schedule_for_fork_reports_the_inherited_entry() {
1591        // `eth_config` (EIP-7910) must report the blob params actually in force at a
1592        // fork's activation, which for Amsterdam is the highest activated BPO entry.
1593        let config = ChainConfig {
1594            osaka_time: Some(0),
1595            bpo1_time: Some(0),
1596            amsterdam_time: Some(100),
1597            ..Default::default()
1598        };
1599
1600        let schedule = config
1601            .get_blob_schedule_for_fork(Fork::Amsterdam)
1602            .expect("Amsterdam must report a blob schedule");
1603        assert_eq!((schedule.target, schedule.max), (10, 15));
1604
1605        // Forks that were never scheduled have nothing to report, and pre-Cancun forks
1606        // are activated by block number rather than timestamp.
1607        assert_eq!(config.get_blob_schedule_for_fork(Fork::BPO2), None);
1608        assert_eq!(config.get_blob_schedule_for_fork(Fork::London), None);
1609    }
1610
1611    #[test]
1612    fn amsterdam_prefers_explicitly_pinned_schedule() {
1613        let mut config = ChainConfig {
1614            osaka_time: Some(0),
1615            bpo1_time: Some(0),
1616            bpo2_time: Some(50),
1617            amsterdam_time: Some(100),
1618            ..Default::default()
1619        };
1620        assert_eq!(
1621            config.get_fork_blob_schedule(100),
1622            Some(default_bpo2_schedule())
1623        );
1624
1625        let pinned = ForkBlobSchedule {
1626            target: 16,
1627            max: 24,
1628            base_fee_update_fraction: 13353910,
1629        };
1630        config.blob_schedule.amsterdam = Some(pinned);
1631        assert_eq!(config.get_fork_blob_schedule(100), Some(pinned));
1632    }
1633
1634    #[test]
1635    fn bpo3_after_amsterdam_replaces_its_schedule() {
1636        // tests@v21.0.2 schedules BPO3 after Amsterdam (`AmsterdamBPOIncrease`), with
1637        // the Amsterdam entry pinned to the BPO2 values. BPO3 must take over from its
1638        // activation on, including when both activate at the same timestamp.
1639        let bpo3 = ForkBlobSchedule {
1640            target: 21,
1641            max: 32,
1642            base_fee_update_fraction: 17527006,
1643        };
1644        let mut config = ChainConfig {
1645            osaka_time: Some(0),
1646            bpo1_time: Some(0),
1647            bpo2_time: Some(0),
1648            amsterdam_time: Some(0),
1649            bpo3_time: Some(15_000),
1650            ..Default::default()
1651        };
1652        config.blob_schedule.amsterdam = Some(default_bpo2_schedule());
1653        config.blob_schedule.bpo3 = Some(bpo3);
1654
1655        assert_eq!(
1656            config.get_fork_blob_schedule(14_999),
1657            Some(default_bpo2_schedule())
1658        );
1659        assert_eq!(config.get_fork_blob_schedule(15_000), Some(bpo3));
1660
1661        config.bpo3_time = Some(0);
1662        assert_eq!(config.get_fork_blob_schedule(0), Some(bpo3));
1663    }
1664}