Skip to main content

reth_chainspec/
spec.rs

1pub use alloy_eips::eip1559::BaseFeeParams;
2
3use crate::{
4    constants::{MAINNET_DEPOSIT_CONTRACT, MAINNET_PRUNE_DELETE_LIMIT},
5    ethereum::SEPOLIA_PARIS_TTD,
6    holesky, hoodi, mainnet,
7    mainnet::{MAINNET_PARIS_BLOCK, MAINNET_PARIS_TTD},
8    sepolia,
9    sepolia::SEPOLIA_PARIS_BLOCK,
10    EthChainSpec,
11};
12use alloc::{
13    boxed::Box,
14    collections::BTreeMap,
15    format,
16    string::{String, ToString},
17    sync::Arc,
18    vec::Vec,
19};
20use alloy_chains::{Chain, NamedChain};
21use alloy_consensus::{
22    constants::{
23        EMPTY_WITHDRAWALS, HOLESKY_GENESIS_HASH, HOODI_GENESIS_HASH, MAINNET_GENESIS_HASH,
24        SEPOLIA_GENESIS_HASH,
25    },
26    Header,
27};
28use alloy_eips::{
29    eip1559::INITIAL_BASE_FEE, eip7685::EMPTY_REQUESTS_HASH, eip7840::BlobParams,
30    eip7892::BlobScheduleBlobParams, eip7928::EMPTY_BLOCK_ACCESS_LIST_HASH,
31};
32use alloy_genesis::{ChainConfig, Genesis};
33use alloy_primitives::{address, b256, Address, BlockNumber, B256, U256};
34use alloy_trie::root::state_root_ref_unhashed;
35use core::fmt::Debug;
36use derive_more::From;
37use reth_ethereum_forks::{
38    ChainHardforks, DisplayHardforks, EthereumHardfork, EthereumHardforks, ForkCondition,
39    ForkFilter, ForkFilterKey, ForkHash, ForkId, Hardfork, Hardforks, Head, DEV_HARDFORKS,
40};
41use reth_network_peers::{holesky_nodes, hoodi_nodes, mainnet_nodes, sepolia_nodes, NodeRecord};
42use reth_primitives_traits::{sync::LazyLock, BlockHeader, SealedHeader};
43use NamedChain as C;
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::ONE)),
193        hardforks,
194        deposit_contract: Some(DepositContract::new(
195            Address::repeat_byte(0x42),
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::ZERO)),
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::ZERO)),
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        match self.chain.try_into().ok()? {
775            C::Mainnet => Some(mainnet_nodes()),
776            C::Sepolia => Some(sepolia_nodes()),
777            C::Holesky => Some(holesky_nodes()),
778            C::Hoodi => Some(hoodi_nodes()),
779            _ => None,
780        }
781    }
782
783    /// Convert header to another type.
784    pub fn map_header<NewH: BlockHeader>(self, f: impl FnOnce(H) -> NewH) -> ChainSpec<NewH> {
785        let Self {
786            chain,
787            genesis,
788            genesis_header,
789            paris_block_and_final_difficulty,
790            hardforks,
791            deposit_contract,
792            base_fee_params,
793            prune_delete_limit,
794            blob_params,
795        } = self;
796        ChainSpec {
797            chain,
798            genesis,
799            genesis_header: SealedHeader::new_unhashed(f(genesis_header.into_header())),
800            paris_block_and_final_difficulty,
801            hardforks,
802            deposit_contract,
803            base_fee_params,
804            prune_delete_limit,
805            blob_params,
806        }
807    }
808}
809
810impl From<Genesis> for ChainSpec {
811    fn from(genesis: Genesis) -> Self {
812        // Block-based hardforks
813        let hardfork_opts = [
814            (EthereumHardfork::Frontier.boxed(), Some(0)),
815            (EthereumHardfork::Homestead.boxed(), genesis.config.homestead_block),
816            (EthereumHardfork::Dao.boxed(), genesis.config.dao_fork_block),
817            (EthereumHardfork::Tangerine.boxed(), genesis.config.eip150_block),
818            (EthereumHardfork::SpuriousDragon.boxed(), genesis.config.eip155_block),
819            (EthereumHardfork::Byzantium.boxed(), genesis.config.byzantium_block),
820            (EthereumHardfork::Constantinople.boxed(), genesis.config.constantinople_block),
821            (EthereumHardfork::Petersburg.boxed(), genesis.config.petersburg_block),
822            (EthereumHardfork::Istanbul.boxed(), genesis.config.istanbul_block),
823            (EthereumHardfork::MuirGlacier.boxed(), genesis.config.muir_glacier_block),
824            (EthereumHardfork::Berlin.boxed(), genesis.config.berlin_block),
825            (EthereumHardfork::London.boxed(), genesis.config.london_block),
826            (EthereumHardfork::ArrowGlacier.boxed(), genesis.config.arrow_glacier_block),
827            (EthereumHardfork::GrayGlacier.boxed(), genesis.config.gray_glacier_block),
828        ];
829        let mut hardforks = hardfork_opts
830            .into_iter()
831            .filter_map(|(hardfork, opt)| opt.map(|block| (hardfork, ForkCondition::Block(block))))
832            .collect::<Vec<_>>();
833
834        // We expect no new networks to be configured with the merge, so we ignore the TTD field
835        // and merge netsplit block from external genesis files. All existing networks that have
836        // merged should have a static ChainSpec already (namely mainnet and sepolia).
837        let paris_block_and_final_difficulty = if let Some(ttd) =
838            genesis.config.terminal_total_difficulty
839        {
840            hardforks.push((
841                EthereumHardfork::Paris.boxed(),
842                ForkCondition::TTD {
843                    // NOTE: this will not work properly if the merge is not activated at
844                    // genesis, and there is no merge netsplit block
845                    activation_block_number: genesis
846                        .config
847                        .merge_netsplit_block
848                        .or_else(|| {
849                            // due to this limitation we can't determine the merge block,
850                            // this is the case for perfnet testing for example
851                            // at the time of this fix, only two networks transitioned: MAINNET +
852                            // SEPOLIA and this parsing from genesis is used for shadowforking, so
853                            // we can reasonably assume that if the TTD and the chainid matches
854                            // those networks we use the activation
855                            // blocks of those networks
856                            match genesis.config.chain_id {
857                                1 if ttd == MAINNET_PARIS_TTD => return Some(MAINNET_PARIS_BLOCK),
858                                11155111 if ttd == SEPOLIA_PARIS_TTD => {
859                                    return Some(SEPOLIA_PARIS_BLOCK)
860                                }
861                                _ => {}
862                            };
863                            None
864                        })
865                        .unwrap_or_default(),
866                    total_difficulty: ttd,
867                    fork_block: genesis.config.merge_netsplit_block,
868                },
869            ));
870
871            genesis.config.merge_netsplit_block.map(|block| (block, ttd))
872        } else {
873            None
874        };
875
876        // Time-based hardforks
877        let time_hardfork_opts = [
878            (EthereumHardfork::Shanghai.boxed(), genesis.config.shanghai_time),
879            (EthereumHardfork::Cancun.boxed(), genesis.config.cancun_time),
880            (EthereumHardfork::Prague.boxed(), genesis.config.prague_time),
881            (EthereumHardfork::Osaka.boxed(), genesis.config.osaka_time),
882            (EthereumHardfork::Bpo1.boxed(), genesis.config.bpo1_time),
883            (EthereumHardfork::Bpo2.boxed(), genesis.config.bpo2_time),
884            (EthereumHardfork::Bpo3.boxed(), genesis.config.bpo3_time),
885            (EthereumHardfork::Bpo4.boxed(), genesis.config.bpo4_time),
886            (EthereumHardfork::Bpo5.boxed(), genesis.config.bpo5_time),
887            (EthereumHardfork::Amsterdam.boxed(), genesis.config.amsterdam_time),
888            (EthereumHardfork::Bogota.boxed(), genesis.config.bogota_time),
889        ];
890
891        let mut time_hardforks = time_hardfork_opts
892            .into_iter()
893            .filter_map(|(hardfork, opt)| {
894                opt.map(|time| (hardfork, ForkCondition::Timestamp(time)))
895            })
896            .collect::<Vec<_>>();
897
898        hardforks.append(&mut time_hardforks);
899
900        // Ordered Hardforks
901        let mainnet_hardforks: ChainHardforks = EthereumHardfork::mainnet().into();
902        let mainnet_order = mainnet_hardforks.forks_iter();
903
904        let mut ordered_hardforks = Vec::with_capacity(hardforks.len());
905        for (hardfork, _) in mainnet_order {
906            if let Some(pos) = hardforks.iter().position(|(e, _)| **e == *hardfork) {
907                ordered_hardforks.push(hardforks.remove(pos));
908            }
909        }
910
911        // append the remaining unknown hardforks to ensure we don't filter any out
912        ordered_hardforks.append(&mut hardforks);
913
914        // Extract blob parameters directly from blob_schedule
915        let blob_params = genesis.config.blob_schedule_blob_params();
916
917        // NOTE: in full node, we prune all receipts except the deposit contract's. We do not
918        // have the deployment block in the genesis file, so we use block zero. We use the same
919        // deposit topic as the mainnet contract if we have the deposit contract address in the
920        // genesis json.
921        let deposit_contract = genesis.config.deposit_contract_address.map(|address| {
922            DepositContract { address, block: 0, topic: MAINNET_DEPOSIT_CONTRACT.topic }
923        });
924
925        let hardforks = ChainHardforks::new(ordered_hardforks);
926
927        Self {
928            chain: genesis.config.chain_id.into(),
929            genesis_header: SealedHeader::new_unhashed(make_genesis_header(&genesis, &hardforks)),
930            genesis,
931            hardforks,
932            paris_block_and_final_difficulty,
933            deposit_contract,
934            blob_params,
935            ..Default::default()
936        }
937    }
938}
939
940impl<H: BlockHeader> Hardforks for ChainSpec<H> {
941    fn fork<HF: Hardfork>(&self, fork: HF) -> ForkCondition {
942        self.hardforks.fork(fork)
943    }
944
945    fn forks_iter(&self) -> impl Iterator<Item = (&dyn Hardfork, ForkCondition)> {
946        self.hardforks.forks_iter()
947    }
948
949    fn fork_id(&self, head: &Head) -> ForkId {
950        self.fork_id(head)
951    }
952
953    fn latest_fork_id(&self) -> ForkId {
954        self.latest_fork_id()
955    }
956
957    fn fork_filter(&self, head: Head) -> ForkFilter {
958        self.fork_filter(head)
959    }
960}
961
962impl<H: BlockHeader> EthereumHardforks for ChainSpec<H> {
963    fn ethereum_fork_activation(&self, fork: EthereumHardfork) -> ForkCondition {
964        self.fork(fork)
965    }
966}
967
968/// A trait for reading the current chainspec.
969#[auto_impl::auto_impl(&, Arc)]
970pub trait ChainSpecProvider: Debug + Send {
971    /// The chain spec type.
972    type ChainSpec: EthChainSpec + 'static;
973
974    /// Get an [`Arc`] to the chainspec.
975    fn chain_spec(&self) -> Arc<Self::ChainSpec>;
976}
977
978/// A helper to build custom chain specs
979#[derive(Debug, Default, Clone)]
980pub struct ChainSpecBuilder {
981    chain: Option<Chain>,
982    genesis: Option<Genesis>,
983    hardforks: ChainHardforks,
984}
985
986impl ChainSpecBuilder {
987    /// Construct a new builder from the mainnet chain spec.
988    pub fn mainnet() -> Self {
989        Self {
990            chain: Some(MAINNET.chain),
991            genesis: Some(MAINNET.genesis.clone()),
992            hardforks: MAINNET.hardforks.clone(),
993        }
994    }
995}
996
997impl ChainSpecBuilder {
998    /// Set the chain ID
999    pub const fn chain(mut self, chain: Chain) -> Self {
1000        self.chain = Some(chain);
1001        self
1002    }
1003
1004    /// Resets any existing hardforks from the builder.
1005    pub fn reset(mut self) -> Self {
1006        self.hardforks = ChainHardforks::default();
1007        self
1008    }
1009
1010    /// Set the genesis block.
1011    pub fn genesis(mut self, genesis: Genesis) -> Self {
1012        self.genesis = Some(genesis);
1013        self
1014    }
1015
1016    /// Add the given fork with the given activation condition to the spec.
1017    pub fn with_fork<H: Hardfork>(mut self, fork: H, condition: ForkCondition) -> Self {
1018        self.hardforks.insert(fork, condition);
1019        self
1020    }
1021
1022    /// Add the given chain hardforks to the spec.
1023    pub fn with_forks(mut self, forks: ChainHardforks) -> Self {
1024        self.hardforks = forks;
1025        self
1026    }
1027
1028    /// Remove the given fork from the spec.
1029    pub fn without_fork<H: Hardfork>(mut self, fork: H) -> Self {
1030        self.hardforks.remove(&fork);
1031        self
1032    }
1033
1034    /// Enable the Paris hardfork at the given TTD.
1035    ///
1036    /// Does not set the merge netsplit block.
1037    pub fn paris_at_ttd(self, ttd: U256, activation_block_number: BlockNumber) -> Self {
1038        self.with_fork(
1039            EthereumHardfork::Paris,
1040            ForkCondition::TTD { activation_block_number, total_difficulty: ttd, fork_block: None },
1041        )
1042    }
1043
1044    /// Enable Frontier at genesis.
1045    pub fn frontier_activated(mut self) -> Self {
1046        self.hardforks.insert(EthereumHardfork::Frontier, ForkCondition::Block(0));
1047        self
1048    }
1049
1050    /// Enable Dao at genesis.
1051    pub fn dao_activated(mut self) -> Self {
1052        self = self.frontier_activated();
1053        self.hardforks.insert(EthereumHardfork::Dao, ForkCondition::Block(0));
1054        self
1055    }
1056
1057    /// Enable Homestead at genesis.
1058    pub fn homestead_activated(mut self) -> Self {
1059        self = self.dao_activated();
1060        self.hardforks.insert(EthereumHardfork::Homestead, ForkCondition::Block(0));
1061        self
1062    }
1063
1064    /// Enable Tangerine at genesis.
1065    pub fn tangerine_whistle_activated(mut self) -> Self {
1066        self = self.homestead_activated();
1067        self.hardforks.insert(EthereumHardfork::Tangerine, ForkCondition::Block(0));
1068        self
1069    }
1070
1071    /// Enable Spurious Dragon at genesis.
1072    pub fn spurious_dragon_activated(mut self) -> Self {
1073        self = self.tangerine_whistle_activated();
1074        self.hardforks.insert(EthereumHardfork::SpuriousDragon, ForkCondition::Block(0));
1075        self
1076    }
1077
1078    /// Enable Byzantium at genesis.
1079    pub fn byzantium_activated(mut self) -> Self {
1080        self = self.spurious_dragon_activated();
1081        self.hardforks.insert(EthereumHardfork::Byzantium, ForkCondition::Block(0));
1082        self
1083    }
1084
1085    /// Enable Constantinople at genesis.
1086    pub fn constantinople_activated(mut self) -> Self {
1087        self = self.byzantium_activated();
1088        self.hardforks.insert(EthereumHardfork::Constantinople, ForkCondition::Block(0));
1089        self
1090    }
1091
1092    /// Enable Petersburg at genesis.
1093    pub fn petersburg_activated(mut self) -> Self {
1094        self = self.constantinople_activated();
1095        self.hardforks.insert(EthereumHardfork::Petersburg, ForkCondition::Block(0));
1096        self
1097    }
1098
1099    /// Enable Istanbul at genesis.
1100    pub fn istanbul_activated(mut self) -> Self {
1101        self = self.petersburg_activated();
1102        self.hardforks.insert(EthereumHardfork::Istanbul, ForkCondition::Block(0));
1103        self
1104    }
1105
1106    /// Enable Muir Glacier at genesis.
1107    pub fn muirglacier_activated(mut self) -> Self {
1108        self = self.istanbul_activated();
1109        self.hardforks.insert(EthereumHardfork::MuirGlacier, ForkCondition::Block(0));
1110        self
1111    }
1112
1113    /// Enable Berlin at genesis.
1114    pub fn berlin_activated(mut self) -> Self {
1115        self = self.muirglacier_activated();
1116        self.hardforks.insert(EthereumHardfork::Berlin, ForkCondition::Block(0));
1117        self
1118    }
1119
1120    /// Enable London at genesis.
1121    pub fn london_activated(mut self) -> Self {
1122        self = self.berlin_activated();
1123        self.hardforks.insert(EthereumHardfork::London, ForkCondition::Block(0));
1124        self
1125    }
1126
1127    /// Enable Arrow Glacier at genesis.
1128    pub fn arrowglacier_activated(mut self) -> Self {
1129        self = self.london_activated();
1130        self.hardforks.insert(EthereumHardfork::ArrowGlacier, ForkCondition::Block(0));
1131        self
1132    }
1133
1134    /// Enable Gray Glacier at genesis.
1135    pub fn grayglacier_activated(mut self) -> Self {
1136        self = self.arrowglacier_activated();
1137        self.hardforks.insert(EthereumHardfork::GrayGlacier, ForkCondition::Block(0));
1138        self
1139    }
1140
1141    /// Enable Paris at genesis.
1142    pub fn paris_activated(mut self) -> Self {
1143        self = self.grayglacier_activated();
1144        self.hardforks.insert(
1145            EthereumHardfork::Paris,
1146            ForkCondition::TTD {
1147                activation_block_number: 0,
1148                total_difficulty: U256::ZERO,
1149                fork_block: None,
1150            },
1151        );
1152        self
1153    }
1154
1155    /// Enable Shanghai at genesis.
1156    pub fn shanghai_activated(mut self) -> Self {
1157        self = self.paris_activated();
1158        self.hardforks.insert(EthereumHardfork::Shanghai, ForkCondition::Timestamp(0));
1159        self
1160    }
1161
1162    /// Enable Cancun at genesis.
1163    pub fn cancun_activated(mut self) -> Self {
1164        self = self.shanghai_activated();
1165        self.hardforks.insert(EthereumHardfork::Cancun, ForkCondition::Timestamp(0));
1166        self
1167    }
1168
1169    /// Enable Prague at genesis.
1170    pub fn prague_activated(mut self) -> Self {
1171        self = self.cancun_activated();
1172        self.hardforks.insert(EthereumHardfork::Prague, ForkCondition::Timestamp(0));
1173        self
1174    }
1175
1176    /// Enable Prague at the given timestamp.
1177    pub fn with_prague_at(mut self, timestamp: u64) -> Self {
1178        self.hardforks.insert(EthereumHardfork::Prague, ForkCondition::Timestamp(timestamp));
1179        self
1180    }
1181
1182    /// Enable Osaka at genesis.
1183    pub fn osaka_activated(mut self) -> Self {
1184        self = self.prague_activated();
1185        self.hardforks.insert(EthereumHardfork::Osaka, ForkCondition::Timestamp(0));
1186        self
1187    }
1188
1189    /// Enable Osaka at the given timestamp.
1190    pub fn with_osaka_at(mut self, timestamp: u64) -> Self {
1191        self.hardforks.insert(EthereumHardfork::Osaka, ForkCondition::Timestamp(timestamp));
1192        self
1193    }
1194
1195    /// Enable Amsterdam at genesis.
1196    pub fn amsterdam_activated(mut self) -> Self {
1197        self = self.osaka_activated();
1198        self.hardforks.insert(EthereumHardfork::Amsterdam, ForkCondition::Timestamp(0));
1199        self
1200    }
1201
1202    /// Enable Amsterdam at the given timestamp.
1203    pub fn with_amsterdam_at(mut self, timestamp: u64) -> Self {
1204        self.hardforks.insert(EthereumHardfork::Amsterdam, ForkCondition::Timestamp(timestamp));
1205        self
1206    }
1207
1208    /// Enable Bogota at genesis.
1209    pub fn bogota_activated(mut self) -> Self {
1210        self = self.amsterdam_activated();
1211        self.hardforks.insert(EthereumHardfork::Bogota, ForkCondition::Timestamp(0));
1212        self
1213    }
1214
1215    /// Enable Bogota at the given timestamp.
1216    pub fn with_bogota_at(mut self, timestamp: u64) -> Self {
1217        self.hardforks.insert(EthereumHardfork::Bogota, ForkCondition::Timestamp(timestamp));
1218        self
1219    }
1220
1221    /// Build the resulting [`ChainSpec`].
1222    ///
1223    /// # Panics
1224    ///
1225    /// This function panics if the chain ID and genesis is not set ([`Self::chain`] and
1226    /// [`Self::genesis`])
1227    pub fn build(self) -> ChainSpec {
1228        let paris_block_and_final_difficulty = {
1229            self.hardforks.get(EthereumHardfork::Paris).and_then(|cond| {
1230                if let ForkCondition::TTD { total_difficulty, activation_block_number, .. } = cond {
1231                    Some((activation_block_number, total_difficulty))
1232                } else {
1233                    None
1234                }
1235            })
1236        };
1237        let genesis = self.genesis.expect("The genesis is required");
1238        ChainSpec {
1239            chain: self.chain.expect("The chain is required"),
1240            genesis_header: SealedHeader::new_unhashed(make_genesis_header(
1241                &genesis,
1242                &self.hardforks,
1243            )),
1244            genesis,
1245            hardforks: self.hardforks,
1246            paris_block_and_final_difficulty,
1247            deposit_contract: None,
1248            ..Default::default()
1249        }
1250    }
1251}
1252
1253impl From<&Arc<ChainSpec>> for ChainSpecBuilder {
1254    fn from(value: &Arc<ChainSpec>) -> Self {
1255        Self {
1256            chain: Some(value.chain),
1257            genesis: Some(value.genesis.clone()),
1258            hardforks: value.hardforks.clone(),
1259        }
1260    }
1261}
1262
1263/// `PoS` deposit contract details.
1264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1265pub struct DepositContract {
1266    /// Deposit Contract Address
1267    pub address: Address,
1268    /// Deployment Block
1269    pub block: BlockNumber,
1270    /// `DepositEvent` event signature
1271    pub topic: B256,
1272}
1273
1274impl DepositContract {
1275    /// Creates a new [`DepositContract`].
1276    pub const fn new(address: Address, block: BlockNumber, topic: B256) -> Self {
1277        Self { address, block, topic }
1278    }
1279}
1280
1281/// Verifies [`ChainSpec`] configuration against expected data in given cases.
1282#[cfg(any(test, feature = "test-utils"))]
1283pub fn test_fork_ids(spec: &ChainSpec, cases: &[(Head, ForkId)]) {
1284    for (block, expected_id) in cases {
1285        let computed_id = spec.fork_id(block);
1286        assert_eq!(
1287            expected_id, &computed_id,
1288            "Expected fork ID {:?}, computed fork ID {:?} at block {}",
1289            expected_id, computed_id, block.number
1290        );
1291    }
1292}
1293
1294#[cfg(test)]
1295mod tests {
1296
1297    use super::*;
1298    use alloy_chains::Chain;
1299    use alloy_eips::{eip4844::BLOB_TX_MIN_BLOB_GASPRICE, eip7840::BlobParams};
1300    use alloy_genesis::{ChainConfig, GenesisAccount};
1301    use alloy_primitives::{b256, hex};
1302    use alloy_trie::{TrieAccount, EMPTY_ROOT_HASH};
1303    use core::ops::Deref;
1304    use reth_ethereum_forks::{ForkCondition, ForkHash, ForkId, Head};
1305    use std::collections::HashMap;
1306
1307    fn test_hardfork_fork_ids(spec: &ChainSpec, cases: &[(EthereumHardfork, ForkId)]) {
1308        for (hardfork, expected_id) in cases {
1309            if let Some(computed_id) = spec.hardfork_fork_id(*hardfork) {
1310                assert_eq!(
1311                    expected_id, &computed_id,
1312                    "Expected fork ID {expected_id:?}, computed fork ID {computed_id:?} for hardfork {hardfork}"
1313                );
1314                if matches!(hardfork, EthereumHardfork::Shanghai) {
1315                    if let Some(shanghai_id) = spec.shanghai_fork_id() {
1316                        assert_eq!(
1317                            expected_id, &shanghai_id,
1318                            "Expected fork ID {expected_id:?}, computed fork ID {computed_id:?} for Shanghai hardfork"
1319                        );
1320                    } else {
1321                        panic!("Expected ForkCondition to return Some for Hardfork::Shanghai");
1322                    }
1323                }
1324            }
1325        }
1326    }
1327
1328    #[test]
1329    fn test_hardfork_list_display_mainnet() {
1330        assert_eq!(
1331            MAINNET.display_hardforks().to_string(),
1332            "Pre-merge hard forks (block based):
1333- Frontier                         @0
1334- Homestead                        @1150000
1335- Dao                              @1920000
1336- Tangerine                        @2463000
1337- SpuriousDragon                   @2675000
1338- Byzantium                        @4370000
1339- Constantinople                   @7280000
1340- Petersburg                       @7280000
1341- Istanbul                         @9069000
1342- MuirGlacier                      @9200000
1343- Berlin                           @12244000
1344- London                           @12965000
1345- ArrowGlacier                     @13773000
1346- GrayGlacier                      @15050000
1347Merge hard forks:
1348- Paris                            @58750000000000000000000 (network is known to be merged)
1349Post-merge hard forks (timestamp based):
1350- Shanghai                         @1681338455
1351- Cancun                           @1710338135          blob: (target: 3, max: 6, fraction: 3338477)
1352- Prague                           @1746612311          blob: (target: 6, max: 9, fraction: 5007716)
1353- Osaka                            @1764798551          blob: (target: 6, max: 9, fraction: 5007716)
1354- Bpo1                             @1765290071          blob: (target: 10, max: 15, fraction: 8346193)
1355- Bpo2                             @1767747671          blob: (target: 14, max: 21, fraction: 11684671)"
1356        );
1357    }
1358
1359    #[test]
1360    fn test_hardfork_list_ignores_disabled_forks() {
1361        let spec = ChainSpec::builder()
1362            .chain(Chain::mainnet())
1363            .genesis(Genesis::default())
1364            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1365            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Never)
1366            .build();
1367        assert_eq!(
1368            spec.display_hardforks().to_string(),
1369            "Pre-merge hard forks (block based):
1370- Frontier                         @0"
1371        );
1372    }
1373
1374    // Tests that we skip any fork blocks in block #0 (the genesis ruleset)
1375    #[test]
1376    fn ignores_genesis_fork_blocks() {
1377        let spec = ChainSpec::builder()
1378            .chain(Chain::mainnet())
1379            .genesis(Genesis::default())
1380            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1381            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(0))
1382            .with_fork(EthereumHardfork::Tangerine, ForkCondition::Block(0))
1383            .with_fork(EthereumHardfork::SpuriousDragon, ForkCondition::Block(0))
1384            .with_fork(EthereumHardfork::Byzantium, ForkCondition::Block(0))
1385            .with_fork(EthereumHardfork::Constantinople, ForkCondition::Block(0))
1386            .with_fork(EthereumHardfork::Istanbul, ForkCondition::Block(0))
1387            .with_fork(EthereumHardfork::MuirGlacier, ForkCondition::Block(0))
1388            .with_fork(EthereumHardfork::Berlin, ForkCondition::Block(0))
1389            .with_fork(EthereumHardfork::London, ForkCondition::Block(0))
1390            .with_fork(EthereumHardfork::ArrowGlacier, ForkCondition::Block(0))
1391            .with_fork(EthereumHardfork::GrayGlacier, ForkCondition::Block(0))
1392            .build();
1393
1394        assert_eq!(spec.deref().len(), 12, "12 forks should be active.");
1395        assert_eq!(
1396            spec.fork_id(&Head { number: 1, ..Default::default() }),
1397            ForkId { hash: ForkHash::from(spec.genesis_hash()), next: 0 },
1398            "the fork ID should be the genesis hash; forks at genesis are ignored for fork filters"
1399        );
1400    }
1401
1402    #[test]
1403    fn ignores_duplicate_fork_blocks() {
1404        let empty_genesis = Genesis::default();
1405        let unique_spec = ChainSpec::builder()
1406            .chain(Chain::mainnet())
1407            .genesis(empty_genesis.clone())
1408            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1409            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(1))
1410            .build();
1411
1412        let duplicate_spec = ChainSpec::builder()
1413            .chain(Chain::mainnet())
1414            .genesis(empty_genesis)
1415            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1416            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(1))
1417            .with_fork(EthereumHardfork::Tangerine, ForkCondition::Block(1))
1418            .build();
1419
1420        assert_eq!(
1421            unique_spec.fork_id(&Head { number: 2, ..Default::default() }),
1422            duplicate_spec.fork_id(&Head { number: 2, ..Default::default() }),
1423            "duplicate fork blocks should be deduplicated for fork filters"
1424        );
1425    }
1426
1427    #[test]
1428    fn test_chainspec_satisfy() {
1429        let empty_genesis = Genesis::default();
1430        // happy path test case
1431        let happy_path_case = ChainSpec::builder()
1432            .chain(Chain::mainnet())
1433            .genesis(empty_genesis.clone())
1434            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1435            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(73))
1436            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(11313123))
1437            .build();
1438        let happy_path_head = happy_path_case.satisfy(ForkCondition::Timestamp(11313123));
1439        let happy_path_expected = Head { number: 73, timestamp: 11313123, ..Default::default() };
1440        assert_eq!(
1441            happy_path_head, happy_path_expected,
1442            "expected satisfy() to return {happy_path_expected:#?}, but got {happy_path_head:#?} "
1443        );
1444        // multiple timestamp test case (i.e Shanghai -> Cancun)
1445        let multiple_timestamp_fork_case = ChainSpec::builder()
1446            .chain(Chain::mainnet())
1447            .genesis(empty_genesis.clone())
1448            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1449            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(73))
1450            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(11313123))
1451            .with_fork(EthereumHardfork::Cancun, ForkCondition::Timestamp(11313398))
1452            .build();
1453        let multi_timestamp_head =
1454            multiple_timestamp_fork_case.satisfy(ForkCondition::Timestamp(11313398));
1455        let mult_timestamp_expected =
1456            Head { number: 73, timestamp: 11313398, ..Default::default() };
1457        assert_eq!(
1458            multi_timestamp_head, mult_timestamp_expected,
1459            "expected satisfy() to return {mult_timestamp_expected:#?}, but got {multi_timestamp_head:#?} "
1460        );
1461        // no ForkCondition::Block test case
1462        let no_block_fork_case = ChainSpec::builder()
1463            .chain(Chain::mainnet())
1464            .genesis(empty_genesis.clone())
1465            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(11313123))
1466            .build();
1467        let no_block_fork_head = no_block_fork_case.satisfy(ForkCondition::Timestamp(11313123));
1468        let no_block_fork_expected = Head { number: 0, timestamp: 11313123, ..Default::default() };
1469        assert_eq!(
1470            no_block_fork_head, no_block_fork_expected,
1471            "expected satisfy() to return {no_block_fork_expected:#?}, but got {no_block_fork_head:#?} ",
1472        );
1473        // spec w/ ForkCondition::TTD with block_num test case (Sepolia merge netsplit edge case)
1474        let fork_cond_ttd_blocknum_case = ChainSpec::builder()
1475            .chain(Chain::mainnet())
1476            .genesis(empty_genesis.clone())
1477            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1478            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(73))
1479            .with_fork(
1480                EthereumHardfork::Paris,
1481                ForkCondition::TTD {
1482                    activation_block_number: 101,
1483                    fork_block: Some(101),
1484                    total_difficulty: U256::from(10_790_000),
1485                },
1486            )
1487            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(11313123))
1488            .build();
1489        let fork_cond_ttd_blocknum_head =
1490            fork_cond_ttd_blocknum_case.satisfy(ForkCondition::Timestamp(11313123));
1491        let fork_cond_ttd_blocknum_expected =
1492            Head { number: 101, timestamp: 11313123, ..Default::default() };
1493        assert_eq!(
1494            fork_cond_ttd_blocknum_head, fork_cond_ttd_blocknum_expected,
1495            "expected satisfy() to return {fork_cond_ttd_blocknum_expected:#?}, but got {fork_cond_ttd_blocknum_head:#?} ",
1496        );
1497
1498        // spec w/ only ForkCondition::Block - test the match arm for ForkCondition::Block to ensure
1499        // no regressions, for these ForkConditions(Block/TTD) - a separate chain spec definition is
1500        // technically unnecessary - but we include it here for thoroughness
1501        let fork_cond_block_only_case = ChainSpec::builder()
1502            .chain(Chain::mainnet())
1503            .genesis(empty_genesis)
1504            .with_fork(EthereumHardfork::Frontier, ForkCondition::Block(0))
1505            .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(73))
1506            .build();
1507        let fork_cond_block_only_head = fork_cond_block_only_case.satisfy(ForkCondition::Block(73));
1508        let fork_cond_block_only_expected = Head { number: 73, ..Default::default() };
1509        assert_eq!(
1510            fork_cond_block_only_head, fork_cond_block_only_expected,
1511            "expected satisfy() to return {fork_cond_block_only_expected:#?}, but got {fork_cond_block_only_head:#?} ",
1512        );
1513        // Fork::ConditionTTD test case without a new chain spec to demonstrate ChainSpec::satisfy
1514        // is independent of ChainSpec for this(these - including ForkCondition::Block) match arm(s)
1515        let fork_cond_ttd_no_new_spec = fork_cond_block_only_case.satisfy(ForkCondition::TTD {
1516            activation_block_number: 101,
1517            fork_block: None,
1518            total_difficulty: U256::from(10_790_000),
1519        });
1520        let fork_cond_ttd_no_new_spec_expected =
1521            Head { total_difficulty: U256::from(10_790_000), ..Default::default() };
1522        assert_eq!(
1523            fork_cond_ttd_no_new_spec, fork_cond_ttd_no_new_spec_expected,
1524            "expected satisfy() to return {fork_cond_ttd_no_new_spec_expected:#?}, but got {fork_cond_ttd_no_new_spec:#?} ",
1525        );
1526    }
1527
1528    #[test]
1529    fn mainnet_hardfork_fork_ids() {
1530        test_hardfork_fork_ids(
1531            &MAINNET,
1532            &[
1533                (
1534                    EthereumHardfork::Frontier,
1535                    ForkId { hash: ForkHash(hex!("0xfc64ec04")), next: 1150000 },
1536                ),
1537                (
1538                    EthereumHardfork::Homestead,
1539                    ForkId { hash: ForkHash(hex!("0x97c2c34c")), next: 1920000 },
1540                ),
1541                (
1542                    EthereumHardfork::Dao,
1543                    ForkId { hash: ForkHash(hex!("0x91d1f948")), next: 2463000 },
1544                ),
1545                (
1546                    EthereumHardfork::Tangerine,
1547                    ForkId { hash: ForkHash(hex!("0x7a64da13")), next: 2675000 },
1548                ),
1549                (
1550                    EthereumHardfork::SpuriousDragon,
1551                    ForkId { hash: ForkHash(hex!("0x3edd5b10")), next: 4370000 },
1552                ),
1553                (
1554                    EthereumHardfork::Byzantium,
1555                    ForkId { hash: ForkHash(hex!("0xa00bc324")), next: 7280000 },
1556                ),
1557                (
1558                    EthereumHardfork::Constantinople,
1559                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
1560                ),
1561                (
1562                    EthereumHardfork::Petersburg,
1563                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
1564                ),
1565                (
1566                    EthereumHardfork::Istanbul,
1567                    ForkId { hash: ForkHash(hex!("0x879d6e30")), next: 9200000 },
1568                ),
1569                (
1570                    EthereumHardfork::MuirGlacier,
1571                    ForkId { hash: ForkHash(hex!("0xe029e991")), next: 12244000 },
1572                ),
1573                (
1574                    EthereumHardfork::Berlin,
1575                    ForkId { hash: ForkHash(hex!("0x0eb440f6")), next: 12965000 },
1576                ),
1577                (
1578                    EthereumHardfork::London,
1579                    ForkId { hash: ForkHash(hex!("0xb715077d")), next: 13773000 },
1580                ),
1581                (
1582                    EthereumHardfork::ArrowGlacier,
1583                    ForkId { hash: ForkHash(hex!("0x20c327fc")), next: 15050000 },
1584                ),
1585                (
1586                    EthereumHardfork::GrayGlacier,
1587                    ForkId { hash: ForkHash(hex!("0xf0afd0e3")), next: 1681338455 },
1588                ),
1589                (
1590                    EthereumHardfork::Shanghai,
1591                    ForkId { hash: ForkHash(hex!("0xdce96c2d")), next: 1710338135 },
1592                ),
1593                (
1594                    EthereumHardfork::Cancun,
1595                    ForkId { hash: ForkHash(hex!("0x9f3d2254")), next: 1746612311 },
1596                ),
1597                (
1598                    EthereumHardfork::Prague,
1599                    ForkId {
1600                        hash: ForkHash(hex!("0xc376cf8b")),
1601                        next: mainnet::MAINNET_OSAKA_TIMESTAMP,
1602                    },
1603                ),
1604            ],
1605        );
1606    }
1607
1608    #[test]
1609    fn sepolia_hardfork_fork_ids() {
1610        test_hardfork_fork_ids(
1611            &SEPOLIA,
1612            &[
1613                (
1614                    EthereumHardfork::Frontier,
1615                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1616                ),
1617                (
1618                    EthereumHardfork::Homestead,
1619                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1620                ),
1621                (
1622                    EthereumHardfork::Tangerine,
1623                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1624                ),
1625                (
1626                    EthereumHardfork::SpuriousDragon,
1627                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1628                ),
1629                (
1630                    EthereumHardfork::Byzantium,
1631                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1632                ),
1633                (
1634                    EthereumHardfork::Constantinople,
1635                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1636                ),
1637                (
1638                    EthereumHardfork::Petersburg,
1639                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1640                ),
1641                (
1642                    EthereumHardfork::Istanbul,
1643                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1644                ),
1645                (
1646                    EthereumHardfork::Berlin,
1647                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1648                ),
1649                (
1650                    EthereumHardfork::London,
1651                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1652                ),
1653                (
1654                    EthereumHardfork::Paris,
1655                    ForkId { hash: ForkHash(hex!("0xb96cbd13")), next: 1677557088 },
1656                ),
1657                (
1658                    EthereumHardfork::Shanghai,
1659                    ForkId { hash: ForkHash(hex!("0xf7f9bc08")), next: 1706655072 },
1660                ),
1661                (
1662                    EthereumHardfork::Cancun,
1663                    ForkId { hash: ForkHash(hex!("0x88cf81d9")), next: 1741159776 },
1664                ),
1665                (
1666                    EthereumHardfork::Prague,
1667                    ForkId {
1668                        hash: ForkHash(hex!("0xed88b5fd")),
1669                        next: sepolia::SEPOLIA_OSAKA_TIMESTAMP,
1670                    },
1671                ),
1672                (
1673                    EthereumHardfork::Osaka,
1674                    ForkId {
1675                        hash: ForkHash(hex!("0xe2ae4999")),
1676                        next: sepolia::SEPOLIA_BPO1_TIMESTAMP,
1677                    },
1678                ),
1679                (
1680                    EthereumHardfork::Bpo1,
1681                    ForkId {
1682                        hash: ForkHash(hex!("0x56078a1e")),
1683                        next: sepolia::SEPOLIA_BPO2_TIMESTAMP,
1684                    },
1685                ),
1686                (
1687                    EthereumHardfork::Bpo2,
1688                    ForkId {
1689                        hash: ForkHash(hex!("0x268956b6")),
1690                        next: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP,
1691                    },
1692                ),
1693                (
1694                    EthereumHardfork::Amsterdam,
1695                    ForkId { hash: ForkHash(hex!("0x6c1d9423")), next: 0 },
1696                ),
1697            ],
1698        );
1699    }
1700
1701    #[test]
1702    fn mainnet_fork_ids() {
1703        test_fork_ids(
1704            &MAINNET,
1705            &[
1706                (
1707                    Head { number: 0, ..Default::default() },
1708                    ForkId { hash: ForkHash(hex!("0xfc64ec04")), next: 1150000 },
1709                ),
1710                (
1711                    Head { number: 1150000, ..Default::default() },
1712                    ForkId { hash: ForkHash(hex!("0x97c2c34c")), next: 1920000 },
1713                ),
1714                (
1715                    Head { number: 1920000, ..Default::default() },
1716                    ForkId { hash: ForkHash(hex!("0x91d1f948")), next: 2463000 },
1717                ),
1718                (
1719                    Head { number: 2463000, ..Default::default() },
1720                    ForkId { hash: ForkHash(hex!("0x7a64da13")), next: 2675000 },
1721                ),
1722                (
1723                    Head { number: 2675000, ..Default::default() },
1724                    ForkId { hash: ForkHash(hex!("0x3edd5b10")), next: 4370000 },
1725                ),
1726                (
1727                    Head { number: 4370000, ..Default::default() },
1728                    ForkId { hash: ForkHash(hex!("0xa00bc324")), next: 7280000 },
1729                ),
1730                (
1731                    Head { number: 7280000, ..Default::default() },
1732                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
1733                ),
1734                (
1735                    Head { number: 9069000, ..Default::default() },
1736                    ForkId { hash: ForkHash(hex!("0x879d6e30")), next: 9200000 },
1737                ),
1738                (
1739                    Head { number: 9200000, ..Default::default() },
1740                    ForkId { hash: ForkHash(hex!("0xe029e991")), next: 12244000 },
1741                ),
1742                (
1743                    Head { number: 12244000, ..Default::default() },
1744                    ForkId { hash: ForkHash(hex!("0x0eb440f6")), next: 12965000 },
1745                ),
1746                (
1747                    Head { number: 12965000, ..Default::default() },
1748                    ForkId { hash: ForkHash(hex!("0xb715077d")), next: 13773000 },
1749                ),
1750                (
1751                    Head { number: 13773000, ..Default::default() },
1752                    ForkId { hash: ForkHash(hex!("0x20c327fc")), next: 15050000 },
1753                ),
1754                (
1755                    Head { number: 15050000, ..Default::default() },
1756                    ForkId { hash: ForkHash(hex!("0xf0afd0e3")), next: 1681338455 },
1757                ),
1758                // First Shanghai block
1759                (
1760                    Head { number: 20000000, timestamp: 1681338455, ..Default::default() },
1761                    ForkId { hash: ForkHash(hex!("0xdce96c2d")), next: 1710338135 },
1762                ),
1763                // First Cancun block
1764                (
1765                    Head { number: 20000001, timestamp: 1710338135, ..Default::default() },
1766                    ForkId { hash: ForkHash(hex!("0x9f3d2254")), next: 1746612311 },
1767                ),
1768                // First Prague block
1769                (
1770                    Head { number: 20000004, timestamp: 1746612311, ..Default::default() },
1771                    ForkId {
1772                        hash: ForkHash(hex!("0xc376cf8b")),
1773                        next: mainnet::MAINNET_OSAKA_TIMESTAMP,
1774                    },
1775                ),
1776                // Osaka block
1777                (
1778                    Head {
1779                        number: 20000004,
1780                        timestamp: mainnet::MAINNET_OSAKA_TIMESTAMP,
1781                        ..Default::default()
1782                    },
1783                    ForkId {
1784                        hash: ForkHash(hex!("0x5167e2a6")),
1785                        next: mainnet::MAINNET_BPO1_TIMESTAMP,
1786                    },
1787                ),
1788            ],
1789        );
1790    }
1791
1792    #[test]
1793    fn hoodi_fork_ids() {
1794        test_fork_ids(
1795            &HOODI,
1796            &[
1797                (
1798                    Head { number: 0, ..Default::default() },
1799                    ForkId { hash: ForkHash(hex!("0xbef71d30")), next: 1742999832 },
1800                ),
1801                // First Prague block
1802                (
1803                    Head { number: 0, timestamp: 1742999833, ..Default::default() },
1804                    ForkId {
1805                        hash: ForkHash(hex!("0x0929e24e")),
1806                        next: hoodi::HOODI_OSAKA_TIMESTAMP,
1807                    },
1808                ),
1809                // First Osaka block
1810                (
1811                    Head {
1812                        number: 0,
1813                        timestamp: hoodi::HOODI_OSAKA_TIMESTAMP,
1814                        ..Default::default()
1815                    },
1816                    ForkId {
1817                        hash: ForkHash(hex!("0xe7e0e7ff")),
1818                        next: hoodi::HOODI_BPO1_TIMESTAMP,
1819                    },
1820                ),
1821                // First BPO1 block.
1822                (
1823                    Head {
1824                        number: 0,
1825                        timestamp: hoodi::HOODI_BPO1_TIMESTAMP,
1826                        ..Default::default()
1827                    },
1828                    ForkId {
1829                        hash: ForkHash(hex!("0x3893353e")),
1830                        next: hoodi::HOODI_BPO2_TIMESTAMP,
1831                    },
1832                ),
1833                // First BPO2 block.
1834                (
1835                    Head {
1836                        number: 0,
1837                        timestamp: hoodi::HOODI_BPO2_TIMESTAMP,
1838                        ..Default::default()
1839                    },
1840                    ForkId {
1841                        hash: ForkHash(hex!("0x23aa1351")),
1842                        next: hoodi::HOODI_AMSTERDAM_TIMESTAMP,
1843                    },
1844                ),
1845                // Last block before Amsterdam.
1846                (
1847                    Head {
1848                        number: 0,
1849                        timestamp: hoodi::HOODI_AMSTERDAM_TIMESTAMP - 1,
1850                        ..Default::default()
1851                    },
1852                    ForkId {
1853                        hash: ForkHash(hex!("0x23aa1351")),
1854                        next: hoodi::HOODI_AMSTERDAM_TIMESTAMP,
1855                    },
1856                ),
1857                // First Amsterdam block.
1858                (
1859                    Head {
1860                        number: 0,
1861                        timestamp: hoodi::HOODI_AMSTERDAM_TIMESTAMP,
1862                        ..Default::default()
1863                    },
1864                    ForkId { hash: ForkHash(hex!("0x3ae0b2e6")), next: 0 },
1865                ),
1866                // After Amsterdam.
1867                (
1868                    Head {
1869                        number: 0,
1870                        timestamp: hoodi::HOODI_AMSTERDAM_TIMESTAMP + 1,
1871                        ..Default::default()
1872                    },
1873                    ForkId { hash: ForkHash(hex!("0x3ae0b2e6")), next: 0 },
1874                ),
1875            ],
1876        )
1877    }
1878
1879    #[test]
1880    fn holesky_fork_ids() {
1881        test_fork_ids(
1882            &HOLESKY,
1883            &[
1884                (
1885                    Head { number: 0, ..Default::default() },
1886                    ForkId { hash: ForkHash(hex!("0xc61a6098")), next: 1696000704 },
1887                ),
1888                // First MergeNetsplit block
1889                (
1890                    Head { number: 123, ..Default::default() },
1891                    ForkId { hash: ForkHash(hex!("0xc61a6098")), next: 1696000704 },
1892                ),
1893                // Last MergeNetsplit block
1894                (
1895                    Head { number: 123, timestamp: 1696000703, ..Default::default() },
1896                    ForkId { hash: ForkHash(hex!("0xc61a6098")), next: 1696000704 },
1897                ),
1898                // First Shanghai block
1899                (
1900                    Head { number: 123, timestamp: 1696000704, ..Default::default() },
1901                    ForkId { hash: ForkHash(hex!("0xfd4f016b")), next: 1707305664 },
1902                ),
1903                // Last Shanghai block
1904                (
1905                    Head { number: 123, timestamp: 1707305663, ..Default::default() },
1906                    ForkId { hash: ForkHash(hex!("0xfd4f016b")), next: 1707305664 },
1907                ),
1908                // First Cancun block
1909                (
1910                    Head { number: 123, timestamp: 1707305664, ..Default::default() },
1911                    ForkId { hash: ForkHash(hex!("0x9b192ad0")), next: 1740434112 },
1912                ),
1913                // Last Cancun block
1914                (
1915                    Head { number: 123, timestamp: 1740434111, ..Default::default() },
1916                    ForkId { hash: ForkHash(hex!("0x9b192ad0")), next: 1740434112 },
1917                ),
1918                // First Prague block
1919                (
1920                    Head { number: 123, timestamp: 1740434112, ..Default::default() },
1921                    ForkId {
1922                        hash: ForkHash(hex!("0xdfbd9bed")),
1923                        next: holesky::HOLESKY_OSAKA_TIMESTAMP,
1924                    },
1925                ),
1926                // First Osaka block
1927                (
1928                    Head {
1929                        number: 123,
1930                        timestamp: holesky::HOLESKY_OSAKA_TIMESTAMP,
1931                        ..Default::default()
1932                    },
1933                    ForkId {
1934                        hash: ForkHash(hex!("0x783def52")),
1935                        next: holesky::HOLESKY_BPO1_TIMESTAMP,
1936                    },
1937                ),
1938            ],
1939        )
1940    }
1941
1942    #[test]
1943    fn sepolia_fork_ids() {
1944        test_fork_ids(
1945            &SEPOLIA,
1946            &[
1947                (
1948                    Head { number: 0, ..Default::default() },
1949                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1950                ),
1951                (
1952                    Head { number: 1735370, ..Default::default() },
1953                    ForkId { hash: ForkHash(hex!("0xfe3366e7")), next: 1735371 },
1954                ),
1955                (
1956                    Head { number: 1735371, ..Default::default() },
1957                    ForkId { hash: ForkHash(hex!("0xb96cbd13")), next: 1677557088 },
1958                ),
1959                (
1960                    Head { number: 1735372, timestamp: 1677557087, ..Default::default() },
1961                    ForkId { hash: ForkHash(hex!("0xb96cbd13")), next: 1677557088 },
1962                ),
1963                // First Shanghai block
1964                (
1965                    Head { number: 1735373, timestamp: 1677557088, ..Default::default() },
1966                    ForkId { hash: ForkHash(hex!("0xf7f9bc08")), next: 1706655072 },
1967                ),
1968                // Last Shanghai block
1969                (
1970                    Head { number: 1735374, timestamp: 1706655071, ..Default::default() },
1971                    ForkId { hash: ForkHash(hex!("0xf7f9bc08")), next: 1706655072 },
1972                ),
1973                // First Cancun block
1974                (
1975                    Head { number: 1735375, timestamp: 1706655072, ..Default::default() },
1976                    ForkId { hash: ForkHash(hex!("0x88cf81d9")), next: 1741159776 },
1977                ),
1978                // Last Cancun block
1979                (
1980                    Head { number: 1735376, timestamp: 1741159775, ..Default::default() },
1981                    ForkId { hash: ForkHash(hex!("0x88cf81d9")), next: 1741159776 },
1982                ),
1983                // First Prague block
1984                (
1985                    Head { number: 1735377, timestamp: 1741159776, ..Default::default() },
1986                    ForkId {
1987                        hash: ForkHash(hex!("0xed88b5fd")),
1988                        next: sepolia::SEPOLIA_OSAKA_TIMESTAMP,
1989                    },
1990                ),
1991                // First Osaka block
1992                (
1993                    Head {
1994                        number: 1735377,
1995                        timestamp: sepolia::SEPOLIA_OSAKA_TIMESTAMP,
1996                        ..Default::default()
1997                    },
1998                    ForkId {
1999                        hash: ForkHash(hex!("0xe2ae4999")),
2000                        next: sepolia::SEPOLIA_BPO1_TIMESTAMP,
2001                    },
2002                ),
2003                // First BPO1 block
2004                (
2005                    Head {
2006                        number: 1735377,
2007                        timestamp: sepolia::SEPOLIA_BPO1_TIMESTAMP,
2008                        ..Default::default()
2009                    },
2010                    ForkId {
2011                        hash: ForkHash(hex!("0x56078a1e")),
2012                        next: sepolia::SEPOLIA_BPO2_TIMESTAMP,
2013                    },
2014                ),
2015                // First BPO2 block
2016                (
2017                    Head {
2018                        number: 1735377,
2019                        timestamp: sepolia::SEPOLIA_BPO2_TIMESTAMP,
2020                        ..Default::default()
2021                    },
2022                    ForkId {
2023                        hash: ForkHash(hex!("0x268956b6")),
2024                        next: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP,
2025                    },
2026                ),
2027                // Last block before Amsterdam
2028                (
2029                    Head {
2030                        number: 1735377,
2031                        timestamp: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP - 1,
2032                        ..Default::default()
2033                    },
2034                    ForkId {
2035                        hash: ForkHash(hex!("0x268956b6")),
2036                        next: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP,
2037                    },
2038                ),
2039                // First Amsterdam block
2040                (
2041                    Head {
2042                        number: 1735377,
2043                        timestamp: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP,
2044                        ..Default::default()
2045                    },
2046                    ForkId { hash: ForkHash(hex!("0x6c1d9423")), next: 0 },
2047                ),
2048                // After Amsterdam
2049                (
2050                    Head {
2051                        number: 1735377,
2052                        timestamp: sepolia::SEPOLIA_AMSTERDAM_TIMESTAMP + 1,
2053                        ..Default::default()
2054                    },
2055                    ForkId { hash: ForkHash(hex!("0x6c1d9423")), next: 0 },
2056                ),
2057            ],
2058        );
2059    }
2060
2061    #[test]
2062    fn dev_fork_ids() {
2063        test_fork_ids(
2064            &DEV,
2065            &[(
2066                Head { number: 0, ..Default::default() },
2067                ForkId { hash: ForkHash(hex!("0x62d16ad0")), next: 0 },
2068            )],
2069        )
2070    }
2071
2072    /// Checks that time-based forks work
2073    ///
2074    /// This is based off of the test vectors here: <https://github.com/ethereum/go-ethereum/blob/5c8cc10d1e05c23ff1108022f4150749e73c0ca1/core/forkid/forkid_test.go#L155-L188>
2075    #[test]
2076    fn timestamped_forks() {
2077        let mainnet_with_timestamps = ChainSpecBuilder::mainnet().build();
2078        test_fork_ids(
2079            &mainnet_with_timestamps,
2080            &[
2081                (
2082                    Head { number: 0, timestamp: 0, ..Default::default() },
2083                    ForkId { hash: ForkHash(hex!("0xfc64ec04")), next: 1150000 },
2084                ), // Unsynced
2085                (
2086                    Head { number: 1149999, timestamp: 0, ..Default::default() },
2087                    ForkId { hash: ForkHash(hex!("0xfc64ec04")), next: 1150000 },
2088                ), // Last Frontier block
2089                (
2090                    Head { number: 1150000, timestamp: 0, ..Default::default() },
2091                    ForkId { hash: ForkHash(hex!("0x97c2c34c")), next: 1920000 },
2092                ), // First Homestead block
2093                (
2094                    Head { number: 1919999, timestamp: 0, ..Default::default() },
2095                    ForkId { hash: ForkHash(hex!("0x97c2c34c")), next: 1920000 },
2096                ), // Last Homestead block
2097                (
2098                    Head { number: 1920000, timestamp: 0, ..Default::default() },
2099                    ForkId { hash: ForkHash(hex!("0x91d1f948")), next: 2463000 },
2100                ), // First DAO block
2101                (
2102                    Head { number: 2462999, timestamp: 0, ..Default::default() },
2103                    ForkId { hash: ForkHash(hex!("0x91d1f948")), next: 2463000 },
2104                ), // Last DAO block
2105                (
2106                    Head { number: 2463000, timestamp: 0, ..Default::default() },
2107                    ForkId { hash: ForkHash(hex!("0x7a64da13")), next: 2675000 },
2108                ), // First Tangerine block
2109                (
2110                    Head { number: 2674999, timestamp: 0, ..Default::default() },
2111                    ForkId { hash: ForkHash(hex!("0x7a64da13")), next: 2675000 },
2112                ), // Last Tangerine block
2113                (
2114                    Head { number: 2675000, timestamp: 0, ..Default::default() },
2115                    ForkId { hash: ForkHash(hex!("0x3edd5b10")), next: 4370000 },
2116                ), // First Spurious block
2117                (
2118                    Head { number: 4369999, timestamp: 0, ..Default::default() },
2119                    ForkId { hash: ForkHash(hex!("0x3edd5b10")), next: 4370000 },
2120                ), // Last Spurious block
2121                (
2122                    Head { number: 4370000, timestamp: 0, ..Default::default() },
2123                    ForkId { hash: ForkHash(hex!("0xa00bc324")), next: 7280000 },
2124                ), // First Byzantium block
2125                (
2126                    Head { number: 7279999, timestamp: 0, ..Default::default() },
2127                    ForkId { hash: ForkHash(hex!("0xa00bc324")), next: 7280000 },
2128                ), // Last Byzantium block
2129                (
2130                    Head { number: 7280000, timestamp: 0, ..Default::default() },
2131                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
2132                ), // First and last Constantinople, first Petersburg block
2133                (
2134                    Head { number: 9068999, timestamp: 0, ..Default::default() },
2135                    ForkId { hash: ForkHash(hex!("0x668db0af")), next: 9069000 },
2136                ), // Last Petersburg block
2137                (
2138                    Head { number: 9069000, timestamp: 0, ..Default::default() },
2139                    ForkId { hash: ForkHash(hex!("0x879d6e30")), next: 9200000 },
2140                ), // First Istanbul and first Muir Glacier block
2141                (
2142                    Head { number: 9199999, timestamp: 0, ..Default::default() },
2143                    ForkId { hash: ForkHash(hex!("0x879d6e30")), next: 9200000 },
2144                ), // Last Istanbul and first Muir Glacier block
2145                (
2146                    Head { number: 9200000, timestamp: 0, ..Default::default() },
2147                    ForkId { hash: ForkHash(hex!("0xe029e991")), next: 12244000 },
2148                ), // First Muir Glacier block
2149                (
2150                    Head { number: 12243999, timestamp: 0, ..Default::default() },
2151                    ForkId { hash: ForkHash(hex!("0xe029e991")), next: 12244000 },
2152                ), // Last Muir Glacier block
2153                (
2154                    Head { number: 12244000, timestamp: 0, ..Default::default() },
2155                    ForkId { hash: ForkHash(hex!("0x0eb440f6")), next: 12965000 },
2156                ), // First Berlin block
2157                (
2158                    Head { number: 12964999, timestamp: 0, ..Default::default() },
2159                    ForkId { hash: ForkHash(hex!("0x0eb440f6")), next: 12965000 },
2160                ), // Last Berlin block
2161                (
2162                    Head { number: 12965000, timestamp: 0, ..Default::default() },
2163                    ForkId { hash: ForkHash(hex!("0xb715077d")), next: 13773000 },
2164                ), // First London block
2165                (
2166                    Head { number: 13772999, timestamp: 0, ..Default::default() },
2167                    ForkId { hash: ForkHash(hex!("0xb715077d")), next: 13773000 },
2168                ), // Last London block
2169                (
2170                    Head { number: 13773000, timestamp: 0, ..Default::default() },
2171                    ForkId { hash: ForkHash(hex!("0x20c327fc")), next: 15050000 },
2172                ), // First Arrow Glacier block
2173                (
2174                    Head { number: 15049999, timestamp: 0, ..Default::default() },
2175                    ForkId { hash: ForkHash(hex!("0x20c327fc")), next: 15050000 },
2176                ), // Last Arrow Glacier block
2177                (
2178                    Head { number: 15050000, timestamp: 0, ..Default::default() },
2179                    ForkId { hash: ForkHash(hex!("0xf0afd0e3")), next: 1681338455 },
2180                ), // First Gray Glacier block
2181                (
2182                    Head { number: 19999999, timestamp: 1667999999, ..Default::default() },
2183                    ForkId { hash: ForkHash(hex!("0xf0afd0e3")), next: 1681338455 },
2184                ), // Last Gray Glacier block
2185                (
2186                    Head { number: 20000000, timestamp: 1681338455, ..Default::default() },
2187                    ForkId { hash: ForkHash(hex!("0xdce96c2d")), next: 1710338135 },
2188                ), // Last Shanghai block
2189                (
2190                    Head { number: 20000001, timestamp: 1710338134, ..Default::default() },
2191                    ForkId { hash: ForkHash(hex!("0xdce96c2d")), next: 1710338135 },
2192                ), // First Cancun block
2193                (
2194                    Head { number: 20000002, timestamp: 1710338135, ..Default::default() },
2195                    ForkId { hash: ForkHash(hex!("0x9f3d2254")), next: 1746612311 },
2196                ), // Last Cancun block
2197                (
2198                    Head { number: 20000003, timestamp: 1746612310, ..Default::default() },
2199                    ForkId { hash: ForkHash(hex!("0x9f3d2254")), next: 1746612311 },
2200                ), // First Prague block
2201                (
2202                    Head { number: 20000004, timestamp: 1746612311, ..Default::default() },
2203                    ForkId {
2204                        hash: ForkHash(hex!("0xc376cf8b")),
2205                        next: mainnet::MAINNET_OSAKA_TIMESTAMP,
2206                    },
2207                ),
2208                // Osaka block
2209                (
2210                    Head {
2211                        number: 20000004,
2212                        timestamp: mainnet::MAINNET_OSAKA_TIMESTAMP,
2213                        ..Default::default()
2214                    },
2215                    ForkId {
2216                        hash: ForkHash(hex!("0x5167e2a6")),
2217                        next: mainnet::MAINNET_BPO1_TIMESTAMP,
2218                    },
2219                ),
2220            ],
2221        );
2222    }
2223
2224    /// Constructs a [`ChainSpec`] with the given [`ChainSpecBuilder`], shanghai, and cancun fork
2225    /// timestamps.
2226    fn construct_chainspec(
2227        builder: ChainSpecBuilder,
2228        shanghai_time: u64,
2229        cancun_time: u64,
2230    ) -> ChainSpec {
2231        builder
2232            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(shanghai_time))
2233            .with_fork(EthereumHardfork::Cancun, ForkCondition::Timestamp(cancun_time))
2234            .build()
2235    }
2236
2237    /// Tests that time-based forks which are active at genesis are not included in forkid hash.
2238    ///
2239    /// This is based off of the test vectors here:
2240    /// <https://github.com/ethereum/go-ethereum/blob/2e02c1ffd9dffd1ec9e43c6b66f6c9bd1e556a0b/core/forkid/forkid_test.go#L390-L440>
2241    #[test]
2242    fn test_timestamp_fork_in_genesis() {
2243        let timestamp = 1690475657u64;
2244        let default_spec_builder = ChainSpecBuilder::default()
2245            .chain(Chain::from_id(1337))
2246            .genesis(Genesis::default().with_timestamp(timestamp))
2247            .paris_activated();
2248
2249        // test format: (chain spec, expected next value) - the forkhash will be determined by the
2250        // genesis hash of the constructed chainspec
2251        let tests = [
2252            (
2253                construct_chainspec(default_spec_builder.clone(), timestamp - 1, timestamp + 1),
2254                timestamp + 1,
2255            ),
2256            (
2257                construct_chainspec(default_spec_builder.clone(), timestamp, timestamp + 1),
2258                timestamp + 1,
2259            ),
2260            (
2261                construct_chainspec(default_spec_builder, timestamp + 1, timestamp + 2),
2262                timestamp + 1,
2263            ),
2264        ];
2265
2266        for (spec, expected_timestamp) in tests {
2267            let got_forkid = spec.fork_id(&Head { number: 0, timestamp: 0, ..Default::default() });
2268            // This is slightly different from the geth test because we use the shanghai timestamp
2269            // to determine whether or not to include a withdrawals root in the genesis header.
2270            // This makes the genesis hash different, and as a result makes the ChainSpec fork hash
2271            // different.
2272            let genesis_hash = spec.genesis_hash();
2273            let expected_forkid =
2274                ForkId { hash: ForkHash::from(genesis_hash), next: expected_timestamp };
2275            assert_eq!(got_forkid, expected_forkid);
2276        }
2277    }
2278
2279    /// Checks that the fork is not active at a terminal ttd block.
2280    #[test]
2281    fn check_terminal_ttd() {
2282        let chainspec = ChainSpecBuilder::mainnet().build();
2283
2284        // Check that Paris is not active on terminal PoW block #15537393.
2285        let terminal_block_ttd = U256::from(58750003716598352816469_u128);
2286        let terminal_block_difficulty = U256::from(11055787484078698_u128);
2287        assert!(!chainspec
2288            .fork(EthereumHardfork::Paris)
2289            .active_at_ttd(terminal_block_ttd, terminal_block_difficulty));
2290
2291        // Check that Paris is active on first PoS block #15537394.
2292        let first_pos_block_ttd = U256::from(58750003716598352816469_u128);
2293        let first_pos_difficulty = U256::ZERO;
2294        assert!(chainspec
2295            .fork(EthereumHardfork::Paris)
2296            .active_at_ttd(first_pos_block_ttd, first_pos_difficulty));
2297    }
2298
2299    #[test]
2300    fn geth_genesis_with_shanghai() {
2301        let geth_genesis = r#"
2302        {
2303          "config": {
2304            "chainId": 1337,
2305            "homesteadBlock": 0,
2306            "eip150Block": 0,
2307            "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2308            "eip155Block": 0,
2309            "eip158Block": 0,
2310            "byzantiumBlock": 0,
2311            "constantinopleBlock": 0,
2312            "petersburgBlock": 0,
2313            "istanbulBlock": 0,
2314            "muirGlacierBlock": 0,
2315            "berlinBlock": 0,
2316            "londonBlock": 0,
2317            "arrowGlacierBlock": 0,
2318            "grayGlacierBlock": 0,
2319            "shanghaiTime": 0,
2320            "cancunTime": 1,
2321            "terminalTotalDifficulty": 0,
2322            "terminalTotalDifficultyPassed": true,
2323            "ethash": {}
2324          },
2325          "nonce": "0x0",
2326          "timestamp": "0x0",
2327          "extraData": "0x",
2328          "gasLimit": "0x4c4b40",
2329          "difficulty": "0x1",
2330          "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2331          "coinbase": "0x0000000000000000000000000000000000000000",
2332          "alloc": {
2333            "658bdf435d810c91414ec09147daa6db62406379": {
2334              "balance": "0x487a9a304539440000"
2335            },
2336            "aa00000000000000000000000000000000000000": {
2337              "code": "0x6042",
2338              "storage": {
2339                "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000000",
2340                "0x0100000000000000000000000000000000000000000000000000000000000000": "0x0100000000000000000000000000000000000000000000000000000000000000",
2341                "0x0200000000000000000000000000000000000000000000000000000000000000": "0x0200000000000000000000000000000000000000000000000000000000000000",
2342                "0x0300000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000303"
2343              },
2344              "balance": "0x1",
2345              "nonce": "0x1"
2346            },
2347            "bb00000000000000000000000000000000000000": {
2348              "code": "0x600154600354",
2349              "storage": {
2350                "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000000",
2351                "0x0100000000000000000000000000000000000000000000000000000000000000": "0x0100000000000000000000000000000000000000000000000000000000000000",
2352                "0x0200000000000000000000000000000000000000000000000000000000000000": "0x0200000000000000000000000000000000000000000000000000000000000000",
2353                "0x0300000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000303"
2354              },
2355              "balance": "0x2",
2356              "nonce": "0x1"
2357            }
2358          },
2359          "number": "0x0",
2360          "gasUsed": "0x0",
2361          "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2362          "baseFeePerGas": "0x3b9aca00"
2363        }
2364        "#;
2365
2366        let genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
2367        let chainspec = ChainSpec::from(genesis);
2368
2369        // assert a bunch of hardforks that should be set
2370        assert_eq!(
2371            chainspec.hardforks.get(EthereumHardfork::Homestead).unwrap(),
2372            ForkCondition::Block(0)
2373        );
2374        assert_eq!(
2375            chainspec.hardforks.get(EthereumHardfork::Tangerine).unwrap(),
2376            ForkCondition::Block(0)
2377        );
2378        assert_eq!(
2379            chainspec.hardforks.get(EthereumHardfork::SpuriousDragon).unwrap(),
2380            ForkCondition::Block(0)
2381        );
2382        assert_eq!(
2383            chainspec.hardforks.get(EthereumHardfork::Byzantium).unwrap(),
2384            ForkCondition::Block(0)
2385        );
2386        assert_eq!(
2387            chainspec.hardforks.get(EthereumHardfork::Constantinople).unwrap(),
2388            ForkCondition::Block(0)
2389        );
2390        assert_eq!(
2391            chainspec.hardforks.get(EthereumHardfork::Petersburg).unwrap(),
2392            ForkCondition::Block(0)
2393        );
2394        assert_eq!(
2395            chainspec.hardforks.get(EthereumHardfork::Istanbul).unwrap(),
2396            ForkCondition::Block(0)
2397        );
2398        assert_eq!(
2399            chainspec.hardforks.get(EthereumHardfork::MuirGlacier).unwrap(),
2400            ForkCondition::Block(0)
2401        );
2402        assert_eq!(
2403            chainspec.hardforks.get(EthereumHardfork::Berlin).unwrap(),
2404            ForkCondition::Block(0)
2405        );
2406        assert_eq!(
2407            chainspec.hardforks.get(EthereumHardfork::London).unwrap(),
2408            ForkCondition::Block(0)
2409        );
2410        assert_eq!(
2411            chainspec.hardforks.get(EthereumHardfork::ArrowGlacier).unwrap(),
2412            ForkCondition::Block(0)
2413        );
2414        assert_eq!(
2415            chainspec.hardforks.get(EthereumHardfork::GrayGlacier).unwrap(),
2416            ForkCondition::Block(0)
2417        );
2418
2419        // including time based hardforks
2420        assert_eq!(
2421            chainspec.hardforks.get(EthereumHardfork::Shanghai).unwrap(),
2422            ForkCondition::Timestamp(0)
2423        );
2424
2425        // including time based hardforks
2426        assert_eq!(
2427            chainspec.hardforks.get(EthereumHardfork::Cancun).unwrap(),
2428            ForkCondition::Timestamp(1)
2429        );
2430
2431        // alloc key -> expected rlp mapping
2432        let key_rlp = vec![
2433            (
2434                hex!("0x658bdf435d810c91414ec09147daa6db62406379"),
2435                &hex!(
2436                    "0xf84d8089487a9a304539440000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
2437                )[..],
2438            ),
2439            (
2440                hex!("0xaa00000000000000000000000000000000000000"),
2441                &hex!(
2442                    "0xf8440101a08afc95b7d18a226944b9c2070b6bda1c3a36afcc3730429d47579c94b9fe5850a0ce92c756baff35fa740c3557c1a971fd24d2d35b7c8e067880d50cd86bb0bc99"
2443                )[..],
2444            ),
2445            (
2446                hex!("0xbb00000000000000000000000000000000000000"),
2447                &hex!(
2448                    "0xf8440102a08afc95b7d18a226944b9c2070b6bda1c3a36afcc3730429d47579c94b9fe5850a0e25a53cbb501cec2976b393719c63d832423dd70a458731a0b64e4847bbca7d2"
2449                )[..],
2450            ),
2451        ];
2452
2453        for (key, expected_rlp) in key_rlp {
2454            let account = chainspec.genesis.alloc.get(&key).expect("account should exist");
2455            assert_eq!(&alloy_rlp::encode(TrieAccount::from(account.clone())), expected_rlp);
2456        }
2457
2458        let expected_state_root: B256 =
2459            b256!("0x078dc6061b1d8eaa8493384b59c9c65ceb917201221d08b80c4de6770b6ec7e7");
2460        assert_eq!(chainspec.genesis_header().state_root, expected_state_root);
2461
2462        assert_eq!(chainspec.genesis_header().withdrawals_root, Some(EMPTY_ROOT_HASH));
2463
2464        let expected_hash: B256 =
2465            b256!("0x1fc027d65f820d3eef441ebeec139ebe09e471cf98516dce7b5643ccb27f418c");
2466        let hash = chainspec.genesis_hash();
2467        assert_eq!(hash, expected_hash);
2468    }
2469
2470    #[test]
2471    fn hive_geth_json() {
2472        let hive_json = r#"
2473        {
2474            "nonce": "0x0000000000000042",
2475            "difficulty": "0x2123456",
2476            "mixHash": "0x123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234",
2477            "coinbase": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2478            "timestamp": "0x123456",
2479            "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2480            "extraData": "0xfafbfcfd",
2481            "gasLimit": "0x2fefd8",
2482            "alloc": {
2483                "dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6": {
2484                    "balance": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
2485                },
2486                "e6716f9544a56c530d868e4bfbacb172315bdead": {
2487                    "balance": "0x11",
2488                    "code": "0x12"
2489                },
2490                "b9c015918bdaba24b4ff057a92a3873d6eb201be": {
2491                    "balance": "0x21",
2492                    "storage": {
2493                        "0x0000000000000000000000000000000000000000000000000000000000000001": "0x22"
2494                    }
2495                },
2496                "1a26338f0d905e295fccb71fa9ea849ffa12aaf4": {
2497                    "balance": "0x31",
2498                    "nonce": "0x32"
2499                },
2500                "0000000000000000000000000000000000000001": {
2501                    "balance": "0x41"
2502                },
2503                "0000000000000000000000000000000000000002": {
2504                    "balance": "0x51"
2505                },
2506                "0000000000000000000000000000000000000003": {
2507                    "balance": "0x61"
2508                },
2509                "0000000000000000000000000000000000000004": {
2510                    "balance": "0x71"
2511                }
2512            },
2513            "config": {
2514                "ethash": {},
2515                "chainId": 10,
2516                "homesteadBlock": 0,
2517                "eip150Block": 0,
2518                "eip155Block": 0,
2519                "eip158Block": 0,
2520                "byzantiumBlock": 0,
2521                "constantinopleBlock": 0,
2522                "petersburgBlock": 0,
2523                "istanbulBlock": 0
2524            }
2525        }
2526        "#;
2527
2528        let genesis = serde_json::from_str::<Genesis>(hive_json).unwrap();
2529        let chainspec: ChainSpec = genesis.into();
2530        assert_eq!(chainspec.chain, Chain::optimism_mainnet());
2531        let expected_state_root: B256 =
2532            b256!("0x9a6049ac535e3dc7436c189eaa81c73f35abd7f282ab67c32944ff0301d63360");
2533        assert_eq!(chainspec.genesis_header().state_root, expected_state_root);
2534        let hard_forks = vec![
2535            EthereumHardfork::Byzantium,
2536            EthereumHardfork::Homestead,
2537            EthereumHardfork::Istanbul,
2538            EthereumHardfork::Petersburg,
2539            EthereumHardfork::Constantinople,
2540        ];
2541        for fork in hard_forks {
2542            assert_eq!(chainspec.hardforks.get(fork).unwrap(), ForkCondition::Block(0));
2543        }
2544
2545        let expected_hash: B256 =
2546            b256!("0x5ae31c6522bd5856129f66be3d582b842e4e9faaa87f21cce547128339a9db3c");
2547        let hash = chainspec.genesis_header().hash_slow();
2548        assert_eq!(hash, expected_hash);
2549    }
2550
2551    #[test]
2552    fn test_hive_paris_block_genesis_json() {
2553        // this tests that we can handle `parisBlock` in the genesis json and can use it to output
2554        // a correct forkid
2555        let hive_paris = r#"
2556        {
2557          "config": {
2558            "ethash": {},
2559            "chainId": 3503995874084926,
2560            "homesteadBlock": 0,
2561            "eip150Block": 6,
2562            "eip155Block": 12,
2563            "eip158Block": 12,
2564            "byzantiumBlock": 18,
2565            "constantinopleBlock": 24,
2566            "petersburgBlock": 30,
2567            "istanbulBlock": 36,
2568            "muirGlacierBlock": 42,
2569            "berlinBlock": 48,
2570            "londonBlock": 54,
2571            "arrowGlacierBlock": 60,
2572            "grayGlacierBlock": 66,
2573            "mergeNetsplitBlock": 72,
2574            "terminalTotalDifficulty": 9454784,
2575            "shanghaiTime": 780,
2576            "cancunTime": 840
2577          },
2578          "nonce": "0x0",
2579          "timestamp": "0x0",
2580          "extraData": "0x68697665636861696e",
2581          "gasLimit": "0x23f3e20",
2582          "difficulty": "0x20000",
2583          "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2584          "coinbase": "0x0000000000000000000000000000000000000000",
2585          "alloc": {
2586            "000f3df6d732807ef1319fb7b8bb8522d0beac02": {
2587              "code": "0x3373fffffffffffffffffffffffffffffffffffffffe14604d57602036146024575f5ffd5b5f35801560495762001fff810690815414603c575f5ffd5b62001fff01545f5260205ff35b5f5ffd5b62001fff42064281555f359062001fff015500",
2588              "balance": "0x2a"
2589            },
2590            "0c2c51a0990aee1d73c1228de158688341557508": {
2591              "balance": "0xc097ce7bc90715b34b9f1000000000"
2592            },
2593            "14e46043e63d0e3cdcf2530519f4cfaf35058cb2": {
2594              "balance": "0xc097ce7bc90715b34b9f1000000000"
2595            },
2596            "16c57edf7fa9d9525378b0b81bf8a3ced0620c1c": {
2597              "balance": "0xc097ce7bc90715b34b9f1000000000"
2598            },
2599            "1f4924b14f34e24159387c0a4cdbaa32f3ddb0cf": {
2600              "balance": "0xc097ce7bc90715b34b9f1000000000"
2601            },
2602            "1f5bde34b4afc686f136c7a3cb6ec376f7357759": {
2603              "balance": "0xc097ce7bc90715b34b9f1000000000"
2604            },
2605            "2d389075be5be9f2246ad654ce152cf05990b209": {
2606              "balance": "0xc097ce7bc90715b34b9f1000000000"
2607            },
2608            "3ae75c08b4c907eb63a8960c45b86e1e9ab6123c": {
2609              "balance": "0xc097ce7bc90715b34b9f1000000000"
2610            },
2611            "4340ee1b812acb40a1eb561c019c327b243b92df": {
2612              "balance": "0xc097ce7bc90715b34b9f1000000000"
2613            },
2614            "4a0f1452281bcec5bd90c3dce6162a5995bfe9df": {
2615              "balance": "0xc097ce7bc90715b34b9f1000000000"
2616            },
2617            "4dde844b71bcdf95512fb4dc94e84fb67b512ed8": {
2618              "balance": "0xc097ce7bc90715b34b9f1000000000"
2619            },
2620            "5f552da00dfb4d3749d9e62dcee3c918855a86a0": {
2621              "balance": "0xc097ce7bc90715b34b9f1000000000"
2622            },
2623            "654aa64f5fbefb84c270ec74211b81ca8c44a72e": {
2624              "balance": "0xc097ce7bc90715b34b9f1000000000"
2625            },
2626            "717f8aa2b982bee0e29f573d31df288663e1ce16": {
2627              "balance": "0xc097ce7bc90715b34b9f1000000000"
2628            },
2629            "7435ed30a8b4aeb0877cef0c6e8cffe834eb865f": {
2630              "balance": "0xc097ce7bc90715b34b9f1000000000"
2631            },
2632            "83c7e323d189f18725ac510004fdc2941f8c4a78": {
2633              "balance": "0xc097ce7bc90715b34b9f1000000000"
2634            },
2635            "84e75c28348fb86acea1a93a39426d7d60f4cc46": {
2636              "balance": "0xc097ce7bc90715b34b9f1000000000"
2637            },
2638            "8bebc8ba651aee624937e7d897853ac30c95a067": {
2639              "storage": {
2640                "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000001",
2641                "0x0000000000000000000000000000000000000000000000000000000000000002": "0x0000000000000000000000000000000000000000000000000000000000000002",
2642                "0x0000000000000000000000000000000000000000000000000000000000000003": "0x0000000000000000000000000000000000000000000000000000000000000003"
2643              },
2644              "balance": "0x1",
2645              "nonce": "0x1"
2646            },
2647            "c7b99a164efd027a93f147376cc7da7c67c6bbe0": {
2648              "balance": "0xc097ce7bc90715b34b9f1000000000"
2649            },
2650            "d803681e487e6ac18053afc5a6cd813c86ec3e4d": {
2651              "balance": "0xc097ce7bc90715b34b9f1000000000"
2652            },
2653            "e7d13f7aa2a838d24c59b40186a0aca1e21cffcc": {
2654              "balance": "0xc097ce7bc90715b34b9f1000000000"
2655            },
2656            "eda8645ba6948855e3b3cd596bbb07596d59c603": {
2657              "balance": "0xc097ce7bc90715b34b9f1000000000"
2658            }
2659          },
2660          "number": "0x0",
2661          "gasUsed": "0x0",
2662          "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
2663          "baseFeePerGas": null,
2664          "excessBlobGas": null,
2665          "blobGasUsed": null
2666        }
2667        "#;
2668
2669        // check that it deserializes properly
2670        let genesis: Genesis = serde_json::from_str(hive_paris).unwrap();
2671        let chainspec = ChainSpec::from(genesis);
2672
2673        // make sure we are at ForkHash("bc0c2605") with Head post-cancun
2674        let expected_forkid = ForkId { hash: ForkHash(hex!("0xbc0c2605")), next: 0 };
2675        let got_forkid =
2676            chainspec.fork_id(&Head { number: 73, timestamp: 840, ..Default::default() });
2677
2678        // check that they're the same
2679        assert_eq!(got_forkid, expected_forkid);
2680        // Check that paris block and final difficulty are set correctly
2681        assert_eq!(chainspec.paris_block_and_final_difficulty, Some((72, U256::from(9454784))));
2682    }
2683
2684    #[test]
2685    fn test_parse_genesis_json() {
2686        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"}"#;
2687        let genesis: Genesis = serde_json::from_str(s).unwrap();
2688        let acc =
2689            genesis.alloc.get(&address!("0xaa00000000000000000000000000000000000000")).unwrap();
2690        assert_eq!(acc.balance, U256::ONE);
2691        assert_eq!(genesis.base_fee_per_gas, Some(0x1337));
2692    }
2693
2694    #[test]
2695    fn test_parse_cancun_genesis_json() {
2696        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"}"#;
2697        let genesis: Genesis = serde_json::from_str(s).unwrap();
2698        let acc =
2699            genesis.alloc.get(&address!("0xaa00000000000000000000000000000000000000")).unwrap();
2700        assert_eq!(acc.balance, U256::ONE);
2701        // assert that the cancun time was picked up
2702        assert_eq!(genesis.config.cancun_time, Some(4661));
2703    }
2704
2705    #[test]
2706    fn test_parse_prague_genesis_all_formats() {
2707        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"}"#;
2708        let genesis: Genesis = serde_json::from_str(s).unwrap();
2709
2710        // assert that the alloc was picked up
2711        let acc =
2712            genesis.alloc.get(&address!("0xaa00000000000000000000000000000000000000")).unwrap();
2713        assert_eq!(acc.balance, U256::ONE);
2714        // assert that the cancun time was picked up
2715        assert_eq!(genesis.config.cancun_time, Some(4661));
2716        // assert that the prague time was picked up
2717        assert_eq!(genesis.config.prague_time, Some(4662));
2718    }
2719
2720    #[test]
2721    fn test_parse_cancun_genesis_all_formats() {
2722        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"}"#;
2723        let genesis: Genesis = serde_json::from_str(s).unwrap();
2724
2725        // assert that the alloc was picked up
2726        let acc =
2727            genesis.alloc.get(&address!("0xaa00000000000000000000000000000000000000")).unwrap();
2728        assert_eq!(acc.balance, U256::ONE);
2729        // assert that the cancun time was picked up
2730        assert_eq!(genesis.config.cancun_time, Some(4661));
2731    }
2732
2733    #[test]
2734    fn test_paris_block_and_total_difficulty() {
2735        let genesis = Genesis { gas_limit: 0x2fefd8u64, ..Default::default() };
2736        let paris_chainspec = ChainSpecBuilder::default()
2737            .chain(Chain::from_id(1337))
2738            .genesis(genesis)
2739            .paris_activated()
2740            .build();
2741        assert_eq!(paris_chainspec.paris_block_and_final_difficulty, Some((0, U256::ZERO)));
2742    }
2743
2744    #[test]
2745    fn test_default_cancun_header_forkhash() {
2746        // set the gas limit from the hive test genesis according to the hash
2747        let genesis = Genesis { gas_limit: 0x2fefd8u64, ..Default::default() };
2748        let default_chainspec = ChainSpecBuilder::default()
2749            .chain(Chain::from_id(1337))
2750            .genesis(genesis)
2751            .cancun_activated()
2752            .build();
2753        let mut header = default_chainspec.genesis_header().clone();
2754
2755        // set the state root to the same as in the hive test the hash was pulled from
2756        header.state_root =
2757            b256!("0x62e2595e017f0ca23e08d17221010721a71c3ae932f4ea3cb12117786bb392d4");
2758
2759        // shanghai is activated so we should have a withdrawals root
2760        assert_eq!(header.withdrawals_root, Some(EMPTY_WITHDRAWALS));
2761
2762        // cancun is activated so we should have a zero parent beacon block root, zero blob gas
2763        // used, and zero excess blob gas
2764        assert_eq!(header.parent_beacon_block_root, Some(B256::ZERO));
2765        assert_eq!(header.blob_gas_used, Some(0));
2766        assert_eq!(header.excess_blob_gas, Some(0));
2767
2768        // check the genesis hash
2769        let genesis_hash = header.hash_slow();
2770        let expected_hash =
2771            b256!("0x16bb7c59613a5bad3f7c04a852fd056545ade2483968d9a25a1abb05af0c4d37");
2772        assert_eq!(genesis_hash, expected_hash);
2773
2774        // check that the forkhash is correct
2775        let expected_forkhash = ForkHash(hex!("0x8062457a"));
2776        assert_eq!(ForkHash::from(genesis_hash), expected_forkhash);
2777    }
2778
2779    #[test]
2780    fn test_amsterdam_genesis_slot_number() {
2781        // a genesis-provided slot number is used as-is
2782        let genesis =
2783            Genesis { gas_limit: 0x2fefd8u64, ..Default::default() }.with_slot_number(Some(999));
2784        let chainspec = ChainSpecBuilder::default()
2785            .chain(Chain::from_id(1337))
2786            .genesis(genesis)
2787            .amsterdam_activated()
2788            .build();
2789        assert_eq!(chainspec.genesis_header().slot_number, Some(999));
2790
2791        // an omitted slot number defaults to 0
2792        let genesis = Genesis { gas_limit: 0x2fefd8u64, ..Default::default() };
2793        let chainspec = ChainSpecBuilder::default()
2794            .chain(Chain::from_id(1337))
2795            .genesis(genesis)
2796            .amsterdam_activated()
2797            .build();
2798        assert_eq!(chainspec.genesis_header().slot_number, Some(0));
2799    }
2800
2801    #[test]
2802    fn holesky_paris_activated_at_genesis() {
2803        assert!(HOLESKY
2804            .fork(EthereumHardfork::Paris)
2805            .active_at_ttd(HOLESKY.genesis.difficulty, HOLESKY.genesis.difficulty));
2806    }
2807
2808    #[test]
2809    fn test_genesis_format_deserialization() {
2810        // custom genesis with chain config
2811        let config = ChainConfig {
2812            chain_id: 2600,
2813            homestead_block: Some(0),
2814            eip150_block: Some(0),
2815            eip155_block: Some(0),
2816            eip158_block: Some(0),
2817            byzantium_block: Some(0),
2818            constantinople_block: Some(0),
2819            petersburg_block: Some(0),
2820            istanbul_block: Some(0),
2821            berlin_block: Some(0),
2822            london_block: Some(0),
2823            shanghai_time: Some(0),
2824            terminal_total_difficulty: Some(U256::ZERO),
2825            terminal_total_difficulty_passed: true,
2826            ..Default::default()
2827        };
2828        // genesis
2829        let genesis = Genesis {
2830            config,
2831            nonce: 0,
2832            timestamp: 1698688670,
2833            gas_limit: 5000,
2834            difficulty: U256::ZERO,
2835            mix_hash: B256::ZERO,
2836            coinbase: Address::ZERO,
2837            ..Default::default()
2838        };
2839
2840        // seed accounts after genesis struct created
2841        let address = address!("0x6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b");
2842        let account = GenesisAccount::default().with_balance(U256::from(33));
2843        let genesis = genesis.extend_accounts(HashMap::from([(address, account)]));
2844
2845        // ensure genesis is deserialized correctly
2846        let serialized_genesis = serde_json::to_string(&genesis).unwrap();
2847        let deserialized_genesis: Genesis = serde_json::from_str(&serialized_genesis).unwrap();
2848
2849        assert_eq!(genesis, deserialized_genesis);
2850    }
2851
2852    #[test]
2853    fn check_fork_id_chainspec_with_fork_condition_never() {
2854        let spec: ChainSpec = ChainSpec {
2855            chain: Chain::mainnet(),
2856            genesis: Genesis::default(),
2857            hardforks: ChainHardforks::new(vec![(
2858                EthereumHardfork::Frontier.boxed(),
2859                ForkCondition::Never,
2860            )]),
2861            paris_block_and_final_difficulty: None,
2862            deposit_contract: None,
2863            ..Default::default()
2864        };
2865
2866        assert_eq!(spec.hardfork_fork_id(EthereumHardfork::Frontier), None);
2867    }
2868
2869    #[test]
2870    fn check_fork_filter_chainspec_with_fork_condition_never() {
2871        let spec: ChainSpec = ChainSpec {
2872            chain: Chain::mainnet(),
2873            genesis: Genesis::default(),
2874            hardforks: ChainHardforks::new(vec![(
2875                EthereumHardfork::Shanghai.boxed(),
2876                ForkCondition::Never,
2877            )]),
2878            paris_block_and_final_difficulty: None,
2879            deposit_contract: None,
2880            ..Default::default()
2881        };
2882
2883        assert_eq!(spec.hardfork_fork_filter(EthereumHardfork::Shanghai), None);
2884    }
2885
2886    #[test]
2887    fn latest_eth_mainnet_fork_id() {
2888        // BPO2
2889        assert_eq!(ForkId { hash: ForkHash(hex!("0x07c9462e")), next: 0 }, MAINNET.latest_fork_id())
2890    }
2891
2892    #[test]
2893    fn latest_hoodi_mainnet_fork_id() {
2894        // Amsterdam.
2895        assert_eq!(ForkId { hash: ForkHash(hex!("0x3ae0b2e6")), next: 0 }, HOODI.latest_fork_id())
2896    }
2897
2898    #[test]
2899    fn latest_holesky_mainnet_fork_id() {
2900        // BPO2
2901        assert_eq!(ForkId { hash: ForkHash(hex!("0x9bc6cb31")), next: 0 }, HOLESKY.latest_fork_id())
2902    }
2903
2904    #[test]
2905    fn latest_sepolia_mainnet_fork_id() {
2906        // Amsterdam
2907        assert_eq!(ForkId { hash: ForkHash(hex!("0x6c1d9423")), next: 0 }, SEPOLIA.latest_fork_id())
2908    }
2909
2910    #[test]
2911    fn test_fork_order_ethereum_mainnet() {
2912        let genesis = Genesis {
2913            config: ChainConfig {
2914                chain_id: 0,
2915                homestead_block: Some(0),
2916                dao_fork_block: Some(0),
2917                dao_fork_support: false,
2918                eip150_block: Some(0),
2919                eip155_block: Some(0),
2920                eip158_block: Some(0),
2921                byzantium_block: Some(0),
2922                constantinople_block: Some(0),
2923                petersburg_block: Some(0),
2924                istanbul_block: Some(0),
2925                muir_glacier_block: Some(0),
2926                berlin_block: Some(0),
2927                london_block: Some(0),
2928                arrow_glacier_block: Some(0),
2929                gray_glacier_block: Some(0),
2930                merge_netsplit_block: Some(0),
2931                shanghai_time: Some(0),
2932                cancun_time: Some(0),
2933                terminal_total_difficulty: Some(U256::ZERO),
2934                ..Default::default()
2935            },
2936            ..Default::default()
2937        };
2938
2939        let chain_spec: ChainSpec = genesis.into();
2940
2941        let hardforks: Vec<_> = chain_spec.hardforks.forks_iter().map(|(h, _)| h).collect();
2942        let expected_hardforks = vec![
2943            EthereumHardfork::Frontier.boxed(),
2944            EthereumHardfork::Homestead.boxed(),
2945            EthereumHardfork::Dao.boxed(),
2946            EthereumHardfork::Tangerine.boxed(),
2947            EthereumHardfork::SpuriousDragon.boxed(),
2948            EthereumHardfork::Byzantium.boxed(),
2949            EthereumHardfork::Constantinople.boxed(),
2950            EthereumHardfork::Petersburg.boxed(),
2951            EthereumHardfork::Istanbul.boxed(),
2952            EthereumHardfork::MuirGlacier.boxed(),
2953            EthereumHardfork::Berlin.boxed(),
2954            EthereumHardfork::London.boxed(),
2955            EthereumHardfork::ArrowGlacier.boxed(),
2956            EthereumHardfork::GrayGlacier.boxed(),
2957            EthereumHardfork::Paris.boxed(),
2958            EthereumHardfork::Shanghai.boxed(),
2959            EthereumHardfork::Cancun.boxed(),
2960        ];
2961
2962        assert!(expected_hardforks
2963            .iter()
2964            .zip(hardforks.iter())
2965            .all(|(expected, actual)| &**expected == *actual));
2966        assert_eq!(expected_hardforks.len(), hardforks.len());
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            // Without an osaka entry, Osaka keeps the chain's Prague blob counts.
3005            osaka: BlobParams {
3006                target_blob_count: 3,
3007                max_blob_count: 6,
3008                update_fraction: 3338477,
3009                min_blob_fee: BLOB_TX_MIN_BLOB_GASPRICE,
3010                max_blobs_per_tx: 6,
3011                blob_base_cost: 8192,
3012            },
3013            ..Default::default()
3014        };
3015        assert_eq!(hardfork_params, expected);
3016    }
3017
3018    #[test]
3019    fn parse_perf_net_genesis() {
3020        let s = r#"{
3021    "config": {
3022        "chainId": 1,
3023        "homesteadBlock": 1150000,
3024        "daoForkBlock": 1920000,
3025        "daoForkSupport": true,
3026        "eip150Block": 2463000,
3027        "eip150Hash": "0x2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0",
3028        "eip155Block": 2675000,
3029        "eip158Block": 2675000,
3030        "byzantiumBlock": 4370000,
3031        "constantinopleBlock": 7280000,
3032        "petersburgBlock": 7280000,
3033        "istanbulBlock": 9069000,
3034        "muirGlacierBlock": 9200000,
3035        "berlinBlock": 12244000,
3036        "londonBlock": 12965000,
3037        "arrowGlacierBlock": 13773000,
3038        "grayGlacierBlock": 15050000,
3039        "terminalTotalDifficulty": 58750000000000000000000,
3040        "terminalTotalDifficultyPassed": true,
3041        "shanghaiTime": 1681338455,
3042        "cancunTime": 1710338135,
3043        "pragueTime": 1746612311,
3044        "ethash": {},
3045        "depositContractAddress": "0x00000000219ab540356cBB839Cbe05303d7705Fa",
3046        "blobSchedule": {
3047            "cancun": {
3048                "target": 3,
3049                "max": 6,
3050                "baseFeeUpdateFraction": 3338477
3051            },
3052            "prague": {
3053                "target": 6,
3054                "max": 9,
3055                "baseFeeUpdateFraction": 5007716
3056            }
3057        }
3058    },
3059    "nonce": "0x42",
3060    "timestamp": "0x0",
3061    "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
3062    "gasLimit": "0x1388",
3063    "difficulty": "0x400000000",
3064    "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
3065    "coinbase": "0x0000000000000000000000000000000000000000",
3066    "number": "0x0",
3067    "gasUsed": "0x0",
3068    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
3069    "baseFeePerGas": null
3070}"#;
3071
3072        let genesis = serde_json::from_str::<Genesis>(s).unwrap();
3073        let chainspec = ChainSpec::from_genesis(genesis);
3074        let activation = chainspec.hardforks.fork(EthereumHardfork::Paris);
3075        assert_eq!(
3076            activation,
3077            ForkCondition::TTD {
3078                activation_block_number: MAINNET_PARIS_BLOCK,
3079                total_difficulty: MAINNET_PARIS_TTD,
3080                fork_block: None,
3081            }
3082        )
3083    }
3084}