Skip to main content

reth_chainspec/
spec.rs

1pub use alloy_eips::eip1559::BaseFeeParams;
2use alloy_evm::eth::spec::EthExecutorSpec;
3
4use crate::{
5    constants::{MAINNET_DEPOSIT_CONTRACT, MAINNET_PRUNE_DELETE_LIMIT},
6    ethereum::SEPOLIA_PARIS_TTD,
7    holesky, hoodi, mainnet,
8    mainnet::{MAINNET_PARIS_BLOCK, MAINNET_PARIS_TTD},
9    sepolia,
10    sepolia::SEPOLIA_PARIS_BLOCK,
11    EthChainSpec,
12};
13use alloc::{
14    boxed::Box,
15    collections::BTreeMap,
16    format,
17    string::{String, ToString},
18    sync::Arc,
19    vec::Vec,
20};
21use alloy_chains::{Chain, NamedChain};
22use alloy_consensus::{
23    constants::{
24        EMPTY_WITHDRAWALS, HOLESKY_GENESIS_HASH, HOODI_GENESIS_HASH, MAINNET_GENESIS_HASH,
25        SEPOLIA_GENESIS_HASH,
26    },
27    Header,
28};
29use alloy_eips::{
30    eip1559::INITIAL_BASE_FEE, eip7685::EMPTY_REQUESTS_HASH, eip7840::BlobParams,
31    eip7892::BlobScheduleBlobParams, eip7928::EMPTY_BLOCK_ACCESS_LIST_HASH,
32};
33use alloy_genesis::{ChainConfig, Genesis};
34use alloy_primitives::{address, b256, Address, BlockNumber, B256, U256};
35use alloy_trie::root::state_root_ref_unhashed;
36use core::fmt::Debug;
37use derive_more::From;
38use reth_ethereum_forks::{
39    ChainHardforks, DisplayHardforks, EthereumHardfork, EthereumHardforks, ForkCondition,
40    ForkFilter, ForkFilterKey, ForkHash, ForkId, Hardfork, Hardforks, Head, DEV_HARDFORKS,
41};
42use reth_network_peers::{holesky_nodes, hoodi_nodes, mainnet_nodes, sepolia_nodes, NodeRecord};
43use reth_primitives_traits::{sync::LazyLock, BlockHeader, SealedHeader};
44
45/// Helper method building a [`Header`] given [`Genesis`] and [`ChainHardforks`].
46pub fn make_genesis_header(genesis: &Genesis, hardforks: &ChainHardforks) -> Header {
47    // If London is activated at genesis, we set the initial base fee as per EIP-1559.
48    let base_fee_per_gas = hardforks
49        .fork(EthereumHardfork::London)
50        .active_at_block(0)
51        .then(|| genesis.base_fee_per_gas.map(|fee| fee as u64).unwrap_or(INITIAL_BASE_FEE));
52
53    // If shanghai is activated, initialize the header with an empty withdrawals hash, and
54    // empty withdrawals list.
55    let withdrawals_root = hardforks
56        .fork(EthereumHardfork::Shanghai)
57        .active_at_timestamp(genesis.timestamp)
58        .then_some(EMPTY_WITHDRAWALS);
59
60    // If Cancun is activated at genesis, we set:
61    // * parent beacon block root to 0x0
62    // * blob gas used to provided genesis or 0x0
63    // * excess blob gas to provided genesis or 0x0
64    let (parent_beacon_block_root, blob_gas_used, excess_blob_gas) =
65        if hardforks.fork(EthereumHardfork::Cancun).active_at_timestamp(genesis.timestamp) {
66            let blob_gas_used = genesis.blob_gas_used.unwrap_or(0);
67            let excess_blob_gas = genesis.excess_blob_gas.unwrap_or(0);
68            (Some(B256::ZERO), Some(blob_gas_used), Some(excess_blob_gas))
69        } else {
70            (None, None, None)
71        };
72
73    // If Prague is activated at genesis we set requests root to an empty trie root.
74    let requests_hash = hardforks
75        .fork(EthereumHardfork::Prague)
76        .active_at_timestamp(genesis.timestamp)
77        .then_some(EMPTY_REQUESTS_HASH);
78
79    // If Amsterdam is activated at genesis we set block access list hash to an empty bal hash
80    let block_access_list_hash = hardforks
81        .fork(EthereumHardfork::Amsterdam)
82        .active_at_timestamp(genesis.timestamp)
83        .then_some(EMPTY_BLOCK_ACCESS_LIST_HASH);
84
85    // If Amsterdam is activated at genesis we set slot number to the provided genesis or 0
86    let slot_number = hardforks
87        .fork(EthereumHardfork::Amsterdam)
88        .active_at_timestamp(genesis.timestamp)
89        .then_some(genesis.slot_number.unwrap_or(0));
90
91    Header {
92        number: genesis.number.unwrap_or_default(),
93        parent_hash: genesis.parent_hash.unwrap_or_default(),
94        gas_limit: genesis.gas_limit,
95        difficulty: genesis.difficulty,
96        nonce: genesis.nonce.into(),
97        extra_data: genesis.extra_data.clone(),
98        state_root: state_root_ref_unhashed(&genesis.alloc),
99        timestamp: genesis.timestamp,
100        mix_hash: genesis.mix_hash,
101        beneficiary: genesis.coinbase,
102        base_fee_per_gas,
103        withdrawals_root,
104        parent_beacon_block_root,
105        blob_gas_used,
106        excess_blob_gas,
107        requests_hash,
108        block_access_list_hash,
109        slot_number,
110        ..Default::default()
111    }
112}
113
114/// The Ethereum mainnet spec
115pub static MAINNET: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
116    let genesis = serde_json::from_str(include_str!("../res/genesis/mainnet.json"))
117        .expect("Can't deserialize Mainnet genesis json");
118    let hardforks = EthereumHardfork::mainnet().into();
119    let mut spec = ChainSpec {
120        chain: Chain::mainnet(),
121        genesis_header: SealedHeader::new(
122            make_genesis_header(&genesis, &hardforks),
123            MAINNET_GENESIS_HASH,
124        ),
125        genesis,
126        // <https://etherscan.io/block/15537394>
127        paris_block_and_final_difficulty: Some((
128            MAINNET_PARIS_BLOCK,
129            U256::from(58_750_003_716_598_352_816_469u128),
130        )),
131        hardforks,
132        // https://etherscan.io/tx/0xe75fb554e433e03763a1560646ee22dcb74e5274b34c5ad644e7c0f619a7e1d0
133        deposit_contract: Some(MAINNET_DEPOSIT_CONTRACT),
134        base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
135        prune_delete_limit: MAINNET_PRUNE_DELETE_LIMIT,
136        blob_params: BlobScheduleBlobParams::default().with_scheduled([
137            (mainnet::MAINNET_BPO1_TIMESTAMP, BlobParams::bpo1()),
138            (mainnet::MAINNET_BPO2_TIMESTAMP, BlobParams::bpo2()),
139        ]),
140    };
141    spec.genesis.config.dao_fork_support = true;
142    spec.into()
143});
144
145/// The Sepolia spec
146pub static SEPOLIA: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
147    let genesis = serde_json::from_str(include_str!("../res/genesis/sepolia.json"))
148        .expect("Can't deserialize Sepolia genesis json");
149    let hardforks = EthereumHardfork::sepolia().into();
150    let mut spec = ChainSpec {
151        chain: Chain::sepolia(),
152        genesis_header: SealedHeader::new(
153            make_genesis_header(&genesis, &hardforks),
154            SEPOLIA_GENESIS_HASH,
155        ),
156        genesis,
157        // <https://sepolia.etherscan.io/block/1450409>
158        paris_block_and_final_difficulty: Some((
159            SEPOLIA_PARIS_BLOCK,
160            U256::from(17_000_018_015_853_232u128),
161        )),
162        hardforks,
163        // https://sepolia.etherscan.io/tx/0x025ecbf81a2f1220da6285d1701dc89fb5a956b62562ee922e1a9efd73eb4b14
164        deposit_contract: Some(DepositContract::new(
165            address!("0x7f02c3e3c98b133055b8b348b2ac625669ed295d"),
166            1273020,
167            b256!("0x649bbc62d0e31342afea4e5cd82d4049e7e1ee912fc0889aa790803be39038c5"),
168        )),
169        base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
170        prune_delete_limit: 10000,
171        blob_params: BlobScheduleBlobParams::default().with_scheduled([
172            (sepolia::SEPOLIA_BPO1_TIMESTAMP, BlobParams::bpo1()),
173            (sepolia::SEPOLIA_BPO2_TIMESTAMP, BlobParams::bpo2()),
174        ]),
175    };
176    spec.genesis.config.dao_fork_support = true;
177    spec.into()
178});
179
180/// The Holesky spec
181pub static HOLESKY: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
182    let genesis = serde_json::from_str(include_str!("../res/genesis/holesky.json"))
183        .expect("Can't deserialize Holesky genesis json");
184    let hardforks = EthereumHardfork::holesky().into();
185    let mut spec = ChainSpec {
186        chain: Chain::holesky(),
187        genesis_header: SealedHeader::new(
188            make_genesis_header(&genesis, &hardforks),
189            HOLESKY_GENESIS_HASH,
190        ),
191        genesis,
192        paris_block_and_final_difficulty: Some((0, U256::from(1))),
193        hardforks,
194        deposit_contract: Some(DepositContract::new(
195            address!("0x4242424242424242424242424242424242424242"),
196            0,
197            b256!("0x649bbc62d0e31342afea4e5cd82d4049e7e1ee912fc0889aa790803be39038c5"),
198        )),
199        base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
200        prune_delete_limit: 10000,
201        blob_params: BlobScheduleBlobParams::default().with_scheduled([
202            (holesky::HOLESKY_BPO1_TIMESTAMP, BlobParams::bpo1()),
203            (holesky::HOLESKY_BPO2_TIMESTAMP, BlobParams::bpo2()),
204        ]),
205    };
206    spec.genesis.config.dao_fork_support = true;
207    spec.into()
208});
209
210/// The Hoodi spec
211///
212/// Genesis files from: <https://github.com/eth-clients/hoodi>
213pub static HOODI: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
214    let genesis = serde_json::from_str(include_str!("../res/genesis/hoodi.json"))
215        .expect("Can't deserialize Hoodi genesis json");
216    let hardforks = EthereumHardfork::hoodi().into();
217    let mut spec = ChainSpec {
218        chain: Chain::hoodi(),
219        genesis_header: SealedHeader::new(
220            make_genesis_header(&genesis, &hardforks),
221            HOODI_GENESIS_HASH,
222        ),
223        genesis,
224        paris_block_and_final_difficulty: Some((0, U256::from(0))),
225        hardforks,
226        deposit_contract: Some(DepositContract::new(
227            address!("0x00000000219ab540356cBB839Cbe05303d7705Fa"),
228            0,
229            b256!("0x649bbc62d0e31342afea4e5cd82d4049e7e1ee912fc0889aa790803be39038c5"),
230        )),
231        base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
232        prune_delete_limit: 10000,
233        blob_params: BlobScheduleBlobParams::default().with_scheduled([
234            (hoodi::HOODI_BPO1_TIMESTAMP, BlobParams::bpo1()),
235            (hoodi::HOODI_BPO2_TIMESTAMP, BlobParams::bpo2()),
236        ]),
237    };
238    spec.genesis.config.dao_fork_support = true;
239    spec.into()
240});
241
242/// Dev testnet specification
243///
244/// Includes 20 prefunded accounts with `10_000` ETH each derived from mnemonic "test test test test
245/// test test test test test test test junk".
246pub static DEV: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| {
247    let genesis = serde_json::from_str(include_str!("../res/genesis/dev.json"))
248        .expect("Can't deserialize Dev testnet genesis json");
249    let hardforks = DEV_HARDFORKS.clone();
250    ChainSpec {
251        chain: Chain::dev(),
252        genesis_header: SealedHeader::seal_slow(make_genesis_header(&genesis, &hardforks)),
253        genesis,
254        paris_block_and_final_difficulty: Some((0, U256::from(0))),
255        hardforks,
256        base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
257        deposit_contract: None, // TODO: do we even have?
258        ..Default::default()
259    }
260    .into()
261});
262
263/// Creates a [`ChainConfig`] from the given chain, hardforks, deposit contract address, and blob
264/// schedule.
265pub fn create_chain_config(
266    chain: Option<Chain>,
267    hardforks: &ChainHardforks,
268    deposit_contract_address: Option<Address>,
269    blob_schedule: BTreeMap<String, BlobParams>,
270) -> ChainConfig {
271    // Helper to extract block number from a hardfork condition
272    let block_num = |fork: EthereumHardfork| hardforks.fork(fork).block_number();
273
274    // Helper to extract timestamp from a hardfork condition
275    let timestamp = |fork: EthereumHardfork| hardforks.fork(fork).as_timestamp();
276
277    // Extract TTD from Paris fork
278    let (terminal_total_difficulty, terminal_total_difficulty_passed) =
279        match hardforks.fork(EthereumHardfork::Paris) {
280            ForkCondition::TTD { total_difficulty, .. } => (Some(total_difficulty), true),
281            _ => (None, false),
282        };
283
284    // Check if DAO fork is supported (it has an activation block)
285    let dao_fork_support = hardforks.fork(EthereumHardfork::Dao) != ForkCondition::Never;
286
287    ChainConfig {
288        chain_id: chain.map(|c| c.id()).unwrap_or(0),
289        homestead_block: block_num(EthereumHardfork::Homestead),
290        dao_fork_block: block_num(EthereumHardfork::Dao),
291        dao_fork_support,
292        eip150_block: block_num(EthereumHardfork::Tangerine),
293        eip155_block: block_num(EthereumHardfork::SpuriousDragon),
294        eip158_block: block_num(EthereumHardfork::SpuriousDragon),
295        byzantium_block: block_num(EthereumHardfork::Byzantium),
296        constantinople_block: block_num(EthereumHardfork::Constantinople),
297        petersburg_block: block_num(EthereumHardfork::Petersburg),
298        istanbul_block: block_num(EthereumHardfork::Istanbul),
299        muir_glacier_block: block_num(EthereumHardfork::MuirGlacier),
300        berlin_block: block_num(EthereumHardfork::Berlin),
301        london_block: block_num(EthereumHardfork::London),
302        arrow_glacier_block: block_num(EthereumHardfork::ArrowGlacier),
303        gray_glacier_block: block_num(EthereumHardfork::GrayGlacier),
304        merge_netsplit_block: None,
305        shanghai_time: timestamp(EthereumHardfork::Shanghai),
306        cancun_time: timestamp(EthereumHardfork::Cancun),
307        prague_time: timestamp(EthereumHardfork::Prague),
308        osaka_time: timestamp(EthereumHardfork::Osaka),
309        amsterdam_time: timestamp(EthereumHardfork::Amsterdam),
310        bogota_time: timestamp(EthereumHardfork::Bogota),
311        bpo1_time: timestamp(EthereumHardfork::Bpo1),
312        bpo2_time: timestamp(EthereumHardfork::Bpo2),
313        bpo3_time: timestamp(EthereumHardfork::Bpo3),
314        bpo4_time: timestamp(EthereumHardfork::Bpo4),
315        bpo5_time: timestamp(EthereumHardfork::Bpo5),
316        terminal_total_difficulty,
317        terminal_total_difficulty_passed,
318        deposit_contract_address,
319        blob_schedule,
320        ..Default::default()
321    }
322}
323
324/// Returns a [`ChainConfig`] for the current Ethereum mainnet chain.
325pub fn mainnet_chain_config() -> ChainConfig {
326    let hardforks: ChainHardforks = EthereumHardfork::mainnet().into();
327    let blob_schedule = blob_params_to_schedule(&MAINNET.blob_params, &hardforks);
328    create_chain_config(
329        Some(Chain::mainnet()),
330        &hardforks,
331        Some(MAINNET_DEPOSIT_CONTRACT.address),
332        blob_schedule,
333    )
334}
335
336/// Converts the given [`BlobScheduleBlobParams`] into blobs schedule.
337pub fn blob_params_to_schedule(
338    params: &BlobScheduleBlobParams,
339    hardforks: &ChainHardforks,
340) -> BTreeMap<String, BlobParams> {
341    let mut schedule = BTreeMap::new();
342    schedule.insert("cancun".to_string(), params.cancun);
343    schedule.insert("prague".to_string(), params.prague);
344    schedule.insert("osaka".to_string(), params.osaka);
345
346    // Map scheduled entries back to bpo fork names by matching timestamps
347    let bpo_forks = EthereumHardfork::bpo_variants();
348    for (timestamp, blob_params) in &params.scheduled {
349        for bpo_fork in bpo_forks {
350            if hardforks.fork(bpo_fork).as_timestamp() == Some(*timestamp) {
351                schedule.insert(bpo_fork.name().to_lowercase(), *blob_params);
352                break;
353            }
354        }
355    }
356
357    schedule
358}
359
360/// A wrapper around [`BaseFeeParams`] that allows for specifying constant or dynamic EIP-1559
361/// parameters based on the active [Hardfork].
362#[derive(Clone, Debug, PartialEq, Eq)]
363pub enum BaseFeeParamsKind {
364    /// Constant [`BaseFeeParams`]; used for chains that don't have dynamic EIP-1559 parameters
365    Constant(BaseFeeParams),
366    /// Variable [`BaseFeeParams`]; used for chains that have dynamic EIP-1559 parameters like
367    /// Optimism
368    Variable(ForkBaseFeeParams),
369}
370
371impl Default for BaseFeeParamsKind {
372    fn default() -> Self {
373        BaseFeeParams::ethereum().into()
374    }
375}
376
377impl From<BaseFeeParams> for BaseFeeParamsKind {
378    fn from(params: BaseFeeParams) -> Self {
379        Self::Constant(params)
380    }
381}
382
383impl From<ForkBaseFeeParams> for BaseFeeParamsKind {
384    fn from(params: ForkBaseFeeParams) -> Self {
385        Self::Variable(params)
386    }
387}
388
389/// A type alias to a vector of tuples of [Hardfork] and [`BaseFeeParams`], sorted by [Hardfork]
390/// activation order. This is used to specify dynamic EIP-1559 parameters for chains like Optimism.
391#[derive(Clone, Debug, PartialEq, Eq, From)]
392pub struct ForkBaseFeeParams(Vec<(Box<dyn Hardfork>, BaseFeeParams)>);
393
394impl<H: BlockHeader> core::ops::Deref for ChainSpec<H> {
395    type Target = ChainHardforks;
396
397    fn deref(&self) -> &Self::Target {
398        &self.hardforks
399    }
400}
401
402/// An Ethereum chain specification.
403///
404/// A chain specification describes:
405///
406/// - Meta-information about the chain (the chain ID)
407/// - The genesis block of the chain ([`Genesis`])
408/// - What hardforks are activated, and under which conditions
409#[derive(Debug, Clone, PartialEq, Eq)]
410pub struct ChainSpec<H: BlockHeader = Header> {
411    /// The chain ID
412    pub chain: Chain,
413
414    /// The genesis block.
415    pub genesis: Genesis,
416
417    /// The header corresponding to the genesis block.
418    pub genesis_header: SealedHeader<H>,
419
420    /// The block at which [`EthereumHardfork::Paris`] was activated and the final difficulty at
421    /// this block.
422    pub paris_block_and_final_difficulty: Option<(u64, U256)>,
423
424    /// The active hard forks and their activation conditions
425    pub hardforks: ChainHardforks,
426
427    /// The deposit contract deployed for `PoS`
428    pub deposit_contract: Option<DepositContract>,
429
430    /// The parameters that configure how a block's base fee is computed
431    pub base_fee_params: BaseFeeParamsKind,
432
433    /// The delete limit for pruner, per run.
434    pub prune_delete_limit: usize,
435
436    /// The settings passed for blob configurations for specific hardforks.
437    pub blob_params: BlobScheduleBlobParams,
438}
439
440impl<H: BlockHeader> Default for ChainSpec<H> {
441    fn default() -> Self {
442        Self {
443            chain: Default::default(),
444            genesis: Default::default(),
445            genesis_header: Default::default(),
446            paris_block_and_final_difficulty: Default::default(),
447            hardforks: Default::default(),
448            deposit_contract: Default::default(),
449            base_fee_params: BaseFeeParamsKind::Constant(BaseFeeParams::ethereum()),
450            prune_delete_limit: MAINNET_PRUNE_DELETE_LIMIT,
451            blob_params: Default::default(),
452        }
453    }
454}
455
456impl ChainSpec {
457    /// Converts the given [`Genesis`] into a [`ChainSpec`].
458    pub fn from_genesis(genesis: Genesis) -> Self {
459        genesis.into()
460    }
461
462    /// Build a chainspec using [`ChainSpecBuilder`]
463    pub fn builder() -> ChainSpecBuilder {
464        ChainSpecBuilder::default()
465    }
466
467    /// Map a chain ID to a known chain spec, if available.
468    pub fn from_chain_id(chain_id: u64) -> Option<Arc<Self>> {
469        match NamedChain::try_from(chain_id).ok()? {
470            NamedChain::Mainnet => Some(MAINNET.clone()),
471            NamedChain::Sepolia => Some(SEPOLIA.clone()),
472            NamedChain::Holesky => Some(HOLESKY.clone()),
473            NamedChain::Hoodi => Some(HOODI.clone()),
474            NamedChain::Dev => Some(DEV.clone()),
475            _ => None,
476        }
477    }
478}
479
480impl<H: BlockHeader> ChainSpec<H> {
481    /// Get information about the chain itself
482    pub const fn chain(&self) -> Chain {
483        self.chain
484    }
485
486    /// Returns `true` if this chain contains Ethereum configuration.
487    #[inline]
488    pub const fn is_ethereum(&self) -> bool {
489        self.chain.is_ethereum()
490    }
491
492    /// Returns `true` if this chain is Optimism mainnet.
493    #[inline]
494    pub fn is_optimism_mainnet(&self) -> bool {
495        self.chain == Chain::optimism_mainnet()
496    }
497
498    /// Returns the known paris block, if it exists.
499    #[inline]
500    pub fn paris_block(&self) -> Option<u64> {
501        self.paris_block_and_final_difficulty.map(|(block, _)| block)
502    }
503
504    /// Get the genesis block specification.
505    ///
506    /// To get the header for the genesis block, use [`Self::genesis_header`] instead.
507    pub const fn genesis(&self) -> &Genesis {
508        &self.genesis
509    }
510
511    /// Get the header for the genesis block.
512    pub fn genesis_header(&self) -> &H {
513        &self.genesis_header
514    }
515
516    /// Get the sealed header for the genesis block.
517    pub fn sealed_genesis_header(&self) -> SealedHeader<H> {
518        SealedHeader::new(self.genesis_header().clone(), self.genesis_hash())
519    }
520
521    /// Get the initial base fee of the genesis block.
522    pub fn initial_base_fee(&self) -> Option<u64> {
523        // If the base fee is set in the genesis block, we use that instead of the default.
524        let genesis_base_fee =
525            self.genesis.base_fee_per_gas.map(|fee| fee as u64).unwrap_or(INITIAL_BASE_FEE);
526
527        // If London is activated at genesis, we set the initial base fee as per EIP-1559.
528        self.is_london_active_at_block(0).then_some(genesis_base_fee)
529    }
530
531    /// Get the [`BaseFeeParams`] for the chain at the given timestamp.
532    pub fn base_fee_params_at_timestamp(&self, timestamp: u64) -> BaseFeeParams {
533        match self.base_fee_params {
534            BaseFeeParamsKind::Constant(bf_params) => bf_params,
535            BaseFeeParamsKind::Variable(ForkBaseFeeParams(ref bf_params)) => {
536                // Walk through the base fee params configuration in reverse order, and return the
537                // first one that corresponds to a hardfork that is active at the
538                // given timestamp.
539                for (fork, params) in bf_params.iter().rev() {
540                    if self.hardforks.is_fork_active_at_timestamp(fork.clone(), timestamp) {
541                        return *params
542                    }
543                }
544
545                bf_params.first().map(|(_, params)| *params).unwrap_or_else(BaseFeeParams::ethereum)
546            }
547        }
548    }
549
550    /// Get the hash of the genesis block.
551    pub fn genesis_hash(&self) -> B256 {
552        self.genesis_header.hash()
553    }
554
555    /// Get the timestamp of the genesis block.
556    pub const fn genesis_timestamp(&self) -> u64 {
557        self.genesis.timestamp
558    }
559
560    /// Returns the final total difficulty if the Paris hardfork is known.
561    pub fn get_final_paris_total_difficulty(&self) -> Option<U256> {
562        self.paris_block_and_final_difficulty.map(|(_, final_difficulty)| final_difficulty)
563    }
564
565    /// Get the fork filter for the given hardfork
566    pub fn hardfork_fork_filter<HF: Hardfork + Clone>(&self, fork: HF) -> Option<ForkFilter> {
567        match self.hardforks.fork(fork.clone()) {
568            ForkCondition::Never => None,
569            _ => Some(self.fork_filter(self.satisfy(self.hardforks.fork(fork)))),
570        }
571    }
572
573    /// Returns the hardfork display helper.
574    pub fn display_hardforks(&self) -> DisplayHardforks {
575        // Create an iterator with hardfork, condition, and optional blob metadata
576        let hardforks_with_meta = self.hardforks.forks_iter().map(|(fork, condition)| {
577            // Generate blob metadata for timestamp-based hardforks that have blob params
578            let metadata = condition.as_timestamp().and_then(|timestamp| {
579                // Try to get blob params for this timestamp
580                // This automatically handles all hardforks with blob support
581                EthChainSpec::blob_params_at_timestamp(self, timestamp).map(|params| {
582                    format!(
583                        "blob: (target: {}, max: {}, fraction: {})",
584                        params.target_blob_count, params.max_blob_count, params.update_fraction
585                    )
586                })
587            });
588            (fork, condition, metadata)
589        });
590
591        DisplayHardforks::with_meta(hardforks_with_meta)
592    }
593
594    /// Get the fork id for the given hardfork.
595    #[inline]
596    pub fn hardfork_fork_id<HF: Hardfork + Clone>(&self, fork: HF) -> Option<ForkId> {
597        let condition = self.hardforks.fork(fork);
598        match condition {
599            ForkCondition::Never => None,
600            _ => Some(self.fork_id(&self.satisfy(condition))),
601        }
602    }
603
604    /// Convenience method to get the fork id for [`EthereumHardfork::Shanghai`] from a given
605    /// chainspec.
606    #[inline]
607    pub fn shanghai_fork_id(&self) -> Option<ForkId> {
608        self.hardfork_fork_id(EthereumHardfork::Shanghai)
609    }
610
611    /// Convenience method to get the fork id for [`EthereumHardfork::Cancun`] from a given
612    /// chainspec.
613    #[inline]
614    pub fn cancun_fork_id(&self) -> Option<ForkId> {
615        self.hardfork_fork_id(EthereumHardfork::Cancun)
616    }
617
618    /// Convenience method to get the latest fork id from the chainspec. Panics if chainspec has no
619    /// hardforks.
620    #[inline]
621    pub fn latest_fork_id(&self) -> ForkId {
622        self.hardfork_fork_id(self.hardforks.last().unwrap().0).unwrap()
623    }
624
625    /// Creates a [`ForkFilter`] for the block described by [Head].
626    pub fn fork_filter(&self, head: Head) -> ForkFilter {
627        let forks = self.hardforks.forks_iter().filter_map(|(_, condition)| {
628            // We filter out TTD-based forks w/o a pre-known block since those do not show up in
629            // the fork filter.
630            Some(match condition {
631                ForkCondition::Block(block) |
632                ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block),
633                ForkCondition::Timestamp(time) => ForkFilterKey::Time(time),
634                _ => return None,
635            })
636        });
637
638        ForkFilter::new(head, self.genesis_hash(), self.genesis_timestamp(), forks)
639    }
640
641    /// Compute the [`ForkId`] for the given [`Head`] following eip-6122 spec.
642    ///
643    /// The fork hash is computed by starting from the genesis hash and iteratively adding
644    /// block numbers (for block-based forks) or timestamps (for timestamp-based forks) of
645    /// active forks. The `next` field indicates the next fork activation point, or `0` if
646    /// all forks are active.
647    ///
648    /// Block-based forks are processed first, then timestamp-based forks. Multiple hardforks
649    /// activated at the same block or timestamp: only the first one is applied.
650    ///
651    /// See: <https://eips.ethereum.org/EIPS/eip-6122>
652    pub fn fork_id(&self, head: &Head) -> ForkId {
653        let mut forkhash = ForkHash::from(self.genesis_hash());
654
655        // this tracks the last applied block or timestamp fork. This is necessary for optimism,
656        // because for the optimism hardforks both the optimism and the corresponding ethereum
657        // hardfork can be configured in `ChainHardforks` if it enables ethereum equivalent
658        // functionality (e.g. additional header,body fields) This is set to 0 so that all
659        // block based hardforks are skipped in the following loop
660        let mut current_applied = 0;
661
662        // handle all block forks before handling timestamp based forks. see: https://eips.ethereum.org/EIPS/eip-6122
663        for (_, cond) in self.hardforks.forks_iter() {
664            // handle block based forks and the sepolia merge netsplit block edge case (TTD
665            // ForkCondition with Some(block))
666            if let ForkCondition::Block(block) |
667            ForkCondition::TTD { fork_block: Some(block), .. } = cond
668            {
669                if head.number >= block {
670                    // skip duplicated hardforks: hardforks enabled at genesis block
671                    if block != current_applied {
672                        forkhash += block;
673                        current_applied = block;
674                    }
675                } else {
676                    // we can return here because this block fork is not active, so we set the
677                    // `next` value
678                    return ForkId { hash: forkhash, next: block }
679                }
680            }
681        }
682
683        // timestamp are ALWAYS applied after the merge.
684        //
685        // this filter ensures that no block-based forks are returned
686        for timestamp in self.hardforks.forks_iter().filter_map(|(_, cond)| {
687            // ensure we only get timestamp forks activated __after__ the genesis block
688            cond.as_timestamp().filter(|time| time > &self.genesis.timestamp)
689        }) {
690            if head.timestamp >= timestamp {
691                // skip duplicated hardfork activated at the same timestamp
692                if timestamp != current_applied {
693                    forkhash += timestamp;
694                    current_applied = timestamp;
695                }
696            } else {
697                // can safely return here because we have already handled all block forks and
698                // have handled all active timestamp forks, and set the next value to the
699                // timestamp that is known but not active yet
700                return ForkId { hash: forkhash, next: timestamp }
701            }
702        }
703
704        ForkId { hash: forkhash, next: 0 }
705    }
706
707    /// An internal helper function that returns a head block that satisfies a given Fork condition.
708    ///
709    /// Creates a [`Head`] representation for a fork activation point, used by [`Self::fork_id`] to
710    /// compute fork IDs. For timestamp-based forks, includes the last block-based fork number
711    /// before the merge (if any).
712    pub(crate) fn satisfy(&self, cond: ForkCondition) -> Head {
713        match cond {
714            ForkCondition::Block(number) => Head { number, ..Default::default() },
715            ForkCondition::Timestamp(timestamp) => {
716                // to satisfy every timestamp ForkCondition, we find the last ForkCondition::Block
717                // if one exists, and include its block_num in the returned Head
718                Head {
719                    timestamp,
720                    number: self.last_block_fork_before_merge_or_timestamp().unwrap_or_default(),
721                    ..Default::default()
722                }
723            }
724            ForkCondition::TTD { total_difficulty, fork_block, .. } => Head {
725                total_difficulty,
726                number: fork_block.unwrap_or_default(),
727                ..Default::default()
728            },
729            ForkCondition::Never => unreachable!(),
730        }
731    }
732
733    /// This internal helper function retrieves the block number of the last block-based fork
734    /// that occurs before:
735    /// - Any existing Total Terminal Difficulty (TTD) or
736    /// - Timestamp-based forks in the current [`ChainSpec`].
737    ///
738    /// The function operates by examining the configured hard forks in the chain. It iterates
739    /// through the fork conditions and identifies the most recent block-based fork that
740    /// precedes any TTD or timestamp-based conditions.
741    ///
742    /// If there are no block-based forks found before these conditions, or if the [`ChainSpec`]
743    /// is not configured with a TTD or timestamp fork, this function will return `None`.
744    pub(crate) fn last_block_fork_before_merge_or_timestamp(&self) -> Option<u64> {
745        let mut hardforks_iter = self.hardforks.forks_iter().peekable();
746        while let Some((_, curr_cond)) = hardforks_iter.next() {
747            if let Some((_, next_cond)) = hardforks_iter.peek() {
748                // Match against the `next_cond` to see if it represents:
749                // - A TTD (merge)
750                // - A timestamp-based fork
751                match next_cond {
752                    // If the next fork is TTD and specifies a specific block, return that block
753                    // number
754                    ForkCondition::TTD { fork_block: Some(block), .. } => return Some(*block),
755
756                    // If the next fork is TTD without a specific block or is timestamp-based,
757                    // return the block number of the current condition if it is block-based.
758                    ForkCondition::TTD { .. } | ForkCondition::Timestamp(_) => {
759                        // Check if `curr_cond` is a block-based fork and return its block number if
760                        // true.
761                        if let ForkCondition::Block(block_num) = curr_cond {
762                            return Some(block_num);
763                        }
764                    }
765                    ForkCondition::Block(_) | ForkCondition::Never => {}
766                }
767            }
768        }
769        None
770    }
771
772    /// Returns the known bootnode records for the given chain.
773    pub fn bootnodes(&self) -> Option<Vec<NodeRecord>> {
774        use NamedChain as C;
775
776        match self.chain.try_into().ok()? {
777            C::Mainnet => Some(mainnet_nodes()),
778            C::Sepolia => Some(sepolia_nodes()),
779            C::Holesky => Some(holesky_nodes()),
780            C::Hoodi => Some(hoodi_nodes()),
781            _ => None,
782        }
783    }
784
785    /// Convert header to another type.
786    pub fn map_header<NewH: BlockHeader>(self, f: impl FnOnce(H) -> NewH) -> ChainSpec<NewH> {
787        let Self {
788            chain,
789            genesis,
790            genesis_header,
791            paris_block_and_final_difficulty,
792            hardforks,
793            deposit_contract,
794            base_fee_params,
795            prune_delete_limit,
796            blob_params,
797        } = self;
798        ChainSpec {
799            chain,
800            genesis,
801            genesis_header: SealedHeader::new_unhashed(f(genesis_header.into_header())),
802            paris_block_and_final_difficulty,
803            hardforks,
804            deposit_contract,
805            base_fee_params,
806            prune_delete_limit,
807            blob_params,
808        }
809    }
810}
811
812impl From<Genesis> for ChainSpec {
813    fn from(genesis: Genesis) -> Self {
814        // Block-based hardforks
815        let hardfork_opts = [
816            (EthereumHardfork::Frontier.boxed(), Some(0)),
817            (EthereumHardfork::Homestead.boxed(), genesis.config.homestead_block),
818            (EthereumHardfork::Dao.boxed(), genesis.config.dao_fork_block),
819            (EthereumHardfork::Tangerine.boxed(), genesis.config.eip150_block),
820            (EthereumHardfork::SpuriousDragon.boxed(), genesis.config.eip155_block),
821            (EthereumHardfork::Byzantium.boxed(), genesis.config.byzantium_block),
822            (EthereumHardfork::Constantinople.boxed(), genesis.config.constantinople_block),
823            (EthereumHardfork::Petersburg.boxed(), genesis.config.petersburg_block),
824            (EthereumHardfork::Istanbul.boxed(), genesis.config.istanbul_block),
825            (EthereumHardfork::MuirGlacier.boxed(), genesis.config.muir_glacier_block),
826            (EthereumHardfork::Berlin.boxed(), genesis.config.berlin_block),
827            (EthereumHardfork::London.boxed(), genesis.config.london_block),
828            (EthereumHardfork::ArrowGlacier.boxed(), genesis.config.arrow_glacier_block),
829            (EthereumHardfork::GrayGlacier.boxed(), genesis.config.gray_glacier_block),
830        ];
831        let mut hardforks = hardfork_opts
832            .into_iter()
833            .filter_map(|(hardfork, opt)| opt.map(|block| (hardfork, ForkCondition::Block(block))))
834            .collect::<Vec<_>>();
835
836        // We expect no new networks to be configured with the merge, so we ignore the TTD field
837        // and merge netsplit block from external genesis files. All existing networks that have
838        // merged should have a static ChainSpec already (namely mainnet and sepolia).
839        let paris_block_and_final_difficulty = if let Some(ttd) =
840            genesis.config.terminal_total_difficulty
841        {
842            hardforks.push((
843                EthereumHardfork::Paris.boxed(),
844                ForkCondition::TTD {
845                    // NOTE: this will not work properly if the merge is not activated at
846                    // genesis, and there is no merge netsplit block
847                    activation_block_number: genesis
848                        .config
849                        .merge_netsplit_block
850                        .or_else(|| {
851                            // due to this limitation we can't determine the merge block,
852                            // this is the case for perfnet testing for example
853                            // at the time of this fix, only two networks transitioned: MAINNET +
854                            // SEPOLIA and this parsing from genesis is used for shadowforking, so
855                            // we can reasonably assume that if the TTD and the chainid matches
856                            // those networks we use the activation
857                            // blocks of those networks
858                            match genesis.config.chain_id {
859                                1 if ttd == MAINNET_PARIS_TTD => return Some(MAINNET_PARIS_BLOCK),
860                                11155111 if ttd == SEPOLIA_PARIS_TTD => {
861                                    return Some(SEPOLIA_PARIS_BLOCK)
862                                }
863                                _ => {}
864                            };
865                            None
866                        })
867                        .unwrap_or_default(),
868                    total_difficulty: ttd,
869                    fork_block: genesis.config.merge_netsplit_block,
870                },
871            ));
872
873            genesis.config.merge_netsplit_block.map(|block| (block, ttd))
874        } else {
875            None
876        };
877
878        // Time-based hardforks
879        let time_hardfork_opts = [
880            (EthereumHardfork::Shanghai.boxed(), genesis.config.shanghai_time),
881            (EthereumHardfork::Cancun.boxed(), genesis.config.cancun_time),
882            (EthereumHardfork::Prague.boxed(), genesis.config.prague_time),
883            (EthereumHardfork::Osaka.boxed(), genesis.config.osaka_time),
884            (EthereumHardfork::Bpo1.boxed(), genesis.config.bpo1_time),
885            (EthereumHardfork::Bpo2.boxed(), genesis.config.bpo2_time),
886            (EthereumHardfork::Bpo3.boxed(), genesis.config.bpo3_time),
887            (EthereumHardfork::Bpo4.boxed(), genesis.config.bpo4_time),
888            (EthereumHardfork::Bpo5.boxed(), genesis.config.bpo5_time),
889            (EthereumHardfork::Amsterdam.boxed(), genesis.config.amsterdam_time),
890            (EthereumHardfork::Bogota.boxed(), genesis.config.bogota_time),
891        ];
892
893        let mut time_hardforks = time_hardfork_opts
894            .into_iter()
895            .filter_map(|(hardfork, opt)| {
896                opt.map(|time| (hardfork, ForkCondition::Timestamp(time)))
897            })
898            .collect::<Vec<_>>();
899
900        hardforks.append(&mut time_hardforks);
901
902        // Ordered Hardforks
903        let mainnet_hardforks: ChainHardforks = EthereumHardfork::mainnet().into();
904        let mainnet_order = mainnet_hardforks.forks_iter();
905
906        let mut ordered_hardforks = Vec::with_capacity(hardforks.len());
907        for (hardfork, _) in mainnet_order {
908            if let Some(pos) = hardforks.iter().position(|(e, _)| **e == *hardfork) {
909                ordered_hardforks.push(hardforks.remove(pos));
910            }
911        }
912
913        // append the remaining unknown hardforks to ensure we don't filter any out
914        ordered_hardforks.append(&mut hardforks);
915
916        // Extract blob parameters directly from blob_schedule
917        let blob_params = genesis.config.blob_schedule_blob_params();
918
919        // NOTE: in full node, we prune all receipts except the deposit contract's. We do not
920        // have the deployment block in the genesis file, so we use block zero. We use the same
921        // deposit topic as the mainnet contract if we have the deposit contract address in the
922        // genesis json.
923        let deposit_contract = genesis.config.deposit_contract_address.map(|address| {
924            DepositContract { address, block: 0, topic: MAINNET_DEPOSIT_CONTRACT.topic }
925        });
926
927        let hardforks = ChainHardforks::new(ordered_hardforks);
928
929        Self {
930            chain: genesis.config.chain_id.into(),
931            genesis_header: SealedHeader::new_unhashed(make_genesis_header(&genesis, &hardforks)),
932            genesis,
933            hardforks,
934            paris_block_and_final_difficulty,
935            deposit_contract,
936            blob_params,
937            ..Default::default()
938        }
939    }
940}
941
942impl<H: BlockHeader> Hardforks for ChainSpec<H> {
943    fn fork<HF: Hardfork>(&self, fork: HF) -> ForkCondition {
944        self.hardforks.fork(fork)
945    }
946
947    fn forks_iter(&self) -> impl Iterator<Item = (&dyn Hardfork, ForkCondition)> {
948        self.hardforks.forks_iter()
949    }
950
951    fn fork_id(&self, head: &Head) -> ForkId {
952        self.fork_id(head)
953    }
954
955    fn latest_fork_id(&self) -> ForkId {
956        self.latest_fork_id()
957    }
958
959    fn fork_filter(&self, head: Head) -> ForkFilter {
960        self.fork_filter(head)
961    }
962}
963
964impl<H: BlockHeader> EthereumHardforks for ChainSpec<H> {
965    fn ethereum_fork_activation(&self, fork: EthereumHardfork) -> ForkCondition {
966        self.fork(fork)
967    }
968}
969
970/// A trait for reading the current chainspec.
971#[auto_impl::auto_impl(&, Arc)]
972pub trait ChainSpecProvider: Debug + Send {
973    /// The chain spec type.
974    type ChainSpec: EthChainSpec + 'static;
975
976    /// Get an [`Arc`] to the chainspec.
977    fn chain_spec(&self) -> Arc<Self::ChainSpec>;
978}
979
980/// A helper to build custom chain specs
981#[derive(Debug, Default, Clone)]
982pub struct ChainSpecBuilder {
983    chain: Option<Chain>,
984    genesis: Option<Genesis>,
985    hardforks: ChainHardforks,
986}
987
988impl ChainSpecBuilder {
989    /// Construct a new builder from the mainnet chain spec.
990    pub fn mainnet() -> Self {
991        Self {
992            chain: Some(MAINNET.chain),
993            genesis: Some(MAINNET.genesis.clone()),
994            hardforks: MAINNET.hardforks.clone(),
995        }
996    }
997}
998
999impl ChainSpecBuilder {
1000    /// Set the chain ID
1001    pub const fn chain(mut self, chain: Chain) -> Self {
1002        self.chain = Some(chain);
1003        self
1004    }
1005
1006    /// Resets any existing hardforks from the builder.
1007    pub fn reset(mut self) -> Self {
1008        self.hardforks = ChainHardforks::default();
1009        self
1010    }
1011
1012    /// Set the genesis block.
1013    pub fn genesis(mut self, genesis: Genesis) -> Self {
1014        self.genesis = Some(genesis);
1015        self
1016    }
1017
1018    /// Add the given fork with the given activation condition to the spec.
1019    pub fn with_fork<H: Hardfork>(mut self, fork: H, condition: ForkCondition) -> Self {
1020        self.hardforks.insert(fork, condition);
1021        self
1022    }
1023
1024    /// Add the given chain hardforks to the spec.
1025    pub fn with_forks(mut self, forks: ChainHardforks) -> Self {
1026        self.hardforks = forks;
1027        self
1028    }
1029
1030    /// Remove the given fork from the spec.
1031    pub fn without_fork<H: Hardfork>(mut self, fork: H) -> Self {
1032        self.hardforks.remove(&fork);
1033        self
1034    }
1035
1036    /// Enable the Paris hardfork at the given TTD.
1037    ///
1038    /// Does not set the merge netsplit block.
1039    pub fn paris_at_ttd(self, ttd: U256, activation_block_number: BlockNumber) -> Self {
1040        self.with_fork(
1041            EthereumHardfork::Paris,
1042            ForkCondition::TTD { activation_block_number, total_difficulty: ttd, fork_block: None },
1043        )
1044    }
1045
1046    /// Enable Frontier at genesis.
1047    pub fn frontier_activated(mut self) -> Self {
1048        self.hardforks.insert(EthereumHardfork::Frontier, ForkCondition::Block(0));
1049        self
1050    }
1051
1052    /// Enable Dao at genesis.
1053    pub fn dao_activated(mut self) -> Self {
1054        self = self.frontier_activated();
1055        self.hardforks.insert(EthereumHardfork::Dao, ForkCondition::Block(0));
1056        self
1057    }
1058
1059    /// Enable Homestead at genesis.
1060    pub fn homestead_activated(mut self) -> Self {
1061        self = self.dao_activated();
1062        self.hardforks.insert(EthereumHardfork::Homestead, ForkCondition::Block(0));
1063        self
1064    }
1065
1066    /// Enable Tangerine at genesis.
1067    pub fn tangerine_whistle_activated(mut self) -> Self {
1068        self = self.homestead_activated();
1069        self.hardforks.insert(EthereumHardfork::Tangerine, ForkCondition::Block(0));
1070        self
1071    }
1072
1073    /// Enable Spurious Dragon at genesis.
1074    pub fn spurious_dragon_activated(mut self) -> Self {
1075        self = self.tangerine_whistle_activated();
1076        self.hardforks.insert(EthereumHardfork::SpuriousDragon, ForkCondition::Block(0));
1077        self
1078    }
1079
1080    /// Enable Byzantium at genesis.
1081    pub fn byzantium_activated(mut self) -> Self {
1082        self = self.spurious_dragon_activated();
1083        self.hardforks.insert(EthereumHardfork::Byzantium, ForkCondition::Block(0));
1084        self
1085    }
1086
1087    /// Enable Constantinople at genesis.
1088    pub fn constantinople_activated(mut self) -> Self {
1089        self = self.byzantium_activated();
1090        self.hardforks.insert(EthereumHardfork::Constantinople, ForkCondition::Block(0));
1091        self
1092    }
1093
1094    /// Enable Petersburg at genesis.
1095    pub fn petersburg_activated(mut self) -> Self {
1096        self = self.constantinople_activated();
1097        self.hardforks.insert(EthereumHardfork::Petersburg, ForkCondition::Block(0));
1098        self
1099    }
1100
1101    /// Enable Istanbul at genesis.
1102    pub fn istanbul_activated(mut self) -> Self {
1103        self = self.petersburg_activated();
1104        self.hardforks.insert(EthereumHardfork::Istanbul, ForkCondition::Block(0));
1105        self
1106    }
1107
1108    /// Enable Muir Glacier at genesis.
1109    pub fn muirglacier_activated(mut self) -> Self {
1110        self = self.istanbul_activated();
1111        self.hardforks.insert(EthereumHardfork::MuirGlacier, ForkCondition::Block(0));
1112        self
1113    }
1114
1115    /// Enable Berlin at genesis.
1116    pub fn berlin_activated(mut self) -> Self {
1117        self = self.muirglacier_activated();
1118        self.hardforks.insert(EthereumHardfork::Berlin, ForkCondition::Block(0));
1119        self
1120    }
1121
1122    /// Enable London at genesis.
1123    pub fn london_activated(mut self) -> Self {
1124        self = self.berlin_activated();
1125        self.hardforks.insert(EthereumHardfork::London, ForkCondition::Block(0));
1126        self
1127    }
1128
1129    /// Enable Arrow Glacier at genesis.
1130    pub fn arrowglacier_activated(mut self) -> Self {
1131        self = self.london_activated();
1132        self.hardforks.insert(EthereumHardfork::ArrowGlacier, ForkCondition::Block(0));
1133        self
1134    }
1135
1136    /// Enable Gray Glacier at genesis.
1137    pub fn grayglacier_activated(mut self) -> Self {
1138        self = self.arrowglacier_activated();
1139        self.hardforks.insert(EthereumHardfork::GrayGlacier, ForkCondition::Block(0));
1140        self
1141    }
1142
1143    /// Enable Paris at genesis.
1144    pub fn paris_activated(mut self) -> Self {
1145        self = self.grayglacier_activated();
1146        self.hardforks.insert(
1147            EthereumHardfork::Paris,
1148            ForkCondition::TTD {
1149                activation_block_number: 0,
1150                total_difficulty: U256::ZERO,
1151                fork_block: None,
1152            },
1153        );
1154        self
1155    }
1156
1157    /// Enable Shanghai at genesis.
1158    pub fn shanghai_activated(mut self) -> Self {
1159        self = self.paris_activated();
1160        self.hardforks.insert(EthereumHardfork::Shanghai, ForkCondition::Timestamp(0));
1161        self
1162    }
1163
1164    /// Enable Cancun at genesis.
1165    pub fn cancun_activated(mut self) -> Self {
1166        self = self.shanghai_activated();
1167        self.hardforks.insert(EthereumHardfork::Cancun, ForkCondition::Timestamp(0));
1168        self
1169    }
1170
1171    /// Enable Prague at genesis.
1172    pub fn prague_activated(mut self) -> Self {
1173        self = self.cancun_activated();
1174        self.hardforks.insert(EthereumHardfork::Prague, ForkCondition::Timestamp(0));
1175        self
1176    }
1177
1178    /// Enable Prague at the given timestamp.
1179    pub fn with_prague_at(mut self, timestamp: u64) -> Self {
1180        self.hardforks.insert(EthereumHardfork::Prague, ForkCondition::Timestamp(timestamp));
1181        self
1182    }
1183
1184    /// Enable Osaka at genesis.
1185    pub fn osaka_activated(mut self) -> Self {
1186        self = self.prague_activated();
1187        self.hardforks.insert(EthereumHardfork::Osaka, ForkCondition::Timestamp(0));
1188        self
1189    }
1190
1191    /// Enable Osaka at the given timestamp.
1192    pub fn with_osaka_at(mut self, timestamp: u64) -> Self {
1193        self.hardforks.insert(EthereumHardfork::Osaka, ForkCondition::Timestamp(timestamp));
1194        self
1195    }
1196
1197    /// Enable Amsterdam at genesis.
1198    pub fn amsterdam_activated(mut self) -> Self {
1199        self = self.osaka_activated();
1200        self.hardforks.insert(EthereumHardfork::Amsterdam, ForkCondition::Timestamp(0));
1201        self
1202    }
1203
1204    /// Enable Amsterdam at the given timestamp.
1205    pub fn with_amsterdam_at(mut self, timestamp: u64) -> Self {
1206        self.hardforks.insert(EthereumHardfork::Amsterdam, ForkCondition::Timestamp(timestamp));
1207        self
1208    }
1209
1210    /// Enable Bogota at genesis.
1211    pub fn bogota_activated(mut self) -> Self {
1212        self = self.amsterdam_activated();
1213        self.hardforks.insert(EthereumHardfork::Bogota, ForkCondition::Timestamp(0));
1214        self
1215    }
1216
1217    /// Enable Bogota at the given timestamp.
1218    pub fn with_bogota_at(mut self, timestamp: u64) -> Self {
1219        self.hardforks.insert(EthereumHardfork::Bogota, ForkCondition::Timestamp(timestamp));
1220        self
1221    }
1222
1223    /// Build the resulting [`ChainSpec`].
1224    ///
1225    /// # Panics
1226    ///
1227    /// This function panics if the chain ID and genesis is not set ([`Self::chain`] and
1228    /// [`Self::genesis`])
1229    pub fn build(self) -> ChainSpec {
1230        let paris_block_and_final_difficulty = {
1231            self.hardforks.get(EthereumHardfork::Paris).and_then(|cond| {
1232                if let ForkCondition::TTD { total_difficulty, activation_block_number, .. } = cond {
1233                    Some((activation_block_number, total_difficulty))
1234                } else {
1235                    None
1236                }
1237            })
1238        };
1239        let genesis = self.genesis.expect("The genesis is required");
1240        ChainSpec {
1241            chain: self.chain.expect("The chain is required"),
1242            genesis_header: SealedHeader::new_unhashed(make_genesis_header(
1243                &genesis,
1244                &self.hardforks,
1245            )),
1246            genesis,
1247            hardforks: self.hardforks,
1248            paris_block_and_final_difficulty,
1249            deposit_contract: None,
1250            ..Default::default()
1251        }
1252    }
1253}
1254
1255impl From<&Arc<ChainSpec>> for ChainSpecBuilder {
1256    fn from(value: &Arc<ChainSpec>) -> Self {
1257        Self {
1258            chain: Some(value.chain),
1259            genesis: Some(value.genesis.clone()),
1260            hardforks: value.hardforks.clone(),
1261        }
1262    }
1263}
1264
1265impl<H: BlockHeader> EthExecutorSpec for ChainSpec<H> {
1266    fn deposit_contract_address(&self) -> Option<Address> {
1267        self.deposit_contract.map(|deposit_contract| deposit_contract.address)
1268    }
1269}
1270
1271/// `PoS` deposit contract details.
1272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1273pub struct DepositContract {
1274    /// Deposit Contract Address
1275    pub address: Address,
1276    /// Deployment Block
1277    pub block: BlockNumber,
1278    /// `DepositEvent` event signature
1279    pub topic: B256,
1280}
1281
1282impl DepositContract {
1283    /// Creates a new [`DepositContract`].
1284    pub const fn new(address: Address, block: BlockNumber, topic: B256) -> Self {
1285        Self { address, block, topic }
1286    }
1287}
1288
1289/// Verifies [`ChainSpec`] configuration against expected data in given cases.
1290#[cfg(any(test, feature = "test-utils"))]
1291pub fn test_fork_ids(spec: &ChainSpec, cases: &[(Head, ForkId)]) {
1292    for (block, expected_id) in cases {
1293        let computed_id = spec.fork_id(block);
1294        assert_eq!(
1295            expected_id, &computed_id,
1296            "Expected fork ID {:?}, computed fork ID {:?} at block {}",
1297            expected_id, computed_id, block.number
1298        );
1299    }
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304    use super::*;
1305    use alloy_chains::Chain;
1306    use alloy_consensus::constants::ETH_TO_WEI;
1307    use alloy_eips::{eip4844::BLOB_TX_MIN_BLOB_GASPRICE, eip7840::BlobParams};
1308    use alloy_evm::block::calc::{base_block_reward, block_reward};
1309    use alloy_genesis::{ChainConfig, GenesisAccount};
1310    use alloy_primitives::{b256, hex};
1311    use alloy_trie::{TrieAccount, EMPTY_ROOT_HASH};
1312    use core::ops::Deref;
1313    use reth_ethereum_forks::{ForkCondition, ForkHash, ForkId, Head};
1314    use std::{collections::HashMap, str::FromStr};
1315
1316    fn test_hardfork_fork_ids(spec: &ChainSpec, cases: &[(EthereumHardfork, ForkId)]) {
1317        for (hardfork, expected_id) in cases {
1318            if let Some(computed_id) = spec.hardfork_fork_id(*hardfork) {
1319                assert_eq!(
1320                    expected_id, &computed_id,
1321                    "Expected fork ID {expected_id:?}, computed fork ID {computed_id:?} for hardfork {hardfork}"
1322                );
1323                if matches!(hardfork, EthereumHardfork::Shanghai) {
1324                    if let Some(shanghai_id) = spec.shanghai_fork_id() {
1325                        assert_eq!(
1326                            expected_id, &shanghai_id,
1327                            "Expected fork ID {expected_id:?}, computed fork ID {computed_id:?} for Shanghai hardfork"
1328                        );
1329                    } else {
1330                        panic!("Expected ForkCondition to return Some for Hardfork::Shanghai");
1331                    }
1332                }
1333            }
1334        }
1335    }
1336
1337    #[test]
1338    fn test_hardfork_list_display_mainnet() {
1339        assert_eq!(
1340            MAINNET.display_hardforks().to_string(),
1341            "Pre-merge hard forks (block based):
1342- Frontier                         @0
1343- Homestead                        @1150000
1344- Dao                              @1920000
1345- Tangerine                        @2463000
1346- SpuriousDragon                   @2675000
1347- Byzantium                        @4370000
1348- Constantinople                   @7280000
1349- Petersburg                       @7280000
1350- Istanbul                         @9069000
1351- MuirGlacier                      @9200000
1352- Berlin                           @12244000
1353- London                           @12965000
1354- ArrowGlacier                     @13773000
1355- GrayGlacier                      @15050000
1356Merge hard forks:
1357- Paris                            @58750000000000000000000 (network is known to be merged)
1358Post-merge hard forks (timestamp based):
1359- Shanghai                         @1681338455
1360- Cancun                           @1710338135          blob: (target: 3, max: 6, fraction: 3338477)
1361- Prague                           @1746612311          blob: (target: 6, max: 9, fraction: 5007716)
1362- Osaka                            @1764798551          blob: (target: 6, max: 9, fraction: 5007716)
1363- Bpo1                             @1765290071          blob: (target: 10, max: 15, fraction: 8346193)
1364- Bpo2                             @1767747671          blob: (target: 14, max: 21, fraction: 11684671)"
1365        );
1366    }
1367
1368    #[test]
1369    fn test_hardfork_list_ignores_disabled_forks() {
1370        let spec = ChainSpec::builder()
1371            .chain(Chain::mainnet())
1372            .genesis(Genesis::default())
1373            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1374            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Never)
1375            .build();
1376        assert_eq!(
1377            spec.display_hardforks().to_string(),
1378            "Pre-merge hard forks (block based):
1379- Frontier                         @0"
1380        );
1381    }
1382
1383    // Tests that we skip any fork blocks in block #0 (the genesis ruleset)
1384    #[test]
1385    fn ignores_genesis_fork_blocks() {
1386        let spec = ChainSpec::builder()
1387            .chain(Chain::mainnet())
1388            .genesis(Genesis::default())
1389            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1390            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(0))
1391            .with_fork(EthereumHardfork::Tangerine, ForkCondition::Block(0))
1392            .with_fork(EthereumHardfork::SpuriousDragon, ForkCondition::Block(0))
1393            .with_fork(EthereumHardfork::Byzantium, ForkCondition::Block(0))
1394            .with_fork(EthereumHardfork::Constantinople, ForkCondition::Block(0))
1395            .with_fork(EthereumHardfork::Istanbul, ForkCondition::Block(0))
1396            .with_fork(EthereumHardfork::MuirGlacier, ForkCondition::Block(0))
1397            .with_fork(EthereumHardfork::Berlin, ForkCondition::Block(0))
1398            .with_fork(EthereumHardfork::London, ForkCondition::Block(0))
1399            .with_fork(EthereumHardfork::ArrowGlacier, ForkCondition::Block(0))
1400            .with_fork(EthereumHardfork::GrayGlacier, ForkCondition::Block(0))
1401            .build();
1402
1403        assert_eq!(spec.deref().len(), 12, "12 forks should be active.");
1404        assert_eq!(
1405            spec.fork_id(&Head { number: 1, ..Default::default() }),
1406            ForkId { hash: ForkHash::from(spec.genesis_hash()), next: 0 },
1407            "the fork ID should be the genesis hash; forks at genesis are ignored for fork filters"
1408        );
1409    }
1410
1411    #[test]
1412    fn ignores_duplicate_fork_blocks() {
1413        let empty_genesis = Genesis::default();
1414        let unique_spec = ChainSpec::builder()
1415            .chain(Chain::mainnet())
1416            .genesis(empty_genesis.clone())
1417            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1418            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(1))
1419            .build();
1420
1421        let duplicate_spec = ChainSpec::builder()
1422            .chain(Chain::mainnet())
1423            .genesis(empty_genesis)
1424            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1425            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(1))
1426            .with_fork(EthereumHardfork::Tangerine, ForkCondition::Block(1))
1427            .build();
1428
1429        assert_eq!(
1430            unique_spec.fork_id(&Head { number: 2, ..Default::default() }),
1431            duplicate_spec.fork_id(&Head { number: 2, ..Default::default() }),
1432            "duplicate fork blocks should be deduplicated for fork filters"
1433        );
1434    }
1435
1436    #[test]
1437    fn test_chainspec_satisfy() {
1438        let empty_genesis = Genesis::default();
1439        // happy path test case
1440        let happy_path_case = ChainSpec::builder()
1441            .chain(Chain::mainnet())
1442            .genesis(empty_genesis.clone())
1443            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1444            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(73))
1445            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(11313123))
1446            .build();
1447        let happy_path_head = happy_path_case.satisfy(ForkCondition::Timestamp(11313123));
1448        let happy_path_expected = Head { number: 73, timestamp: 11313123, ..Default::default() };
1449        assert_eq!(
1450            happy_path_head, happy_path_expected,
1451            "expected satisfy() to return {happy_path_expected:#?}, but got {happy_path_head:#?} "
1452        );
1453        // multiple timestamp test case (i.e Shanghai -> Cancun)
1454        let multiple_timestamp_fork_case = ChainSpec::builder()
1455            .chain(Chain::mainnet())
1456            .genesis(empty_genesis.clone())
1457            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1458            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(73))
1459            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(11313123))
1460            .with_fork(EthereumHardfork::Cancun, ForkCondition::Timestamp(11313398))
1461            .build();
1462        let multi_timestamp_head =
1463            multiple_timestamp_fork_case.satisfy(ForkCondition::Timestamp(11313398));
1464        let mult_timestamp_expected =
1465            Head { number: 73, timestamp: 11313398, ..Default::default() };
1466        assert_eq!(
1467            multi_timestamp_head, mult_timestamp_expected,
1468            "expected satisfy() to return {mult_timestamp_expected:#?}, but got {multi_timestamp_head:#?} "
1469        );
1470        // no ForkCondition::Block test case
1471        let no_block_fork_case = ChainSpec::builder()
1472            .chain(Chain::mainnet())
1473            .genesis(empty_genesis.clone())
1474            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(11313123))
1475            .build();
1476        let no_block_fork_head = no_block_fork_case.satisfy(ForkCondition::Timestamp(11313123));
1477        let no_block_fork_expected = Head { number: 0, timestamp: 11313123, ..Default::default() };
1478        assert_eq!(
1479            no_block_fork_head, no_block_fork_expected,
1480            "expected satisfy() to return {no_block_fork_expected:#?}, but got {no_block_fork_head:#?} ",
1481        );
1482        // spec w/ ForkCondition::TTD with block_num test case (Sepolia merge netsplit edge case)
1483        let fork_cond_ttd_blocknum_case = ChainSpec::builder()
1484            .chain(Chain::mainnet())
1485            .genesis(empty_genesis.clone())
1486            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1487            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(73))
1488            .with_fork(
1489                EthereumHardfork::Paris,
1490                ForkCondition::TTD {
1491                    activation_block_number: 101,
1492                    fork_block: Some(101),
1493                    total_difficulty: U256::from(10_790_000),
1494                },
1495            )
1496            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(11313123))
1497            .build();
1498        let fork_cond_ttd_blocknum_head =
1499            fork_cond_ttd_blocknum_case.satisfy(ForkCondition::Timestamp(11313123));
1500        let fork_cond_ttd_blocknum_expected =
1501            Head { number: 101, timestamp: 11313123, ..Default::default() };
1502        assert_eq!(
1503            fork_cond_ttd_blocknum_head, fork_cond_ttd_blocknum_expected,
1504            "expected satisfy() to return {fork_cond_ttd_blocknum_expected:#?}, but got {fork_cond_ttd_blocknum_head:#?} ",
1505        );
1506
1507        // spec w/ only ForkCondition::Block - test the match arm for ForkCondition::Block to ensure
1508        // no regressions, for these ForkConditions(Block/TTD) - a separate chain spec definition is
1509        // technically unnecessary - but we include it here for thoroughness
1510        let fork_cond_block_only_case = ChainSpec::builder()
1511            .chain(Chain::mainnet())
1512            .genesis(empty_genesis)
1513            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1514            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(73))
1515            .build();
1516        let fork_cond_block_only_head = fork_cond_block_only_case.satisfy(ForkCondition::Block(73));
1517        let fork_cond_block_only_expected = Head { number: 73, ..Default::default() };
1518        assert_eq!(
1519            fork_cond_block_only_head, fork_cond_block_only_expected,
1520            "expected satisfy() to return {fork_cond_block_only_expected:#?}, but got {fork_cond_block_only_head:#?} ",
1521        );
1522        // Fork::ConditionTTD test case without a new chain spec to demonstrate ChainSpec::satisfy
1523        // is independent of ChainSpec for this(these - including ForkCondition::Block) match arm(s)
1524        let fork_cond_ttd_no_new_spec = fork_cond_block_only_case.satisfy(ForkCondition::TTD {
1525            activation_block_number: 101,
1526            fork_block: None,
1527            total_difficulty: U256::from(10_790_000),
1528        });
1529        let fork_cond_ttd_no_new_spec_expected =
1530            Head { total_difficulty: U256::from(10_790_000), ..Default::default() };
1531        assert_eq!(
1532            fork_cond_ttd_no_new_spec, fork_cond_ttd_no_new_spec_expected,
1533            "expected satisfy() to return {fork_cond_ttd_no_new_spec_expected:#?}, but got {fork_cond_ttd_no_new_spec:#?} ",
1534        );
1535    }
1536
1537    #[test]
1538    fn mainnet_hardfork_fork_ids() {
1539        test_hardfork_fork_ids(
1540            &MAINNET,
1541            &[
1542                (
1543                    EthereumHardfork::Frontier,
1544                    ForkId { hash: ForkHash(hex!("0xfc64ec04")), next: 1150000 },
1545                ),
1546                (
1547                    EthereumHardfork::Homestead,
1548                    ForkId { hash: ForkHash(hex!("0x97c2c34c")), next: 1920000 },
1549                ),
1550                (
1551                    EthereumHardfork::Dao,
1552                    ForkId { hash: ForkHash(hex!("0x91d1f948")), next: 2463000 },
1553                ),
1554                (
1555                    EthereumHardfork::Tangerine,
1556                    ForkId { hash: ForkHash(hex!("0x7a64da13")), next: 2675000 },
1557                ),
1558                (
1559                    EthereumHardfork::SpuriousDragon,
1560                    ForkId { hash: ForkHash(hex!("0x3edd5b10")), next: 4370000 },
1561                ),
1562                (
1563                    EthereumHardfork::Byzantium,
1564                    ForkId { hash: ForkHash(hex!("0xa00bc324")), next: 7280000 },
1565                ),
1566                (
1567                    EthereumHardfork::Constantinople,
1568                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
1569                ),
1570                (
1571                    EthereumHardfork::Petersburg,
1572                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
1573                ),
1574                (
1575                    EthereumHardfork::Istanbul,
1576                    ForkId { hash: ForkHash(hex!("0x879d6e30")), next: 9200000 },
1577                ),
1578                (
1579                    EthereumHardfork::MuirGlacier,
1580                    ForkId { hash: ForkHash(hex!("0xe029e991")), next: 12244000 },
1581                ),
1582                (
1583                    EthereumHardfork::Berlin,
1584                    ForkId { hash: ForkHash(hex!("0x0eb440f6")), next: 12965000 },
1585                ),
1586                (
1587                    EthereumHardfork::London,
1588                    ForkId { hash: ForkHash(hex!("0xb715077d")), next: 13773000 },
1589                ),
1590                (
1591                    EthereumHardfork::ArrowGlacier,
1592                    ForkId { hash: ForkHash(hex!("0x20c327fc")), next: 15050000 },
1593                ),
1594                (
1595                    EthereumHardfork::GrayGlacier,
1596                    ForkId { hash: ForkHash(hex!("0xf0afd0e3")), next: 1681338455 },
1597                ),
1598                (
1599                    EthereumHardfork::Shanghai,
1600                    ForkId { hash: ForkHash(hex!("0xdce96c2d")), next: 1710338135 },
1601                ),
1602                (
1603                    EthereumHardfork::Cancun,
1604                    ForkId { hash: ForkHash(hex!("0x9f3d2254")), next: 1746612311 },
1605                ),
1606                (
1607                    EthereumHardfork::Prague,
1608                    ForkId {
1609                        hash: ForkHash(hex!("0xc376cf8b")),
1610                        next: mainnet::MAINNET_OSAKA_TIMESTAMP,
1611                    },
1612                ),
1613            ],
1614        );
1615    }
1616
1617    #[test]
1618    fn sepolia_hardfork_fork_ids() {
1619        test_hardfork_fork_ids(
1620            &SEPOLIA,
1621            &[
1622                (
1623                    EthereumHardfork::Frontier,
1624                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1625                ),
1626                (
1627                    EthereumHardfork::Homestead,
1628                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1629                ),
1630                (
1631                    EthereumHardfork::Tangerine,
1632                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1633                ),
1634                (
1635                    EthereumHardfork::SpuriousDragon,
1636                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1637                ),
1638                (
1639                    EthereumHardfork::Byzantium,
1640                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1641                ),
1642                (
1643                    EthereumHardfork::Constantinople,
1644                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1645                ),
1646                (
1647                    EthereumHardfork::Petersburg,
1648                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1649                ),
1650                (
1651                    EthereumHardfork::Istanbul,
1652                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1653                ),
1654                (
1655                    EthereumHardfork::Berlin,
1656                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1657                ),
1658                (
1659                    EthereumHardfork::London,
1660                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1661                ),
1662                (
1663                    EthereumHardfork::Paris,
1664                    ForkId { hash: ForkHash(hex!("0xb96cbd13")), next: 1677557088 },
1665                ),
1666                (
1667                    EthereumHardfork::Shanghai,
1668                    ForkId { hash: ForkHash(hex!("0xf7f9bc08")), next: 1706655072 },
1669                ),
1670                (
1671                    EthereumHardfork::Cancun,
1672                    ForkId { hash: ForkHash(hex!("0x88cf81d9")), next: 1741159776 },
1673                ),
1674                (
1675                    EthereumHardfork::Prague,
1676                    ForkId {
1677                        hash: ForkHash(hex!("0xed88b5fd")),
1678                        next: sepolia::SEPOLIA_OSAKA_TIMESTAMP,
1679                    },
1680                ),
1681                (
1682                    EthereumHardfork::Osaka,
1683                    ForkId {
1684                        hash: ForkHash(hex!("0xe2ae4999")),
1685                        next: sepolia::SEPOLIA_BPO1_TIMESTAMP,
1686                    },
1687                ),
1688                (
1689                    EthereumHardfork::Bpo1,
1690                    ForkId {
1691                        hash: ForkHash(hex!("0x56078a1e")),
1692                        next: sepolia::SEPOLIA_BPO2_TIMESTAMP,
1693                    },
1694                ),
1695                (
1696                    EthereumHardfork::Bpo2,
1697                    ForkId {
1698                        hash: ForkHash(hex!("0x268956b6")),
1699                        next: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP,
1700                    },
1701                ),
1702                (
1703                    EthereumHardfork::Amsterdam,
1704                    ForkId { hash: ForkHash(hex!("0x6c1d9423")), next: 0 },
1705                ),
1706            ],
1707        );
1708    }
1709
1710    #[test]
1711    fn mainnet_fork_ids() {
1712        test_fork_ids(
1713            &MAINNET,
1714            &[
1715                (
1716                    Head { number: 0, ..Default::default() },
1717                    ForkId { hash: ForkHash(hex!("0xfc64ec04")), next: 1150000 },
1718                ),
1719                (
1720                    Head { number: 1150000, ..Default::default() },
1721                    ForkId { hash: ForkHash(hex!("0x97c2c34c")), next: 1920000 },
1722                ),
1723                (
1724                    Head { number: 1920000, ..Default::default() },
1725                    ForkId { hash: ForkHash(hex!("0x91d1f948")), next: 2463000 },
1726                ),
1727                (
1728                    Head { number: 2463000, ..Default::default() },
1729                    ForkId { hash: ForkHash(hex!("0x7a64da13")), next: 2675000 },
1730                ),
1731                (
1732                    Head { number: 2675000, ..Default::default() },
1733                    ForkId { hash: ForkHash(hex!("0x3edd5b10")), next: 4370000 },
1734                ),
1735                (
1736                    Head { number: 4370000, ..Default::default() },
1737                    ForkId { hash: ForkHash(hex!("0xa00bc324")), next: 7280000 },
1738                ),
1739                (
1740                    Head { number: 7280000, ..Default::default() },
1741                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
1742                ),
1743                (
1744                    Head { number: 9069000, ..Default::default() },
1745                    ForkId { hash: ForkHash(hex!("0x879d6e30")), next: 9200000 },
1746                ),
1747                (
1748                    Head { number: 9200000, ..Default::default() },
1749                    ForkId { hash: ForkHash(hex!("0xe029e991")), next: 12244000 },
1750                ),
1751                (
1752                    Head { number: 12244000, ..Default::default() },
1753                    ForkId { hash: ForkHash(hex!("0x0eb440f6")), next: 12965000 },
1754                ),
1755                (
1756                    Head { number: 12965000, ..Default::default() },
1757                    ForkId { hash: ForkHash(hex!("0xb715077d")), next: 13773000 },
1758                ),
1759                (
1760                    Head { number: 13773000, ..Default::default() },
1761                    ForkId { hash: ForkHash(hex!("0x20c327fc")), next: 15050000 },
1762                ),
1763                (
1764                    Head { number: 15050000, ..Default::default() },
1765                    ForkId { hash: ForkHash(hex!("0xf0afd0e3")), next: 1681338455 },
1766                ),
1767                // First Shanghai block
1768                (
1769                    Head { number: 20000000, timestamp: 1681338455, ..Default::default() },
1770                    ForkId { hash: ForkHash(hex!("0xdce96c2d")), next: 1710338135 },
1771                ),
1772                // First Cancun block
1773                (
1774                    Head { number: 20000001, timestamp: 1710338135, ..Default::default() },
1775                    ForkId { hash: ForkHash(hex!("0x9f3d2254")), next: 1746612311 },
1776                ),
1777                // First Prague block
1778                (
1779                    Head { number: 20000004, timestamp: 1746612311, ..Default::default() },
1780                    ForkId {
1781                        hash: ForkHash(hex!("0xc376cf8b")),
1782                        next: mainnet::MAINNET_OSAKA_TIMESTAMP,
1783                    },
1784                ),
1785                // Osaka block
1786                (
1787                    Head {
1788                        number: 20000004,
1789                        timestamp: mainnet::MAINNET_OSAKA_TIMESTAMP,
1790                        ..Default::default()
1791                    },
1792                    ForkId {
1793                        hash: ForkHash(hex!("0x5167e2a6")),
1794                        next: mainnet::MAINNET_BPO1_TIMESTAMP,
1795                    },
1796                ),
1797            ],
1798        );
1799    }
1800
1801    #[test]
1802    fn hoodi_fork_ids() {
1803        test_fork_ids(
1804            &HOODI,
1805            &[
1806                (
1807                    Head { number: 0, ..Default::default() },
1808                    ForkId { hash: ForkHash(hex!("0xbef71d30")), next: 1742999832 },
1809                ),
1810                // First Prague block
1811                (
1812                    Head { number: 0, timestamp: 1742999833, ..Default::default() },
1813                    ForkId {
1814                        hash: ForkHash(hex!("0x0929e24e")),
1815                        next: hoodi::HOODI_OSAKA_TIMESTAMP,
1816                    },
1817                ),
1818                // First Osaka block
1819                (
1820                    Head {
1821                        number: 0,
1822                        timestamp: hoodi::HOODI_OSAKA_TIMESTAMP,
1823                        ..Default::default()
1824                    },
1825                    ForkId {
1826                        hash: ForkHash(hex!("0xe7e0e7ff")),
1827                        next: hoodi::HOODI_BPO1_TIMESTAMP,
1828                    },
1829                ),
1830            ],
1831        )
1832    }
1833
1834    #[test]
1835    fn holesky_fork_ids() {
1836        test_fork_ids(
1837            &HOLESKY,
1838            &[
1839                (
1840                    Head { number: 0, ..Default::default() },
1841                    ForkId { hash: ForkHash(hex!("0xc61a6098")), next: 1696000704 },
1842                ),
1843                // First MergeNetsplit block
1844                (
1845                    Head { number: 123, ..Default::default() },
1846                    ForkId { hash: ForkHash(hex!("0xc61a6098")), next: 1696000704 },
1847                ),
1848                // Last MergeNetsplit block
1849                (
1850                    Head { number: 123, timestamp: 1696000703, ..Default::default() },
1851                    ForkId { hash: ForkHash(hex!("0xc61a6098")), next: 1696000704 },
1852                ),
1853                // First Shanghai block
1854                (
1855                    Head { number: 123, timestamp: 1696000704, ..Default::default() },
1856                    ForkId { hash: ForkHash(hex!("0xfd4f016b")), next: 1707305664 },
1857                ),
1858                // Last Shanghai block
1859                (
1860                    Head { number: 123, timestamp: 1707305663, ..Default::default() },
1861                    ForkId { hash: ForkHash(hex!("0xfd4f016b")), next: 1707305664 },
1862                ),
1863                // First Cancun block
1864                (
1865                    Head { number: 123, timestamp: 1707305664, ..Default::default() },
1866                    ForkId { hash: ForkHash(hex!("0x9b192ad0")), next: 1740434112 },
1867                ),
1868                // Last Cancun block
1869                (
1870                    Head { number: 123, timestamp: 1740434111, ..Default::default() },
1871                    ForkId { hash: ForkHash(hex!("0x9b192ad0")), next: 1740434112 },
1872                ),
1873                // First Prague block
1874                (
1875                    Head { number: 123, timestamp: 1740434112, ..Default::default() },
1876                    ForkId {
1877                        hash: ForkHash(hex!("0xdfbd9bed")),
1878                        next: holesky::HOLESKY_OSAKA_TIMESTAMP,
1879                    },
1880                ),
1881                // First Osaka block
1882                (
1883                    Head {
1884                        number: 123,
1885                        timestamp: holesky::HOLESKY_OSAKA_TIMESTAMP,
1886                        ..Default::default()
1887                    },
1888                    ForkId {
1889                        hash: ForkHash(hex!("0x783def52")),
1890                        next: holesky::HOLESKY_BPO1_TIMESTAMP,
1891                    },
1892                ),
1893            ],
1894        )
1895    }
1896
1897    #[test]
1898    fn sepolia_fork_ids() {
1899        test_fork_ids(
1900            &SEPOLIA,
1901            &[
1902                (
1903                    Head { number: 0, ..Default::default() },
1904                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1905                ),
1906                (
1907                    Head { number: 1735370, ..Default::default() },
1908                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1909                ),
1910                (
1911                    Head { number: 1735371, ..Default::default() },
1912                    ForkId { hash: ForkHash(hex!("0xb96cbd13")), next: 1677557088 },
1913                ),
1914                (
1915                    Head { number: 1735372, timestamp: 1677557087, ..Default::default() },
1916                    ForkId { hash: ForkHash(hex!("0xb96cbd13")), next: 1677557088 },
1917                ),
1918                // First Shanghai block
1919                (
1920                    Head { number: 1735373, timestamp: 1677557088, ..Default::default() },
1921                    ForkId { hash: ForkHash(hex!("0xf7f9bc08")), next: 1706655072 },
1922                ),
1923                // Last Shanghai block
1924                (
1925                    Head { number: 1735374, timestamp: 1706655071, ..Default::default() },
1926                    ForkId { hash: ForkHash(hex!("0xf7f9bc08")), next: 1706655072 },
1927                ),
1928                // First Cancun block
1929                (
1930                    Head { number: 1735375, timestamp: 1706655072, ..Default::default() },
1931                    ForkId { hash: ForkHash(hex!("0x88cf81d9")), next: 1741159776 },
1932                ),
1933                // Last Cancun block
1934                (
1935                    Head { number: 1735376, timestamp: 1741159775, ..Default::default() },
1936                    ForkId { hash: ForkHash(hex!("0x88cf81d9")), next: 1741159776 },
1937                ),
1938                // First Prague block
1939                (
1940                    Head { number: 1735377, timestamp: 1741159776, ..Default::default() },
1941                    ForkId {
1942                        hash: ForkHash(hex!("0xed88b5fd")),
1943                        next: sepolia::SEPOLIA_OSAKA_TIMESTAMP,
1944                    },
1945                ),
1946                // First Osaka block
1947                (
1948                    Head {
1949                        number: 1735377,
1950                        timestamp: sepolia::SEPOLIA_OSAKA_TIMESTAMP,
1951                        ..Default::default()
1952                    },
1953                    ForkId {
1954                        hash: ForkHash(hex!("0xe2ae4999")),
1955                        next: sepolia::SEPOLIA_BPO1_TIMESTAMP,
1956                    },
1957                ),
1958                // First BPO1 block
1959                (
1960                    Head {
1961                        number: 1735377,
1962                        timestamp: sepolia::SEPOLIA_BPO1_TIMESTAMP,
1963                        ..Default::default()
1964                    },
1965                    ForkId {
1966                        hash: ForkHash(hex!("0x56078a1e")),
1967                        next: sepolia::SEPOLIA_BPO2_TIMESTAMP,
1968                    },
1969                ),
1970                // First BPO2 block
1971                (
1972                    Head {
1973                        number: 1735377,
1974                        timestamp: sepolia::SEPOLIA_BPO2_TIMESTAMP,
1975                        ..Default::default()
1976                    },
1977                    ForkId {
1978                        hash: ForkHash(hex!("0x268956b6")),
1979                        next: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP,
1980                    },
1981                ),
1982                // Last block before Amsterdam
1983                (
1984                    Head {
1985                        number: 1735377,
1986                        timestamp: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP - 1,
1987                        ..Default::default()
1988                    },
1989                    ForkId {
1990                        hash: ForkHash(hex!("0x268956b6")),
1991                        next: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP,
1992                    },
1993                ),
1994                // First Amsterdam block
1995                (
1996                    Head {
1997                        number: 1735377,
1998                        timestamp: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP,
1999                        ..Default::default()
2000                    },
2001                    ForkId { hash: ForkHash(hex!("0x6c1d9423")), next: 0 },
2002                ),
2003                // After Amsterdam
2004                (
2005                    Head {
2006                        number: 1735377,
2007                        timestamp: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP + 1,
2008                        ..Default::default()
2009                    },
2010                    ForkId { hash: ForkHash(hex!("0x6c1d9423")), next: 0 },
2011                ),
2012            ],
2013        );
2014    }
2015
2016    #[test]
2017    fn dev_fork_ids() {
2018        test_fork_ids(
2019            &DEV,
2020            &[(
2021                Head { number: 0, ..Default::default() },
2022                ForkId { hash: ForkHash(hex!("0x0b1a4ef7")), next: 0 },
2023            )],
2024        )
2025    }
2026
2027    /// Checks that time-based forks work
2028    ///
2029    /// This is based off of the test vectors here: <https://github.com/ethereum/go-ethereum/blob/5c8cc10d1e05c23ff1108022f4150749e73c0ca1/core/forkid/forkid_test.go#L155-L188>
2030    #[test]
2031    fn timestamped_forks() {
2032        let mainnet_with_timestamps = ChainSpecBuilder::mainnet().build();
2033        test_fork_ids(
2034            &mainnet_with_timestamps,
2035            &[
2036                (
2037                    Head { number: 0, timestamp: 0, ..Default::default() },
2038                    ForkId { hash: ForkHash(hex!("0xfc64ec04")), next: 1150000 },
2039                ), // Unsynced
2040                (
2041                    Head { number: 1149999, timestamp: 0, ..Default::default() },
2042                    ForkId { hash: ForkHash(hex!("0xfc64ec04")), next: 1150000 },
2043                ), // Last Frontier block
2044                (
2045                    Head { number: 1150000, timestamp: 0, ..Default::default() },
2046                    ForkId { hash: ForkHash(hex!("0x97c2c34c")), next: 1920000 },
2047                ), // First Homestead block
2048                (
2049                    Head { number: 1919999, timestamp: 0, ..Default::default() },
2050                    ForkId { hash: ForkHash(hex!("0x97c2c34c")), next: 1920000 },
2051                ), // Last Homestead block
2052                (
2053                    Head { number: 1920000, timestamp: 0, ..Default::default() },
2054                    ForkId { hash: ForkHash(hex!("0x91d1f948")), next: 2463000 },
2055                ), // First DAO block
2056                (
2057                    Head { number: 2462999, timestamp: 0, ..Default::default() },
2058                    ForkId { hash: ForkHash(hex!("0x91d1f948")), next: 2463000 },
2059                ), // Last DAO block
2060                (
2061                    Head { number: 2463000, timestamp: 0, ..Default::default() },
2062                    ForkId { hash: ForkHash(hex!("0x7a64da13")), next: 2675000 },
2063                ), // First Tangerine block
2064                (
2065                    Head { number: 2674999, timestamp: 0, ..Default::default() },
2066                    ForkId { hash: ForkHash(hex!("0x7a64da13")), next: 2675000 },
2067                ), // Last Tangerine block
2068                (
2069                    Head { number: 2675000, timestamp: 0, ..Default::default() },
2070                    ForkId { hash: ForkHash(hex!("0x3edd5b10")), next: 4370000 },
2071                ), // First Spurious block
2072                (
2073                    Head { number: 4369999, timestamp: 0, ..Default::default() },
2074                    ForkId { hash: ForkHash(hex!("0x3edd5b10")), next: 4370000 },
2075                ), // Last Spurious block
2076                (
2077                    Head { number: 4370000, timestamp: 0, ..Default::default() },
2078                    ForkId { hash: ForkHash(hex!("0xa00bc324")), next: 7280000 },
2079                ), // First Byzantium block
2080                (
2081                    Head { number: 7279999, timestamp: 0, ..Default::default() },
2082                    ForkId { hash: ForkHash(hex!("0xa00bc324")), next: 7280000 },
2083                ), // Last Byzantium block
2084                (
2085                    Head { number: 7280000, timestamp: 0, ..Default::default() },
2086                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
2087                ), // First and last Constantinople, first Petersburg block
2088                (
2089                    Head { number: 9068999, timestamp: 0, ..Default::default() },
2090                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
2091                ), // Last Petersburg block
2092                (
2093                    Head { number: 9069000, timestamp: 0, ..Default::default() },
2094                    ForkId { hash: ForkHash(hex!("0x879d6e30")), next: 9200000 },
2095                ), // First Istanbul and first Muir Glacier block
2096                (
2097                    Head { number: 9199999, timestamp: 0, ..Default::default() },
2098                    ForkId { hash: ForkHash(hex!("0x879d6e30")), next: 9200000 },
2099                ), // Last Istanbul and first Muir Glacier block
2100                (
2101                    Head { number: 9200000, timestamp: 0, ..Default::default() },
2102                    ForkId { hash: ForkHash(hex!("0xe029e991")), next: 12244000 },
2103                ), // First Muir Glacier block
2104                (
2105                    Head { number: 12243999, timestamp: 0, ..Default::default() },
2106                    ForkId { hash: ForkHash(hex!("0xe029e991")), next: 12244000 },
2107                ), // Last Muir Glacier block
2108                (
2109                    Head { number: 12244000, timestamp: 0, ..Default::default() },
2110                    ForkId { hash: ForkHash(hex!("0x0eb440f6")), next: 12965000 },
2111                ), // First Berlin block
2112                (
2113                    Head { number: 12964999, timestamp: 0, ..Default::default() },
2114                    ForkId { hash: ForkHash(hex!("0x0eb440f6")), next: 12965000 },
2115                ), // Last Berlin block
2116                (
2117                    Head { number: 12965000, timestamp: 0, ..Default::default() },
2118                    ForkId { hash: ForkHash(hex!("0xb715077d")), next: 13773000 },
2119                ), // First London block
2120                (
2121                    Head { number: 13772999, timestamp: 0, ..Default::default() },
2122                    ForkId { hash: ForkHash(hex!("0xb715077d")), next: 13773000 },
2123                ), // Last London block
2124                (
2125                    Head { number: 13773000, timestamp: 0, ..Default::default() },
2126                    ForkId { hash: ForkHash(hex!("0x20c327fc")), next: 15050000 },
2127                ), // First Arrow Glacier block
2128                (
2129                    Head { number: 15049999, timestamp: 0, ..Default::default() },
2130                    ForkId { hash: ForkHash(hex!("0x20c327fc")), next: 15050000 },
2131                ), // Last Arrow Glacier block
2132                (
2133                    Head { number: 15050000, timestamp: 0, ..Default::default() },
2134                    ForkId { hash: ForkHash(hex!("0xf0afd0e3")), next: 1681338455 },
2135                ), // First Gray Glacier block
2136                (
2137                    Head { number: 19999999, timestamp: 1667999999, ..Default::default() },
2138                    ForkId { hash: ForkHash(hex!("0xf0afd0e3")), next: 1681338455 },
2139                ), // Last Gray Glacier block
2140                (
2141                    Head { number: 20000000, timestamp: 1681338455, ..Default::default() },
2142                    ForkId { hash: ForkHash(hex!("0xdce96c2d")), next: 1710338135 },
2143                ), // Last Shanghai block
2144                (
2145                    Head { number: 20000001, timestamp: 1710338134, ..Default::default() },
2146                    ForkId { hash: ForkHash(hex!("0xdce96c2d")), next: 1710338135 },
2147                ), // First Cancun block
2148                (
2149                    Head { number: 20000002, timestamp: 1710338135, ..Default::default() },
2150                    ForkId { hash: ForkHash(hex!("0x9f3d2254")), next: 1746612311 },
2151                ), // Last Cancun block
2152                (
2153                    Head { number: 20000003, timestamp: 1746612310, ..Default::default() },
2154                    ForkId { hash: ForkHash(hex!("0x9f3d2254")), next: 1746612311 },
2155                ), // First Prague block
2156                (
2157                    Head { number: 20000004, timestamp: 1746612311, ..Default::default() },
2158                    ForkId {
2159                        hash: ForkHash(hex!("0xc376cf8b")),
2160                        next: mainnet::MAINNET_OSAKA_TIMESTAMP,
2161                    },
2162                ),
2163                // Osaka block
2164                (
2165                    Head {
2166                        number: 20000004,
2167                        timestamp: mainnet::MAINNET_OSAKA_TIMESTAMP,
2168                        ..Default::default()
2169                    },
2170                    ForkId {
2171                        hash: ForkHash(hex!("0x5167e2a6")),
2172                        next: mainnet::MAINNET_BPO1_TIMESTAMP,
2173                    },
2174                ),
2175            ],
2176        );
2177    }
2178
2179    /// Constructs a [`ChainSpec`] with the given [`ChainSpecBuilder`], shanghai, and cancun fork
2180    /// timestamps.
2181    fn construct_chainspec(
2182        builder: ChainSpecBuilder,
2183        shanghai_time: u64,
2184        cancun_time: u64,
2185    ) -> ChainSpec {
2186        builder
2187            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(shanghai_time))
2188            .with_fork(EthereumHardfork::Cancun, ForkCondition::Timestamp(cancun_time))
2189            .build()
2190    }
2191
2192    /// Tests that time-based forks which are active at genesis are not included in forkid hash.
2193    ///
2194    /// This is based off of the test vectors here:
2195    /// <https://github.com/ethereum/go-ethereum/blob/2e02c1ffd9dffd1ec9e43c6b66f6c9bd1e556a0b/core/forkid/forkid_test.go#L390-L440>
2196    #[test]
2197    fn test_timestamp_fork_in_genesis() {
2198        let timestamp = 1690475657u64;
2199        let default_spec_builder = ChainSpecBuilder::default()
2200            .chain(Chain::from_id(1337))
2201            .genesis(Genesis::default().with_timestamp(timestamp))
2202            .paris_activated();
2203
2204        // test format: (chain spec, expected next value) - the forkhash will be determined by the
2205        // genesis hash of the constructed chainspec
2206        let tests = [
2207            (
2208                construct_chainspec(default_spec_builder.clone(), timestamp - 1, timestamp + 1),
2209                timestamp + 1,
2210            ),
2211            (
2212                construct_chainspec(default_spec_builder.clone(), timestamp, timestamp + 1),
2213                timestamp + 1,
2214            ),
2215            (
2216                construct_chainspec(default_spec_builder, timestamp + 1, timestamp + 2),
2217                timestamp + 1,
2218            ),
2219        ];
2220
2221        for (spec, expected_timestamp) in tests {
2222            let got_forkid = spec.fork_id(&Head { number: 0, timestamp: 0, ..Default::default() });
2223            // This is slightly different from the geth test because we use the shanghai timestamp
2224            // to determine whether or not to include a withdrawals root in the genesis header.
2225            // This makes the genesis hash different, and as a result makes the ChainSpec fork hash
2226            // different.
2227            let genesis_hash = spec.genesis_hash();
2228            let expected_forkid =
2229                ForkId { hash: ForkHash::from(genesis_hash), next: expected_timestamp };
2230            assert_eq!(got_forkid, expected_forkid);
2231        }
2232    }
2233
2234    /// Checks that the fork is not active at a terminal ttd block.
2235    #[test]
2236    fn check_terminal_ttd() {
2237        let chainspec = ChainSpecBuilder::mainnet().build();
2238
2239        // Check that Paris is not active on terminal PoW block #15537393.
2240        let terminal_block_ttd = U256::from(58750003716598352816469_u128);
2241        let terminal_block_difficulty = U256::from(11055787484078698_u128);
2242        assert!(!chainspec
2243            .fork(EthereumHardfork::Paris)
2244            .active_at_ttd(terminal_block_ttd, terminal_block_difficulty));
2245
2246        // Check that Paris is active on first PoS block #15537394.
2247        let first_pos_block_ttd = U256::from(58750003716598352816469_u128);
2248        let first_pos_difficulty = U256::ZERO;
2249        assert!(chainspec
2250            .fork(EthereumHardfork::Paris)
2251            .active_at_ttd(first_pos_block_ttd, first_pos_difficulty));
2252    }
2253
2254    #[test]
2255    fn geth_genesis_with_shanghai() {
2256        let geth_genesis = r#"
2257        {
2258          "config": {
2259            "chainId": 1337,
2260            "homesteadBlock": 0,
2261            "eip150Block": 0,
2262            "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2263            "eip155Block": 0,
2264            "eip158Block": 0,
2265            "byzantiumBlock": 0,
2266            "constantinopleBlock": 0,
2267            "petersburgBlock": 0,
2268            "istanbulBlock": 0,
2269            "muirGlacierBlock": 0,
2270            "berlinBlock": 0,
2271            "londonBlock": 0,
2272            "arrowGlacierBlock": 0,
2273            "grayGlacierBlock": 0,
2274            "shanghaiTime": 0,
2275            "cancunTime": 1,
2276            "terminalTotalDifficulty": 0,
2277            "terminalTotalDifficultyPassed": true,
2278            "ethash": {}
2279          },
2280          "nonce": "0x0",
2281          "timestamp": "0x0",
2282          "extraData": "0x",
2283          "gasLimit": "0x4c4b40",
2284          "difficulty": "0x1",
2285          "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2286          "coinbase": "0x0000000000000000000000000000000000000000",
2287          "alloc": {
2288            "658bdf435d810c91414ec09147daa6db62406379": {
2289              "balance": "0x487a9a304539440000"
2290            },
2291            "aa00000000000000000000000000000000000000": {
2292              "code": "0x6042",
2293              "storage": {
2294                "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000000",
2295                "0x0100000000000000000000000000000000000000000000000000000000000000": "0x0100000000000000000000000000000000000000000000000000000000000000",
2296                "0x0200000000000000000000000000000000000000000000000000000000000000": "0x0200000000000000000000000000000000000000000000000000000000000000",
2297                "0x0300000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000303"
2298              },
2299              "balance": "0x1",
2300              "nonce": "0x1"
2301            },
2302            "bb00000000000000000000000000000000000000": {
2303              "code": "0x600154600354",
2304              "storage": {
2305                "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000000",
2306                "0x0100000000000000000000000000000000000000000000000000000000000000": "0x0100000000000000000000000000000000000000000000000000000000000000",
2307                "0x0200000000000000000000000000000000000000000000000000000000000000": "0x0200000000000000000000000000000000000000000000000000000000000000",
2308                "0x0300000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000303"
2309              },
2310              "balance": "0x2",
2311              "nonce": "0x1"
2312            }
2313          },
2314          "number": "0x0",
2315          "gasUsed": "0x0",
2316          "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2317          "baseFeePerGas": "0x3b9aca00"
2318        }
2319        "#;
2320
2321        let genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
2322        let chainspec = ChainSpec::from(genesis);
2323
2324        // assert a bunch of hardforks that should be set
2325        assert_eq!(
2326            chainspec.hardforks.get(EthereumHardfork::Homestead).unwrap(),
2327            ForkCondition::Block(0)
2328        );
2329        assert_eq!(
2330            chainspec.hardforks.get(EthereumHardfork::Tangerine).unwrap(),
2331            ForkCondition::Block(0)
2332        );
2333        assert_eq!(
2334            chainspec.hardforks.get(EthereumHardfork::SpuriousDragon).unwrap(),
2335            ForkCondition::Block(0)
2336        );
2337        assert_eq!(
2338            chainspec.hardforks.get(EthereumHardfork::Byzantium).unwrap(),
2339            ForkCondition::Block(0)
2340        );
2341        assert_eq!(
2342            chainspec.hardforks.get(EthereumHardfork::Constantinople).unwrap(),
2343            ForkCondition::Block(0)
2344        );
2345        assert_eq!(
2346            chainspec.hardforks.get(EthereumHardfork::Petersburg).unwrap(),
2347            ForkCondition::Block(0)
2348        );
2349        assert_eq!(
2350            chainspec.hardforks.get(EthereumHardfork::Istanbul).unwrap(),
2351            ForkCondition::Block(0)
2352        );
2353        assert_eq!(
2354            chainspec.hardforks.get(EthereumHardfork::MuirGlacier).unwrap(),
2355            ForkCondition::Block(0)
2356        );
2357        assert_eq!(
2358            chainspec.hardforks.get(EthereumHardfork::Berlin).unwrap(),
2359            ForkCondition::Block(0)
2360        );
2361        assert_eq!(
2362            chainspec.hardforks.get(EthereumHardfork::London).unwrap(),
2363            ForkCondition::Block(0)
2364        );
2365        assert_eq!(
2366            chainspec.hardforks.get(EthereumHardfork::ArrowGlacier).unwrap(),
2367            ForkCondition::Block(0)
2368        );
2369        assert_eq!(
2370            chainspec.hardforks.get(EthereumHardfork::GrayGlacier).unwrap(),
2371            ForkCondition::Block(0)
2372        );
2373
2374        // including time based hardforks
2375        assert_eq!(
2376            chainspec.hardforks.get(EthereumHardfork::Shanghai).unwrap(),
2377            ForkCondition::Timestamp(0)
2378        );
2379
2380        // including time based hardforks
2381        assert_eq!(
2382            chainspec.hardforks.get(EthereumHardfork::Cancun).unwrap(),
2383            ForkCondition::Timestamp(1)
2384        );
2385
2386        // alloc key -> expected rlp mapping
2387        let key_rlp = vec![
2388            (
2389                hex!("0x658bdf435d810c91414ec09147daa6db62406379"),
2390                &hex!(
2391                    "0xf84d8089487a9a304539440000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
2392                )[..],
2393            ),
2394            (
2395                hex!("0xaa00000000000000000000000000000000000000"),
2396                &hex!(
2397                    "0xf8440101a08afc95b7d18a226944b9c2070b6bda1c3a36afcc3730429d47579c94b9fe5850a0ce92c756baff35fa740c3557c1a971fd24d2d35b7c8e067880d50cd86bb0bc99"
2398                )[..],
2399            ),
2400            (
2401                hex!("0xbb00000000000000000000000000000000000000"),
2402                &hex!(
2403                    "0xf8440102a08afc95b7d18a226944b9c2070b6bda1c3a36afcc3730429d47579c94b9fe5850a0e25a53cbb501cec2976b393719c63d832423dd70a458731a0b64e4847bbca7d2"
2404                )[..],
2405            ),
2406        ];
2407
2408        for (key, expected_rlp) in key_rlp {
2409            let account = chainspec.genesis.alloc.get(&key).expect("account should exist");
2410            assert_eq!(&alloy_rlp::encode(TrieAccount::from(account.clone())), expected_rlp);
2411        }
2412
2413        let expected_state_root: B256 =
2414            hex!("0x078dc6061b1d8eaa8493384b59c9c65ceb917201221d08b80c4de6770b6ec7e7").into();
2415        assert_eq!(chainspec.genesis_header().state_root, expected_state_root);
2416
2417        assert_eq!(chainspec.genesis_header().withdrawals_root, Some(EMPTY_ROOT_HASH));
2418
2419        let expected_hash: B256 =
2420            hex!("0x1fc027d65f820d3eef441ebeec139ebe09e471cf98516dce7b5643ccb27f418c").into();
2421        let hash = chainspec.genesis_hash();
2422        assert_eq!(hash, expected_hash);
2423    }
2424
2425    #[test]
2426    fn hive_geth_json() {
2427        let hive_json = r#"
2428        {
2429            "nonce": "0x0000000000000042",
2430            "difficulty": "0x2123456",
2431            "mixHash": "0x123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234",
2432            "coinbase": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2433            "timestamp": "0x123456",
2434            "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2435            "extraData": "0xfafbfcfd",
2436            "gasLimit": "0x2fefd8",
2437            "alloc": {
2438                "dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6": {
2439                    "balance": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
2440                },
2441                "e6716f9544a56c530d868e4bfbacb172315bdead": {
2442                    "balance": "0x11",
2443                    "code": "0x12"
2444                },
2445                "b9c015918bdaba24b4ff057a92a3873d6eb201be": {
2446                    "balance": "0x21",
2447                    "storage": {
2448                        "0x0000000000000000000000000000000000000000000000000000000000000001": "0x22"
2449                    }
2450                },
2451                "1a26338f0d905e295fccb71fa9ea849ffa12aaf4": {
2452                    "balance": "0x31",
2453                    "nonce": "0x32"
2454                },
2455                "0000000000000000000000000000000000000001": {
2456                    "balance": "0x41"
2457                },
2458                "0000000000000000000000000000000000000002": {
2459                    "balance": "0x51"
2460                },
2461                "0000000000000000000000000000000000000003": {
2462                    "balance": "0x61"
2463                },
2464                "0000000000000000000000000000000000000004": {
2465                    "balance": "0x71"
2466                }
2467            },
2468            "config": {
2469                "ethash": {},
2470                "chainId": 10,
2471                "homesteadBlock": 0,
2472                "eip150Block": 0,
2473                "eip155Block": 0,
2474                "eip158Block": 0,
2475                "byzantiumBlock": 0,
2476                "constantinopleBlock": 0,
2477                "petersburgBlock": 0,
2478                "istanbulBlock": 0
2479            }
2480        }
2481        "#;
2482
2483        let genesis = serde_json::from_str::<Genesis>(hive_json).unwrap();
2484        let chainspec: ChainSpec = genesis.into();
2485        assert_eq!(chainspec.chain, Chain::from_named(NamedChain::Optimism));
2486        let expected_state_root: B256 =
2487            hex!("0x9a6049ac535e3dc7436c189eaa81c73f35abd7f282ab67c32944ff0301d63360").into();
2488        assert_eq!(chainspec.genesis_header().state_root, expected_state_root);
2489        let hard_forks = vec![
2490            EthereumHardfork::Byzantium,
2491            EthereumHardfork::Homestead,
2492            EthereumHardfork::Istanbul,
2493            EthereumHardfork::Petersburg,
2494            EthereumHardfork::Constantinople,
2495        ];
2496        for fork in hard_forks {
2497            assert_eq!(chainspec.hardforks.get(fork).unwrap(), ForkCondition::Block(0));
2498        }
2499
2500        let expected_hash: B256 =
2501            hex!("0x5ae31c6522bd5856129f66be3d582b842e4e9faaa87f21cce547128339a9db3c").into();
2502        let hash = chainspec.genesis_header().hash_slow();
2503        assert_eq!(hash, expected_hash);
2504    }
2505
2506    #[test]
2507    fn test_hive_paris_block_genesis_json() {
2508        // this tests that we can handle `parisBlock` in the genesis json and can use it to output
2509        // a correct forkid
2510        let hive_paris = r#"
2511        {
2512          "config": {
2513            "ethash": {},
2514            "chainId": 3503995874084926,
2515            "homesteadBlock": 0,
2516            "eip150Block": 6,
2517            "eip155Block": 12,
2518            "eip158Block": 12,
2519            "byzantiumBlock": 18,
2520            "constantinopleBlock": 24,
2521            "petersburgBlock": 30,
2522            "istanbulBlock": 36,
2523            "muirGlacierBlock": 42,
2524            "berlinBlock": 48,
2525            "londonBlock": 54,
2526            "arrowGlacierBlock": 60,
2527            "grayGlacierBlock": 66,
2528            "mergeNetsplitBlock": 72,
2529            "terminalTotalDifficulty": 9454784,
2530            "shanghaiTime": 780,
2531            "cancunTime": 840
2532          },
2533          "nonce": "0x0",
2534          "timestamp": "0x0",
2535          "extraData": "0x68697665636861696e",
2536          "gasLimit": "0x23f3e20",
2537          "difficulty": "0x20000",
2538          "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2539          "coinbase": "0x0000000000000000000000000000000000000000",
2540          "alloc": {
2541            "000f3df6d732807ef1319fb7b8bb8522d0beac02": {
2542              "code": "0x3373fffffffffffffffffffffffffffffffffffffffe14604d57602036146024575f5ffd5b5f35801560495762001fff810690815414603c575f5ffd5b62001fff01545f5260205ff35b5f5ffd5b62001fff42064281555f359062001fff015500",
2543              "balance": "0x2a"
2544            },
2545            "0c2c51a0990aee1d73c1228de158688341557508": {
2546              "balance": "0xc097ce7bc90715b34b9f1000000000"
2547            },
2548            "14e46043e63d0e3cdcf2530519f4cfaf35058cb2": {
2549              "balance": "0xc097ce7bc90715b34b9f1000000000"
2550            },
2551            "16c57edf7fa9d9525378b0b81bf8a3ced0620c1c": {
2552              "balance": "0xc097ce7bc90715b34b9f1000000000"
2553            },
2554            "1f4924b14f34e24159387c0a4cdbaa32f3ddb0cf": {
2555              "balance": "0xc097ce7bc90715b34b9f1000000000"
2556            },
2557            "1f5bde34b4afc686f136c7a3cb6ec376f7357759": {
2558              "balance": "0xc097ce7bc90715b34b9f1000000000"
2559            },
2560            "2d389075be5be9f2246ad654ce152cf05990b209": {
2561              "balance": "0xc097ce7bc90715b34b9f1000000000"
2562            },
2563            "3ae75c08b4c907eb63a8960c45b86e1e9ab6123c": {
2564              "balance": "0xc097ce7bc90715b34b9f1000000000"
2565            },
2566            "4340ee1b812acb40a1eb561c019c327b243b92df": {
2567              "balance": "0xc097ce7bc90715b34b9f1000000000"
2568            },
2569            "4a0f1452281bcec5bd90c3dce6162a5995bfe9df": {
2570              "balance": "0xc097ce7bc90715b34b9f1000000000"
2571            },
2572            "4dde844b71bcdf95512fb4dc94e84fb67b512ed8": {
2573              "balance": "0xc097ce7bc90715b34b9f1000000000"
2574            },
2575            "5f552da00dfb4d3749d9e62dcee3c918855a86a0": {
2576              "balance": "0xc097ce7bc90715b34b9f1000000000"
2577            },
2578            "654aa64f5fbefb84c270ec74211b81ca8c44a72e": {
2579              "balance": "0xc097ce7bc90715b34b9f1000000000"
2580            },
2581            "717f8aa2b982bee0e29f573d31df288663e1ce16": {
2582              "balance": "0xc097ce7bc90715b34b9f1000000000"
2583            },
2584            "7435ed30a8b4aeb0877cef0c6e8cffe834eb865f": {
2585              "balance": "0xc097ce7bc90715b34b9f1000000000"
2586            },
2587            "83c7e323d189f18725ac510004fdc2941f8c4a78": {
2588              "balance": "0xc097ce7bc90715b34b9f1000000000"
2589            },
2590            "84e75c28348fb86acea1a93a39426d7d60f4cc46": {
2591              "balance": "0xc097ce7bc90715b34b9f1000000000"
2592            },
2593            "8bebc8ba651aee624937e7d897853ac30c95a067": {
2594              "storage": {
2595                "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000001",
2596                "0x0000000000000000000000000000000000000000000000000000000000000002": "0x0000000000000000000000000000000000000000000000000000000000000002",
2597                "0x0000000000000000000000000000000000000000000000000000000000000003": "0x0000000000000000000000000000000000000000000000000000000000000003"
2598              },
2599              "balance": "0x1",
2600              "nonce": "0x1"
2601            },
2602            "c7b99a164efd027a93f147376cc7da7c67c6bbe0": {
2603              "balance": "0xc097ce7bc90715b34b9f1000000000"
2604            },
2605            "d803681e487e6ac18053afc5a6cd813c86ec3e4d": {
2606              "balance": "0xc097ce7bc90715b34b9f1000000000"
2607            },
2608            "e7d13f7aa2a838d24c59b40186a0aca1e21cffcc": {
2609              "balance": "0xc097ce7bc90715b34b9f1000000000"
2610            },
2611            "eda8645ba6948855e3b3cd596bbb07596d59c603": {
2612              "balance": "0xc097ce7bc90715b34b9f1000000000"
2613            }
2614          },
2615          "number": "0x0",
2616          "gasUsed": "0x0",
2617          "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2618          "baseFeePerGas": null,
2619          "excessBlobGas": null,
2620          "blobGasUsed": null
2621        }
2622        "#;
2623
2624        // check that it deserializes properly
2625        let genesis: Genesis = serde_json::from_str(hive_paris).unwrap();
2626        let chainspec = ChainSpec::from(genesis);
2627
2628        // make sure we are at ForkHash("bc0c2605") with Head post-cancun
2629        let expected_forkid = ForkId { hash: ForkHash(hex!("0xbc0c2605")), next: 0 };
2630        let got_forkid =
2631            chainspec.fork_id(&Head { number: 73, timestamp: 840, ..Default::default() });
2632
2633        // check that they're the same
2634        assert_eq!(got_forkid, expected_forkid);
2635        // Check that paris block and final difficulty are set correctly
2636        assert_eq!(chainspec.paris_block_and_final_difficulty, Some((72, U256::from(9454784))));
2637    }
2638
2639    #[test]
2640    fn test_parse_genesis_json() {
2641        let s = r#"{"config":{"ethash":{},"chainId":1337,"homesteadBlock":0,"eip150Block":0,"eip155Block":0,"eip158Block":0,"byzantiumBlock":0,"constantinopleBlock":0,"petersburgBlock":0,"istanbulBlock":0,"berlinBlock":0,"londonBlock":0,"terminalTotalDifficulty":0,"terminalTotalDifficultyPassed":true,"shanghaiTime":0},"nonce":"0x0","timestamp":"0x0","extraData":"0x","gasLimit":"0x4c4b40","difficulty":"0x1","mixHash":"0x0000000000000000000000000000000000000000000000000000000000000000","coinbase":"0x0000000000000000000000000000000000000000","alloc":{"658bdf435d810c91414ec09147daa6db62406379":{"balance":"0x487a9a304539440000"},"aa00000000000000000000000000000000000000":{"code":"0x6042","storage":{"0x0000000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000000","0x0100000000000000000000000000000000000000000000000000000000000000":"0x0100000000000000000000000000000000000000000000000000000000000000","0x0200000000000000000000000000000000000000000000000000000000000000":"0x0200000000000000000000000000000000000000000000000000000000000000","0x0300000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000303"},"balance":"0x1","nonce":"0x1"},"bb00000000000000000000000000000000000000":{"code":"0x600154600354","storage":{"0x0000000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000000","0x0100000000000000000000000000000000000000000000000000000000000000":"0x0100000000000000000000000000000000000000000000000000000000000000","0x0200000000000000000000000000000000000000000000000000000000000000":"0x0200000000000000000000000000000000000000000000000000000000000000","0x0300000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000303"},"balance":"0x2","nonce":"0x1"}},"number":"0x0","gasUsed":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","baseFeePerGas":"0x1337"}"#;
2642        let genesis: Genesis = serde_json::from_str(s).unwrap();
2643        let acc = genesis
2644            .alloc
2645            .get(&"0xaa00000000000000000000000000000000000000".parse::<Address>().unwrap())
2646            .unwrap();
2647        assert_eq!(acc.balance, U256::from(1));
2648        assert_eq!(genesis.base_fee_per_gas, Some(0x1337));
2649    }
2650
2651    #[test]
2652    fn test_parse_cancun_genesis_json() {
2653        let s = r#"{"config":{"ethash":{},"chainId":1337,"homesteadBlock":0,"eip150Block":0,"eip155Block":0,"eip158Block":0,"byzantiumBlock":0,"constantinopleBlock":0,"petersburgBlock":0,"istanbulBlock":0,"berlinBlock":0,"londonBlock":0,"terminalTotalDifficulty":0,"terminalTotalDifficultyPassed":true,"shanghaiTime":0,"cancunTime":4661},"nonce":"0x0","timestamp":"0x0","extraData":"0x","gasLimit":"0x4c4b40","difficulty":"0x1","mixHash":"0x0000000000000000000000000000000000000000000000000000000000000000","coinbase":"0x0000000000000000000000000000000000000000","alloc":{"658bdf435d810c91414ec09147daa6db62406379":{"balance":"0x487a9a304539440000"},"aa00000000000000000000000000000000000000":{"code":"0x6042","storage":{"0x0000000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000000","0x0100000000000000000000000000000000000000000000000000000000000000":"0x0100000000000000000000000000000000000000000000000000000000000000","0x0200000000000000000000000000000000000000000000000000000000000000":"0x0200000000000000000000000000000000000000000000000000000000000000","0x0300000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000303"},"balance":"0x1","nonce":"0x1"},"bb00000000000000000000000000000000000000":{"code":"0x600154600354","storage":{"0x0000000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000000","0x0100000000000000000000000000000000000000000000000000000000000000":"0x0100000000000000000000000000000000000000000000000000000000000000","0x0200000000000000000000000000000000000000000000000000000000000000":"0x0200000000000000000000000000000000000000000000000000000000000000","0x0300000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000303"},"balance":"0x2","nonce":"0x1"}},"number":"0x0","gasUsed":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","baseFeePerGas":"0x3b9aca00"}"#;
2654        let genesis: Genesis = serde_json::from_str(s).unwrap();
2655        let acc = genesis
2656            .alloc
2657            .get(&"0xaa00000000000000000000000000000000000000".parse::<Address>().unwrap())
2658            .unwrap();
2659        assert_eq!(acc.balance, U256::from(1));
2660        // assert that the cancun time was picked up
2661        assert_eq!(genesis.config.cancun_time, Some(4661));
2662    }
2663
2664    #[test]
2665    fn test_parse_prague_genesis_all_formats() {
2666        let s = r#"{"config":{"ethash":{},"chainId":1337,"homesteadBlock":0,"eip150Block":0,"eip155Block":0,"eip158Block":0,"byzantiumBlock":0,"constantinopleBlock":0,"petersburgBlock":0,"istanbulBlock":0,"berlinBlock":0,"londonBlock":0,"terminalTotalDifficulty":0,"terminalTotalDifficultyPassed":true,"shanghaiTime":0,"cancunTime":4661, "pragueTime": 4662},"nonce":"0x0","timestamp":"0x0","extraData":"0x","gasLimit":"0x4c4b40","difficulty":"0x1","mixHash":"0x0000000000000000000000000000000000000000000000000000000000000000","coinbase":"0x0000000000000000000000000000000000000000","alloc":{"658bdf435d810c91414ec09147daa6db62406379":{"balance":"0x487a9a304539440000"},"aa00000000000000000000000000000000000000":{"code":"0x6042","storage":{"0x0000000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000000","0x0100000000000000000000000000000000000000000000000000000000000000":"0x0100000000000000000000000000000000000000000000000000000000000000","0x0200000000000000000000000000000000000000000000000000000000000000":"0x0200000000000000000000000000000000000000000000000000000000000000","0x0300000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000303"},"balance":"0x1","nonce":"0x1"},"bb00000000000000000000000000000000000000":{"code":"0x600154600354","storage":{"0x0000000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000000","0x0100000000000000000000000000000000000000000000000000000000000000":"0x0100000000000000000000000000000000000000000000000000000000000000","0x0200000000000000000000000000000000000000000000000000000000000000":"0x0200000000000000000000000000000000000000000000000000000000000000","0x0300000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000303"},"balance":"0x2","nonce":"0x1"}},"number":"0x0","gasUsed":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","baseFeePerGas":"0x3b9aca00"}"#;
2667        let genesis: Genesis = serde_json::from_str(s).unwrap();
2668
2669        // assert that the alloc was picked up
2670        let acc = genesis
2671            .alloc
2672            .get(&"0xaa00000000000000000000000000000000000000".parse::<Address>().unwrap())
2673            .unwrap();
2674        assert_eq!(acc.balance, U256::from(1));
2675        // assert that the cancun time was picked up
2676        assert_eq!(genesis.config.cancun_time, Some(4661));
2677        // assert that the prague time was picked up
2678        assert_eq!(genesis.config.prague_time, Some(4662));
2679    }
2680
2681    #[test]
2682    fn test_parse_cancun_genesis_all_formats() {
2683        let s = r#"{"config":{"ethash":{},"chainId":1337,"homesteadBlock":0,"eip150Block":0,"eip155Block":0,"eip158Block":0,"byzantiumBlock":0,"constantinopleBlock":0,"petersburgBlock":0,"istanbulBlock":0,"berlinBlock":0,"londonBlock":0,"terminalTotalDifficulty":0,"terminalTotalDifficultyPassed":true,"shanghaiTime":0,"cancunTime":4661},"nonce":"0x0","timestamp":"0x0","extraData":"0x","gasLimit":"0x4c4b40","difficulty":"0x1","mixHash":"0x0000000000000000000000000000000000000000000000000000000000000000","coinbase":"0x0000000000000000000000000000000000000000","alloc":{"658bdf435d810c91414ec09147daa6db62406379":{"balance":"0x487a9a304539440000"},"aa00000000000000000000000000000000000000":{"code":"0x6042","storage":{"0x0000000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000000","0x0100000000000000000000000000000000000000000000000000000000000000":"0x0100000000000000000000000000000000000000000000000000000000000000","0x0200000000000000000000000000000000000000000000000000000000000000":"0x0200000000000000000000000000000000000000000000000000000000000000","0x0300000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000303"},"balance":"0x1","nonce":"0x1"},"bb00000000000000000000000000000000000000":{"code":"0x600154600354","storage":{"0x0000000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000000","0x0100000000000000000000000000000000000000000000000000000000000000":"0x0100000000000000000000000000000000000000000000000000000000000000","0x0200000000000000000000000000000000000000000000000000000000000000":"0x0200000000000000000000000000000000000000000000000000000000000000","0x0300000000000000000000000000000000000000000000000000000000000000":"0x0000000000000000000000000000000000000000000000000000000000000303"},"balance":"0x2","nonce":"0x1"}},"number":"0x0","gasUsed":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","baseFeePerGas":"0x3b9aca00"}"#;
2684        let genesis: Genesis = serde_json::from_str(s).unwrap();
2685
2686        // assert that the alloc was picked up
2687        let acc = genesis
2688            .alloc
2689            .get(&"0xaa00000000000000000000000000000000000000".parse::<Address>().unwrap())
2690            .unwrap();
2691        assert_eq!(acc.balance, U256::from(1));
2692        // assert that the cancun time was picked up
2693        assert_eq!(genesis.config.cancun_time, Some(4661));
2694    }
2695
2696    #[test]
2697    fn test_paris_block_and_total_difficulty() {
2698        let genesis = Genesis { gas_limit: 0x2fefd8u64, ..Default::default() };
2699        let paris_chainspec = ChainSpecBuilder::default()
2700            .chain(Chain::from_id(1337))
2701            .genesis(genesis)
2702            .paris_activated()
2703            .build();
2704        assert_eq!(paris_chainspec.paris_block_and_final_difficulty, Some((0, U256::ZERO)));
2705    }
2706
2707    #[test]
2708    fn test_default_cancun_header_forkhash() {
2709        // set the gas limit from the hive test genesis according to the hash
2710        let genesis = Genesis { gas_limit: 0x2fefd8u64, ..Default::default() };
2711        let default_chainspec = ChainSpecBuilder::default()
2712            .chain(Chain::from_id(1337))
2713            .genesis(genesis)
2714            .cancun_activated()
2715            .build();
2716        let mut header = default_chainspec.genesis_header().clone();
2717
2718        // set the state root to the same as in the hive test the hash was pulled from
2719        header.state_root =
2720            B256::from_str("0x62e2595e017f0ca23e08d17221010721a71c3ae932f4ea3cb12117786bb392d4")
2721                .unwrap();
2722
2723        // shanghai is activated so we should have a withdrawals root
2724        assert_eq!(header.withdrawals_root, Some(EMPTY_WITHDRAWALS));
2725
2726        // cancun is activated so we should have a zero parent beacon block root, zero blob gas
2727        // used, and zero excess blob gas
2728        assert_eq!(header.parent_beacon_block_root, Some(B256::ZERO));
2729        assert_eq!(header.blob_gas_used, Some(0));
2730        assert_eq!(header.excess_blob_gas, Some(0));
2731
2732        // check the genesis hash
2733        let genesis_hash = header.hash_slow();
2734        let expected_hash =
2735            b256!("0x16bb7c59613a5bad3f7c04a852fd056545ade2483968d9a25a1abb05af0c4d37");
2736        assert_eq!(genesis_hash, expected_hash);
2737
2738        // check that the forkhash is correct
2739        let expected_forkhash = ForkHash(hex!("0x8062457a"));
2740        assert_eq!(ForkHash::from(genesis_hash), expected_forkhash);
2741    }
2742
2743    #[test]
2744    fn test_amsterdam_genesis_slot_number() {
2745        // a genesis-provided slot number is used as-is
2746        let genesis =
2747            Genesis { gas_limit: 0x2fefd8u64, ..Default::default() }.with_slot_number(Some(999));
2748        let chainspec = ChainSpecBuilder::default()
2749            .chain(Chain::from_id(1337))
2750            .genesis(genesis)
2751            .amsterdam_activated()
2752            .build();
2753        assert_eq!(chainspec.genesis_header().slot_number, Some(999));
2754
2755        // an omitted slot number defaults to 0
2756        let genesis = Genesis { gas_limit: 0x2fefd8u64, ..Default::default() };
2757        let chainspec = ChainSpecBuilder::default()
2758            .chain(Chain::from_id(1337))
2759            .genesis(genesis)
2760            .amsterdam_activated()
2761            .build();
2762        assert_eq!(chainspec.genesis_header().slot_number, Some(0));
2763    }
2764
2765    #[test]
2766    fn holesky_paris_activated_at_genesis() {
2767        assert!(HOLESKY
2768            .fork(EthereumHardfork::Paris)
2769            .active_at_ttd(HOLESKY.genesis.difficulty, HOLESKY.genesis.difficulty));
2770    }
2771
2772    #[test]
2773    fn test_genesis_format_deserialization() {
2774        // custom genesis with chain config
2775        let config = ChainConfig {
2776            chain_id: 2600,
2777            homestead_block: Some(0),
2778            eip150_block: Some(0),
2779            eip155_block: Some(0),
2780            eip158_block: Some(0),
2781            byzantium_block: Some(0),
2782            constantinople_block: Some(0),
2783            petersburg_block: Some(0),
2784            istanbul_block: Some(0),
2785            berlin_block: Some(0),
2786            london_block: Some(0),
2787            shanghai_time: Some(0),
2788            terminal_total_difficulty: Some(U256::ZERO),
2789            terminal_total_difficulty_passed: true,
2790            ..Default::default()
2791        };
2792        // genesis
2793        let genesis = Genesis {
2794            config,
2795            nonce: 0,
2796            timestamp: 1698688670,
2797            gas_limit: 5000,
2798            difficulty: U256::ZERO,
2799            mix_hash: B256::ZERO,
2800            coinbase: Address::ZERO,
2801            ..Default::default()
2802        };
2803
2804        // seed accounts after genesis struct created
2805        let address = hex!("0x6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").into();
2806        let account = GenesisAccount::default().with_balance(U256::from(33));
2807        let genesis = genesis.extend_accounts(HashMap::from([(address, account)]));
2808
2809        // ensure genesis is deserialized correctly
2810        let serialized_genesis = serde_json::to_string(&genesis).unwrap();
2811        let deserialized_genesis: Genesis = serde_json::from_str(&serialized_genesis).unwrap();
2812
2813        assert_eq!(genesis, deserialized_genesis);
2814    }
2815
2816    #[test]
2817    fn check_fork_id_chainspec_with_fork_condition_never() {
2818        let spec: ChainSpec = ChainSpec {
2819            chain: Chain::mainnet(),
2820            genesis: Genesis::default(),
2821            hardforks: ChainHardforks::new(vec![(
2822                EthereumHardfork::Frontier.boxed(),
2823                ForkCondition::Never,
2824            )]),
2825            paris_block_and_final_difficulty: None,
2826            deposit_contract: None,
2827            ..Default::default()
2828        };
2829
2830        assert_eq!(spec.hardfork_fork_id(EthereumHardfork::Frontier), None);
2831    }
2832
2833    #[test]
2834    fn check_fork_filter_chainspec_with_fork_condition_never() {
2835        let spec: ChainSpec = ChainSpec {
2836            chain: Chain::mainnet(),
2837            genesis: Genesis::default(),
2838            hardforks: ChainHardforks::new(vec![(
2839                EthereumHardfork::Shanghai.boxed(),
2840                ForkCondition::Never,
2841            )]),
2842            paris_block_and_final_difficulty: None,
2843            deposit_contract: None,
2844            ..Default::default()
2845        };
2846
2847        assert_eq!(spec.hardfork_fork_filter(EthereumHardfork::Shanghai), None);
2848    }
2849
2850    #[test]
2851    fn latest_eth_mainnet_fork_id() {
2852        // BPO2
2853        assert_eq!(ForkId { hash: ForkHash(hex!("0x07c9462e")), next: 0 }, MAINNET.latest_fork_id())
2854    }
2855
2856    #[test]
2857    fn latest_hoodi_mainnet_fork_id() {
2858        // BPO2
2859        assert_eq!(ForkId { hash: ForkHash(hex!("0x23aa1351")), next: 0 }, HOODI.latest_fork_id())
2860    }
2861
2862    #[test]
2863    fn latest_holesky_mainnet_fork_id() {
2864        // BPO2
2865        assert_eq!(ForkId { hash: ForkHash(hex!("0x9bc6cb31")), next: 0 }, HOLESKY.latest_fork_id())
2866    }
2867
2868    #[test]
2869    fn latest_sepolia_mainnet_fork_id() {
2870        // Amsterdam
2871        assert_eq!(ForkId { hash: ForkHash(hex!("0x6c1d9423")), next: 0 }, SEPOLIA.latest_fork_id())
2872    }
2873
2874    #[test]
2875    fn test_fork_order_ethereum_mainnet() {
2876        let genesis = Genesis {
2877            config: ChainConfig {
2878                chain_id: 0,
2879                homestead_block: Some(0),
2880                dao_fork_block: Some(0),
2881                dao_fork_support: false,
2882                eip150_block: Some(0),
2883                eip155_block: Some(0),
2884                eip158_block: Some(0),
2885                byzantium_block: Some(0),
2886                constantinople_block: Some(0),
2887                petersburg_block: Some(0),
2888                istanbul_block: Some(0),
2889                muir_glacier_block: Some(0),
2890                berlin_block: Some(0),
2891                london_block: Some(0),
2892                arrow_glacier_block: Some(0),
2893                gray_glacier_block: Some(0),
2894                merge_netsplit_block: Some(0),
2895                shanghai_time: Some(0),
2896                cancun_time: Some(0),
2897                terminal_total_difficulty: Some(U256::ZERO),
2898                ..Default::default()
2899            },
2900            ..Default::default()
2901        };
2902
2903        let chain_spec: ChainSpec = genesis.into();
2904
2905        let hardforks: Vec<_> = chain_spec.hardforks.forks_iter().map(|(h, _)| h).collect();
2906        let expected_hardforks = vec![
2907            EthereumHardfork::Frontier.boxed(),
2908            EthereumHardfork::Homestead.boxed(),
2909            EthereumHardfork::Dao.boxed(),
2910            EthereumHardfork::Tangerine.boxed(),
2911            EthereumHardfork::SpuriousDragon.boxed(),
2912            EthereumHardfork::Byzantium.boxed(),
2913            EthereumHardfork::Constantinople.boxed(),
2914            EthereumHardfork::Petersburg.boxed(),
2915            EthereumHardfork::Istanbul.boxed(),
2916            EthereumHardfork::MuirGlacier.boxed(),
2917            EthereumHardfork::Berlin.boxed(),
2918            EthereumHardfork::London.boxed(),
2919            EthereumHardfork::ArrowGlacier.boxed(),
2920            EthereumHardfork::GrayGlacier.boxed(),
2921            EthereumHardfork::Paris.boxed(),
2922            EthereumHardfork::Shanghai.boxed(),
2923            EthereumHardfork::Cancun.boxed(),
2924        ];
2925
2926        assert!(expected_hardforks
2927            .iter()
2928            .zip(hardforks.iter())
2929            .all(|(expected, actual)| &**expected == *actual));
2930        assert_eq!(expected_hardforks.len(), hardforks.len());
2931    }
2932
2933    #[test]
2934    fn test_calc_base_block_reward() {
2935        // ((block number, td), reward)
2936        let cases = [
2937            // Pre-byzantium
2938            ((0, U256::ZERO), Some(ETH_TO_WEI * 5)),
2939            // Byzantium
2940            ((4370000, U256::ZERO), Some(ETH_TO_WEI * 3)),
2941            // Petersburg
2942            ((7280000, U256::ZERO), Some(ETH_TO_WEI * 2)),
2943            // Merge
2944            ((15537394, U256::from(58_750_000_000_000_000_000_000_u128)), None),
2945        ];
2946
2947        for ((block_number, _td), expected_reward) in cases {
2948            assert_eq!(base_block_reward(&*MAINNET, block_number), expected_reward);
2949        }
2950    }
2951
2952    #[test]
2953    fn test_calc_full_block_reward() {
2954        let base_reward = ETH_TO_WEI;
2955        let one_thirty_twoth_reward = base_reward >> 5;
2956
2957        // (num_ommers, reward)
2958        let cases = [
2959            (0, base_reward),
2960            (1, base_reward + one_thirty_twoth_reward),
2961            (2, base_reward + one_thirty_twoth_reward * 2),
2962        ];
2963
2964        for (num_ommers, expected_reward) in cases {
2965            assert_eq!(block_reward(base_reward, num_ommers), expected_reward);
2966        }
2967    }
2968
2969    #[test]
2970    fn blob_params_from_genesis() {
2971        let s = r#"{
2972            "blobSchedule": {
2973                "cancun":{
2974                    "baseFeeUpdateFraction":3338477,
2975                    "max":6,
2976                    "target":3
2977                },
2978                "prague":{
2979                    "baseFeeUpdateFraction":3338477,
2980                    "max":6,
2981                    "target":3
2982                }
2983            }
2984        }"#;
2985        let config: ChainConfig = serde_json::from_str(s).unwrap();
2986        let hardfork_params = config.blob_schedule_blob_params();
2987        let expected = BlobScheduleBlobParams {
2988            cancun: BlobParams {
2989                target_blob_count: 3,
2990                max_blob_count: 6,
2991                update_fraction: 3338477,
2992                min_blob_fee: BLOB_TX_MIN_BLOB_GASPRICE,
2993                max_blobs_per_tx: 6,
2994                blob_base_cost: 0,
2995            },
2996            prague: BlobParams {
2997                target_blob_count: 3,
2998                max_blob_count: 6,
2999                update_fraction: 3338477,
3000                min_blob_fee: BLOB_TX_MIN_BLOB_GASPRICE,
3001                max_blobs_per_tx: 6,
3002                blob_base_cost: 0,
3003            },
3004            ..Default::default()
3005        };
3006        assert_eq!(hardfork_params, expected);
3007    }
3008
3009    #[test]
3010    fn parse_perf_net_genesis() {
3011        let s = r#"{
3012    "config": {
3013        "chainId": 1,
3014        "homesteadBlock": 1150000,
3015        "daoForkBlock": 1920000,
3016        "daoForkSupport": true,
3017        "eip150Block": 2463000,
3018        "eip150Hash": "0x2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0",
3019        "eip155Block": 2675000,
3020        "eip158Block": 2675000,
3021        "byzantiumBlock": 4370000,
3022        "constantinopleBlock": 7280000,
3023        "petersburgBlock": 7280000,
3024        "istanbulBlock": 9069000,
3025        "muirGlacierBlock": 9200000,
3026        "berlinBlock": 12244000,
3027        "londonBlock": 12965000,
3028        "arrowGlacierBlock": 13773000,
3029        "grayGlacierBlock": 15050000,
3030        "terminalTotalDifficulty": 58750000000000000000000,
3031        "terminalTotalDifficultyPassed": true,
3032        "shanghaiTime": 1681338455,
3033        "cancunTime": 1710338135,
3034        "pragueTime": 1746612311,
3035        "ethash": {},
3036        "depositContractAddress": "0x00000000219ab540356cBB839Cbe05303d7705Fa",
3037        "blobSchedule": {
3038            "cancun": {
3039                "target": 3,
3040                "max": 6,
3041                "baseFeeUpdateFraction": 3338477
3042            },
3043            "prague": {
3044                "target": 6,
3045                "max": 9,
3046                "baseFeeUpdateFraction": 5007716
3047            }
3048        }
3049    },
3050    "nonce": "0x42",
3051    "timestamp": "0x0",
3052    "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
3053    "gasLimit": "0x1388",
3054    "difficulty": "0x400000000",
3055    "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
3056    "coinbase": "0x0000000000000000000000000000000000000000",
3057    "number": "0x0",
3058    "gasUsed": "0x0",
3059    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
3060    "baseFeePerGas": null
3061}"#;
3062
3063        let genesis = serde_json::from_str::<Genesis>(s).unwrap();
3064        let chainspec = ChainSpec::from_genesis(genesis);
3065        let activation = chainspec.hardforks.fork(EthereumHardfork::Paris);
3066        assert_eq!(
3067            activation,
3068            ForkCondition::TTD {
3069                activation_block_number: MAINNET_PARIS_BLOCK,
3070                total_difficulty: MAINNET_PARIS_TTD,
3071                fork_block: None,
3072            }
3073        )
3074    }
3075}