Skip to main content

ef_tests/
models.rs

1//! Shared models for <https://github.com/ethereum/tests>
2
3use crate::{assert::assert_equal, Error};
4use alloy_consensus::Header as RethHeader;
5use alloy_eips::{eip4844::DATA_GAS_PER_BLOB, eip4895::Withdrawals, eip7840::BlobParams};
6use alloy_genesis::{Genesis, GenesisAccount};
7use alloy_primitives::{
8    keccak256, map::HashMap, Address, Bloom, Bytes, B256, B64, U128, U256, U64,
9};
10use reth_chainspec::{Chain, ChainSpec, ChainSpecBuilder, EthereumHardfork, ForkCondition};
11use reth_db_api::{cursor::DbDupCursorRO, tables, transaction::DbTx};
12use reth_primitives_traits::SealedHeader;
13use serde::Deserialize;
14use std::{
15    collections::BTreeMap,
16    ops::Deref,
17    sync::{Arc, OnceLock, RwLock},
18};
19
20/// The definition of a blockchain test.
21#[derive(Debug, PartialEq, Eq, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct BlockchainTest {
24    /// Genesis block header.
25    pub genesis_block_header: Header,
26    /// RLP encoded genesis block.
27    #[serde(rename = "genesisRLP")]
28    pub genesis_rlp: Option<Bytes>,
29    /// Block data.
30    pub blocks: Vec<Block>,
31    /// The expected post state.
32    pub post_state: Option<BTreeMap<Address, Account>>,
33    /// The test pre-state.
34    pub pre: State,
35    /// Hash of the best block.
36    pub lastblockhash: B256,
37    /// Network spec.
38    pub network: ForkSpec,
39    /// Chain ID and blob schedule supplied by the fixture.
40    #[serde(default)]
41    pub config: FixtureConfig,
42    /// Engine spec.
43    #[serde(default)]
44    pub seal_engine: SealEngine,
45}
46
47impl BlockchainTest {
48    /// Builds the fixture's fork schedule, chain ID, blob parameters and genesis allocation.
49    ///
50    /// # Errors
51    /// Returns an error for unsupported forks, out-of-range genesis quantities, or invalid blob
52    /// parameters.
53    pub fn chain_spec(&self) -> Result<ChainSpec, FixtureConfigError> {
54        fixture_chain_spec(&self.genesis_block_header, &self.pre, self.network, &self.config)
55    }
56}
57
58/// A blockchain test in the engine format, whose blocks are Engine API payloads.
59#[derive(Debug, PartialEq, Eq, Deserialize)]
60#[serde(rename_all = "camelCase")]
61pub struct EngineTest {
62    /// Genesis block header.
63    pub genesis_block_header: Header,
64    /// The test pre-state.
65    pub pre: State,
66    /// Hash of the best block.
67    pub lastblockhash: B256,
68    /// Network spec.
69    pub network: ForkSpec,
70    /// Chain ID and blob schedule supplied by the fixture.
71    #[serde(default)]
72    pub config: FixtureConfig,
73    /// The payloads to send, in order.
74    pub engine_new_payloads: Vec<EngineNewPayload>,
75}
76
77impl EngineTest {
78    /// Returns the chain spec of the test's network, with the test's genesis block.
79    ///
80    /// # Errors
81    /// Returns an error for unsupported forks, out-of-range genesis quantities, or invalid blob
82    /// parameters.
83    pub fn chain_spec(&self) -> Result<ChainSpec, FixtureConfigError> {
84        fixture_chain_spec(&self.genesis_block_header, &self.pre, self.network, &self.config)
85    }
86}
87
88/// One `engine_newPayload` call of an [`EngineTest`].
89#[derive(Debug, PartialEq, Eq, Deserialize)]
90#[serde(rename_all = "camelCase")]
91pub struct EngineNewPayload {
92    /// The call's parameters, sent to the client as they are.
93    pub params: Vec<serde_json::Value>,
94    /// The version of `engine_newPayload` to call.
95    pub new_payload_version: String,
96    /// The version of `engine_forkchoiceUpdated` to call once the payload is accepted.
97    pub forkchoice_updated_version: String,
98    /// The expected validation error, if the payload is invalid.
99    pub validation_error: Option<String>,
100    /// The expected JSON-RPC error code, if the call must fail.
101    pub error_code: Option<String>,
102}
103
104/// Execution configuration embedded in a fixture.
105#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
106#[serde(rename_all = "camelCase")]
107pub struct FixtureConfig {
108    /// The chain ID; absent legacy configurations use mainnet's ID.
109    #[serde(rename = "chainid")]
110    pub chain_id: Option<U64>,
111    /// Per-fork blob parameters. Unlisted forks retain their protocol defaults.
112    #[serde(default)]
113    pub blob_schedule: BTreeMap<ForkSpec, FixtureBlobParams>,
114}
115
116/// Quantity-encoded EIP-7840 parameters from the fixture format.
117#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
118#[serde(rename_all = "camelCase")]
119pub struct FixtureBlobParams {
120    /// Target number of blobs in a block.
121    pub target: U64,
122    /// Maximum number of blobs in a block.
123    pub max: U64,
124    /// Nonzero denominator used to update the blob base fee.
125    #[serde(deserialize_with = "deserialize_blob_update_fraction")]
126    pub base_fee_update_fraction: U128,
127}
128
129/// A fixture configuration that the runner cannot execute.
130#[derive(Debug, thiserror::Error)]
131#[non_exhaustive]
132pub enum FixtureConfigError {
133    /// An experimental fork has no matching EVM configuration.
134    #[error("unsupported fixture fork: {0:?}")]
135    UnsupportedFork(ForkSpec),
136    /// A genesis header quantity exceeds the client's representation.
137    #[error("fixture genesis {field} does not fit in u64: {source}")]
138    HeaderQuantity {
139        /// The fixture's header field.
140        field: &'static str,
141        /// The failed checked conversion.
142        #[source]
143        source: alloy_primitives::ruint::FromUintError<u64>,
144    },
145    /// Blob parameters would overflow or divide by zero during header validation.
146    #[error("unsupported fixture blob schedule for {fork:?}: target {target}, maximum {max}")]
147    BlobParams {
148        /// The fork whose parameters cannot be executed.
149        fork: ForkSpec,
150        /// The configured target.
151        target: u64,
152        /// The configured maximum.
153        max: u64,
154    },
155}
156
157/// A block header in an Ethereum blockchain test.
158#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Default)]
159#[serde(rename_all = "camelCase")]
160pub struct Header {
161    /// Bloom filter.
162    pub bloom: Bloom,
163    /// Coinbase.
164    pub coinbase: Address,
165    /// Difficulty.
166    pub difficulty: U256,
167    /// Extra data.
168    pub extra_data: Bytes,
169    /// Gas limit.
170    pub gas_limit: U256,
171    /// Gas used.
172    pub gas_used: U256,
173    /// Block Hash.
174    pub hash: B256,
175    /// Mix hash.
176    pub mix_hash: B256,
177    /// Seal nonce.
178    pub nonce: B64,
179    /// Block number.
180    pub number: U256,
181    /// Parent hash.
182    pub parent_hash: B256,
183    /// Receipt trie.
184    pub receipt_trie: B256,
185    /// State root.
186    pub state_root: B256,
187    /// Timestamp.
188    pub timestamp: U256,
189    /// Transactions trie.
190    pub transactions_trie: B256,
191    /// Uncle hash.
192    pub uncle_hash: B256,
193    /// Base fee per gas.
194    pub base_fee_per_gas: Option<U256>,
195    /// Withdrawals root.
196    pub withdrawals_root: Option<B256>,
197    /// Blob gas used.
198    pub blob_gas_used: Option<U256>,
199    /// Excess blob gas.
200    pub excess_blob_gas: Option<U256>,
201    /// Parent beacon block root.
202    pub parent_beacon_block_root: Option<B256>,
203    /// Requests root.
204    pub requests_hash: Option<B256>,
205    /// Target blobs per block.
206    pub target_blobs_per_block: Option<U256>,
207    /// Block access list hash.
208    pub block_access_list_hash: Option<B256>,
209    /// Slot number.
210    pub slot_number: Option<U256>,
211}
212
213impl TryFrom<Header> for SealedHeader {
214    type Error = FixtureConfigError;
215
216    fn try_from(value: Header) -> Result<Self, Self::Error> {
217        let quantity = |value: U256, field| {
218            u64::try_from(value)
219                .map_err(|source| FixtureConfigError::HeaderQuantity { field, source })
220        };
221        let header = RethHeader {
222            base_fee_per_gas: value
223                .base_fee_per_gas
224                .map(|v| quantity(v, "baseFeePerGas"))
225                .transpose()?,
226            beneficiary: value.coinbase,
227            difficulty: value.difficulty,
228            extra_data: value.extra_data,
229            gas_limit: quantity(value.gas_limit, "gasLimit")?,
230            gas_used: quantity(value.gas_used, "gasUsed")?,
231            mix_hash: value.mix_hash,
232            nonce: u64::from_be_bytes(value.nonce.0).into(),
233            number: quantity(value.number, "number")?,
234            timestamp: quantity(value.timestamp, "timestamp")?,
235            transactions_root: value.transactions_trie,
236            receipts_root: value.receipt_trie,
237            ommers_hash: value.uncle_hash,
238            state_root: value.state_root,
239            parent_hash: value.parent_hash,
240            logs_bloom: value.bloom,
241            withdrawals_root: value.withdrawals_root,
242            blob_gas_used: value.blob_gas_used.map(|v| quantity(v, "blobGasUsed")).transpose()?,
243            excess_blob_gas: value
244                .excess_blob_gas
245                .map(|v| quantity(v, "excessBlobGas"))
246                .transpose()?,
247            parent_beacon_block_root: value.parent_beacon_block_root,
248            requests_hash: value.requests_hash,
249            block_access_list_hash: value.block_access_list_hash,
250            slot_number: value.slot_number.map(|v| quantity(v, "slotNumber")).transpose()?,
251        };
252        Ok(Self::new(header, value.hash))
253    }
254}
255
256/// A block in an Ethereum blockchain test.
257#[derive(Debug, PartialEq, Eq, Deserialize, Default)]
258#[serde(rename_all = "camelCase")]
259pub struct Block {
260    /// Block header.
261    pub block_header: Option<Header>,
262    /// RLP encoded block bytes
263    pub rlp: Bytes,
264    /// If the execution of the block should fail,
265    /// `expect_exception` is `Some`.
266    /// Its contents detail the reason for the failure.
267    pub expect_exception: Option<String>,
268    /// Transactions
269    pub transactions: Option<Vec<Transaction>>,
270    /// Uncle/ommer headers
271    pub uncle_headers: Option<Vec<Header>>,
272    /// Transaction Sequence
273    pub transaction_sequence: Option<Vec<TransactionSequence>>,
274    /// Withdrawals
275    pub withdrawals: Option<Withdrawals>,
276    /// The block's access list (EIP-7928), delivered beside the block. Kept as JSON so that a
277    /// malformed list is dropped instead of failing the whole file.
278    pub block_access_list: Option<serde_json::Value>,
279    /// The decoded fields of a block that is expected to be invalid.
280    #[serde(rename = "rlp_decoded")]
281    pub rlp_decoded: Option<RlpDecodedBlock>,
282}
283
284impl Block {
285    /// Returns the access list delivered with this block, if any.
286    pub fn access_list(&self) -> Option<&serde_json::Value> {
287        self.block_access_list
288            .as_ref()
289            .or_else(|| self.rlp_decoded.as_ref()?.block_access_list.as_ref())
290    }
291}
292
293/// The decoded fields of a block that is expected to be invalid.
294#[derive(Debug, PartialEq, Eq, Deserialize, Default)]
295#[serde(rename_all = "camelCase")]
296pub struct RlpDecodedBlock {
297    /// The block's access list (EIP-7928).
298    pub block_access_list: Option<serde_json::Value>,
299}
300
301/// Transaction sequence in block
302#[derive(Debug, PartialEq, Eq, Deserialize, Default)]
303#[serde(deny_unknown_fields)]
304#[serde(rename_all = "camelCase")]
305pub struct TransactionSequence {
306    exception: String,
307    raw_bytes: Bytes,
308    valid: String,
309}
310
311/// Ethereum blockchain test data state.
312#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Default)]
313pub struct State(BTreeMap<Address, Account>);
314
315impl State {
316    /// Return state as genesis state.
317    pub fn into_genesis_state(self) -> BTreeMap<Address, GenesisAccount> {
318        self.0
319            .into_iter()
320            .map(|(address, account)| {
321                let storage = account
322                    .storage
323                    .iter()
324                    .filter(|(_, v)| !v.is_zero())
325                    .map(|(k, v)| (B256::from(*k), B256::from(*v)))
326                    .collect();
327                let account = GenesisAccount {
328                    balance: account.balance,
329                    nonce: Some(account.nonce.try_into().unwrap()),
330                    code: Some(account.code).filter(|c| !c.is_empty()),
331                    storage: Some(storage),
332                    ..Default::default()
333                };
334                (address, account)
335            })
336            .collect::<BTreeMap<_, _>>()
337    }
338}
339
340impl Deref for State {
341    type Target = BTreeMap<Address, Account>;
342
343    fn deref(&self) -> &Self::Target {
344        &self.0
345    }
346}
347
348/// An account.
349#[derive(Debug, PartialEq, Eq, Deserialize, Clone, Default)]
350#[serde(deny_unknown_fields)]
351pub struct Account {
352    /// Balance.
353    pub balance: U256,
354    /// Code.
355    pub code: Bytes,
356    /// Nonce.
357    pub nonce: U256,
358    /// Storage.
359    pub storage: BTreeMap<U256, U256>,
360}
361
362impl Account {
363    /// Check that the account matches what is in the database.
364    ///
365    /// In case of a mismatch, `Err(Error::Assertion)` is returned.
366    pub fn assert_db(&self, address: Address, tx: &impl DbTx) -> Result<(), Error> {
367        let account =
368            tx.get_by_encoded_key::<tables::PlainAccountState>(&address)?.ok_or_else(|| {
369                Error::Assertion(format!(
370                    "Expected account ({address}) is missing from DB: {self:?}"
371                ))
372            })?;
373
374        assert_equal(self.balance, account.balance, "Balance does not match")?;
375        assert_equal(self.nonce.to(), account.nonce, "Nonce does not match")?;
376
377        if let Some(bytecode_hash) = account.bytecode_hash {
378            assert_equal(keccak256(&self.code), bytecode_hash, "Bytecode does not match")?;
379        } else {
380            assert_equal(
381                self.code.is_empty(),
382                true,
383                "Expected empty bytecode, got bytecode in db.",
384            )?;
385        }
386
387        let mut storage_cursor = tx.cursor_dup_read::<tables::PlainStorageState>()?;
388        for (slot, value) in &self.storage {
389            if let Some(entry) = storage_cursor.seek_by_key_subkey(address, B256::from(*slot))? {
390                if U256::from_be_bytes(entry.key.0) == *slot {
391                    assert_equal(
392                        *value,
393                        entry.value,
394                        &format!("Storage for slot {slot:?} does not match"),
395                    )?;
396                } else {
397                    return Err(Error::Assertion(format!(
398                        "Slot {slot:?} is missing from the database. Expected {value:?}"
399                    )))
400                }
401            } else {
402                return Err(Error::Assertion(format!(
403                    "Slot {slot:?} is missing from the database. Expected {value:?}"
404                )))
405            }
406        }
407
408        Ok(())
409    }
410}
411
412/// Fork specification.
413#[derive(Debug, PartialEq, Eq, PartialOrd, Hash, Ord, Clone, Copy, Deserialize)]
414pub enum ForkSpec {
415    /// Frontier
416    Frontier,
417    /// Frontier to Homestead
418    FrontierToHomesteadAt5,
419    /// Homestead
420    Homestead,
421    /// Homestead to DAO
422    HomesteadToDaoAt5,
423    /// Homestead to Tangerine
424    HomesteadToEIP150At5,
425    /// Tangerine
426    #[serde(alias = "TangerineWhistle")]
427    EIP150,
428    /// Spurious Dragon
429    #[serde(alias = "SpuriousDragon")]
430    EIP158, // EIP-161: State trie clearing
431    /// Spurious Dragon to Byzantium
432    EIP158ToByzantiumAt5,
433    /// Byzantium
434    Byzantium,
435    /// Byzantium to Constantinople
436    ByzantiumToConstantinopleAt5, // SKIPPED
437    /// Byzantium to Constantinople
438    ByzantiumToConstantinopleFixAt5,
439    /// Constantinople
440    Constantinople, // SKIPPED
441    /// Constantinople fix
442    ConstantinopleFix,
443    /// Istanbul
444    Istanbul,
445    /// Berlin
446    Berlin,
447    /// Berlin to London
448    BerlinToLondonAt5,
449    /// London
450    London,
451    /// Paris aka The Merge
452    #[serde(alias = "Paris")]
453    Merge,
454    /// Paris to Shanghai at time 15k
455    ParisToShanghaiAtTime15k,
456    /// Shanghai
457    Shanghai,
458    /// Shanghai to Cancun at time 15k
459    ShanghaiToCancunAtTime15k,
460    /// Merge EOF test
461    #[serde(alias = "Merge+3540+3670")]
462    MergeEOF,
463    /// After Merge Init Code test
464    #[serde(alias = "Merge+3860")]
465    MergeMeterInitCode,
466    /// After Merge plus new PUSH0 opcode
467    #[serde(alias = "Merge+3855")]
468    MergePush0,
469    /// Cancun
470    Cancun,
471    /// Cancun to Prague at time 15k
472    CancunToPragueAtTime15k,
473    /// Prague
474    Prague,
475    /// Osaka
476    Osaka,
477    /// Amsterdam.
478    Amsterdam,
479    /// Prague to Osaka at timestamp 15,000.
480    PragueToOsakaAtTime15k,
481    /// First mainnet blob-parameter-only update.
482    BPO1,
483    /// Second mainnet blob-parameter-only update.
484    BPO2,
485    /// Osaka to BPO1 at timestamp 15,000.
486    OsakaToBPO1AtTime15k,
487    /// BPO1 to BPO2 at timestamp 15,000.
488    BPO1ToBPO2AtTime15k,
489    /// BPO2 to Amsterdam at timestamp 15,000.
490    BPO2ToAmsterdamAtTime15k,
491    /// Amsterdam with the fixture's increased blob parameters.
492    AmsterdamBPOIncrease,
493    /// Amsterdam with the fixture's decreased blob parameters.
494    AmsterdamBPODecrease,
495    /// Amsterdam to increased blob parameters at timestamp 15,000.
496    AmsterdamToBPOIncreaseAtTime15k,
497    /// Amsterdam to decreased blob parameters at timestamp 15,000.
498    AmsterdamToBPODecreaseAtTime15k,
499}
500
501impl ForkSpec {
502    /// Converts this EF fork spec to a Reth [`ChainSpec`].
503    pub fn to_chain_spec(self) -> Arc<ChainSpec> {
504        static MAP: OnceLock<RwLock<HashMap<ForkSpec, Arc<ChainSpec>>>> = OnceLock::new();
505        let map = MAP.get_or_init(Default::default);
506        if let Some(r) = map.read().unwrap().get(&self) {
507            return r.clone();
508        }
509        map.write()
510            .unwrap()
511            .entry(self)
512            .or_insert_with(|| Arc::new(self.to_chain_spec_inner()))
513            .clone()
514    }
515
516    fn to_chain_spec_inner(self) -> ChainSpec {
517        self.build_chain_spec(self.chain_spec_builder())
518    }
519
520    /// Returns the chain spec of this fork spec on the given genesis.
521    pub fn chain_spec_on(self, genesis: Genesis) -> ChainSpec {
522        self.build_chain_spec(self.chain_spec_builder().genesis(genesis))
523    }
524
525    fn build_chain_spec(self, builder: ChainSpecBuilder) -> ChainSpec {
526        let mut spec = builder.build();
527
528        let scheduled = match self {
529            Self::BPO1 => vec![(0, BlobParams::bpo1())],
530            Self::BPO2 | Self::Amsterdam | Self::BPO2ToAmsterdamAtTime15k => {
531                vec![(0, BlobParams::bpo2())]
532            }
533            Self::OsakaToBPO1AtTime15k => vec![(15_000, BlobParams::bpo1())],
534            Self::BPO1ToBPO2AtTime15k => {
535                vec![(0, BlobParams::bpo1()), (15_000, BlobParams::bpo2())]
536            }
537            Self::AmsterdamBPOIncrease |
538            Self::AmsterdamBPODecrease |
539            Self::AmsterdamToBPOIncreaseAtTime15k |
540            Self::AmsterdamToBPODecreaseAtTime15k => vec![(0, BlobParams::bpo2())],
541            _ => Vec::new(),
542        };
543        spec.blob_params = spec.blob_params.with_scheduled(scheduled);
544        spec
545    }
546
547    /// Returns a builder of the chain spec with the hardforks of this fork spec, on the mainnet
548    /// genesis.
549    fn chain_spec_builder(self) -> ChainSpecBuilder {
550        let spec_builder = ChainSpecBuilder::mainnet().reset();
551
552        match self {
553            Self::Frontier => spec_builder.frontier_activated(),
554            Self::FrontierToHomesteadAt5 => spec_builder
555                .frontier_activated()
556                .with_fork(EthereumHardfork::Homestead, ForkCondition::Block(5)),
557            Self::Homestead => spec_builder.homestead_activated(),
558            Self::HomesteadToDaoAt5 => spec_builder
559                .homestead_activated()
560                .with_fork(EthereumHardfork::Dao, ForkCondition::Block(5)),
561            Self::HomesteadToEIP150At5 => spec_builder
562                .homestead_activated()
563                .with_fork(EthereumHardfork::Tangerine, ForkCondition::Block(5)),
564            Self::EIP150 => spec_builder.tangerine_whistle_activated(),
565            Self::EIP158 => spec_builder.spurious_dragon_activated(),
566            Self::EIP158ToByzantiumAt5 => spec_builder
567                .spurious_dragon_activated()
568                .with_fork(EthereumHardfork::Byzantium, ForkCondition::Block(5)),
569            Self::Byzantium => spec_builder.byzantium_activated(),
570            Self::ByzantiumToConstantinopleAt5 => spec_builder
571                .byzantium_activated()
572                .with_fork(EthereumHardfork::Constantinople, ForkCondition::Block(5)),
573            Self::ByzantiumToConstantinopleFixAt5 => spec_builder
574                .byzantium_activated()
575                .with_fork(EthereumHardfork::Petersburg, ForkCondition::Block(5)),
576            Self::Constantinople => spec_builder.constantinople_activated(),
577            Self::ConstantinopleFix => spec_builder.petersburg_activated(),
578            Self::Istanbul => spec_builder.istanbul_activated(),
579            Self::Berlin => spec_builder.berlin_activated(),
580            Self::BerlinToLondonAt5 => spec_builder
581                .berlin_activated()
582                .with_fork(EthereumHardfork::London, ForkCondition::Block(5)),
583            Self::London => spec_builder.london_activated(),
584            Self::Merge | Self::MergeEOF | Self::MergeMeterInitCode | Self::MergePush0 => {
585                spec_builder.paris_activated()
586            }
587            Self::ParisToShanghaiAtTime15k => spec_builder
588                .paris_activated()
589                .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(15_000)),
590            Self::Shanghai => spec_builder.shanghai_activated(),
591            Self::ShanghaiToCancunAtTime15k => spec_builder
592                .shanghai_activated()
593                .with_fork(EthereumHardfork::Cancun, ForkCondition::Timestamp(15_000)),
594            Self::Cancun => spec_builder.cancun_activated(),
595            Self::CancunToPragueAtTime15k => spec_builder
596                .cancun_activated()
597                .with_fork(EthereumHardfork::Prague, ForkCondition::Timestamp(15_000)),
598            Self::Prague => spec_builder.prague_activated(),
599            Self::Osaka => spec_builder.osaka_activated(),
600            Self::Amsterdam => spec_builder.amsterdam_activated(),
601            Self::PragueToOsakaAtTime15k => spec_builder
602                .prague_activated()
603                .with_fork(EthereumHardfork::Osaka, ForkCondition::Timestamp(15_000)),
604            Self::BPO1 | Self::OsakaToBPO1AtTime15k => spec_builder.osaka_activated().with_fork(
605                EthereumHardfork::Bpo1,
606                ForkCondition::Timestamp(if self == Self::BPO1 { 0 } else { 15_000 }),
607            ),
608            Self::BPO2 | Self::BPO1ToBPO2AtTime15k | Self::BPO2ToAmsterdamAtTime15k => {
609                let builder = spec_builder
610                    .osaka_activated()
611                    .with_fork(EthereumHardfork::Bpo1, ForkCondition::Timestamp(0))
612                    .with_fork(
613                        EthereumHardfork::Bpo2,
614                        ForkCondition::Timestamp(if self == Self::BPO1ToBPO2AtTime15k {
615                            15_000
616                        } else {
617                            0
618                        }),
619                    );
620                if self == Self::BPO2ToAmsterdamAtTime15k {
621                    builder.with_fork(EthereumHardfork::Amsterdam, ForkCondition::Timestamp(15_000))
622                } else {
623                    builder
624                }
625            }
626            Self::AmsterdamBPOIncrease |
627            Self::AmsterdamBPODecrease |
628            Self::AmsterdamToBPOIncreaseAtTime15k |
629            Self::AmsterdamToBPODecreaseAtTime15k => {
630                let timestamp =
631                    if matches!(self, Self::AmsterdamBPOIncrease | Self::AmsterdamBPODecrease) {
632                        0
633                    } else {
634                        15_000
635                    };
636                spec_builder
637                    .amsterdam_activated()
638                    .with_fork(EthereumHardfork::Bpo1, ForkCondition::Timestamp(0))
639                    .with_fork(EthereumHardfork::Bpo2, ForkCondition::Timestamp(0))
640                    .with_fork(EthereumHardfork::Bpo3, ForkCondition::Timestamp(timestamp))
641            }
642        }
643    }
644}
645
646/// Possible seal engines.
647#[derive(Debug, PartialEq, Eq, Default, Deserialize)]
648pub enum SealEngine {
649    /// No consensus checks.
650    #[default]
651    NoProof,
652}
653
654/// Ethereum blockchain test transaction data.
655#[derive(Debug, PartialEq, Eq, Deserialize)]
656#[serde(rename_all = "camelCase")]
657pub struct Transaction {
658    /// Transaction type
659    #[serde(rename = "type")]
660    pub transaction_type: Option<U256>,
661    /// Data.
662    pub data: Bytes,
663    /// Gas limit.
664    pub gas_limit: U256,
665    /// Gas price.
666    pub gas_price: Option<U256>,
667    /// Nonce.
668    pub nonce: U256,
669    /// Signature r part.
670    pub r: U256,
671    /// Signature s part.
672    pub s: U256,
673    /// Parity bit.
674    pub v: U256,
675    /// Transaction value.
676    pub value: U256,
677    /// Chain ID.
678    pub chain_id: Option<U256>,
679    /// Access list.
680    pub access_list: Option<AccessList>,
681    /// Max fee per gas.
682    pub max_fee_per_gas: Option<U256>,
683    /// Max priority fee per gas
684    pub max_priority_fee_per_gas: Option<U256>,
685    /// Transaction hash.
686    pub hash: Option<B256>,
687}
688
689/// Access list item
690#[derive(Debug, PartialEq, Eq, Deserialize, Clone)]
691#[serde(rename_all = "camelCase")]
692pub struct AccessListItem {
693    /// Account address
694    pub address: Address,
695    /// Storage key.
696    pub storage_keys: Vec<B256>,
697}
698
699/// Access list.
700pub type AccessList = Vec<AccessListItem>;
701
702// Fixture quantities need their own decoder because BlobParams' serde form uses JSON numbers.
703fn deserialize_blob_update_fraction<'de, D: serde::Deserializer<'de>>(
704    deserializer: D,
705) -> Result<U128, D::Error> {
706    let fraction = U128::deserialize(deserializer)?;
707    if fraction.is_zero() {
708        return Err(serde::de::Error::custom("blob base fee update fraction must be nonzero"))
709    }
710    Ok(fraction)
711}
712
713fn fixture_chain_spec(
714    header: &Header,
715    pre: &State,
716    network: ForkSpec,
717    config: &FixtureConfig,
718) -> Result<ChainSpec, FixtureConfigError> {
719    if matches!(network, ForkSpec::MergeEOF | ForkSpec::MergeMeterInitCode | ForkSpec::MergePush0) {
720        return Err(FixtureConfigError::UnsupportedFork(network))
721    }
722    let header = SealedHeader::try_from(header.clone())?;
723    let genesis = Genesis::default()
724        .with_nonce(u64::from_be_bytes(header.nonce.0))
725        .with_timestamp(header.timestamp)
726        .with_extra_data(header.extra_data.clone())
727        .with_gas_limit(header.gas_limit)
728        .with_difficulty(header.difficulty)
729        .with_mix_hash(header.mix_hash)
730        .with_coinbase(header.beneficiary)
731        .with_base_fee(header.base_fee_per_gas.map(u128::from))
732        .with_excess_blob_gas(header.excess_blob_gas)
733        .with_blob_gas_used(header.blob_gas_used)
734        .with_slot_number(header.slot_number)
735        .extend_accounts(pre.clone().into_genesis_state());
736    let mut spec = network.chain_spec_on(genesis);
737    if let Some(chain_id) = config.chain_id {
738        spec.chain = Chain::from_id(chain_id.to());
739    }
740    spec.blob_params.cancun =
741        fixture_blob_params(ForkSpec::Cancun, spec.blob_params.cancun, config)?;
742    spec.blob_params.prague =
743        fixture_blob_params(ForkSpec::Prague, spec.blob_params.prague, config)?;
744    spec.blob_params.osaka = fixture_blob_params(ForkSpec::Osaka, spec.blob_params.osaka, config)?;
745
746    let bpo3 = match network {
747        ForkSpec::AmsterdamBPOIncrease | ForkSpec::AmsterdamToBPOIncreaseAtTime15k => {
748            Some(ForkSpec::AmsterdamBPOIncrease)
749        }
750        ForkSpec::AmsterdamBPODecrease | ForkSpec::AmsterdamToBPODecreaseAtTime15k => {
751            Some(ForkSpec::AmsterdamBPODecrease)
752        }
753        _ => None,
754    };
755    // Apply forks in protocol order, including defaults. Later forks win when genesis activates
756    // multiple forks at the same timestamp, independently of ForkSpec's declaration order.
757    let forks = [
758        (ForkSpec::BPO1, EthereumHardfork::Bpo1, BlobParams::bpo1()),
759        (ForkSpec::BPO2, EthereumHardfork::Bpo2, BlobParams::bpo2()),
760        (ForkSpec::Amsterdam, EthereumHardfork::Amsterdam, BlobParams::bpo2()),
761    ];
762    let mut scheduled = BTreeMap::new();
763    for (fork, hardfork, defaults) in
764        forks.into_iter().chain(bpo3.map(|fork| (fork, EthereumHardfork::Bpo3, BlobParams::bpo2())))
765    {
766        if let Some(timestamp) = spec.hardforks.fork(hardfork).as_timestamp() {
767            scheduled.insert(timestamp, fixture_blob_params(fork, defaults, config)?);
768        }
769    }
770    spec.blob_params.scheduled = scheduled.into_iter().collect();
771    Ok(spec)
772}
773
774fn fixture_blob_params(
775    fork: ForkSpec,
776    mut params: BlobParams,
777    config: &FixtureConfig,
778) -> Result<BlobParams, FixtureConfigError> {
779    let Some(fixture) = config.blob_schedule.get(&fork) else { return Ok(params) };
780    params.target_blob_count = fixture.target.to();
781    params.max_blob_count = fixture.max.to();
782    params.update_fraction = fixture.base_fee_update_fraction.to();
783    if params.target_blob_count > params.max_blob_count ||
784        params.max_blob_count > u64::MAX / DATA_GAS_PER_BLOB ||
785        (params.blob_base_cost != 0 && params.max_blob_count == 0)
786    {
787        return Err(FixtureConfigError::BlobParams {
788            fork,
789            target: params.target_blob_count,
790            max: params.max_blob_count,
791        })
792    }
793    if matches!(fork, ForkSpec::Cancun | ForkSpec::Prague) {
794        params.max_blobs_per_tx = params.max_blob_count;
795    }
796    Ok(params)
797}
798
799#[cfg(test)]
800mod tests {
801    use super::*;
802    use alloy_consensus::{SignableTransaction, TxEip4844};
803    use alloy_eips::eip4844::VERSIONED_HASH_VERSION_KZG;
804    use alloy_primitives::Signature;
805    use reth_chainspec::EthChainSpec;
806    use reth_ethereum_primitives::{EthPrimitives, TransactionSigned};
807    use reth_evm::{database::StateProviderDatabase, ConfigureEvm, Evm, EvmEnv};
808    use reth_evm_ethereum::EthEvmConfig;
809    use reth_primitives_traits::SignedTransaction;
810    use reth_provider::{
811        test_utils::{ExtendedAccount, MockEthProvider},
812        StateProvider,
813    };
814
815    #[test]
816    fn amsterdam_uses_bpo2_blob_params_on_any_genesis() {
817        for spec in [
818            ForkSpec::Amsterdam.to_chain_spec(),
819            Arc::new(ForkSpec::Amsterdam.chain_spec_on(Genesis::default())),
820        ] {
821            assert_eq!(spec.blob_params_at_timestamp(0), Some(BlobParams::bpo2()));
822        }
823    }
824
825    #[test]
826    fn fixture_chain_id_and_blob_schedule_are_applied() {
827        let config: FixtureConfig = serde_json::from_value(serde_json::json!({
828            "chainid": "0x07",
829            "blobSchedule": {
830                "Amsterdam": {"target": "0x0e", "max": "0x15", "baseFeeUpdateFraction": "0xb24b3f"},
831                "AmsterdamBPOIncrease": {"target": "0x15", "max": "0x20", "baseFeeUpdateFraction": "0x10b70de"}
832            }
833        })).unwrap();
834        let spec = fixture_chain_spec(
835            &Header::default(),
836            &State::default(),
837            ForkSpec::AmsterdamToBPOIncreaseAtTime15k,
838            &config,
839        )
840        .unwrap();
841        assert_eq!(spec.chain.id(), 7);
842        assert_eq!(spec.blob_params_at_timestamp(14_999).unwrap().target_blob_count, 14);
843        assert_eq!(spec.blob_params_at_timestamp(15_000).unwrap().target_blob_count, 21);
844        assert_eq!(spec.blob_params_at_timestamp(15_000).unwrap().max_blob_count, 32);
845    }
846
847    #[test]
848    fn bpo_transition_uses_the_fixture_activation_time() {
849        let spec = ForkSpec::BPO1ToBPO2AtTime15k.chain_spec_on(Genesis::default());
850        assert_eq!(spec.blob_params_at_timestamp(14_999), Some(BlobParams::bpo1()));
851        assert_eq!(spec.blob_params_at_timestamp(15_000), Some(BlobParams::bpo2()));
852    }
853
854    #[test]
855    fn fixture_aliases_and_zero_blob_fraction() {
856        assert_eq!(
857            serde_json::from_str::<ForkSpec>("\"SpuriousDragon\"").unwrap(),
858            ForkSpec::EIP158
859        );
860        assert_eq!(
861            serde_json::from_str::<ForkSpec>("\"TangerineWhistle\"").unwrap(),
862            ForkSpec::EIP150
863        );
864        let error = serde_json::from_value::<FixtureConfig>(serde_json::json!({
865            "blobSchedule": {"BPO1": {"target": "0xa", "max": "0xf", "baseFeeUpdateFraction": "0x0"}}
866        })).unwrap_err();
867        assert_eq!(error.to_string(), "blob base fee update fraction must be nonzero");
868    }
869
870    #[test]
871    fn fixture_blob_maximum_applies_during_transaction_execution() {
872        for (fork, max, count) in [(ForkSpec::Cancun, 9, 7), (ForkSpec::Prague, 12, 10)] {
873            let config = FixtureConfig {
874                blob_schedule: BTreeMap::from([(
875                    fork,
876                    FixtureBlobParams {
877                        target: U64::from(3),
878                        max: U64::from(max),
879                        base_fee_update_fraction: U128::from(3_338_477),
880                    },
881                )]),
882                ..Default::default()
883            };
884            let spec =
885                fixture_chain_spec(&Header::default(), &State::default(), fork, &config).unwrap();
886            let evm_config = EthEvmConfig::new(Arc::new(spec));
887            let env = evm_config
888                .evm_env(&RethHeader {
889                    gas_limit: 30_000_000,
890                    base_fee_per_gas: Some(0),
891                    excess_blob_gas: Some(0),
892                    ..Default::default()
893                })
894                .unwrap();
895            let sender = Address::with_last_byte(0x42);
896            let provider = MockEthProvider::<EthPrimitives>::default();
897            provider.add_account(sender, ExtendedAccount::new(0, U256::MAX));
898            let tx = TransactionSigned::Eip4844(
899                TxEip4844 {
900                    chain_id: 1,
901                    gas_limit: 21_000,
902                    max_fee_per_blob_gas: 1,
903                    blob_versioned_hashes: vec![
904                        B256::repeat_byte(VERSIONED_HASH_VERSION_KZG);
905                        count
906                    ],
907                    ..Default::default()
908                }
909                .into_signed(Signature::test_signature()),
910            );
911            let tx = evm_config.tx_env(tx.with_signer(sender));
912            let mut evm = evm_config
913                .evm_with_env(StateProviderDatabase(provider.into_evm_state_provider()), env);
914            evm.transact_and_discard(&tx, |_| {}).unwrap();
915        }
916        let config = FixtureConfig {
917            blob_schedule: BTreeMap::from([(
918                ForkSpec::Osaka,
919                FixtureBlobParams {
920                    target: U64::from(6),
921                    max: U64::from(12),
922                    base_fee_update_fraction: U128::from(5_007_716),
923                },
924            )]),
925            ..Default::default()
926        };
927        let spec =
928            fixture_chain_spec(&Header::default(), &State::default(), ForkSpec::Osaka, &config)
929                .unwrap();
930        let env = EthEvmConfig::new(Arc::new(spec)).evm_env(&RethHeader::default()).unwrap();
931        assert_eq!(
932            env.version().max_blobs_per_tx,
933            usize::try_from(BlobParams::osaka().max_blobs_per_tx).unwrap()
934        );
935    }
936
937    #[test]
938    fn equal_timestamp_blob_overrides_follow_fork_order() {
939        let mut config = FixtureConfig {
940            blob_schedule: BTreeMap::from([
941                (
942                    ForkSpec::BPO2,
943                    FixtureBlobParams {
944                        target: U64::from(14),
945                        max: U64::from(21),
946                        base_fee_update_fraction: U128::from(5_007_716),
947                    },
948                ),
949                (
950                    ForkSpec::Amsterdam,
951                    FixtureBlobParams {
952                        target: U64::from(16),
953                        max: U64::from(24),
954                        base_fee_update_fraction: U128::from(5_007_716),
955                    },
956                ),
957            ]),
958            ..Default::default()
959        };
960        for fork in
961            [ForkSpec::AmsterdamToBPOIncreaseAtTime15k, ForkSpec::AmsterdamToBPODecreaseAtTime15k]
962        {
963            let spec =
964                fixture_chain_spec(&Header::default(), &State::default(), fork, &config).unwrap();
965            let params = spec.blob_params_at_timestamp(14_999).unwrap();
966            assert_eq!((params.target_blob_count, params.max_blob_count), (16, 24));
967        }
968        config.blob_schedule.remove(&ForkSpec::Amsterdam);
969        let spec = fixture_chain_spec(
970            &Header::default(),
971            &State::default(),
972            ForkSpec::AmsterdamToBPOIncreaseAtTime15k,
973            &config,
974        )
975        .unwrap();
976        assert_eq!(spec.blob_params_at_timestamp(0), Some(BlobParams::bpo2()));
977    }
978
979    #[test]
980    fn experimental_merge_forks_are_not_executed_as_paris() {
981        for fork in [ForkSpec::MergeEOF, ForkSpec::MergeMeterInitCode, ForkSpec::MergePush0] {
982            let error = fixture_chain_spec(
983                &Header::default(),
984                &State::default(),
985                fork,
986                &FixtureConfig::default(),
987            )
988            .unwrap_err();
989            assert!(matches!(error, FixtureConfigError::UnsupportedFork(actual) if actual == fork));
990        }
991    }
992
993    #[test]
994    fn genesis_quantities_return_errors_instead_of_panicking() {
995        for field in [
996            "gasLimit",
997            "gasUsed",
998            "number",
999            "timestamp",
1000            "baseFeePerGas",
1001            "blobGasUsed",
1002            "excessBlobGas",
1003            "slotNumber",
1004        ] {
1005            let mut header = Header::default();
1006            let value = U256::from(u64::MAX) + U256::ONE;
1007            match field {
1008                "gasLimit" => header.gas_limit = value,
1009                "gasUsed" => header.gas_used = value,
1010                "number" => header.number = value,
1011                "timestamp" => header.timestamp = value,
1012                "baseFeePerGas" => header.base_fee_per_gas = Some(value),
1013                "blobGasUsed" => header.blob_gas_used = Some(value),
1014                "excessBlobGas" => header.excess_blob_gas = Some(value),
1015                "slotNumber" => header.slot_number = Some(value),
1016                _ => unreachable!(),
1017            }
1018            let error = fixture_chain_spec(
1019                &header,
1020                &State::default(),
1021                ForkSpec::Merge,
1022                &FixtureConfig::default(),
1023            )
1024            .unwrap_err();
1025            assert!(
1026                matches!(error, FixtureConfigError::HeaderQuantity {field: actual, ..} if actual == field)
1027            );
1028        }
1029    }
1030
1031    #[test]
1032    fn unsafe_blob_schedules_return_configuration_errors() {
1033        for (target, max) in [(0, 0), (2, 1), (1, u64::MAX)] {
1034            let config = FixtureConfig {
1035                blob_schedule: BTreeMap::from([(
1036                    ForkSpec::Osaka,
1037                    FixtureBlobParams {
1038                        target: U64::from(target),
1039                        max: U64::from(max),
1040                        base_fee_update_fraction: U128::from(5_007_716),
1041                    },
1042                )]),
1043                ..Default::default()
1044            };
1045            let error =
1046                fixture_chain_spec(&Header::default(), &State::default(), ForkSpec::Osaka, &config)
1047                    .unwrap_err();
1048            assert!(
1049                matches!(error, FixtureConfigError::BlobParams {fork: ForkSpec::Osaka, target: actual_target, max: actual_max} if actual_target == target && actual_max == max)
1050            );
1051        }
1052    }
1053
1054    #[test]
1055    fn header_deserialize() {
1056        let test = r#"{
1057            "baseFeePerGas" : "0x0a",
1058            "bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
1059            "coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
1060            "difficulty" : "0x020000",
1061            "extraData" : "0x00",
1062            "gasLimit" : "0x10000000000000",
1063            "gasUsed" : "0x10000000000000",
1064            "hash" : "0x7ebfee2a2c785fef181b8ffd92d4a48a0660ec000f465f309757e3f092d13882",
1065            "mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
1066            "nonce" : "0x0000000000000000",
1067            "number" : "0x01",
1068            "parentHash" : "0xa8f2eb2ea9dccbf725801eef5a31ce59bada431e888dfd5501677cc4365dc3be",
1069            "receiptTrie" : "0xbdd943f5c62ae0299324244a0f65524337ada9817e18e1764631cc1424f3a293",
1070            "stateRoot" : "0xc9c6306ee3e5acbaabe8e2fa28a10c12e27bad1d1aacc271665149f70519f8b0",
1071            "timestamp" : "0x03e8",
1072            "transactionsTrie" : "0xf5893b055ca05e4f14d1792745586a1376e218180bd56bd96b2b024e1dc78300",
1073            "uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
1074        }"#;
1075        let res = serde_json::from_str::<Header>(test);
1076        assert!(res.is_ok(), "Failed to deserialize Header with error: {res:?}");
1077    }
1078
1079    #[test]
1080    fn block_access_list_deserialize() {
1081        let valid = r#"{"rlp": "0xc0", "blockAccessList": [{"address": "0x01"}]}"#;
1082        let block = serde_json::from_str::<Block>(valid).unwrap();
1083        assert_eq!(block.access_list(), Some(&serde_json::json!([{"address": "0x01"}])));
1084
1085        let invalid = r#"{
1086            "rlp": "0xc0",
1087            "expectException": "BlockException.INVALID_BLOCK_ACCESS_LIST",
1088            "rlp_decoded": {"blockAccessList": []}
1089        }"#;
1090        let block = serde_json::from_str::<Block>(invalid).unwrap();
1091        assert_eq!(block.access_list(), Some(&serde_json::json!([])));
1092    }
1093
1094    #[test]
1095    fn transaction_deserialize() {
1096        let test = r#"[
1097            {
1098                "accessList" : [
1099                ],
1100                "chainId" : "0x01",
1101                "data" : "0x693c61390000000000000000000000000000000000000000000000000000000000000000",
1102                "gasLimit" : "0x10000000000000",
1103                "maxFeePerGas" : "0x07d0",
1104                "maxPriorityFeePerGas" : "0x00",
1105                "nonce" : "0x01",
1106                "r" : "0x5fecc3972a35c9e341b41b0c269d9a7325e13269fb01c2f64cbce1046b3441c8",
1107                "s" : "0x7d4d0eda0e4ebd53c5d0b6fc35c600b317f8fa873b3963ab623ec9cec7d969bd",
1108                "sender" : "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
1109                "to" : "0xcccccccccccccccccccccccccccccccccccccccc",
1110                "type" : "0x02",
1111                "v" : "0x01",
1112                "value" : "0x00"
1113            }
1114        ]"#;
1115
1116        let res = serde_json::from_str::<Vec<Transaction>>(test);
1117        assert!(res.is_ok(), "Failed to deserialize transaction with error: {res:?}");
1118    }
1119}