alloy_genesis/
lib.rs

1//! Alloy genesis types
2
3#![doc = include_str!(".././README.md")]
4#![doc(
5    html_logo_url = "https://raw.githubusercontent.com/alloy-rs/core/main/assets/alloy.jpg",
6    html_favicon_url = "https://raw.githubusercontent.com/alloy-rs/core/main/assets/favicon.ico"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10#![cfg_attr(not(feature = "std"), no_std)]
11
12extern crate alloc;
13
14use alloc::{collections::BTreeMap, string::String, vec::Vec};
15use alloy_eips::{
16    eip7594,
17    eip7840::{self, BlobParams},
18    BlobScheduleBlobParams,
19};
20use alloy_primitives::{keccak256, Address, Bytes, B256, U256};
21use alloy_serde::{storage::deserialize_storage_map, OtherFields};
22use alloy_trie::{TrieAccount, EMPTY_ROOT_HASH, KECCAK_EMPTY};
23use core::str::FromStr;
24use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize};
25
26/// The genesis block specification.
27#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "camelCase", default)]
29pub struct Genesis {
30    /// The fork configuration for this network.
31    #[serde(default)]
32    pub config: ChainConfig,
33    /// The genesis header nonce.
34    #[serde(with = "alloy_serde::quantity")]
35    pub nonce: u64,
36    /// The genesis header timestamp.
37    #[serde(with = "alloy_serde::quantity")]
38    pub timestamp: u64,
39    /// The genesis header extra data.
40    pub extra_data: Bytes,
41    /// The genesis header gas limit.
42    #[serde(with = "alloy_serde::quantity")]
43    pub gas_limit: u64,
44    /// The genesis header difficulty.
45    pub difficulty: U256,
46    /// The genesis header mix hash.
47    pub mix_hash: B256,
48    /// The genesis header coinbase address.
49    pub coinbase: Address,
50    /// The initial state of accounts in the genesis block.
51    pub alloc: BTreeMap<Address, GenesisAccount>,
52    // NOTE: the following fields:
53    // * base_fee_per_gas
54    // * excess_blob_gas
55    // * blob_gas_used
56    // * number
57    // should NOT be set in a real genesis file, but are included here for compatibility with
58    // consensus tests, which have genesis files with these fields populated.
59    /// The genesis header base fee
60    #[serde(default, skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt")]
61    pub base_fee_per_gas: Option<u128>,
62    /// The genesis header excess blob gas
63    #[serde(default, skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt")]
64    pub excess_blob_gas: Option<u64>,
65    /// The genesis header blob gas used
66    #[serde(default, skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt")]
67    pub blob_gas_used: Option<u64>,
68    /// The genesis block number
69    #[serde(default, skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt")]
70    pub number: Option<u64>,
71}
72
73impl Genesis {
74    /// Creates a chain config for Clique using the given chain id and funds the given address with
75    /// max coins.
76    ///
77    /// Enables all hard forks up to London at genesis.
78    pub fn clique_genesis(chain_id: u64, signer_addr: Address) -> Self {
79        // set up a clique config with an instant sealing period and short (8 block) epoch
80        let clique_config = CliqueConfig { period: Some(0), epoch: Some(8) };
81
82        let config = ChainConfig {
83            chain_id,
84            eip155_block: Some(0),
85            eip150_block: Some(0),
86            eip158_block: Some(0),
87
88            homestead_block: Some(0),
89            byzantium_block: Some(0),
90            constantinople_block: Some(0),
91            petersburg_block: Some(0),
92            istanbul_block: Some(0),
93            muir_glacier_block: Some(0),
94            berlin_block: Some(0),
95            london_block: Some(0),
96            clique: Some(clique_config),
97            ..Default::default()
98        };
99
100        // fund account
101        let alloc = BTreeMap::from([(
102            signer_addr,
103            GenesisAccount { balance: U256::MAX, ..Default::default() },
104        )]);
105
106        // put signer address in the extra data, padded by the required amount of zeros
107        // Clique issue: https://github.com/ethereum/EIPs/issues/225
108        // Clique EIP: https://eips.ethereum.org/EIPS/eip-225
109        //
110        // The first 32 bytes are vanity data, so we will populate it with zeros
111        // This is followed by the signer address, which is 20 bytes
112        // There are 65 bytes of zeros after the signer address, which is usually populated with the
113        // proposer signature. Because the genesis does not have a proposer signature, it will be
114        // populated with zeros.
115        let extra_data_bytes = [&[0u8; 32][..], signer_addr.as_slice(), &[0u8; 65][..]].concat();
116        let extra_data = extra_data_bytes.into();
117
118        Self {
119            config,
120            alloc,
121            difficulty: U256::from(1),
122            gas_limit: 5_000_000,
123            extra_data,
124            ..Default::default()
125        }
126    }
127
128    /// Set the nonce.
129    pub const fn with_nonce(mut self, nonce: u64) -> Self {
130        self.nonce = nonce;
131        self
132    }
133
134    /// Set the timestamp.
135    pub const fn with_timestamp(mut self, timestamp: u64) -> Self {
136        self.timestamp = timestamp;
137        self
138    }
139
140    /// Set the extra data.
141    pub fn with_extra_data(mut self, extra_data: Bytes) -> Self {
142        self.extra_data = extra_data;
143        self
144    }
145
146    /// Set the gas limit.
147    pub const fn with_gas_limit(mut self, gas_limit: u64) -> Self {
148        self.gas_limit = gas_limit;
149        self
150    }
151
152    /// Set the difficulty.
153    pub const fn with_difficulty(mut self, difficulty: U256) -> Self {
154        self.difficulty = difficulty;
155        self
156    }
157
158    /// Set the mix hash of the header.
159    pub const fn with_mix_hash(mut self, mix_hash: B256) -> Self {
160        self.mix_hash = mix_hash;
161        self
162    }
163
164    /// Set the coinbase address.
165    pub const fn with_coinbase(mut self, address: Address) -> Self {
166        self.coinbase = address;
167        self
168    }
169
170    /// Set the base fee.
171    pub const fn with_base_fee(mut self, base_fee: Option<u128>) -> Self {
172        self.base_fee_per_gas = base_fee;
173        self
174    }
175
176    /// Set the excess blob gas.
177    pub const fn with_excess_blob_gas(mut self, excess_blob_gas: Option<u64>) -> Self {
178        self.excess_blob_gas = excess_blob_gas;
179        self
180    }
181
182    /// Set the blob gas used.
183    pub const fn with_blob_gas_used(mut self, blob_gas_used: Option<u64>) -> Self {
184        self.blob_gas_used = blob_gas_used;
185        self
186    }
187
188    /// Add accounts to the genesis block. If the address is already present,
189    /// the account is updated.
190    pub fn extend_accounts(
191        mut self,
192        accounts: impl IntoIterator<Item = (Address, GenesisAccount)>,
193    ) -> Self {
194        self.alloc.extend(accounts);
195        self
196    }
197}
198
199/// An account in the state of the genesis block.
200#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
201#[serde(deny_unknown_fields)]
202pub struct GenesisAccount {
203    /// The nonce of the account at genesis.
204    #[serde(skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt", default)]
205    pub nonce: Option<u64>,
206    /// The balance of the account at genesis.
207    pub balance: U256,
208    /// The account's bytecode at genesis.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub code: Option<Bytes>,
211    /// The account's storage at genesis.
212    #[serde(
213        default,
214        skip_serializing_if = "Option::is_none",
215        deserialize_with = "deserialize_storage_map"
216    )]
217    pub storage: Option<BTreeMap<B256, B256>>,
218    /// The account's private key. Should only be used for testing.
219    #[serde(
220        rename = "secretKey",
221        default,
222        skip_serializing_if = "Option::is_none",
223        deserialize_with = "deserialize_private_key"
224    )]
225    pub private_key: Option<B256>,
226}
227
228impl GenesisAccount {
229    /// Set the nonce.
230    pub const fn with_nonce(mut self, nonce: Option<u64>) -> Self {
231        self.nonce = nonce;
232        self
233    }
234
235    /// Set the balance.
236    pub const fn with_balance(mut self, balance: U256) -> Self {
237        self.balance = balance;
238        self
239    }
240
241    /// Set the code.
242    pub fn with_code(mut self, code: Option<Bytes>) -> Self {
243        self.code = code;
244        self
245    }
246
247    /// Set the storage.
248    pub fn with_storage(mut self, storage: Option<BTreeMap<B256, B256>>) -> Self {
249        self.storage = storage;
250        self
251    }
252
253    /// Returns an iterator over the storage slots in (`B256`, `U256`) format.
254    pub fn storage_slots(&self) -> impl Iterator<Item = (B256, U256)> + '_ {
255        self.storage.as_ref().into_iter().flat_map(|storage| storage.iter()).map(|(key, value)| {
256            let value = U256::from_be_bytes(value.0);
257            (*key, value)
258        })
259    }
260
261    /// Convert the genesis account into the [`TrieAccount`] format.
262    pub fn into_trie_account(self) -> TrieAccount {
263        self.into()
264    }
265}
266
267impl From<GenesisAccount> for TrieAccount {
268    fn from(account: GenesisAccount) -> Self {
269        let storage_root = account
270            .storage
271            .map(|storage| {
272                alloy_trie::root::storage_root_unhashed(
273                    storage
274                        .into_iter()
275                        .filter(|(_, value)| !value.is_zero())
276                        .map(|(slot, value)| (slot, U256::from_be_bytes(*value))),
277                )
278            })
279            .unwrap_or(EMPTY_ROOT_HASH);
280
281        Self {
282            nonce: account.nonce.unwrap_or_default(),
283            balance: account.balance,
284            storage_root,
285            code_hash: account.code.map_or(KECCAK_EMPTY, keccak256),
286        }
287    }
288}
289
290/// Defines core blockchain settings per block.
291///
292/// Tailors unique settings for each network based on its genesis block.
293///
294/// Governs crucial blockchain behavior and adaptability.
295///
296/// Encapsulates parameters shaping network evolution and behavior.
297///
298/// See [geth's `ChainConfig`
299/// struct](https://github.com/ethereum/go-ethereum/blob/v1.14.0/params/config.go#L326)
300/// for the source of each field.
301#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(default, rename_all = "camelCase")]
303pub struct ChainConfig {
304    /// The network's chain ID.
305    pub chain_id: u64,
306
307    /// The homestead switch block (None = no fork, 0 = already homestead).
308    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
309    pub homestead_block: Option<u64>,
310
311    /// The DAO fork switch block (None = no fork).
312    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
313    pub dao_fork_block: Option<u64>,
314
315    /// Whether or not the node supports the DAO hard-fork.
316    pub dao_fork_support: bool,
317
318    /// The [EIP-150](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-150.md) hard fork block (None = no fork).
319    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
320    pub eip150_block: Option<u64>,
321
322    /// The [EIP-155](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md) hard fork block.
323    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
324    pub eip155_block: Option<u64>,
325
326    /// The [EIP-158](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-158.md) hard fork block.
327    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
328    pub eip158_block: Option<u64>,
329
330    /// The Byzantium hard fork block (None = no fork, 0 = already on byzantium).
331    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
332    pub byzantium_block: Option<u64>,
333
334    /// The Constantinople hard fork block (None = no fork, 0 = already on constantinople).
335    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
336    pub constantinople_block: Option<u64>,
337
338    /// The Petersburg hard fork block (None = no fork, 0 = already on petersburg).
339    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
340    pub petersburg_block: Option<u64>,
341
342    /// The Istanbul hard fork block (None = no fork, 0 = already on istanbul).
343    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
344    pub istanbul_block: Option<u64>,
345
346    /// The Muir Glacier hard fork block (None = no fork, 0 = already on muir glacier).
347    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
348    pub muir_glacier_block: Option<u64>,
349
350    /// The Berlin hard fork block (None = no fork, 0 = already on berlin).
351    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
352    pub berlin_block: Option<u64>,
353
354    /// The London hard fork block (None = no fork, 0 = already on london).
355    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
356    pub london_block: Option<u64>,
357
358    /// The Arrow Glacier hard fork block (None = no fork, 0 = already on arrow glacier).
359    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
360    pub arrow_glacier_block: Option<u64>,
361
362    /// The Gray Glacier hard fork block (None = no fork, 0 = already on gray glacier).
363    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
364    pub gray_glacier_block: Option<u64>,
365
366    /// Virtual fork after the merge to use as a network splitter.
367    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
368    pub merge_netsplit_block: Option<u64>,
369
370    /// Shanghai switch time (None = no fork, 0 = already on shanghai).
371    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
372    pub shanghai_time: Option<u64>,
373
374    /// Cancun switch time (None = no fork, 0 = already on cancun).
375    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
376    pub cancun_time: Option<u64>,
377
378    /// Prague switch time (None = no fork, 0 = already on prague).
379    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
380    pub prague_time: Option<u64>,
381
382    /// Osaka switch time (None = no fork, 0 = already on osaka).
383    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
384    pub osaka_time: Option<u64>,
385
386    /// BPO1 switch time (None = no fork, 0 = already on BPO1).
387    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
388    pub bpo1_time: Option<u64>,
389
390    /// BPO2 switch time (None = no fork, 0 = already on BPO2).
391    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
392    pub bpo2_time: Option<u64>,
393
394    /// BPO3 switch time (None = no fork, 0 = already on BPO3).
395    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
396    pub bpo3_time: Option<u64>,
397
398    /// BPO4 switch time (None = no fork, 0 = already on BPO4).
399    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
400    pub bpo4_time: Option<u64>,
401
402    /// BPO5 switch time (None = no fork, 0 = already on BPO5).
403    #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_u64_opt")]
404    pub bpo5_time: Option<u64>,
405
406    /// Total difficulty reached that triggers the merge consensus upgrade.
407    #[serde(skip_serializing_if = "Option::is_none", with = "alloy_serde::ttd")]
408    pub terminal_total_difficulty: Option<U256>,
409
410    /// A flag specifying that the network already passed the terminal total difficulty. Its
411    /// purpose is to disable legacy sync without having seen the TTD locally.
412    pub terminal_total_difficulty_passed: bool,
413
414    /// Ethash parameters.
415    #[serde(skip_serializing_if = "Option::is_none")]
416    pub ethash: Option<EthashConfig>,
417
418    /// Clique parameters.
419    #[serde(skip_serializing_if = "Option::is_none")]
420    pub clique: Option<CliqueConfig>,
421
422    /// Parlia parameters.
423    #[serde(skip_serializing_if = "Option::is_none")]
424    pub parlia: Option<ParliaConfig>,
425
426    /// Additional fields specific to each chain.
427    #[serde(flatten, default)]
428    pub extra_fields: OtherFields,
429
430    /// The deposit contract address
431    #[serde(default, skip_serializing_if = "Option::is_none")]
432    pub deposit_contract_address: Option<Address>,
433
434    /// The blob schedule for the chain, indexed by hardfork name.
435    ///
436    /// See [EIP-7840](https://github.com/ethereum/EIPs/tree/master/EIPS/eip-7840.md).
437    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
438    pub blob_schedule: BTreeMap<String, BlobParams>,
439}
440
441/// Bincode-compatible [`ChainConfig`] serde implementation.
442#[cfg(feature = "serde-bincode-compat")]
443pub mod serde_bincode_compat {
444    use alloc::{
445        borrow::Cow,
446        collections::BTreeMap,
447        string::{String, ToString},
448    };
449    use alloy_primitives::{Address, U256};
450    use alloy_serde::OtherFields;
451    use serde::{Deserialize, Deserializer, Serialize, Serializer};
452    use serde_with::{DeserializeAs, SerializeAs};
453
454    /// Bincode-compatible [`super::ChainConfig`] serde implementation.
455    ///
456    /// Intended to use with the [`serde_with::serde_as`] macro in the following way:
457    /// ```rust
458    /// use alloy_genesis::{serde_bincode_compat, ChainConfig};
459    /// use serde::{Deserialize, Serialize};
460    /// use serde_with::serde_as;
461    ///
462    /// #[serde_as]
463    /// #[derive(Serialize, Deserialize)]
464    /// struct Data {
465    ///     #[serde_as(as = "serde_bincode_compat::ChainConfig")]
466    ///     config: ChainConfig,
467    /// }
468    /// ```
469    #[derive(Debug, Serialize, Deserialize)]
470    pub struct ChainConfig<'a> {
471        chain_id: u64,
472        #[serde(default)]
473        homestead_block: Option<u64>,
474        #[serde(default)]
475        dao_fork_block: Option<u64>,
476        #[serde(default)]
477        dao_fork_support: bool,
478        #[serde(default)]
479        eip150_block: Option<u64>,
480        #[serde(default)]
481        eip155_block: Option<u64>,
482        #[serde(default)]
483        eip158_block: Option<u64>,
484        #[serde(default)]
485        byzantium_block: Option<u64>,
486        #[serde(default)]
487        constantinople_block: Option<u64>,
488        #[serde(default)]
489        petersburg_block: Option<u64>,
490        #[serde(default)]
491        istanbul_block: Option<u64>,
492        #[serde(default)]
493        muir_glacier_block: Option<u64>,
494        #[serde(default)]
495        berlin_block: Option<u64>,
496        #[serde(default)]
497        london_block: Option<u64>,
498        #[serde(default)]
499        arrow_glacier_block: Option<u64>,
500        #[serde(default)]
501        gray_glacier_block: Option<u64>,
502        #[serde(default)]
503        merge_netsplit_block: Option<u64>,
504        #[serde(default)]
505        shanghai_time: Option<u64>,
506        #[serde(default)]
507        cancun_time: Option<u64>,
508        #[serde(default)]
509        prague_time: Option<u64>,
510        #[serde(default)]
511        osaka_time: Option<u64>,
512        #[serde(default)]
513        bpo1_time: Option<u64>,
514        #[serde(default)]
515        bpo2_time: Option<u64>,
516        #[serde(default)]
517        bpo3_time: Option<u64>,
518        #[serde(default)]
519        bpo4_time: Option<u64>,
520        #[serde(default)]
521        bpo5_time: Option<u64>,
522        #[serde(default)]
523        terminal_total_difficulty: Option<U256>,
524        #[serde(default)]
525        terminal_total_difficulty_passed: bool,
526        #[serde(default)]
527        ethash: Option<super::EthashConfig>,
528        #[serde(default)]
529        clique: Option<super::CliqueConfig>,
530        #[serde(default)]
531        parlia: Option<super::ParliaConfig>,
532        #[serde(default)]
533        deposit_contract_address: Option<Address>,
534        #[serde(default)]
535        blob_schedule: Cow<'a, BTreeMap<String, super::BlobParams>>,
536        /// Extra fields as string key-value pairs (bincode-compatible alternative to OtherFields)
537        #[serde(default)]
538        extra_fields: BTreeMap<String, String>,
539    }
540
541    impl<'a> From<&'a super::ChainConfig> for ChainConfig<'a> {
542        fn from(value: &'a super::ChainConfig) -> Self {
543            Self {
544                chain_id: value.chain_id,
545                homestead_block: value.homestead_block,
546                dao_fork_block: value.dao_fork_block,
547                dao_fork_support: value.dao_fork_support,
548                eip150_block: value.eip150_block,
549                eip155_block: value.eip155_block,
550                eip158_block: value.eip158_block,
551                byzantium_block: value.byzantium_block,
552                constantinople_block: value.constantinople_block,
553                petersburg_block: value.petersburg_block,
554                istanbul_block: value.istanbul_block,
555                muir_glacier_block: value.muir_glacier_block,
556                berlin_block: value.berlin_block,
557                london_block: value.london_block,
558                arrow_glacier_block: value.arrow_glacier_block,
559                gray_glacier_block: value.gray_glacier_block,
560                merge_netsplit_block: value.merge_netsplit_block,
561                shanghai_time: value.shanghai_time,
562                cancun_time: value.cancun_time,
563                prague_time: value.prague_time,
564                osaka_time: value.osaka_time,
565                bpo1_time: value.bpo1_time,
566                bpo2_time: value.bpo2_time,
567                bpo3_time: value.bpo3_time,
568                bpo4_time: value.bpo4_time,
569                bpo5_time: value.bpo5_time,
570                terminal_total_difficulty: value.terminal_total_difficulty,
571                terminal_total_difficulty_passed: value.terminal_total_difficulty_passed,
572                ethash: value.ethash,
573                clique: value.clique,
574                parlia: value.parlia,
575                deposit_contract_address: value.deposit_contract_address,
576                blob_schedule: Cow::Borrowed(&value.blob_schedule),
577                extra_fields: {
578                    let mut extra_fields = BTreeMap::new();
579                    for (k, v) in value.extra_fields.clone().into_iter() {
580                        // Convert all serde_json::Value types to string for bincode compatibility
581                        extra_fields.insert(k, v.to_string());
582                    }
583                    extra_fields
584                },
585            }
586        }
587    }
588
589    impl From<ChainConfig<'_>> for super::ChainConfig {
590        fn from(value: ChainConfig<'_>) -> Self {
591            Self {
592                chain_id: value.chain_id,
593                homestead_block: value.homestead_block,
594                dao_fork_block: value.dao_fork_block,
595                dao_fork_support: value.dao_fork_support,
596                eip150_block: value.eip150_block,
597                eip155_block: value.eip155_block,
598                eip158_block: value.eip158_block,
599                byzantium_block: value.byzantium_block,
600                constantinople_block: value.constantinople_block,
601                petersburg_block: value.petersburg_block,
602                istanbul_block: value.istanbul_block,
603                muir_glacier_block: value.muir_glacier_block,
604                berlin_block: value.berlin_block,
605                london_block: value.london_block,
606                arrow_glacier_block: value.arrow_glacier_block,
607                gray_glacier_block: value.gray_glacier_block,
608                merge_netsplit_block: value.merge_netsplit_block,
609                shanghai_time: value.shanghai_time,
610                cancun_time: value.cancun_time,
611                prague_time: value.prague_time,
612                osaka_time: value.osaka_time,
613                bpo1_time: value.bpo1_time,
614                bpo2_time: value.bpo2_time,
615                bpo3_time: value.bpo3_time,
616                bpo4_time: value.bpo4_time,
617                bpo5_time: value.bpo5_time,
618                terminal_total_difficulty: value.terminal_total_difficulty,
619                terminal_total_difficulty_passed: value.terminal_total_difficulty_passed,
620                ethash: value.ethash,
621                clique: value.clique,
622                parlia: value.parlia,
623                extra_fields: {
624                    let mut extra_fields = OtherFields::default();
625                    for (k, v) in value.extra_fields {
626                        // Parse strings back to serde_json::Value
627                        extra_fields.insert(
628                            k,
629                            v.parse().expect("Failed to parse extra field value back to JSON"),
630                        );
631                    }
632                    extra_fields
633                },
634                deposit_contract_address: value.deposit_contract_address,
635                blob_schedule: value.blob_schedule.into_owned(),
636            }
637        }
638    }
639
640    impl<'a> SerializeAs<super::ChainConfig> for ChainConfig<'a> {
641        fn serialize_as<S>(source: &super::ChainConfig, serializer: S) -> Result<S::Ok, S::Error>
642        where
643            S: Serializer,
644        {
645            ChainConfig::from(source).serialize(serializer)
646        }
647    }
648
649    impl<'de> DeserializeAs<'de, super::ChainConfig> for ChainConfig<'de> {
650        fn deserialize_as<D>(deserializer: D) -> Result<super::ChainConfig, D::Error>
651        where
652            D: Deserializer<'de>,
653        {
654            ChainConfig::deserialize(deserializer).map(Into::into)
655        }
656    }
657
658    #[cfg(test)]
659    mod tests {
660        use super::super::ChainConfig;
661        use bincode::config;
662        use serde::{Deserialize, Serialize};
663        use serde_with::serde_as;
664
665        #[test]
666        fn test_chain_config_bincode_roundtrip() {
667            #[serde_as]
668            #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
669            struct Data {
670                #[serde_as(as = "super::ChainConfig")]
671                config: ChainConfig,
672            }
673
674            // Create a test config with mixed Some/None values to test serialization
675            let config = ChainConfig {
676                chain_id: 1,
677                homestead_block: None,
678                dao_fork_block: Some(100),
679                dao_fork_support: false,
680                eip150_block: None,
681                eip155_block: Some(200),
682                eip158_block: None,
683                byzantium_block: Some(300),
684                constantinople_block: None,
685                petersburg_block: None,
686                istanbul_block: None,
687                muir_glacier_block: None,
688                berlin_block: None,
689                london_block: None,
690                arrow_glacier_block: None,
691                gray_glacier_block: None,
692                merge_netsplit_block: None,
693                shanghai_time: None,
694                cancun_time: None,
695                prague_time: None,
696                osaka_time: None,
697                bpo1_time: None,
698                bpo2_time: None,
699                bpo3_time: None,
700                bpo4_time: None,
701                bpo5_time: None,
702                terminal_total_difficulty: None,
703                terminal_total_difficulty_passed: false,
704                ethash: None,
705                clique: None,
706                parlia: None,
707                extra_fields: Default::default(),
708                deposit_contract_address: None,
709                blob_schedule: Default::default(),
710            };
711
712            let data = Data { config };
713
714            let encoded = bincode::serde::encode_to_vec(&data, config::legacy()).unwrap();
715            let (decoded, _) =
716                bincode::serde::decode_from_slice::<Data, _>(&encoded, config::legacy()).unwrap();
717            assert_eq!(decoded, data);
718        }
719
720        #[test]
721        fn test_chain_config_serde_bincode_compat() {
722            use serde_with::serde_as;
723
724            #[serde_as]
725            #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
726            struct Data {
727                #[serde_as(as = "super::ChainConfig")]
728                config: crate::ChainConfig,
729            }
730
731            let mut config = crate::ChainConfig {
732                chain_id: 1,
733                homestead_block: None,
734                dao_fork_block: Some(100),
735                dao_fork_support: false,
736                eip150_block: None,
737                eip155_block: Some(200),
738                eip158_block: None,
739                byzantium_block: Some(300),
740                constantinople_block: None,
741                petersburg_block: None,
742                istanbul_block: None,
743                muir_glacier_block: None,
744                berlin_block: None,
745                london_block: None,
746                arrow_glacier_block: None,
747                gray_glacier_block: None,
748                merge_netsplit_block: None,
749                shanghai_time: None,
750                cancun_time: None,
751                prague_time: None,
752                osaka_time: None,
753                bpo1_time: None,
754                bpo2_time: None,
755                bpo3_time: None,
756                bpo4_time: None,
757                bpo5_time: None,
758                terminal_total_difficulty: None,
759                terminal_total_difficulty_passed: false,
760                ethash: None,
761                clique: None,
762                parlia: None,
763                extra_fields: Default::default(),
764                deposit_contract_address: None,
765                blob_schedule: Default::default(),
766            };
767
768            // Add some extra fields with different serde_json::Value types
769            config.extra_fields.insert(
770                "string_field".to_string(),
771                serde_json::Value::String("test_value".to_string()),
772            );
773            config.extra_fields.insert(
774                "number_field".to_string(),
775                serde_json::Value::Number(serde_json::Number::from(42)),
776            );
777            config.extra_fields.insert("bool_field".to_string(), serde_json::Value::Bool(true));
778
779            let data = Data { config };
780
781            // Test bincode serialization with serde_bincode_compat
782            let encoded = bincode::serde::encode_to_vec(&data, bincode::config::legacy()).unwrap();
783            let (decoded, _) =
784                bincode::serde::decode_from_slice::<Data, _>(&encoded, bincode::config::legacy())
785                    .unwrap();
786
787            assert_eq!(decoded, data);
788        }
789
790        #[test]
791        fn test_default_genesis_chain_config_bincode() {
792            use serde_with::serde_as;
793
794            #[serde_as]
795            #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
796            struct Data {
797                #[serde_as(as = "super::ChainConfig")]
798                config: crate::ChainConfig,
799            }
800
801            // Create a default genesis and extract its chain config
802            let genesis = crate::Genesis::default();
803            let config = genesis.config;
804
805            let data = Data { config };
806
807            // Test bincode serialization with serde_bincode_compat
808            let encoded = bincode::serde::encode_to_vec(&data, bincode::config::legacy()).unwrap();
809            let (decoded, _) =
810                bincode::serde::decode_from_slice::<Data, _>(&encoded, bincode::config::legacy())
811                    .unwrap();
812
813            assert_eq!(decoded, data);
814        }
815
816        #[test]
817        fn test_mainnet_genesis_chain_config_bincode() {
818            use serde_with::serde_as;
819
820            #[serde_as]
821            #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
822            struct Data {
823                #[serde_as(as = "super::ChainConfig")]
824                config: crate::ChainConfig,
825            }
826
827            // Parse the mainnet genesis JSON
828            let mainnet_genesis_json = include_str!("../dumpgenesis/mainnet.json");
829
830            // Parse the genesis JSON
831            let genesis: crate::Genesis = serde_json::from_str(mainnet_genesis_json).unwrap();
832            let config = genesis.config;
833
834            let data = Data { config };
835
836            // Test bincode serialization with serde_bincode_compat
837            let encoded = bincode::serde::encode_to_vec(&data, bincode::config::legacy()).unwrap();
838            let (decoded, _) =
839                bincode::serde::decode_from_slice::<Data, _>(&encoded, bincode::config::legacy())
840                    .unwrap();
841
842            assert_eq!(decoded, data);
843        }
844    }
845}
846
847impl ChainConfig {
848    /// Returns the [`BlobScheduleBlobParams`] from the configured blob schedule values.
849    pub fn blob_schedule_blob_params(&self) -> BlobScheduleBlobParams {
850        let mut cancun = None;
851        let mut prague = None;
852        let mut osaka = None;
853        let mut scheduled = Vec::new();
854
855        for (key, params) in &self.blob_schedule {
856            match key.as_str() {
857                "cancun" => {
858                    cancun = Some(*params);
859                    continue;
860                }
861                "prague" => {
862                    prague = Some(*params);
863                    continue;
864                }
865                _ => {}
866            };
867
868            // Apply values relevant after Osaka hardfork.
869            let params = params
870                .with_blob_base_cost(eip7840::BLOB_BASE_COST)
871                .with_max_blobs_per_tx(eip7594::MAX_BLOBS_PER_TX_FUSAKA);
872
873            match key.as_str() {
874                "osaka" => osaka = Some(params),
875                "bpo1" => {
876                    if let Some(timestamp) = self.bpo1_time {
877                        scheduled.push((timestamp, params));
878                    }
879                }
880                "bpo2" => {
881                    if let Some(timestamp) = self.bpo2_time {
882                        scheduled.push((timestamp, params));
883                    }
884                }
885                "bpo3" => {
886                    if let Some(timestamp) = self.bpo3_time {
887                        scheduled.push((timestamp, params));
888                    }
889                }
890                "bpo4" => {
891                    if let Some(timestamp) = self.bpo4_time {
892                        scheduled.push((timestamp, params));
893                    }
894                }
895                "bpo5" => {
896                    if let Some(timestamp) = self.bpo5_time {
897                        scheduled.push((timestamp, params));
898                    }
899                }
900                _ => (),
901            }
902        }
903
904        scheduled.sort_by_key(|(timestamp, _)| *timestamp);
905
906        BlobScheduleBlobParams {
907            cancun: cancun.unwrap_or_else(BlobParams::cancun),
908            prague: prague.unwrap_or_else(BlobParams::prague),
909            osaka: osaka.unwrap_or_else(BlobParams::osaka),
910            scheduled,
911        }
912    }
913
914    /// Checks if the blockchain is active at or after the Homestead fork block.
915    pub fn is_homestead_active_at_block(&self, block: u64) -> bool {
916        self.is_active_at_block(self.homestead_block, block)
917    }
918
919    /// Checks if the blockchain is active at or after the EIP150 fork block.
920    pub fn is_eip150_active_at_block(&self, block: u64) -> bool {
921        self.is_active_at_block(self.eip150_block, block)
922    }
923
924    /// Checks if the blockchain is active at or after the EIP155 fork block.
925    pub fn is_eip155_active_at_block(&self, block: u64) -> bool {
926        self.is_active_at_block(self.eip155_block, block)
927    }
928
929    /// Checks if the blockchain is active at or after the EIP158 fork block.
930    pub fn is_eip158_active_at_block(&self, block: u64) -> bool {
931        self.is_active_at_block(self.eip158_block, block)
932    }
933
934    /// Checks if the blockchain is active at or after the Byzantium fork block.
935    pub fn is_byzantium_active_at_block(&self, block: u64) -> bool {
936        self.is_active_at_block(self.byzantium_block, block)
937    }
938
939    /// Checks if the blockchain is active at or after the Constantinople fork block.
940    pub fn is_constantinople_active_at_block(&self, block: u64) -> bool {
941        self.is_active_at_block(self.constantinople_block, block)
942    }
943
944    /// Checks if the blockchain is active at or after the Muir Glacier (EIP-2384) fork block.
945    pub fn is_muir_glacier_active_at_block(&self, block: u64) -> bool {
946        self.is_active_at_block(self.muir_glacier_block, block)
947    }
948
949    /// Checks if the blockchain is active at or after the Petersburg fork block.
950    pub fn is_petersburg_active_at_block(&self, block: u64) -> bool {
951        self.is_active_at_block(self.petersburg_block, block)
952    }
953
954    /// Checks if the blockchain is active at or after the Istanbul fork block.
955    pub fn is_istanbul_active_at_block(&self, block: u64) -> bool {
956        self.is_active_at_block(self.istanbul_block, block)
957    }
958
959    /// Checks if the blockchain is active at or after the Berlin fork block.
960    pub fn is_berlin_active_at_block(&self, block: u64) -> bool {
961        self.is_active_at_block(self.berlin_block, block)
962    }
963
964    /// Checks if the blockchain is active at or after the London fork block.
965    pub fn is_london_active_at_block(&self, block: u64) -> bool {
966        self.is_active_at_block(self.london_block, block)
967    }
968
969    /// Checks if the blockchain is active at or after the Arrow Glacier (EIP-4345) fork block.
970    pub fn is_arrow_glacier_active_at_block(&self, block: u64) -> bool {
971        self.is_active_at_block(self.arrow_glacier_block, block)
972    }
973
974    /// Checks if the blockchain is active at or after the Gray Glacier (EIP-5133) fork block.
975    pub fn is_gray_glacier_active_at_block(&self, block: u64) -> bool {
976        self.is_active_at_block(self.gray_glacier_block, block)
977    }
978
979    /// Checks if the blockchain is active at or after the Shanghai fork block and the specified
980    /// timestamp.
981    pub fn is_shanghai_active_at_block_and_timestamp(&self, block: u64, timestamp: u64) -> bool {
982        self.is_london_active_at_block(block)
983            && self.is_active_at_timestamp(self.shanghai_time, timestamp)
984    }
985
986    /// Checks if the blockchain is active at or after the Cancun fork block and the specified
987    /// timestamp.
988    pub fn is_cancun_active_at_block_and_timestamp(&self, block: u64, timestamp: u64) -> bool {
989        self.is_london_active_at_block(block)
990            && self.is_active_at_timestamp(self.cancun_time, timestamp)
991    }
992
993    // Private function handling the comparison logic for block numbers
994    fn is_active_at_block(&self, config_block: Option<u64>, block: u64) -> bool {
995        config_block.is_some_and(|cb| cb <= block)
996    }
997
998    // Private function handling the comparison logic for timestamps
999    fn is_active_at_timestamp(&self, config_timestamp: Option<u64>, timestamp: u64) -> bool {
1000        config_timestamp.is_some_and(|cb| cb <= timestamp)
1001    }
1002}
1003
1004impl Default for ChainConfig {
1005    fn default() -> Self {
1006        Self {
1007            // mainnet
1008            chain_id: 1,
1009            homestead_block: None,
1010            dao_fork_block: None,
1011            dao_fork_support: false,
1012            eip150_block: None,
1013            eip155_block: None,
1014            eip158_block: None,
1015            byzantium_block: None,
1016            constantinople_block: None,
1017            petersburg_block: None,
1018            istanbul_block: None,
1019            muir_glacier_block: None,
1020            berlin_block: None,
1021            london_block: None,
1022            arrow_glacier_block: None,
1023            gray_glacier_block: None,
1024            merge_netsplit_block: None,
1025            shanghai_time: None,
1026            cancun_time: None,
1027            prague_time: None,
1028            osaka_time: None,
1029            bpo1_time: None,
1030            bpo2_time: None,
1031            bpo3_time: None,
1032            bpo4_time: None,
1033            bpo5_time: None,
1034            terminal_total_difficulty: None,
1035            terminal_total_difficulty_passed: false,
1036            ethash: None,
1037            clique: None,
1038            parlia: None,
1039            extra_fields: Default::default(),
1040            deposit_contract_address: None,
1041            blob_schedule: Default::default(),
1042        }
1043    }
1044}
1045
1046/// Empty consensus configuration for proof-of-work networks.
1047#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1048pub struct EthashConfig {}
1049
1050/// Consensus configuration for Clique.
1051#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1052pub struct CliqueConfig {
1053    /// Number of seconds between blocks to enforce.
1054    #[serde(default, skip_serializing_if = "Option::is_none")]
1055    pub period: Option<u64>,
1056
1057    /// Epoch length to reset votes and checkpoints.
1058    #[serde(default, skip_serializing_if = "Option::is_none")]
1059    pub epoch: Option<u64>,
1060}
1061
1062/// Consensus configuration for Parlia.
1063///
1064/// Parlia is the consensus engine for BNB Smart Chain.
1065/// For the general introduction: <https://docs.bnbchain.org/docs/learn/consensus/>
1066/// For the specification: <https://github.com/bnb-chain/bsc/blob/master/params/config.go#L558>
1067#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1068pub struct ParliaConfig {
1069    /// Number of seconds between blocks to enforce.
1070    #[serde(default, skip_serializing_if = "Option::is_none")]
1071    pub period: Option<u64>,
1072
1073    /// Epoch length to update validator set.
1074    #[serde(default, skip_serializing_if = "Option::is_none")]
1075    pub epoch: Option<u64>,
1076}
1077
1078/// Custom deserialization function for the private key.
1079///
1080/// This function allows the private key to be deserialized from a string or a `null` value.
1081///
1082/// We need a custom function here especially to handle the case where the private key is `0x` and
1083/// should be deserialized as `None`.
1084fn deserialize_private_key<'de, D>(deserializer: D) -> Result<Option<B256>, D::Error>
1085where
1086    D: Deserializer<'de>,
1087{
1088    if deserializer.is_human_readable() {
1089        match Option::<String>::deserialize(deserializer)? {
1090            Some(ref s) => {
1091                if s == "0x" {
1092                    return Ok(None);
1093                }
1094                B256::from_str(s).map(Some).map_err(D::Error::custom)
1095            }
1096            None => Ok(None),
1097        }
1098    } else {
1099        Option::<B256>::deserialize(deserializer)
1100    }
1101}
1102
1103/// Custom deserialization function for `Option<u64>`.
1104///
1105/// This function allows it to be deserialized from a number or a "quantity" hex string.
1106/// We need a custom function as this should only be used for non-human-readable formats.
1107fn deserialize_u64_opt<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
1108where
1109    D: Deserializer<'de>,
1110{
1111    if deserializer.is_human_readable() {
1112        alloy_serde::quantity::opt::deserialize(deserializer)
1113    } else {
1114        Option::<u64>::deserialize(deserializer)
1115    }
1116}
1117
1118#[cfg(test)]
1119mod tests {
1120    use super::*;
1121    use alloc::{collections::BTreeMap, vec};
1122    use alloy_primitives::{hex, Bytes};
1123    use alloy_trie::{root::storage_root_unhashed, TrieAccount};
1124    use core::str::FromStr;
1125    use serde_json::json;
1126
1127    #[test]
1128    fn genesis_defaults_config() {
1129        let s = r#"{}"#;
1130        let genesis: Genesis = serde_json::from_str(s).unwrap();
1131        assert_eq!(genesis.config.chain_id, 1);
1132    }
1133
1134    #[test]
1135    fn test_genesis() {
1136        let default_genesis = Genesis::default();
1137
1138        let nonce = 999;
1139        let timestamp = 12345;
1140        let extra_data = Bytes::from(b"extra-data");
1141        let gas_limit = 333333;
1142        let difficulty = U256::from(9000);
1143        let mix_hash =
1144            hex!("74385b512f1e0e47100907efe2b00ac78df26acba6dd16b0772923068a5801a8").into();
1145        let coinbase = hex!("265873b6faf3258b3ab0827805386a2a20ed040e").into();
1146        // create dummy account
1147        let first_address: Address = hex!("7618a8c597b89e01c66a1f662078992c52a30c9a").into();
1148        let mut account = BTreeMap::default();
1149        account.insert(first_address, GenesisAccount::default());
1150
1151        // check values updated
1152        let custom_genesis = Genesis::default()
1153            .with_nonce(nonce)
1154            .with_timestamp(timestamp)
1155            .with_extra_data(extra_data.clone())
1156            .with_gas_limit(gas_limit)
1157            .with_difficulty(difficulty)
1158            .with_mix_hash(mix_hash)
1159            .with_coinbase(coinbase)
1160            .extend_accounts(account.clone());
1161
1162        assert_ne!(custom_genesis, default_genesis);
1163        // check every field
1164        assert_eq!(custom_genesis.nonce, nonce);
1165        assert_eq!(custom_genesis.timestamp, timestamp);
1166        assert_eq!(custom_genesis.extra_data, extra_data);
1167        assert_eq!(custom_genesis.gas_limit, gas_limit);
1168        assert_eq!(custom_genesis.difficulty, difficulty);
1169        assert_eq!(custom_genesis.mix_hash, mix_hash);
1170        assert_eq!(custom_genesis.coinbase, coinbase);
1171        assert_eq!(custom_genesis.alloc, account.clone());
1172
1173        // update existing account
1174        assert_eq!(custom_genesis.alloc.len(), 1);
1175        let same_address = first_address;
1176        let new_alloc_account = GenesisAccount {
1177            nonce: Some(1),
1178            balance: U256::from(1),
1179            code: Some(b"code".into()),
1180            storage: Some(BTreeMap::default()),
1181            private_key: None,
1182        };
1183        let mut updated_account = BTreeMap::default();
1184        updated_account.insert(same_address, new_alloc_account);
1185        let custom_genesis = custom_genesis.extend_accounts(updated_account.clone());
1186        assert_ne!(account, updated_account);
1187        assert_eq!(custom_genesis.alloc.len(), 1);
1188
1189        // add second account
1190        let different_address = hex!("94e0681e3073dd71cec54b53afe988f39078fd1a").into();
1191        let more_accounts = BTreeMap::from([(different_address, GenesisAccount::default())]);
1192        let custom_genesis = custom_genesis.extend_accounts(more_accounts);
1193        assert_eq!(custom_genesis.alloc.len(), 2);
1194
1195        // ensure accounts are different
1196        let first_account = custom_genesis.alloc.get(&first_address);
1197        let second_account = custom_genesis.alloc.get(&different_address);
1198        assert!(first_account.is_some());
1199        assert!(second_account.is_some());
1200        assert_ne!(first_account, second_account);
1201    }
1202
1203    #[test]
1204    fn test_genesis_account() {
1205        let default_account = GenesisAccount::default();
1206
1207        let nonce = Some(1);
1208        let balance = U256::from(33);
1209        let code = Some(b"code".into());
1210        let root = hex!("9474ddfcea39c5a690d2744103e39d1ff1b03d18db10fc147d970ad24699395a").into();
1211        let value = hex!("58eb8294d9bb16832a9dabfcb270fff99ab8ee1d8764e4f3d9fdf59ec1dee469").into();
1212        let mut map = BTreeMap::default();
1213        map.insert(root, value);
1214        let storage = Some(map);
1215
1216        let genesis_account = GenesisAccount::default()
1217            .with_nonce(nonce)
1218            .with_balance(balance)
1219            .with_code(code.clone())
1220            .with_storage(storage.clone());
1221
1222        assert_ne!(default_account, genesis_account);
1223        // check every field
1224        assert_eq!(genesis_account.nonce, nonce);
1225        assert_eq!(genesis_account.balance, balance);
1226        assert_eq!(genesis_account.code, code);
1227        assert_eq!(genesis_account.storage, storage);
1228    }
1229
1230    #[test]
1231    fn parse_hive_genesis() {
1232        let geth_genesis = r#"
1233    {
1234        "difficulty": "0x20000",
1235        "gasLimit": "0x1",
1236        "alloc": {},
1237        "config": {
1238          "ethash": {},
1239          "chainId": 1
1240        }
1241    }
1242    "#;
1243
1244        let _genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
1245    }
1246
1247    #[test]
1248    fn parse_hive_clique_smoke_genesis() {
1249        let geth_genesis = r#"
1250    {
1251      "difficulty": "0x1",
1252      "gasLimit": "0x400000",
1253      "extraData":
1254    "0x0000000000000000000000000000000000000000000000000000000000000000658bdf435d810c91414ec09147daa6db624063790000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
1255    ,   "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1256      "nonce": "0x0",
1257      "timestamp": "0x5c51a607",
1258      "alloc": {}
1259    }
1260    "#;
1261
1262        let _genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
1263    }
1264
1265    #[test]
1266    fn parse_non_hex_prefixed_balance() {
1267        // tests that we can parse balance / difficulty fields that are either hex or decimal
1268        let example_balance_json = r#"
1269    {
1270        "nonce": "0x0000000000000042",
1271        "difficulty": "34747478",
1272        "mixHash": "0x123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234",
1273        "coinbase": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1274        "timestamp": "0x123456",
1275        "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1276        "extraData": "0xfafbfcfd",
1277        "gasLimit": "0x2fefd8",
1278        "alloc": {
1279            "0x3E951C9f69a06Bc3AD71fF7358DbC56bEd94b9F2": {
1280              "balance": "1000000000000000000000000000"
1281            },
1282            "0xe228C30d4e5245f967ac21726d5412dA27aD071C": {
1283              "balance": "1000000000000000000000000000"
1284            },
1285            "0xD59Ce7Ccc6454a2D2C2e06bbcf71D0Beb33480eD": {
1286              "balance": "1000000000000000000000000000"
1287            },
1288            "0x1CF4D54414eF51b41f9B2238c57102ab2e61D1F2": {
1289              "balance": "1000000000000000000000000000"
1290            },
1291            "0x249bE3fDEd872338C733cF3975af9736bdCb9D4D": {
1292              "balance": "1000000000000000000000000000"
1293            },
1294            "0x3fCd1bff94513712f8cD63d1eD66776A67D5F78e": {
1295              "balance": "1000000000000000000000000000"
1296            }
1297        },
1298        "config": {
1299            "ethash": {},
1300            "chainId": 10,
1301            "homesteadBlock": 0,
1302            "eip150Block": 0,
1303            "eip155Block": 0,
1304            "eip158Block": 0,
1305            "byzantiumBlock": 0,
1306            "constantinopleBlock": 0,
1307            "petersburgBlock": 0,
1308            "istanbulBlock": 0
1309        }
1310    }
1311    "#;
1312
1313        let genesis: Genesis = serde_json::from_str(example_balance_json).unwrap();
1314
1315        // check difficulty against hex ground truth
1316        let expected_difficulty = U256::from_str("0x2123456").unwrap();
1317        assert_eq!(expected_difficulty, genesis.difficulty);
1318
1319        // check all alloc balances
1320        let dec_balance = U256::from_str("1000000000000000000000000000").unwrap();
1321        for alloc in &genesis.alloc {
1322            assert_eq!(alloc.1.balance, dec_balance);
1323        }
1324    }
1325
1326    #[test]
1327    fn parse_hive_rpc_genesis() {
1328        let geth_genesis = r#"
1329    {
1330      "config": {
1331        "chainId": 7,
1332        "homesteadBlock": 0,
1333        "eip150Block": 0,
1334        "eip150Hash": "0x5de1ee4135274003348e80b788e5afa4b18b18d320a5622218d5c493fedf5689",
1335        "eip155Block": 0,
1336        "eip158Block": 0
1337      },
1338      "coinbase": "0x0000000000000000000000000000000000000000",
1339      "difficulty": "0x20000",
1340      "extraData":
1341    "0x0000000000000000000000000000000000000000000000000000000000000000658bdf435d810c91414ec09147daa6db624063790000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
1342    ,   "gasLimit": "0x2fefd8",
1343      "nonce": "0x0000000000000000",
1344      "timestamp": "0x1234",
1345      "alloc": {
1346        "cf49fda3be353c69b41ed96333cd24302da4556f": {
1347          "balance": "0x123450000000000000000"
1348        },
1349        "0161e041aad467a890839d5b08b138c1e6373072": {
1350          "balance": "0x123450000000000000000"
1351        },
1352        "87da6a8c6e9eff15d703fc2773e32f6af8dbe301": {
1353          "balance": "0x123450000000000000000"
1354        },
1355        "b97de4b8c857e4f6bc354f226dc3249aaee49209": {
1356          "balance": "0x123450000000000000000"
1357        },
1358        "c5065c9eeebe6df2c2284d046bfc906501846c51": {
1359          "balance": "0x123450000000000000000"
1360        },
1361        "0000000000000000000000000000000000000314": {
1362          "balance": "0x0",
1363          "code":
1364    "0x60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063a223e05d1461006a578063abd1a0cf1461008d578063abfced1d146100d4578063e05c914a14610110578063e6768b451461014c575b610000565b346100005761007761019d565b6040518082815260200191505060405180910390f35b34610000576100be600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506101a3565b6040518082815260200191505060405180910390f35b346100005761010e600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506101ed565b005b346100005761014a600480803590602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610236565b005b346100005761017960048080359060200190919080359060200190919080359060200190919050506103c4565b60405180848152602001838152602001828152602001935050505060405180910390f35b60005481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b80600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b5050565b7f6031a8d62d7c95988fa262657cd92107d90ed96e08d8f867d32f26edfe85502260405180905060405180910390a17f47e2689743f14e97f7dcfa5eec10ba1dff02f83b3d1d4b9c07b206cbbda66450826040518082815260200191505060405180910390a1817fa48a6b249a5084126c3da369fbc9b16827ead8cb5cdc094b717d3f1dcd995e2960405180905060405180910390a27f7890603b316f3509577afd111710f9ebeefa15e12f72347d9dffd0d65ae3bade81604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a18073ffffffffffffffffffffffffffffffffffffffff167f7efef9ea3f60ddc038e50cccec621f86a0195894dc0520482abf8b5c6b659e4160405180905060405180910390a28181604051808381526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a05b5050565b6000600060008585859250925092505b935093509390505600a165627a7a72305820aaf842d0d0c35c45622c5263cbb54813d2974d3999c8c38551d7c613ea2bc1170029"
1365    ,       "storage": {
1366            "0x0000000000000000000000000000000000000000000000000000000000000000": "0x1234",
1367            "0x6661e9d6d8b923d5bbaab1b96e1dd51ff6ea2a93520fdc9eb75d059238b8c5e9": "0x01"
1368          }
1369        },
1370        "0000000000000000000000000000000000000315": {
1371          "balance": "0x9999999999999999999999999999999",
1372          "code":
1373    "0x60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ef2769ca1461003e575b610000565b3461000057610078600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061007a565b005b8173ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051809050600060405180830381858888f1935050505015610106578173ffffffffffffffffffffffffffffffffffffffff167f30a3c50752f2552dcc2b93f5b96866280816a986c0c0408cb6778b9fa198288f826040518082815260200191505060405180910390a25b5b50505600a165627a7a72305820637991fabcc8abad4294bf2bb615db78fbec4edff1635a2647d3894e2daf6a610029"
1374        }
1375      }
1376    }
1377    "#;
1378
1379        let _genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
1380    }
1381
1382    #[test]
1383    fn parse_hive_graphql_genesis() {
1384        let geth_genesis = r#"
1385    {
1386        "config"     : {},
1387        "coinbase"   : "0x8888f1f195afa192cfee860698584c030f4c9db1",
1388        "difficulty" : "0x020000",
1389        "extraData"  : "0x42",
1390        "gasLimit"   : "0x2fefd8",
1391        "mixHash"    : "0x2c85bcbce56429100b2108254bb56906257582aeafcbd682bc9af67a9f5aee46",
1392        "nonce"      : "0x78cc16f7b4f65485",
1393        "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
1394        "timestamp"  : "0x54c98c81",
1395        "alloc"      : {
1396            "a94f5374fce5edbc8e2a8697c15331677e6ebf0b": {
1397                "balance" : "0x09184e72a000"
1398            }
1399        }
1400    }
1401    "#;
1402
1403        let _genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
1404    }
1405
1406    #[test]
1407    fn parse_hive_engine_genesis() {
1408        let geth_genesis = r#"
1409    {
1410      "config": {
1411        "chainId": 7,
1412        "homesteadBlock": 0,
1413        "eip150Block": 0,
1414        "eip150Hash": "0x5de1ee4135274003348e80b788e5afa4b18b18d320a5622218d5c493fedf5689",
1415        "eip155Block": 0,
1416        "eip158Block": 0,
1417        "byzantiumBlock": 0,
1418        "constantinopleBlock": 0,
1419        "petersburgBlock": 0,
1420        "istanbulBlock": 0,
1421        "muirGlacierBlock": 0,
1422        "berlinBlock": 0,
1423        "yolov2Block": 0,
1424        "yolov3Block": 0,
1425        "londonBlock": 0
1426      },
1427      "coinbase": "0x0000000000000000000000000000000000000000",
1428      "difficulty": "0x30000",
1429      "extraData":
1430    "0x0000000000000000000000000000000000000000000000000000000000000000658bdf435d810c91414ec09147daa6db624063790000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
1431    ,   "gasLimit": "0x2fefd8",
1432      "nonce": "0x0000000000000000",
1433      "timestamp": "0x1234",
1434      "alloc": {
1435        "cf49fda3be353c69b41ed96333cd24302da4556f": {
1436          "balance": "0x123450000000000000000"
1437        },
1438        "0161e041aad467a890839d5b08b138c1e6373072": {
1439          "balance": "0x123450000000000000000"
1440        },
1441        "87da6a8c6e9eff15d703fc2773e32f6af8dbe301": {
1442          "balance": "0x123450000000000000000"
1443        },
1444        "b97de4b8c857e4f6bc354f226dc3249aaee49209": {
1445          "balance": "0x123450000000000000000"
1446        },
1447        "c5065c9eeebe6df2c2284d046bfc906501846c51": {
1448          "balance": "0x123450000000000000000"
1449        },
1450        "0000000000000000000000000000000000000314": {
1451          "balance": "0x0",
1452          "code":
1453    "0x60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063a223e05d1461006a578063abd1a0cf1461008d578063abfced1d146100d4578063e05c914a14610110578063e6768b451461014c575b610000565b346100005761007761019d565b6040518082815260200191505060405180910390f35b34610000576100be600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506101a3565b6040518082815260200191505060405180910390f35b346100005761010e600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506101ed565b005b346100005761014a600480803590602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610236565b005b346100005761017960048080359060200190919080359060200190919080359060200190919050506103c4565b60405180848152602001838152602001828152602001935050505060405180910390f35b60005481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b80600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b5050565b7f6031a8d62d7c95988fa262657cd92107d90ed96e08d8f867d32f26edfe85502260405180905060405180910390a17f47e2689743f14e97f7dcfa5eec10ba1dff02f83b3d1d4b9c07b206cbbda66450826040518082815260200191505060405180910390a1817fa48a6b249a5084126c3da369fbc9b16827ead8cb5cdc094b717d3f1dcd995e2960405180905060405180910390a27f7890603b316f3509577afd111710f9ebeefa15e12f72347d9dffd0d65ae3bade81604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a18073ffffffffffffffffffffffffffffffffffffffff167f7efef9ea3f60ddc038e50cccec621f86a0195894dc0520482abf8b5c6b659e4160405180905060405180910390a28181604051808381526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a05b5050565b6000600060008585859250925092505b935093509390505600a165627a7a72305820aaf842d0d0c35c45622c5263cbb54813d2974d3999c8c38551d7c613ea2bc1170029"
1454    ,       "storage": {
1455            "0x0000000000000000000000000000000000000000000000000000000000000000": "0x1234",
1456            "0x6661e9d6d8b923d5bbaab1b96e1dd51ff6ea2a93520fdc9eb75d059238b8c5e9": "0x01"
1457          }
1458        },
1459        "0000000000000000000000000000000000000315": {
1460          "balance": "0x9999999999999999999999999999999",
1461          "code":
1462    "0x60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ef2769ca1461003e575b610000565b3461000057610078600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061007a565b005b8173ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051809050600060405180830381858888f1935050505015610106578173ffffffffffffffffffffffffffffffffffffffff167f30a3c50752f2552dcc2b93f5b96866280816a986c0c0408cb6778b9fa198288f826040518082815260200191505060405180910390a25b5b50505600a165627a7a72305820637991fabcc8abad4294bf2bb615db78fbec4edff1635a2647d3894e2daf6a610029"
1463        },
1464        "0000000000000000000000000000000000000316": {
1465          "balance": "0x0",
1466          "code": "0x444355"
1467        },
1468        "0000000000000000000000000000000000000317": {
1469          "balance": "0x0",
1470          "code": "0x600160003555"
1471        }
1472      }
1473    }
1474    "#;
1475
1476        let _genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
1477    }
1478
1479    #[test]
1480    fn parse_hive_devp2p_genesis() {
1481        let geth_genesis = r#"
1482    {
1483        "config": {
1484            "chainId": 19763,
1485            "homesteadBlock": 0,
1486            "eip150Block": 0,
1487            "eip155Block": 0,
1488            "eip158Block": 0,
1489            "byzantiumBlock": 0,
1490            "ethash": {}
1491        },
1492        "nonce": "0xdeadbeefdeadbeef",
1493        "timestamp": "0x0",
1494        "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
1495        "gasLimit": "0x80000000",
1496        "difficulty": "0x20000",
1497        "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1498        "coinbase": "0x0000000000000000000000000000000000000000",
1499        "alloc": {
1500            "71562b71999873db5b286df957af199ec94617f7": {
1501                "balance": "0xffffffffffffffffffffffffff"
1502            }
1503        },
1504        "number": "0x0",
1505        "gasUsed": "0x0",
1506        "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
1507    }
1508    "#;
1509
1510        let _genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
1511    }
1512
1513    #[test]
1514    fn parse_deposit_contract_address() {
1515        let genesis = r#"
1516    {
1517      "config": {
1518        "chainId": 1337,
1519        "homesteadBlock": 0,
1520        "eip150Block": 0,
1521        "eip155Block": 0,
1522        "eip158Block": 0,
1523        "byzantiumBlock": 0,
1524        "constantinopleBlock": 0,
1525        "petersburgBlock": 0,
1526        "istanbulBlock": 0,
1527        "muirGlacierBlock": 0,
1528        "berlinBlock": 0,
1529        "londonBlock": 0,
1530        "arrowGlacierBlock": 0,
1531        "grayGlacierBlock": 0,
1532        "shanghaiTime": 0,
1533        "cancunTime": 0,
1534        "pragueTime": 1,
1535        "osakaTime": 2,
1536        "terminalTotalDifficulty": 0,
1537        "depositContractAddress": "0x0000000000000000000000000000000000000000",
1538        "terminalTotalDifficultyPassed": true
1539      },
1540      "nonce": "0x0",
1541      "timestamp": "0x0",
1542      "extraData": "0x",
1543      "gasLimit": "0x4c4b40",
1544      "difficulty": "0x1",
1545      "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1546      "coinbase": "0x0000000000000000000000000000000000000000"
1547    }
1548    "#;
1549
1550        let got_genesis: Genesis = serde_json::from_str(genesis).unwrap();
1551        let expected_genesis = Genesis {
1552            config: ChainConfig {
1553                chain_id: 1337,
1554                homestead_block: Some(0),
1555                eip150_block: Some(0),
1556                eip155_block: Some(0),
1557                eip158_block: Some(0),
1558                byzantium_block: Some(0),
1559                constantinople_block: Some(0),
1560                petersburg_block: Some(0),
1561                istanbul_block: Some(0),
1562                muir_glacier_block: Some(0),
1563                berlin_block: Some(0),
1564                london_block: Some(0),
1565                arrow_glacier_block: Some(0),
1566                gray_glacier_block: Some(0),
1567                dao_fork_block: None,
1568                dao_fork_support: false,
1569                shanghai_time: Some(0),
1570                cancun_time: Some(0),
1571                prague_time: Some(1),
1572                osaka_time: Some(2),
1573                terminal_total_difficulty: Some(U256::ZERO),
1574                terminal_total_difficulty_passed: true,
1575                deposit_contract_address: Some(Address::ZERO),
1576                ..Default::default()
1577            },
1578            nonce: 0,
1579            timestamp: 0,
1580            extra_data: Bytes::new(),
1581            gas_limit: 0x4c4b40,
1582            difficulty: U256::from(1),
1583            ..Default::default()
1584        };
1585
1586        assert_eq!(expected_genesis, got_genesis);
1587    }
1588
1589    #[test]
1590    fn parse_prague_time() {
1591        let genesis = r#"
1592    {
1593      "config": {
1594        "chainId": 1337,
1595        "homesteadBlock": 0,
1596        "eip150Block": 0,
1597        "eip155Block": 0,
1598        "eip158Block": 0,
1599        "byzantiumBlock": 0,
1600        "constantinopleBlock": 0,
1601        "petersburgBlock": 0,
1602        "istanbulBlock": 0,
1603        "muirGlacierBlock": 0,
1604        "berlinBlock": 0,
1605        "londonBlock": 0,
1606        "arrowGlacierBlock": 0,
1607        "grayGlacierBlock": 0,
1608        "shanghaiTime": 0,
1609        "cancunTime": 0,
1610        "pragueTime": 1,
1611        "terminalTotalDifficulty": 0,
1612        "terminalTotalDifficultyPassed": true
1613      },
1614      "nonce": "0x0",
1615      "timestamp": "0x0",
1616      "extraData": "0x",
1617      "gasLimit": "0x4c4b40",
1618      "difficulty": "0x1",
1619      "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1620      "coinbase": "0x0000000000000000000000000000000000000000"
1621    }
1622    "#;
1623
1624        let got_genesis: Genesis = serde_json::from_str(genesis).unwrap();
1625        let expected_genesis = Genesis {
1626            config: ChainConfig {
1627                chain_id: 1337,
1628                homestead_block: Some(0),
1629                eip150_block: Some(0),
1630                eip155_block: Some(0),
1631                eip158_block: Some(0),
1632                byzantium_block: Some(0),
1633                constantinople_block: Some(0),
1634                petersburg_block: Some(0),
1635                istanbul_block: Some(0),
1636                muir_glacier_block: Some(0),
1637                berlin_block: Some(0),
1638                london_block: Some(0),
1639                arrow_glacier_block: Some(0),
1640                gray_glacier_block: Some(0),
1641                dao_fork_block: None,
1642                dao_fork_support: false,
1643                shanghai_time: Some(0),
1644                cancun_time: Some(0),
1645                prague_time: Some(1),
1646                terminal_total_difficulty: Some(U256::ZERO),
1647                terminal_total_difficulty_passed: true,
1648                ..Default::default()
1649            },
1650            nonce: 0,
1651            timestamp: 0,
1652            extra_data: Bytes::new(),
1653            gas_limit: 0x4c4b40,
1654            difficulty: U256::from(1),
1655            ..Default::default()
1656        };
1657
1658        assert_eq!(expected_genesis, got_genesis);
1659    }
1660
1661    #[test]
1662    fn parse_execution_apis_genesis() {
1663        let geth_genesis = r#"
1664    {
1665      "config": {
1666        "chainId": 1337,
1667        "homesteadBlock": 0,
1668        "eip150Block": 0,
1669        "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1670        "eip155Block": 0,
1671        "eip158Block": 0,
1672        "byzantiumBlock": 0,
1673        "constantinopleBlock": 0,
1674        "petersburgBlock": 0,
1675        "istanbulBlock": 0,
1676        "muirGlacierBlock": 0,
1677        "berlinBlock": 0,
1678        "londonBlock": 0,
1679        "arrowGlacierBlock": 0,
1680        "grayGlacierBlock": 0,
1681        "shanghaiTime": 0,
1682        "terminalTotalDifficulty": 0,
1683        "terminalTotalDifficultyPassed": true,
1684        "ethash": {}
1685      },
1686      "nonce": "0x0",
1687      "timestamp": "0x0",
1688      "extraData": "0x",
1689      "gasLimit": "0x4c4b40",
1690      "difficulty": "0x1",
1691      "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1692      "coinbase": "0x0000000000000000000000000000000000000000",
1693      "alloc": {
1694        "658bdf435d810c91414ec09147daa6db62406379": {
1695          "balance": "0x487a9a304539440000"
1696        },
1697        "aa00000000000000000000000000000000000000": {
1698          "code": "0x6042",
1699          "storage": {
1700            "0x0000000000000000000000000000000000000000000000000000000000000000":
1701    "0x0000000000000000000000000000000000000000000000000000000000000000",
1702            "0x0100000000000000000000000000000000000000000000000000000000000000":
1703    "0x0100000000000000000000000000000000000000000000000000000000000000",
1704            "0x0200000000000000000000000000000000000000000000000000000000000000":
1705    "0x0200000000000000000000000000000000000000000000000000000000000000",
1706            "0x0300000000000000000000000000000000000000000000000000000000000000":
1707    "0x0000000000000000000000000000000000000000000000000000000000000303"       },
1708          "balance": "0x1",
1709          "nonce": "0x1"
1710        },
1711        "bb00000000000000000000000000000000000000": {
1712          "code": "0x600154600354",
1713          "storage": {
1714            "0x0000000000000000000000000000000000000000000000000000000000000000":
1715    "0x0000000000000000000000000000000000000000000000000000000000000000",
1716            "0x0100000000000000000000000000000000000000000000000000000000000000":
1717    "0x0100000000000000000000000000000000000000000000000000000000000000",
1718            "0x0200000000000000000000000000000000000000000000000000000000000000":
1719    "0x0200000000000000000000000000000000000000000000000000000000000000",
1720            "0x0300000000000000000000000000000000000000000000000000000000000000":
1721    "0x0000000000000000000000000000000000000000000000000000000000000303"       },
1722          "balance": "0x2",
1723          "nonce": "0x1"
1724        }
1725      }
1726    }
1727    "#;
1728
1729        let _genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
1730    }
1731
1732    #[test]
1733    fn parse_hive_rpc_genesis_full() {
1734        let geth_genesis = r#"
1735    {
1736      "config": {
1737        "clique": {
1738          "period": 1
1739        },
1740        "chainId": 7,
1741        "homesteadBlock": 0,
1742        "eip150Block": 0,
1743        "eip155Block": 0,
1744        "eip158Block": 0
1745      },
1746      "coinbase": "0x0000000000000000000000000000000000000000",
1747      "difficulty": "0x020000",
1748      "extraData":
1749    "0x0000000000000000000000000000000000000000000000000000000000000000658bdf435d810c91414ec09147daa6db624063790000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
1750    ,   "gasLimit": "0x2fefd8",
1751      "nonce": "0x0000000000000000",
1752      "timestamp": "0x1234",
1753      "alloc": {
1754        "cf49fda3be353c69b41ed96333cd24302da4556f": {
1755          "balance": "0x123450000000000000000"
1756        },
1757        "0161e041aad467a890839d5b08b138c1e6373072": {
1758          "balance": "0x123450000000000000000"
1759        },
1760        "87da6a8c6e9eff15d703fc2773e32f6af8dbe301": {
1761          "balance": "0x123450000000000000000"
1762        },
1763        "b97de4b8c857e4f6bc354f226dc3249aaee49209": {
1764          "balance": "0x123450000000000000000"
1765        },
1766        "c5065c9eeebe6df2c2284d046bfc906501846c51": {
1767          "balance": "0x123450000000000000000"
1768        },
1769        "0000000000000000000000000000000000000314": {
1770          "balance": "0x0",
1771          "code":
1772    "0x60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063a223e05d1461006a578063abd1a0cf1461008d578063abfced1d146100d4578063e05c914a14610110578063e6768b451461014c575b610000565b346100005761007761019d565b6040518082815260200191505060405180910390f35b34610000576100be600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506101a3565b6040518082815260200191505060405180910390f35b346100005761010e600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506101ed565b005b346100005761014a600480803590602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610236565b005b346100005761017960048080359060200190919080359060200190919080359060200190919050506103c4565b60405180848152602001838152602001828152602001935050505060405180910390f35b60005481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b80600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b5050565b7f6031a8d62d7c95988fa262657cd92107d90ed96e08d8f867d32f26edfe85502260405180905060405180910390a17f47e2689743f14e97f7dcfa5eec10ba1dff02f83b3d1d4b9c07b206cbbda66450826040518082815260200191505060405180910390a1817fa48a6b249a5084126c3da369fbc9b16827ead8cb5cdc094b717d3f1dcd995e2960405180905060405180910390a27f7890603b316f3509577afd111710f9ebeefa15e12f72347d9dffd0d65ae3bade81604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a18073ffffffffffffffffffffffffffffffffffffffff167f7efef9ea3f60ddc038e50cccec621f86a0195894dc0520482abf8b5c6b659e4160405180905060405180910390a28181604051808381526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a05b5050565b6000600060008585859250925092505b935093509390505600a165627a7a72305820aaf842d0d0c35c45622c5263cbb54813d2974d3999c8c38551d7c613ea2bc1170029"
1773    ,       "storage": {
1774            "0x0000000000000000000000000000000000000000000000000000000000000000": "0x1234",
1775            "0x6661e9d6d8b923d5bbaab1b96e1dd51ff6ea2a93520fdc9eb75d059238b8c5e9": "0x01"
1776          }
1777        },
1778        "0000000000000000000000000000000000000315": {
1779          "balance": "0x9999999999999999999999999999999",
1780          "code":
1781    "0x60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ef2769ca1461003e575b610000565b3461000057610078600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061007a565b005b8173ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051809050600060405180830381858888f1935050505015610106578173ffffffffffffffffffffffffffffffffffffffff167f30a3c50752f2552dcc2b93f5b96866280816a986c0c0408cb6778b9fa198288f826040518082815260200191505060405180910390a25b5b50505600a165627a7a72305820637991fabcc8abad4294bf2bb615db78fbec4edff1635a2647d3894e2daf6a610029"
1782        }
1783      },
1784      "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1785      "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
1786    }
1787    "#;
1788
1789        let genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
1790        let alloc_entry = genesis
1791            .alloc
1792            .get(&Address::from_str("0000000000000000000000000000000000000314").unwrap())
1793            .expect("missing account for parsed genesis");
1794        let storage = alloc_entry.storage.as_ref().expect("missing storage for parsed genesis");
1795        let expected_storage = BTreeMap::from_iter(vec![
1796            (
1797                B256::from_str(
1798                    "0x0000000000000000000000000000000000000000000000000000000000000000",
1799                )
1800                .unwrap(),
1801                B256::from_str(
1802                    "0x0000000000000000000000000000000000000000000000000000000000001234",
1803                )
1804                .unwrap(),
1805            ),
1806            (
1807                B256::from_str(
1808                    "0x6661e9d6d8b923d5bbaab1b96e1dd51ff6ea2a93520fdc9eb75d059238b8c5e9",
1809                )
1810                .unwrap(),
1811                B256::from_str(
1812                    "0x0000000000000000000000000000000000000000000000000000000000000001",
1813                )
1814                .unwrap(),
1815            ),
1816        ]);
1817        assert_eq!(storage, &expected_storage);
1818
1819        let expected_code =
1820    Bytes::from_str("0x60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063a223e05d1461006a578063abd1a0cf1461008d578063abfced1d146100d4578063e05c914a14610110578063e6768b451461014c575b610000565b346100005761007761019d565b6040518082815260200191505060405180910390f35b34610000576100be600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506101a3565b6040518082815260200191505060405180910390f35b346100005761010e600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506101ed565b005b346100005761014a600480803590602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610236565b005b346100005761017960048080359060200190919080359060200190919080359060200190919050506103c4565b60405180848152602001838152602001828152602001935050505060405180910390f35b60005481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b80600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b5050565b7f6031a8d62d7c95988fa262657cd92107d90ed96e08d8f867d32f26edfe85502260405180905060405180910390a17f47e2689743f14e97f7dcfa5eec10ba1dff02f83b3d1d4b9c07b206cbbda66450826040518082815260200191505060405180910390a1817fa48a6b249a5084126c3da369fbc9b16827ead8cb5cdc094b717d3f1dcd995e2960405180905060405180910390a27f7890603b316f3509577afd111710f9ebeefa15e12f72347d9dffd0d65ae3bade81604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a18073ffffffffffffffffffffffffffffffffffffffff167f7efef9ea3f60ddc038e50cccec621f86a0195894dc0520482abf8b5c6b659e4160405180905060405180910390a28181604051808381526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a05b5050565b6000600060008585859250925092505b935093509390505600a165627a7a72305820aaf842d0d0c35c45622c5263cbb54813d2974d3999c8c38551d7c613ea2bc1170029"
1821    ).unwrap();
1822        let code = alloc_entry.code.as_ref().expect(
1823            "missing code for parsed
1824    genesis",
1825        );
1826        assert_eq!(code, &expected_code);
1827    }
1828
1829    #[test]
1830    fn test_hive_smoke_alloc_deserialize() {
1831        let hive_genesis = r#"
1832    {
1833        "nonce": "0x0000000000000042",
1834        "difficulty": "0x2123456",
1835        "mixHash": "0x123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234",
1836        "coinbase": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1837        "timestamp": "0x123456",
1838        "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
1839        "extraData": "0xfafbfcfd",
1840        "gasLimit": "0x2fefd8",
1841        "alloc": {
1842            "dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6": {
1843                "balance": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
1844            },
1845            "e6716f9544a56c530d868e4bfbacb172315bdead": {
1846                "balance": "0x11",
1847                "code": "0x12"
1848            },
1849            "b9c015918bdaba24b4ff057a92a3873d6eb201be": {
1850                "balance": "0x21",
1851                "storage": {
1852                    "0x0000000000000000000000000000000000000000000000000000000000000001": "0x22"
1853                }
1854            },
1855            "1a26338f0d905e295fccb71fa9ea849ffa12aaf4": {
1856                "balance": "0x31",
1857                "nonce": "0x32"
1858            },
1859            "0000000000000000000000000000000000000001": {
1860                "balance": "0x41"
1861            },
1862            "0000000000000000000000000000000000000002": {
1863                "balance": "0x51"
1864            },
1865            "0000000000000000000000000000000000000003": {
1866                "balance": "0x61"
1867            },
1868            "0000000000000000000000000000000000000004": {
1869                "balance": "0x71"
1870            }
1871        },
1872        "config": {
1873            "ethash": {},
1874            "chainId": 10,
1875            "homesteadBlock": 0,
1876            "eip150Block": 0,
1877            "eip155Block": 0,
1878            "eip158Block": 0,
1879            "byzantiumBlock": 0,
1880            "constantinopleBlock": 0,
1881            "petersburgBlock": 0,
1882            "istanbulBlock": 0
1883        }
1884    }
1885    "#;
1886
1887        let expected_genesis =
1888            Genesis {
1889                nonce: 0x0000000000000042,
1890                difficulty: U256::from(0x2123456),
1891                mix_hash: B256::from_str(
1892                    "0x123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234",
1893                )
1894                .unwrap(),
1895                coinbase: Address::from_str("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap(),
1896                timestamp: 0x123456,
1897                extra_data: Bytes::from_str("0xfafbfcfd").unwrap(),
1898                gas_limit: 0x2fefd8,
1899                base_fee_per_gas: None,
1900                excess_blob_gas: None,
1901                blob_gas_used: None,
1902                number: None,
1903                alloc: BTreeMap::from_iter(vec![
1904                (
1905                    Address::from_str("0xdbdbdb2cbd23b783741e8d7fcf51e459b497e4a6").unwrap(),
1906                    GenesisAccount {
1907                        balance:
1908    U256::from_str("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").
1909    unwrap(),                     nonce: None,
1910                        code: None,
1911                        storage: None,
1912                        private_key: None,
1913                    },
1914                ),
1915                (
1916                    Address::from_str("0xe6716f9544a56c530d868e4bfbacb172315bdead").unwrap(),
1917                    GenesisAccount {
1918                        balance: U256::from_str("0x11").unwrap(),
1919                        nonce: None,
1920                        code: Some(Bytes::from_str("0x12").unwrap()),
1921                        storage: None,
1922                        private_key: None,
1923                    },
1924                ),
1925                (
1926                    Address::from_str("0xb9c015918bdaba24b4ff057a92a3873d6eb201be").unwrap(),
1927                    GenesisAccount {
1928                        balance: U256::from_str("0x21").unwrap(),
1929                        nonce: None,
1930                        code: None,
1931                        storage: Some(BTreeMap::from_iter(vec![
1932                            (
1933
1934    B256::from_str("0x0000000000000000000000000000000000000000000000000000000000000001").
1935    unwrap(),
1936    B256::from_str("0x0000000000000000000000000000000000000000000000000000000000000022").
1937    unwrap(),                         ),
1938                        ])),
1939                        private_key: None,
1940                    },
1941                ),
1942                (
1943                    Address::from_str("0x1a26338f0d905e295fccb71fa9ea849ffa12aaf4").unwrap(),
1944                    GenesisAccount {
1945                        balance: U256::from_str("0x31").unwrap(),
1946                        nonce: Some(0x32u64),
1947                        code: None,
1948                        storage: None,
1949                        private_key: None,
1950                    },
1951                ),
1952                (
1953                    Address::from_str("0x0000000000000000000000000000000000000001").unwrap(),
1954                    GenesisAccount {
1955                        balance: U256::from_str("0x41").unwrap(),
1956                        nonce: None,
1957                        code: None,
1958                        storage: None,
1959                        private_key: None,
1960                    },
1961                ),
1962                (
1963                    Address::from_str("0x0000000000000000000000000000000000000002").unwrap(),
1964                    GenesisAccount {
1965                        balance: U256::from_str("0x51").unwrap(),
1966                        nonce: None,
1967                        code: None,
1968                        storage: None,
1969                        private_key: None,
1970                    },
1971                ),
1972                (
1973                    Address::from_str("0x0000000000000000000000000000000000000003").unwrap(),
1974                    GenesisAccount {
1975                        balance: U256::from_str("0x61").unwrap(),
1976                        nonce: None,
1977                        code: None,
1978                        storage: None,
1979                        private_key: None,
1980                    },
1981                ),
1982                (
1983                    Address::from_str("0x0000000000000000000000000000000000000004").unwrap(),
1984                    GenesisAccount {
1985                        balance: U256::from_str("0x71").unwrap(),
1986                        nonce: None,
1987                        code: None,
1988                        storage: None,
1989                        private_key: None,
1990                    },
1991                ),
1992            ]),
1993                config: ChainConfig {
1994                    ethash: Some(EthashConfig {}),
1995                    chain_id: 10,
1996                    homestead_block: Some(0),
1997                    eip150_block: Some(0),
1998                    eip155_block: Some(0),
1999                    eip158_block: Some(0),
2000                    byzantium_block: Some(0),
2001                    constantinople_block: Some(0),
2002                    petersburg_block: Some(0),
2003                    istanbul_block: Some(0),
2004                    deposit_contract_address: None,
2005                    ..Default::default()
2006                },
2007            };
2008
2009        let deserialized_genesis: Genesis = serde_json::from_str(hive_genesis).unwrap();
2010        assert_eq!(
2011            deserialized_genesis, expected_genesis,
2012            "deserialized genesis
2013    {deserialized_genesis:#?} does not match expected {expected_genesis:#?}"
2014        );
2015    }
2016
2017    #[test]
2018    fn parse_dump_genesis_mainnet() {
2019        let mainnet = include_str!("../dumpgenesis/mainnet.json");
2020        let gen1 = serde_json::from_str::<Genesis>(mainnet).unwrap();
2021        let s = serde_json::to_string_pretty(&gen1).unwrap();
2022        let gen2 = serde_json::from_str::<Genesis>(&s).unwrap();
2023        assert_eq!(gen1, gen2);
2024    }
2025
2026    #[test]
2027    fn parse_dump_genesis_sepolia() {
2028        let sepolia = include_str!("../dumpgenesis/sepolia.json");
2029        let gen1 = serde_json::from_str::<Genesis>(sepolia).unwrap();
2030        let s = serde_json::to_string_pretty(&gen1).unwrap();
2031        let gen2 = serde_json::from_str::<Genesis>(&s).unwrap();
2032        assert_eq!(gen1, gen2);
2033    }
2034
2035    #[test]
2036    fn parse_dump_genesis_holesky() {
2037        let holesky = include_str!("../dumpgenesis/holesky.json");
2038        let gen1 = serde_json::from_str::<Genesis>(holesky).unwrap();
2039        let s = serde_json::to_string_pretty(&gen1).unwrap();
2040        let gen2 = serde_json::from_str::<Genesis>(&s).unwrap();
2041        assert_eq!(gen1, gen2);
2042    }
2043
2044    #[test]
2045    fn parse_extra_fields() {
2046        let geth_genesis = r#"
2047    {
2048        "difficulty": "0x20000",
2049        "gasLimit": "0x1",
2050        "alloc": {},
2051        "config": {
2052          "ethash": {},
2053          "chainId": 1,
2054          "string_field": "string_value",
2055          "numeric_field": 7,
2056          "object_field": {
2057            "sub_field": "sub_value"
2058          }
2059        }
2060    }
2061    "#;
2062        let genesis: Genesis = serde_json::from_str(geth_genesis).unwrap();
2063        let actual_string_value = genesis.config.extra_fields.get("string_field").unwrap();
2064        assert_eq!(actual_string_value, "string_value");
2065        let actual_numeric_value = genesis.config.extra_fields.get("numeric_field").unwrap();
2066        assert_eq!(actual_numeric_value, 7);
2067        let actual_object_value = genesis.config.extra_fields.get("object_field").unwrap();
2068        assert_eq!(actual_object_value, &serde_json::json!({"sub_field": "sub_value"}));
2069    }
2070
2071    #[test]
2072    fn deserialize_private_key_as_none_when_0x() {
2073        // Test case where "secretKey" is "0x", expecting None
2074        let json_data = json!({
2075            "balance": "0x0",
2076            "secretKey": "0x"
2077        });
2078
2079        let account: GenesisAccount = serde_json::from_value(json_data).unwrap();
2080        assert_eq!(account.private_key, None);
2081    }
2082
2083    #[test]
2084    fn deserialize_private_key_with_valid_hex() {
2085        // Test case where "secretKey" is a valid hex string
2086        let json_data = json!({
2087            "balance": "0x0",
2088            "secretKey": "0x123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234"
2089        });
2090
2091        let account: GenesisAccount = serde_json::from_value(json_data).unwrap();
2092        let expected_key =
2093            B256::from_str("123456789abcdef123456789abcdef123456789abcdef123456789abcdef1234")
2094                .unwrap();
2095        assert_eq!(account.private_key, Some(expected_key));
2096    }
2097
2098    #[test]
2099    fn deserialize_private_key_as_none_when_null() {
2100        // Test case where "secretKey" is null, expecting None
2101        let json_data = json!({
2102            "balance": "0x0",
2103            "secretKey": null
2104        });
2105
2106        let account: GenesisAccount = serde_json::from_value(json_data).unwrap();
2107        assert_eq!(account.private_key, None);
2108    }
2109
2110    #[test]
2111    fn deserialize_private_key_with_invalid_hex_fails() {
2112        // Test case where "secretKey" is an invalid hex string, expecting an error
2113        let json_data = json!({
2114            "balance": "0x0",
2115            "secretKey": "0xINVALIDHEX"
2116        });
2117
2118        let result: Result<GenesisAccount, _> = serde_json::from_value(json_data);
2119        assert!(result.is_err()); // The deserialization should fail due to invalid hex
2120    }
2121
2122    #[test]
2123    fn deserialize_private_key_with_empty_string_fails() {
2124        // Test case where "secretKey" is an empty string, expecting an error
2125        let json_data = json!({
2126            "secretKey": ""
2127        });
2128
2129        let result: Result<GenesisAccount, _> = serde_json::from_value(json_data);
2130        assert!(result.is_err()); // The deserialization should fail due to an empty string
2131    }
2132
2133    #[test]
2134    fn test_from_genesis_account_with_default_values() {
2135        let genesis_account = GenesisAccount::default();
2136
2137        // Convert the GenesisAccount to a TrieAccount
2138        let trie_account: TrieAccount = genesis_account.into();
2139
2140        // Check the fields are properly set.
2141        assert_eq!(trie_account.nonce, 0);
2142        assert_eq!(trie_account.balance, U256::default());
2143        assert_eq!(trie_account.storage_root, EMPTY_ROOT_HASH);
2144        assert_eq!(trie_account.code_hash, KECCAK_EMPTY);
2145
2146        // Check that the default Account converts to the same TrieAccount
2147        assert_eq!(TrieAccount::default(), trie_account);
2148    }
2149
2150    #[test]
2151    fn test_from_genesis_account_with_values() {
2152        // Create a GenesisAccount with specific values
2153        let mut storage = BTreeMap::new();
2154        storage.insert(B256::from([0x01; 32]), B256::from([0x02; 32]));
2155
2156        let genesis_account = GenesisAccount {
2157            nonce: Some(10),
2158            balance: U256::from(1000),
2159            code: Some(Bytes::from(vec![0x60, 0x61])),
2160            storage: Some(storage),
2161            private_key: None,
2162        };
2163
2164        // Convert the GenesisAccount to a TrieAccount
2165        let trie_account: TrieAccount = genesis_account.into();
2166
2167        let expected_storage_root = storage_root_unhashed(BTreeMap::from([(
2168            B256::from([0x01; 32]),
2169            U256::from_be_bytes(*B256::from([0x02; 32])),
2170        )]));
2171
2172        // Check that the fields are properly set.
2173        assert_eq!(trie_account.nonce, 10);
2174        assert_eq!(trie_account.balance, U256::from(1000));
2175        assert_eq!(trie_account.storage_root, expected_storage_root);
2176        assert_eq!(trie_account.code_hash, keccak256([0x60, 0x61]));
2177    }
2178
2179    #[test]
2180    fn test_from_genesis_account_with_zeroed_storage_values() {
2181        // Create a GenesisAccount with storage containing zero values
2182        let storage = BTreeMap::from([(B256::from([0x01; 32]), B256::from([0x00; 32]))]);
2183
2184        let genesis_account = GenesisAccount {
2185            nonce: Some(3),
2186            balance: U256::from(300),
2187            code: None,
2188            storage: Some(storage),
2189            private_key: None,
2190        };
2191
2192        // Convert the GenesisAccount to a TrieAccount
2193        let trie_account: TrieAccount = genesis_account.into();
2194
2195        // Check the fields are properly set.
2196        assert_eq!(trie_account.nonce, 3);
2197        assert_eq!(trie_account.balance, U256::from(300));
2198        // Zero values in storage should result in EMPTY_ROOT_HASH
2199        assert_eq!(trie_account.storage_root, EMPTY_ROOT_HASH);
2200        // No code provided, so code hash should be KECCAK_EMPTY
2201        assert_eq!(trie_account.code_hash, KECCAK_EMPTY);
2202    }
2203}