From 2aa3dd0fd8b02b067eb39631bc30de47c434f0f0 Mon Sep 17 00:00:00 2001 From: Arsenii Kulikov Date: Sat, 28 Sep 2024 16:06:52 +0300 Subject: [PATCH] feat: use `OpChainSpec` in `OptimismNode` and its components (#11304) --- Cargo.lock | 2 + crates/chainspec/src/api.rs | 9 ++ crates/chainspec/src/spec.rs | 4 +- crates/cli/commands/src/common.rs | 8 +- crates/cli/commands/src/db/checksum.rs | 9 +- crates/cli/commands/src/db/get.rs | 14 +-- crates/cli/commands/src/db/list.rs | 4 +- crates/cli/commands/src/db/mod.rs | 6 +- crates/cli/commands/src/db/stats.rs | 11 +-- crates/cli/commands/src/dump_genesis.rs | 4 +- crates/cli/commands/src/import.rs | 12 +-- crates/cli/commands/src/init_cmd.rs | 4 +- crates/cli/commands/src/init_state.rs | 10 +- crates/cli/commands/src/node.rs | 10 +- crates/cli/commands/src/p2p/mod.rs | 8 +- crates/cli/commands/src/prune.rs | 4 +- crates/cli/commands/src/recover/mod.rs | 4 +- .../cli/commands/src/recover/storage_tries.rs | 4 +- crates/cli/commands/src/stage/drop.rs | 6 +- .../cli/commands/src/stage/dump/execution.rs | 12 ++- .../src/stage/dump/hashing_account.rs | 14 +-- .../src/stage/dump/hashing_storage.rs | 14 +-- crates/cli/commands/src/stage/dump/merkle.rs | 14 +-- crates/cli/commands/src/stage/dump/mod.rs | 12 ++- crates/cli/commands/src/stage/mod.rs | 6 +- crates/cli/commands/src/stage/run.rs | 8 +- crates/cli/commands/src/stage/unwind.rs | 10 +- crates/e2e-test-utils/src/lib.rs | 9 +- crates/e2e-test-utils/src/node.rs | 4 +- crates/e2e-test-utils/src/rpc.rs | 4 +- .../engine/invalid-block-hooks/src/witness.rs | 14 ++- crates/node/builder/src/builder/mod.rs | 4 +- crates/node/builder/src/launch/common.rs | 6 +- crates/node/builder/src/launch/engine.rs | 15 ++- crates/node/core/src/args/network.rs | 9 +- crates/node/core/src/node_config.rs | 35 ++++--- crates/optimism/chainspec/Cargo.toml | 2 + crates/optimism/chainspec/src/lib.rs | 94 ++++++++++++++++++- crates/optimism/cli/src/chainspec.rs | 5 +- .../cli/src/commands/build_pipeline.rs | 4 +- crates/optimism/cli/src/commands/import.rs | 4 +- .../cli/src/commands/import_receipts.rs | 14 +-- .../cli/src/commands/init_state/mod.rs | 4 +- crates/optimism/cli/src/commands/mod.rs | 7 +- crates/optimism/cli/src/lib.rs | 16 ++-- crates/optimism/consensus/Cargo.toml | 1 + crates/optimism/consensus/src/lib.rs | 12 +-- crates/optimism/evm/src/execute.rs | 27 +++--- crates/optimism/evm/src/l1.rs | 3 +- crates/optimism/node/src/engine.rs | 5 +- crates/optimism/node/src/node.rs | 61 +++++------- crates/optimism/node/tests/e2e/utils.rs | 6 +- crates/optimism/node/tests/it/builder.rs | 5 +- crates/optimism/payload/Cargo.toml | 1 + crates/optimism/payload/src/builder.rs | 7 +- crates/optimism/payload/src/payload.rs | 7 +- crates/optimism/rpc/Cargo.toml | 1 + crates/optimism/rpc/src/eth/block.rs | 5 +- crates/optimism/rpc/src/eth/call.rs | 4 +- crates/optimism/rpc/src/eth/mod.rs | 4 +- crates/optimism/rpc/src/eth/receipt.rs | 5 +- crates/revm/src/state_change.rs | 5 +- crates/storage/db-common/src/db_tool/mod.rs | 7 +- crates/storage/db-common/src/init.rs | 8 +- crates/transaction-pool/src/maintain.rs | 16 +--- 65 files changed, 379 insertions(+), 284 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 81d8e8f9d4c5..d402a96b58c6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7970,6 +7970,7 @@ dependencies = [ "op-alloy-rpc-types", "reth-chainspec", "reth-ethereum-forks", + "reth-network-peers", "reth-optimism-forks", "reth-primitives-traits", "serde_json", @@ -8133,6 +8134,7 @@ dependencies = [ "reth-chainspec", "reth-evm", "reth-execution-types", + "reth-optimism-chainspec", "reth-optimism-consensus", "reth-optimism-evm", "reth-optimism-forks", diff --git a/crates/chainspec/src/api.rs b/crates/chainspec/src/api.rs index fb9744a53164..fb64e08ae1ef 100644 --- a/crates/chainspec/src/api.rs +++ b/crates/chainspec/src/api.rs @@ -1,9 +1,11 @@ use crate::{ChainSpec, DepositContract}; +use alloc::vec::Vec; use alloy_chains::Chain; use alloy_eips::eip1559::BaseFeeParams; use alloy_genesis::Genesis; use alloy_primitives::B256; use core::fmt::{Debug, Display}; +use reth_network_peers::NodeRecord; use reth_primitives_traits::Header; /// Trait representing type configuring a chain spec. @@ -41,6 +43,9 @@ pub trait EthChainSpec: Send + Sync + Unpin + Debug { /// The block gas limit. fn max_gas_limit(&self) -> u64; + + /// The bootnodes for the chain, if any. + fn bootnodes(&self) -> Option>; } impl EthChainSpec for ChainSpec { @@ -83,4 +88,8 @@ impl EthChainSpec for ChainSpec { fn max_gas_limit(&self) -> u64 { self.max_gas_limit } + + fn bootnodes(&self) -> Option> { + self.bootnodes() + } } diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index c62ed4f67223..c830e5117196 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -825,13 +825,13 @@ fn into_optimism_chain_spec(genesis: Genesis) -> ChainSpec { } } -/// A trait for reading the current [`ChainSpec`]. +/// A trait for reading the current chainspec. #[auto_impl::auto_impl(&, Arc)] pub trait ChainSpecProvider: Send + Sync { /// The chain spec type. type ChainSpec: EthChainSpec + 'static; - /// Get an [`Arc`] to the [`ChainSpec`]. + /// Get an [`Arc`] to the chainspec. fn chain_spec(&self) -> Arc; } diff --git a/crates/cli/commands/src/common.rs b/crates/cli/commands/src/common.rs index 3b4a00b2d2b2..956a63a5aa0e 100644 --- a/crates/cli/commands/src/common.rs +++ b/crates/cli/commands/src/common.rs @@ -3,7 +3,7 @@ use alloy_primitives::B256; use clap::Parser; use reth_beacon_consensus::EthBeaconConsensus; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_config::{config::EtlConfig, Config}; use reth_db::{init_db, open_db_read_only, DatabaseEnv}; @@ -50,14 +50,14 @@ pub struct EnvironmentArgs { pub db: DatabaseArgs, } -impl> EnvironmentArgs { +impl> EnvironmentArgs { /// Initializes environment according to [`AccessRights`] and returns an instance of /// [`Environment`]. pub fn init>( &self, access: AccessRights, ) -> eyre::Result> { - let data_dir = self.datadir.clone().resolve_datadir(self.chain.chain); + let data_dir = self.datadir.clone().resolve_datadir(self.chain.chain()); let db_path = data_dir.db(); let sf_path = data_dir.static_files(); @@ -93,7 +93,7 @@ impl> EnvironmentArgs { let provider_factory = self.create_provider_factory(&config, db, sfp)?; if access.is_read_write() { - debug!(target: "reth::cli", chain=%self.chain.chain, genesis=?self.chain.genesis_hash(), "Initializing genesis"); + debug!(target: "reth::cli", chain=%self.chain.chain(), genesis=?self.chain.genesis_hash(), "Initializing genesis"); init_genesis(&provider_factory)?; } diff --git a/crates/cli/commands/src/db/checksum.rs b/crates/cli/commands/src/db/checksum.rs index 7aeed6dfe141..60ec09c9606e 100644 --- a/crates/cli/commands/src/db/checksum.rs +++ b/crates/cli/commands/src/db/checksum.rs @@ -1,11 +1,12 @@ use crate::db::get::{maybe_json_value_parser, table_key}; use ahash::RandomState; use clap::Parser; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthereumHardforks; use reth_db::{DatabaseEnv, RawKey, RawTable, RawValue, TableViewer, Tables}; use reth_db_api::{cursor::DbCursorRO, table::Table, transaction::DbTx}; use reth_db_common::DbTool; use reth_node_builder::{NodeTypesWithDB, NodeTypesWithDBAdapter, NodeTypesWithEngine}; +use reth_provider::providers::ProviderNodeTypes; use std::{ hash::{BuildHasher, Hasher}, sync::Arc, @@ -35,7 +36,7 @@ pub struct Command { impl Command { /// Execute `db checksum` command - pub fn execute>( + pub fn execute>( self, tool: &DbTool>>, ) -> eyre::Result<()> { @@ -63,9 +64,7 @@ impl ChecksumViewer<'_, N> { } } -impl> TableViewer<(u64, Duration)> - for ChecksumViewer<'_, N> -{ +impl TableViewer<(u64, Duration)> for ChecksumViewer<'_, N> { type Error = eyre::Report; fn view(&self) -> Result<(u64, Duration), Self::Error> { diff --git a/crates/cli/commands/src/db/get.rs b/crates/cli/commands/src/db/get.rs index 2734e1da1854..5b794feeada2 100644 --- a/crates/cli/commands/src/db/get.rs +++ b/crates/cli/commands/src/db/get.rs @@ -1,6 +1,5 @@ -use alloy_primitives::BlockHash; +use alloy_primitives::{hex, BlockHash}; use clap::Parser; -use reth_chainspec::ChainSpec; use reth_db::{ static_file::{ColumnSelectorOne, ColumnSelectorTwo, HeaderMask, ReceiptMask, TransactionMask}, tables, RawKey, RawTable, Receipts, TableViewer, Transactions, @@ -8,8 +7,8 @@ use reth_db::{ use reth_db_api::table::{Decompress, DupSort, Table}; use reth_db_common::DbTool; use reth_node_builder::NodeTypesWithDB; -use reth_primitives::{hex, Header}; -use reth_provider::StaticFileProviderFactory; +use reth_primitives::Header; +use reth_provider::{providers::ProviderNodeTypes, StaticFileProviderFactory}; use reth_static_file_types::StaticFileSegment; use tracing::error; @@ -54,10 +53,7 @@ enum Subcommand { impl Command { /// Execute `db get` command - pub fn execute>( - self, - tool: &DbTool, - ) -> eyre::Result<()> { + pub fn execute(self, tool: &DbTool) -> eyre::Result<()> { match self.subcommand { Subcommand::Mdbx { table, key, subkey, raw } => { table.view(&GetValueViewer { tool, key, subkey, raw })? @@ -148,7 +144,7 @@ struct GetValueViewer<'a, N: NodeTypesWithDB> { raw: bool, } -impl> TableViewer<()> for GetValueViewer<'_, N> { +impl TableViewer<()> for GetValueViewer<'_, N> { type Error = eyre::Report; fn view(&self) -> Result<(), Self::Error> { diff --git a/crates/cli/commands/src/db/list.rs b/crates/cli/commands/src/db/list.rs index 3dfa4f388486..63eca1d8683b 100644 --- a/crates/cli/commands/src/db/list.rs +++ b/crates/cli/commands/src/db/list.rs @@ -2,7 +2,7 @@ use super::tui::DbListTUI; use alloy_primitives::hex; use clap::Parser; use eyre::WrapErr; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthereumHardforks; use reth_db::{DatabaseEnv, RawValue, TableViewer, Tables}; use reth_db_api::{database::Database, table::Table}; use reth_db_common::{DbTool, ListFilter}; @@ -53,7 +53,7 @@ pub struct Command { impl Command { /// Execute `db list` command - pub fn execute>( + pub fn execute>( self, tool: &DbTool>>, ) -> eyre::Result<()> { diff --git a/crates/cli/commands/src/db/mod.rs b/crates/cli/commands/src/db/mod.rs index 6d48256101fb..be1b117d9e8c 100644 --- a/crates/cli/commands/src/db/mod.rs +++ b/crates/cli/commands/src/db/mod.rs @@ -1,6 +1,6 @@ use crate::common::{AccessRights, Environment, EnvironmentArgs}; use clap::{Parser, Subcommand}; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_db::version::{get_db_version, DatabaseVersionError, DB_VERSION}; use reth_db_common::DbTool; @@ -63,12 +63,12 @@ macro_rules! db_ro_exec { }; } -impl> Command { +impl> Command { /// Execute `db` command pub async fn execute>( self, ) -> eyre::Result<()> { - let data_dir = self.env.datadir.clone().resolve_datadir(self.env.chain.chain); + let data_dir = self.env.datadir.clone().resolve_datadir(self.env.chain.chain()); let db_path = data_dir.db(); let static_files_path = data_dir.static_files(); diff --git a/crates/cli/commands/src/db/stats.rs b/crates/cli/commands/src/db/stats.rs index 76fb69b4a956..ac36b866b07a 100644 --- a/crates/cli/commands/src/db/stats.rs +++ b/crates/cli/commands/src/db/stats.rs @@ -4,14 +4,14 @@ use comfy_table::{Cell, Row, Table as ComfyTable}; use eyre::WrapErr; use human_bytes::human_bytes; use itertools::Itertools; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthereumHardforks; use reth_db::{mdbx, static_file::iter_static_files, DatabaseEnv, TableViewer, Tables}; use reth_db_api::database::Database; use reth_db_common::DbTool; use reth_fs_util as fs; use reth_node_builder::{NodeTypesWithDB, NodeTypesWithDBAdapter, NodeTypesWithEngine}; use reth_node_core::dirs::{ChainPath, DataDirPath}; -use reth_provider::providers::StaticFileProvider; +use reth_provider::providers::{ProviderNodeTypes, StaticFileProvider}; use reth_static_file_types::SegmentRangeInclusive; use std::{sync::Arc, time::Duration}; @@ -38,7 +38,7 @@ pub struct Command { impl Command { /// Execute `db stats` command - pub fn execute>( + pub fn execute>( self, data_dir: ChainPath, tool: &DbTool>>, @@ -325,10 +325,7 @@ impl Command { Ok(table) } - fn checksum_report>( - &self, - tool: &DbTool, - ) -> eyre::Result { + fn checksum_report(&self, tool: &DbTool) -> eyre::Result { let mut table = ComfyTable::new(); table.load_preset(comfy_table::presets::ASCII_MARKDOWN); table.set_header(vec![Cell::new("Table"), Cell::new("Checksum"), Cell::new("Elapsed")]); diff --git a/crates/cli/commands/src/dump_genesis.rs b/crates/cli/commands/src/dump_genesis.rs index 30d3bc9651df..44c0b660fc5d 100644 --- a/crates/cli/commands/src/dump_genesis.rs +++ b/crates/cli/commands/src/dump_genesis.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use clap::Parser; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthChainSpec; use reth_cli::chainspec::ChainSpecParser; /// Dumps genesis block JSON configuration to stdout @@ -21,7 +21,7 @@ pub struct DumpGenesisCommand { chain: Arc, } -impl> DumpGenesisCommand { +impl> DumpGenesisCommand { /// Execute the `dump-genesis` command pub async fn execute(self) -> eyre::Result<()> { println!("{}", serde_json::to_string_pretty(self.chain.genesis())?); diff --git a/crates/cli/commands/src/import.rs b/crates/cli/commands/src/import.rs index 5b35e8aa1c7b..15407f29d788 100644 --- a/crates/cli/commands/src/import.rs +++ b/crates/cli/commands/src/import.rs @@ -4,7 +4,7 @@ use alloy_primitives::B256; use clap::Parser; use futures::{Stream, StreamExt}; use reth_beacon_consensus::EthBeaconConsensus; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_config::Config; use reth_consensus::Consensus; @@ -20,12 +20,12 @@ use reth_network_p2p::{ bodies::downloader::BodyDownloader, headers::downloader::{HeaderDownloader, SyncTarget}, }; -use reth_node_builder::{NodeTypesWithDB, NodeTypesWithEngine}; +use reth_node_builder::NodeTypesWithEngine; use reth_node_core::version::SHORT_VERSION; use reth_node_events::node::NodeEvent; use reth_provider::{ - BlockNumReader, ChainSpecProvider, HeaderProvider, ProviderError, ProviderFactory, - StageCheckpointReader, + providers::ProviderNodeTypes, BlockNumReader, ChainSpecProvider, HeaderProvider, ProviderError, + ProviderFactory, StageCheckpointReader, }; use reth_prune::PruneModes; use reth_stages::{prelude::*, Pipeline, StageId, StageSet}; @@ -56,7 +56,7 @@ pub struct ImportCommand { path: PathBuf, } -impl> ImportCommand { +impl> ImportCommand { /// Execute `import` command pub async fn execute(self, executor: F) -> eyre::Result<()> where @@ -168,7 +168,7 @@ pub fn build_import_pipeline( executor: E, ) -> eyre::Result<(Pipeline, impl Stream)> where - N: NodeTypesWithDB, + N: ProviderNodeTypes, C: Consensus + 'static, E: BlockExecutorProvider, { diff --git a/crates/cli/commands/src/init_cmd.rs b/crates/cli/commands/src/init_cmd.rs index 63a8827eb24c..5fde9ac0d0ba 100644 --- a/crates/cli/commands/src/init_cmd.rs +++ b/crates/cli/commands/src/init_cmd.rs @@ -2,7 +2,7 @@ use crate::common::{AccessRights, Environment, EnvironmentArgs}; use clap::Parser; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_node_builder::NodeTypesWithEngine; use reth_provider::BlockHashReader; @@ -15,7 +15,7 @@ pub struct InitCommand { env: EnvironmentArgs, } -impl> InitCommand { +impl> InitCommand { /// Execute the `init` command pub async fn execute>( self, diff --git a/crates/cli/commands/src/init_state.rs b/crates/cli/commands/src/init_state.rs index 67955d714aff..16e99f8fe976 100644 --- a/crates/cli/commands/src/init_state.rs +++ b/crates/cli/commands/src/init_state.rs @@ -3,12 +3,12 @@ use crate::common::{AccessRights, Environment, EnvironmentArgs}; use alloy_primitives::B256; use clap::Parser; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_config::config::EtlConfig; use reth_db_common::init::init_from_state_dump; -use reth_node_builder::{NodeTypesWithDB, NodeTypesWithEngine}; -use reth_provider::ProviderFactory; +use reth_node_builder::NodeTypesWithEngine; +use reth_provider::{providers::ProviderNodeTypes, ProviderFactory}; use std::{fs::File, io::BufReader, path::PathBuf}; use tracing::info; @@ -40,7 +40,7 @@ pub struct InitStateCommand { pub state: PathBuf, } -impl> InitStateCommand { +impl> InitStateCommand { /// Execute the `init` command pub async fn execute>( self, @@ -59,7 +59,7 @@ impl> InitStateCommand { } /// Initialize chain with state at specific block, from a file with state dump. -pub fn init_at_state>( +pub fn init_at_state( state_dump_path: PathBuf, factory: ProviderFactory, etl_config: EtlConfig, diff --git a/crates/cli/commands/src/node.rs b/crates/cli/commands/src/node.rs index ae85e0acf73d..abdb00dff2cb 100644 --- a/crates/cli/commands/src/node.rs +++ b/crates/cli/commands/src/node.rs @@ -1,7 +1,7 @@ //! Main node command for launching a node use clap::{value_parser, Args, Parser}; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_cli_runner::CliContext; use reth_cli_util::parse_socket_address; @@ -112,7 +112,7 @@ pub struct NodeCommand< pub ext: Ext, } -impl> NodeCommand { +impl NodeCommand { /// Parsers only the default CLI arguments pub fn parse_args() -> Self { Self::parse() @@ -128,7 +128,11 @@ impl> NodeCommand { } } -impl, Ext: clap::Args + fmt::Debug> NodeCommand { +impl< + C: ChainSpecParser, + Ext: clap::Args + fmt::Debug, + > NodeCommand +{ /// Launches the node /// /// This transforms the node command into a node config and launches the node using the given diff --git a/crates/cli/commands/src/p2p/mod.rs b/crates/cli/commands/src/p2p/mod.rs index 6d40e414dd33..f36d78bd1646 100644 --- a/crates/cli/commands/src/p2p/mod.rs +++ b/crates/cli/commands/src/p2p/mod.rs @@ -5,7 +5,7 @@ use std::{path::PathBuf, sync::Arc}; use alloy_eips::BlockHashOrNumber; use backon::{ConstantBuilder, Retryable}; use clap::{Parser, Subcommand}; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_cli_util::{get_secret_key, hash_or_num_value_parser}; use reth_config::Config; @@ -73,10 +73,10 @@ pub enum Subcommands { Rlpx(rlpx::Command), } -impl> Command { +impl> Command { /// Execute `p2p` command pub async fn execute(self) -> eyre::Result<()> { - let data_dir = self.datadir.clone().resolve_datadir(self.chain.chain); + let data_dir = self.datadir.clone().resolve_datadir(self.chain.chain()); let config_path = self.config.clone().unwrap_or_else(|| data_dir.config()); // Load configuration @@ -100,7 +100,7 @@ impl> Command { let net = NetworkConfigBuilder::new(p2p_secret_key) .peer_config(config.peers_config_with_basic_nodes_from_file(None)) .external_ip_resolver(self.network.nat) - .disable_discv4_discovery_if(self.chain.chain.is_optimism()) + .disable_discv4_discovery_if(self.chain.chain().is_optimism()) .boot_nodes(boot_nodes.clone()) .apply(|builder| { self.network.discovery.apply_to_builder(builder, rlpx_socket, boot_nodes) diff --git a/crates/cli/commands/src/prune.rs b/crates/cli/commands/src/prune.rs index d19247e21a7b..7dbb66fc2faf 100644 --- a/crates/cli/commands/src/prune.rs +++ b/crates/cli/commands/src/prune.rs @@ -1,7 +1,7 @@ //! Command that runs pruning without any limits. use crate::common::{AccessRights, Environment, EnvironmentArgs}; use clap::Parser; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_node_builder::NodeTypesWithEngine; use reth_prune::PrunerBuilder; @@ -15,7 +15,7 @@ pub struct PruneCommand { env: EnvironmentArgs, } -impl> PruneCommand { +impl> PruneCommand { /// Execute the `prune` command pub async fn execute>( self, diff --git a/crates/cli/commands/src/recover/mod.rs b/crates/cli/commands/src/recover/mod.rs index 9bf81817458d..3216449e49b6 100644 --- a/crates/cli/commands/src/recover/mod.rs +++ b/crates/cli/commands/src/recover/mod.rs @@ -1,7 +1,7 @@ //! `reth recover` command. use clap::{Parser, Subcommand}; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_cli_runner::CliContext; use reth_node_builder::NodeTypesWithEngine; @@ -22,7 +22,7 @@ pub enum Subcommands { StorageTries(storage_tries::Command), } -impl> Command { +impl> Command { /// Execute `recover` command pub async fn execute>( self, diff --git a/crates/cli/commands/src/recover/storage_tries.rs b/crates/cli/commands/src/recover/storage_tries.rs index 65cb741f324e..304075ede0c1 100644 --- a/crates/cli/commands/src/recover/storage_tries.rs +++ b/crates/cli/commands/src/recover/storage_tries.rs @@ -1,6 +1,6 @@ use crate::common::{AccessRights, Environment, EnvironmentArgs}; use clap::Parser; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_cli_runner::CliContext; use reth_db::tables; @@ -21,7 +21,7 @@ pub struct Command { env: EnvironmentArgs, } -impl> Command { +impl> Command { /// Execute `storage-tries` recovery command pub async fn execute>( self, diff --git a/crates/cli/commands/src/stage/drop.rs b/crates/cli/commands/src/stage/drop.rs index 6571cbaae864..26165497d0b7 100644 --- a/crates/cli/commands/src/stage/drop.rs +++ b/crates/cli/commands/src/stage/drop.rs @@ -2,7 +2,7 @@ use crate::common::{AccessRights, Environment, EnvironmentArgs}; use clap::Parser; use itertools::Itertools; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_db::{static_file::iter_static_files, tables}; use reth_db_api::transaction::DbTxMut; @@ -25,7 +25,7 @@ pub struct Command { stage: StageEnum, } -impl> Command { +impl> Command { /// Execute `db` command pub async fn execute>( self, @@ -164,7 +164,7 @@ impl> Command { StageId::IndexStorageHistory.to_string(), Default::default(), )?; - insert_genesis_history(&provider_rw.0, self.env.chain.genesis.alloc.iter())?; + insert_genesis_history(&provider_rw.0, self.env.chain.genesis().alloc.iter())?; } StageEnum::TxLookup => { tx.clear::()?; diff --git a/crates/cli/commands/src/stage/dump/execution.rs b/crates/cli/commands/src/stage/dump/execution.rs index c807ac94145d..709fc59190d4 100644 --- a/crates/cli/commands/src/stage/dump/execution.rs +++ b/crates/cli/commands/src/stage/dump/execution.rs @@ -1,7 +1,6 @@ use std::sync::Arc; use super::setup; -use reth_chainspec::ChainSpec; use reth_db::{tables, DatabaseEnv}; use reth_db_api::{ cursor::DbCursorRO, database::Database, table::TableImporter, transaction::DbTx, @@ -10,7 +9,10 @@ use reth_db_common::DbTool; use reth_evm::{execute::BlockExecutorProvider, noop::NoopBlockExecutorProvider}; use reth_node_builder::{NodeTypesWithDB, NodeTypesWithDBAdapter}; use reth_node_core::dirs::{ChainPath, DataDirPath}; -use reth_provider::{providers::StaticFileProvider, DatabaseProviderFactory, ProviderFactory}; +use reth_provider::{ + providers::{ProviderNodeTypes, StaticFileProvider}, + DatabaseProviderFactory, ProviderFactory, +}; use reth_stages::{stages::ExecutionStage, Stage, StageCheckpoint, UnwindInput}; use tracing::info; @@ -23,7 +25,7 @@ pub(crate) async fn dump_execution_stage( executor: E, ) -> eyre::Result<()> where - N: NodeTypesWithDB, + N: ProviderNodeTypes, E: BlockExecutorProvider, { let (output_db, tip_block_number) = setup(from, to, &output_datadir.db(), db_tool)?; @@ -129,7 +131,7 @@ fn import_tables_with_range( /// Dry-run an unwind to FROM block, so we can get the `PlainStorageState` and /// `PlainAccountState` safely. There might be some state dependency from an address /// which hasn't been changed in the given range. -fn unwind_and_copy>( +fn unwind_and_copy( db_tool: &DbTool, from: u64, tip_block_number: u64, @@ -166,7 +168,7 @@ fn dry_run( executor: E, ) -> eyre::Result<()> where - N: NodeTypesWithDB, + N: ProviderNodeTypes, E: BlockExecutorProvider, { info!(target: "reth::cli", "Executing stage. [dry-run]"); diff --git a/crates/cli/commands/src/stage/dump/hashing_account.rs b/crates/cli/commands/src/stage/dump/hashing_account.rs index 94d8129e0382..738dcabafa70 100644 --- a/crates/cli/commands/src/stage/dump/hashing_account.rs +++ b/crates/cli/commands/src/stage/dump/hashing_account.rs @@ -3,17 +3,19 @@ use std::sync::Arc; use super::setup; use alloy_primitives::BlockNumber; use eyre::Result; -use reth_chainspec::ChainSpec; use reth_db::{tables, DatabaseEnv}; use reth_db_api::{database::Database, table::TableImporter}; use reth_db_common::DbTool; -use reth_node_builder::{NodeTypesWithDB, NodeTypesWithDBAdapter}; +use reth_node_builder::NodeTypesWithDBAdapter; use reth_node_core::dirs::{ChainPath, DataDirPath}; -use reth_provider::{providers::StaticFileProvider, DatabaseProviderFactory, ProviderFactory}; +use reth_provider::{ + providers::{ProviderNodeTypes, StaticFileProvider}, + DatabaseProviderFactory, ProviderFactory, +}; use reth_stages::{stages::AccountHashingStage, Stage, StageCheckpoint, UnwindInput}; use tracing::info; -pub(crate) async fn dump_hashing_account_stage>( +pub(crate) async fn dump_hashing_account_stage( db_tool: &DbTool, from: BlockNumber, to: BlockNumber, @@ -49,7 +51,7 @@ pub(crate) async fn dump_hashing_account_stage>( +fn unwind_and_copy( db_tool: &DbTool, from: u64, tip_block_number: u64, @@ -74,7 +76,7 @@ fn unwind_and_copy>( } /// Try to re-execute the stage straight away -fn dry_run>( +fn dry_run( output_provider_factory: ProviderFactory, to: u64, from: u64, diff --git a/crates/cli/commands/src/stage/dump/hashing_storage.rs b/crates/cli/commands/src/stage/dump/hashing_storage.rs index 16a90eeedcb3..204c087a234d 100644 --- a/crates/cli/commands/src/stage/dump/hashing_storage.rs +++ b/crates/cli/commands/src/stage/dump/hashing_storage.rs @@ -2,17 +2,19 @@ use std::sync::Arc; use super::setup; use eyre::Result; -use reth_chainspec::ChainSpec; use reth_db::{tables, DatabaseEnv}; use reth_db_api::{database::Database, table::TableImporter}; use reth_db_common::DbTool; -use reth_node_builder::{NodeTypesWithDB, NodeTypesWithDBAdapter}; +use reth_node_builder::NodeTypesWithDBAdapter; use reth_node_core::dirs::{ChainPath, DataDirPath}; -use reth_provider::{providers::StaticFileProvider, DatabaseProviderFactory, ProviderFactory}; +use reth_provider::{ + providers::{ProviderNodeTypes, StaticFileProvider}, + DatabaseProviderFactory, ProviderFactory, +}; use reth_stages::{stages::StorageHashingStage, Stage, StageCheckpoint, UnwindInput}; use tracing::info; -pub(crate) async fn dump_hashing_storage_stage>( +pub(crate) async fn dump_hashing_storage_stage( db_tool: &DbTool, from: u64, to: u64, @@ -39,7 +41,7 @@ pub(crate) async fn dump_hashing_storage_stage>( +fn unwind_and_copy( db_tool: &DbTool, from: u64, tip_block_number: u64, @@ -69,7 +71,7 @@ fn unwind_and_copy>( } /// Try to re-execute the stage straight away -fn dry_run>( +fn dry_run( output_provider_factory: ProviderFactory, to: u64, from: u64, diff --git a/crates/cli/commands/src/stage/dump/merkle.rs b/crates/cli/commands/src/stage/dump/merkle.rs index 4b3d9c30331e..f7e9e2fc1afc 100644 --- a/crates/cli/commands/src/stage/dump/merkle.rs +++ b/crates/cli/commands/src/stage/dump/merkle.rs @@ -3,16 +3,18 @@ use std::sync::Arc; use super::setup; use alloy_primitives::BlockNumber; use eyre::Result; -use reth_chainspec::ChainSpec; use reth_config::config::EtlConfig; use reth_db::{tables, DatabaseEnv}; use reth_db_api::{database::Database, table::TableImporter}; use reth_db_common::DbTool; use reth_evm::noop::NoopBlockExecutorProvider; use reth_exex::ExExManagerHandle; -use reth_node_builder::{NodeTypesWithDB, NodeTypesWithDBAdapter}; +use reth_node_builder::NodeTypesWithDBAdapter; use reth_node_core::dirs::{ChainPath, DataDirPath}; -use reth_provider::{providers::StaticFileProvider, DatabaseProviderFactory, ProviderFactory}; +use reth_provider::{ + providers::{ProviderNodeTypes, StaticFileProvider}, + DatabaseProviderFactory, ProviderFactory, +}; use reth_prune::PruneModes; use reth_stages::{ stages::{ @@ -23,7 +25,7 @@ use reth_stages::{ }; use tracing::info; -pub(crate) async fn dump_merkle_stage>( +pub(crate) async fn dump_merkle_stage( db_tool: &DbTool, from: BlockNumber, to: BlockNumber, @@ -66,7 +68,7 @@ pub(crate) async fn dump_merkle_stage> } /// Dry-run an unwind to FROM block and copy the necessary table data to the new database. -fn unwind_and_copy>( +fn unwind_and_copy( db_tool: &DbTool, range: (u64, u64), tip_block_number: u64, @@ -144,7 +146,7 @@ fn unwind_and_copy>( } /// Try to re-execute the stage straight away -fn dry_run>( +fn dry_run( output_provider_factory: ProviderFactory, to: u64, from: u64, diff --git a/crates/cli/commands/src/stage/dump/mod.rs b/crates/cli/commands/src/stage/dump/mod.rs index 44161d9b3bb2..6fd2f23aa0e5 100644 --- a/crates/cli/commands/src/stage/dump/mod.rs +++ b/crates/cli/commands/src/stage/dump/mod.rs @@ -1,7 +1,7 @@ //! Database debugging tool use crate::common::{AccessRights, Environment, EnvironmentArgs}; use clap::Parser; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_db::{init_db, mdbx::DatabaseArguments, tables, DatabaseEnv}; use reth_db_api::{ @@ -75,24 +75,26 @@ pub struct StageCommand { macro_rules! handle_stage { ($stage_fn:ident, $tool:expr, $command:expr) => {{ let StageCommand { output_datadir, from, to, dry_run, .. } = $command; - let output_datadir = output_datadir.with_chain($tool.chain().chain, DatadirArgs::default()); + let output_datadir = + output_datadir.with_chain($tool.chain().chain(), DatadirArgs::default()); $stage_fn($tool, *from, *to, output_datadir, *dry_run).await? }}; ($stage_fn:ident, $tool:expr, $command:expr, $executor:expr) => {{ let StageCommand { output_datadir, from, to, dry_run, .. } = $command; - let output_datadir = output_datadir.with_chain($tool.chain().chain, DatadirArgs::default()); + let output_datadir = + output_datadir.with_chain($tool.chain().chain(), DatadirArgs::default()); $stage_fn($tool, *from, *to, output_datadir, *dry_run, $executor).await? }}; } -impl> Command { +impl> Command { /// Execute `dump-stage` command pub async fn execute(self, executor: F) -> eyre::Result<()> where N: NodeTypesWithEngine, E: BlockExecutorProvider, - F: FnOnce(Arc) -> E, + F: FnOnce(Arc) -> E, { let Environment { provider_factory, .. } = self.env.init::(AccessRights::RO)?; let tool = DbTool::new(provider_factory)?; diff --git a/crates/cli/commands/src/stage/mod.rs b/crates/cli/commands/src/stage/mod.rs index a4e0d088ac94..562bd73a28d7 100644 --- a/crates/cli/commands/src/stage/mod.rs +++ b/crates/cli/commands/src/stage/mod.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use clap::{Parser, Subcommand}; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_cli_runner::CliContext; use reth_evm::execute::BlockExecutorProvider; @@ -39,13 +39,13 @@ pub enum Subcommands { Unwind(unwind::Command), } -impl> Command { +impl> Command { /// Execute `stage` command pub async fn execute(self, ctx: CliContext, executor: F) -> eyre::Result<()> where N: NodeTypesWithEngine, E: BlockExecutorProvider, - F: FnOnce(Arc) -> E, + F: FnOnce(Arc) -> E, { match self.command { Subcommands::Run(command) => command.execute::(ctx, executor).await, diff --git a/crates/cli/commands/src/stage/run.rs b/crates/cli/commands/src/stage/run.rs index 9bc0fa04a365..23d6f6f28ac6 100644 --- a/crates/cli/commands/src/stage/run.rs +++ b/crates/cli/commands/src/stage/run.rs @@ -6,7 +6,7 @@ use crate::common::{AccessRights, Environment, EnvironmentArgs}; use alloy_eips::BlockHashOrNumber; use clap::Parser; use reth_beacon_consensus::EthBeaconConsensus; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_cli_runner::CliContext; use reth_cli_util::get_secret_key; @@ -102,13 +102,13 @@ pub struct Command { network: NetworkArgs, } -impl> Command { +impl> Command { /// Execute `stage` command pub async fn execute(self, ctx: CliContext, executor: F) -> eyre::Result<()> where N: NodeTypesWithEngine, E: BlockExecutorProvider, - F: FnOnce(Arc) -> E, + F: FnOnce(Arc) -> E, { // Raise the fd limit of the process. // Does not do anything on windows. @@ -131,7 +131,7 @@ impl> Command { target_triple: VERGEN_CARGO_TARGET_TRIPLE, build_profile: BUILD_PROFILE_NAME, }, - ChainSpecInfo { name: provider_factory.chain_spec().chain.to_string() }, + ChainSpecInfo { name: provider_factory.chain_spec().chain().to_string() }, ctx.task_executor, Hooks::new( provider_factory.db_ref().clone(), diff --git a/crates/cli/commands/src/stage/unwind.rs b/crates/cli/commands/src/stage/unwind.rs index 6c7bdebd1184..c1029f33beea 100644 --- a/crates/cli/commands/src/stage/unwind.rs +++ b/crates/cli/commands/src/stage/unwind.rs @@ -5,7 +5,7 @@ use alloy_eips::BlockHashOrNumber; use alloy_primitives::{BlockNumber, B256}; use clap::{Parser, Subcommand}; use reth_beacon_consensus::EthBeaconConsensus; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_cli::chainspec::ChainSpecParser; use reth_config::Config; use reth_consensus::Consensus; @@ -16,8 +16,8 @@ use reth_exex::ExExManagerHandle; use reth_node_builder::{NodeTypesWithDB, NodeTypesWithEngine}; use reth_node_core::args::NetworkArgs; use reth_provider::{ - BlockExecutionWriter, BlockNumReader, ChainSpecProvider, FinalizedBlockReader, - FinalizedBlockWriter, ProviderFactory, StaticFileProviderFactory, + providers::ProviderNodeTypes, BlockExecutionWriter, BlockNumReader, ChainSpecProvider, + FinalizedBlockReader, FinalizedBlockWriter, ProviderFactory, StaticFileProviderFactory, }; use reth_prune::PruneModes; use reth_stages::{ @@ -48,7 +48,7 @@ pub struct Command { offline: bool, } -impl> Command { +impl> Command { /// Execute `db stage unwind` command pub async fn execute>( self, @@ -189,7 +189,7 @@ impl Subcommands { /// Returns the block range to unwind. /// /// This returns an inclusive range: [target..=latest] - fn unwind_range>>( + fn unwind_range>>( &self, factory: ProviderFactory, ) -> eyre::Result> { diff --git a/crates/e2e-test-utils/src/lib.rs b/crates/e2e-test-utils/src/lib.rs index 3d2961cf8cd9..998b48e70431 100644 --- a/crates/e2e-test-utils/src/lib.rs +++ b/crates/e2e-test-utils/src/lib.rs @@ -10,7 +10,7 @@ use reth::{ rpc::api::eth::{helpers::AddDevSigners, FullEthApiServer}, tasks::TaskManager, }; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_db::{test_utils::TempDatabase, DatabaseEnv}; use reth_node_builder::{ components::NodeComponentsBuilder, rpc::EthApiBuilderProvider, FullNodeTypesAdapter, Node, @@ -47,11 +47,11 @@ mod traits; /// Creates the initial setup with `num_nodes` started and interconnected. pub async fn setup( num_nodes: usize, - chain_spec: Arc, + chain_spec: Arc, is_dev: bool, ) -> eyre::Result<(Vec>, TaskManager, Wallet)> where - N: Default + Node> + NodeTypesWithEngine, + N: Default + Node> + NodeTypesWithEngine, N::ComponentsBuilder: NodeComponentsBuilder< TmpNodeAdapter, Components: NodeComponents, Network: PeersHandleProvider>, @@ -73,8 +73,7 @@ where let mut nodes: Vec> = Vec::with_capacity(num_nodes); for idx in 0..num_nodes { - let node_config = NodeConfig::test() - .with_chain(chain_spec.clone()) + let node_config = NodeConfig::new(chain_spec.clone()) .with_network(network_config.clone()) .with_unused_ports() .with_rpc(RpcServerArgs::default().with_unused_ports().with_http()) diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index 391a070df7dd..2ea39348f5de 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -17,7 +17,7 @@ use reth::{ types::engine::PayloadStatusEnum, }, }; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthereumHardforks; use reth_node_builder::{NodeAddOns, NodeTypesWithEngine}; use reth_stages_types::StageId; use tokio_stream::StreamExt; @@ -50,7 +50,7 @@ impl NodeTestContext where Engine: EngineTypes, Node: FullNodeComponents, - Node::Types: NodeTypesWithEngine, + Node::Types: NodeTypesWithEngine, Node::Network: PeersHandleProvider, AddOns: NodeAddOns, { diff --git a/crates/e2e-test-utils/src/rpc.rs b/crates/e2e-test-utils/src/rpc.rs index 3ff378a08304..b8cbe4d77add 100644 --- a/crates/e2e-test-utils/src/rpc.rs +++ b/crates/e2e-test-utils/src/rpc.rs @@ -8,7 +8,7 @@ use reth::{ DebugApiServer, }, }; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthereumHardforks; use reth_node_builder::{EthApiTypes, NodeTypes}; #[allow(missing_debug_implementations)] @@ -18,7 +18,7 @@ pub struct RpcTestContext { impl RpcTestContext where - Node: FullNodeComponents>, + Node: FullNodeComponents>, EthApi: EthApiSpec + EthTransactions + TraceExt, { /// Injects a raw transaction into the node tx pool via RPC server diff --git a/crates/engine/invalid-block-hooks/src/witness.rs b/crates/engine/invalid-block-hooks/src/witness.rs index 06bfee747cc0..59cab6adecae 100644 --- a/crates/engine/invalid-block-hooks/src/witness.rs +++ b/crates/engine/invalid-block-hooks/src/witness.rs @@ -4,7 +4,7 @@ use alloy_primitives::{keccak256, B256, U256}; use alloy_rpc_types_debug::ExecutionWitness; use eyre::OptionExt; use pretty_assertions::Comparison; -use reth_chainspec::ChainSpec; +use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_engine_primitives::InvalidBlockHook; use reth_evm::{ system_calls::{apply_beacon_root_contract_call, apply_blockhashes_contract_call}, @@ -52,7 +52,11 @@ impl InvalidBlockWitnessHook { impl InvalidBlockWitnessHook where - P: StateProviderFactory + ChainSpecProvider + Send + Sync + 'static, + P: StateProviderFactory + + ChainSpecProvider + + Send + + Sync + + 'static, EvmConfig: ConfigureEvm
, { fn on_invalid_block( @@ -295,7 +299,11 @@ where impl InvalidBlockHook for InvalidBlockWitnessHook where - P: StateProviderFactory + ChainSpecProvider + Send + Sync + 'static, + P: StateProviderFactory + + ChainSpecProvider + + Send + + Sync + + 'static, EvmConfig: ConfigureEvm
, { fn on_invalid_block( diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index 61141f0677cc..4989589c9f98 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -10,7 +10,7 @@ pub use states::*; use std::sync::Arc; use futures::Future; -use reth_chainspec::{ChainSpec, EthChainSpec, EthereumHardforks, Hardforks}; +use reth_chainspec::{EthChainSpec, EthereumHardforks, Hardforks}; use reth_cli_util::get_secret_key; use reth_db_api::{ database::Database, @@ -641,7 +641,7 @@ impl BuilderContext { } } -impl>> BuilderContext { +impl>> BuilderContext { /// Creates the [`NetworkBuilder`] for the node. pub async fn network_builder(&self) -> eyre::Result> { let network_config = self.network_config()?; diff --git a/crates/node/builder/src/launch/common.rs b/crates/node/builder/src/launch/common.rs index 720f69c18464..99e9b29368a0 100644 --- a/crates/node/builder/src/launch/common.rs +++ b/crates/node/builder/src/launch/common.rs @@ -10,7 +10,7 @@ use reth_beacon_consensus::EthBeaconConsensus; use reth_blockchain_tree::{ BlockchainTree, BlockchainTreeConfig, ShareableBlockchainTree, TreeExternals, }; -use reth_chainspec::{Chain, ChainSpec, EthChainSpec, EthereumHardforks}; +use reth_chainspec::{Chain, EthChainSpec, EthereumHardforks}; use reth_config::{config::EtlConfig, PruneConfig}; use reth_consensus::Consensus; use reth_db_api::database::Database; @@ -879,8 +879,8 @@ impl > where T: FullNodeTypes< - Provider: WithTree + StateProviderFactory + ChainSpecProvider, - Types: NodeTypes, + Provider: WithTree + StateProviderFactory + ChainSpecProvider, + Types: NodeTypes, >, CB: NodeComponentsBuilder, { diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index 708d791a0e84..6f2d37c1c490 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -7,7 +7,7 @@ use reth_beacon_consensus::{ BeaconConsensusEngineHandle, }; use reth_blockchain_tree::BlockchainTreeConfig; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthChainSpec; use reth_consensus_debug_client::{DebugConsensusClient, EtherscanBlockProvider}; use reth_engine_service::service::{ChainEvent, EngineService}; use reth_engine_tree::{ @@ -18,9 +18,7 @@ use reth_engine_util::EngineMessageStreamExt; use reth_exex::ExExManagerHandle; use reth_network::{NetworkSyncUpdater, SyncState}; use reth_network_api::{BlockDownloaderProvider, NetworkEventListenerProvider}; -use reth_node_api::{ - BuiltPayload, FullNodeTypes, NodeAddOns, NodeTypesWithDB, NodeTypesWithEngine, -}; +use reth_node_api::{BuiltPayload, FullNodeTypes, NodeAddOns, NodeTypesWithEngine}; use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, @@ -30,7 +28,8 @@ use reth_node_core::{ }; use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; use reth_payload_primitives::PayloadBuilder; -use reth_provider::providers::BlockchainProvider2; +use reth_primitives::EthereumHardforks; +use reth_provider::providers::{BlockchainProvider2, ProviderNodeTypes}; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; use reth_tasks::TaskExecutor; use reth_tokio_util::EventSender; @@ -72,7 +71,7 @@ impl EngineNodeLauncher { impl LaunchNode> for EngineNodeLauncher where - Types: NodeTypesWithDB + NodeTypesWithEngine, + Types: ProviderNodeTypes + NodeTypesWithEngine, T: FullNodeTypes>, CB: NodeComponentsBuilder, AO: NodeAddOns< @@ -127,7 +126,7 @@ where debug!(target: "reth::cli", chain=%this.chain_id(), genesis=?this.genesis_hash(), "Initializing genesis"); }) .with_genesis()? - .inspect(|this: &LaunchContextWith, _>>| { + .inspect(|this: &LaunchContextWith, _>>| { info!(target: "reth::cli", "\n{}", this.chain_spec().display_hardforks()); }) .with_metrics_task() @@ -296,7 +295,7 @@ where if let Some(maybe_custom_etherscan_url) = ctx.node_config().debug.etherscan.clone() { info!(target: "reth::cli", "Using etherscan as consensus client"); - let chain = ctx.node_config().chain.chain; + let chain = ctx.node_config().chain.chain(); let etherscan_url = maybe_custom_etherscan_url.map(Ok).unwrap_or_else(|| { // If URL isn't provided, use default Etherscan URL for the chain if it is known chain diff --git a/crates/node/core/src/args/network.rs b/crates/node/core/src/args/network.rs index d25ebd8ea157..0f1465bc5795 100644 --- a/crates/node/core/src/args/network.rs +++ b/crates/node/core/src/args/network.rs @@ -4,11 +4,10 @@ use std::{ net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}, ops::Not, path::PathBuf, - sync::Arc, }; use clap::Args; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthChainSpec; use reth_config::Config; use reth_discv4::{NodeRecord, DEFAULT_DISCOVERY_ADDR, DEFAULT_DISCOVERY_PORT}; use reth_discv5::{ @@ -186,8 +185,8 @@ impl NetworkArgs { }) } - /// Build a [`NetworkConfigBuilder`] from a [`Config`] and a [`ChainSpec`], in addition to the - /// values in this option struct. + /// Build a [`NetworkConfigBuilder`] from a [`Config`] and a [`EthChainSpec`], in addition to + /// the values in this option struct. /// /// The `default_peers_file` will be used as the default location to store the persistent peers /// file if `no_persist_peers` is false, and there is no provided `peers_file`. @@ -200,7 +199,7 @@ impl NetworkArgs { pub fn network_config( &self, config: &Config, - chain_spec: Arc, + chain_spec: impl EthChainSpec, secret_key: SecretKey, default_peers_file: PathBuf, ) -> NetworkConfigBuilder { diff --git a/crates/node/core/src/node_config.rs b/crates/node/core/src/node_config.rs index de6929824676..a8799d80df1c 100644 --- a/crates/node/core/src/node_config.rs +++ b/crates/node/core/src/node_config.rs @@ -139,6 +139,25 @@ impl NodeConfig { } impl NodeConfig { + /// Creates a new config with given chain spec, setting all fields to default values. + pub fn new(chain: Arc) -> Self { + Self { + config: None, + chain, + metrics: None, + instance: 1, + network: NetworkArgs::default(), + rpc: RpcServerArgs::default(), + txpool: TxPoolArgs::default(), + builder: PayloadBuilderArgs::default(), + debug: DebugArgs::default(), + db: DatabaseArgs::default(), + dev: DevArgs::default(), + pruning: PruningArgs::default(), + datadir: DatadirArgs::default(), + } + } + /// Sets --dev mode for the node. /// /// In addition to setting the `--dev` flag, this also: @@ -407,21 +426,7 @@ impl NodeConfig { impl Default for NodeConfig { fn default() -> Self { - Self { - config: None, - chain: MAINNET.clone(), - metrics: None, - instance: 1, - network: NetworkArgs::default(), - rpc: RpcServerArgs::default(), - txpool: TxPoolArgs::default(), - builder: PayloadBuilderArgs::default(), - debug: DebugArgs::default(), - db: DatabaseArgs::default(), - dev: DevArgs::default(), - pruning: PruningArgs::default(), - datadir: DatadirArgs::default(), - } + Self::new(MAINNET.clone()) } } diff --git a/crates/optimism/chainspec/Cargo.toml b/crates/optimism/chainspec/Cargo.toml index ce899837e061..41b54902c201 100644 --- a/crates/optimism/chainspec/Cargo.toml +++ b/crates/optimism/chainspec/Cargo.toml @@ -16,12 +16,14 @@ workspace = true reth-chainspec = { workspace = true, features = ["optimism"] } reth-ethereum-forks.workspace = true reth-primitives-traits.workspace = true +reth-network-peers.workspace = true # op-reth reth-optimism-forks.workspace = true # ethereum alloy-chains.workspace = true +alloy-genesis.workspace = true alloy-primitives.workspace = true # io diff --git a/crates/optimism/chainspec/src/lib.rs b/crates/optimism/chainspec/src/lib.rs index 63b6896f6142..2668c374500d 100644 --- a/crates/optimism/chainspec/src/lib.rs +++ b/crates/optimism/chainspec/src/lib.rs @@ -16,7 +16,10 @@ mod dev; mod op; mod op_sepolia; -use alloy_primitives::{Parity, Signature, U256}; +use std::fmt::Display; + +use alloy_genesis::Genesis; +use alloy_primitives::{Parity, Signature, B256, U256}; pub use base::BASE_MAINNET; pub use base_sepolia::BASE_SEPOLIA; pub use dev::OP_DEV; @@ -24,10 +27,15 @@ pub use op::OP_MAINNET; pub use op_sepolia::OP_SEPOLIA; use derive_more::{Constructor, Deref, Into}; -use reth_chainspec::ChainSpec; +use reth_chainspec::{ + BaseFeeParams, ChainSpec, DepositContract, EthChainSpec, EthereumHardforks, ForkFilter, ForkId, + Hardforks, Head, +}; +use reth_network_peers::NodeRecord; +use reth_primitives_traits::Header; /// OP stack chain spec type. -#[derive(Debug, Clone, Deref, Into, Constructor)] +#[derive(Debug, Clone, Deref, Into, Constructor, PartialEq, Eq)] pub struct OpChainSpec { /// [`ChainSpec`]. pub inner: ChainSpec, @@ -39,6 +47,86 @@ pub fn optimism_deposit_tx_signature() -> Signature { Signature::new(U256::ZERO, U256::ZERO, Parity::Parity(false)) } +impl EthChainSpec for OpChainSpec { + fn chain(&self) -> alloy_chains::Chain { + self.inner.chain() + } + + fn base_fee_params_at_timestamp(&self, timestamp: u64) -> BaseFeeParams { + self.inner.base_fee_params_at_timestamp(timestamp) + } + + fn base_fee_params_at_block(&self, block_number: u64) -> BaseFeeParams { + self.inner.base_fee_params_at_block(block_number) + } + + fn deposit_contract(&self) -> Option<&DepositContract> { + self.inner.deposit_contract() + } + + fn genesis_hash(&self) -> B256 { + self.inner.genesis_hash() + } + + fn prune_delete_limit(&self) -> usize { + self.inner.prune_delete_limit() + } + + fn display_hardforks(&self) -> impl Display { + self.inner.display_hardforks() + } + + fn genesis_header(&self) -> &Header { + self.inner.genesis_header() + } + + fn genesis(&self) -> &Genesis { + self.inner.genesis() + } + + fn max_gas_limit(&self) -> u64 { + self.inner.max_gas_limit() + } + + fn bootnodes(&self) -> Option> { + self.inner.bootnodes() + } +} + +impl Hardforks for OpChainSpec { + fn fork(&self, fork: H) -> reth_chainspec::ForkCondition { + self.inner.fork(fork) + } + + fn forks_iter( + &self, + ) -> impl Iterator { + self.inner.forks_iter() + } + + fn fork_id(&self, head: &Head) -> ForkId { + self.inner.fork_id(head) + } + + fn latest_fork_id(&self) -> ForkId { + self.inner.latest_fork_id() + } + + fn fork_filter(&self, head: Head) -> ForkFilter { + self.inner.fork_filter(head) + } +} + +impl EthereumHardforks for OpChainSpec { + fn final_paris_total_difficulty(&self, block_number: u64) -> Option { + self.inner.final_paris_total_difficulty(block_number) + } + + fn get_final_paris_total_difficulty(&self) -> Option { + self.inner.get_final_paris_total_difficulty() + } +} + #[cfg(test)] mod tests { use alloy_genesis::Genesis; diff --git a/crates/optimism/cli/src/chainspec.rs b/crates/optimism/cli/src/chainspec.rs index 03d78cba0a3c..e76bfd5f0656 100644 --- a/crates/optimism/cli/src/chainspec.rs +++ b/crates/optimism/cli/src/chainspec.rs @@ -1,6 +1,5 @@ use std::sync::Arc; -use reth_chainspec::ChainSpec; use reth_cli::chainspec::ChainSpecParser; use reth_node_core::args::utils::parse_custom_chain_spec; use reth_optimism_chainspec::{ @@ -27,7 +26,7 @@ fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> { pub struct OpChainSpecParser; impl ChainSpecParser for OpChainSpecParser { - type ChainSpec = ChainSpec; + type ChainSpec = OpChainSpec; const SUPPORTED_CHAINS: &'static [&'static str] = &[ "dev", @@ -40,7 +39,7 @@ impl ChainSpecParser for OpChainSpecParser { ]; fn parse(s: &str) -> eyre::Result> { - chain_value_parser(s).map(|s| Arc::new(Arc::unwrap_or_clone(s).inner)) + chain_value_parser(s) } } diff --git a/crates/optimism/cli/src/commands/build_pipeline.rs b/crates/optimism/cli/src/commands/build_pipeline.rs index b2ac97eef2d1..1c3dee5f1ebd 100644 --- a/crates/optimism/cli/src/commands/build_pipeline.rs +++ b/crates/optimism/cli/src/commands/build_pipeline.rs @@ -1,6 +1,5 @@ use alloy_primitives::B256; use futures_util::{Stream, StreamExt}; -use reth_chainspec::ChainSpec; use reth_config::Config; use reth_consensus::Consensus; use reth_downloaders::{ @@ -14,6 +13,7 @@ use reth_network_p2p::{ }; use reth_node_builder::NodeTypesWithDB; use reth_node_events::node::NodeEvent; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_evm::OpExecutorProvider; use reth_provider::{BlockNumReader, ChainSpecProvider, HeaderProvider, ProviderFactory}; use reth_prune::PruneModes; @@ -36,7 +36,7 @@ pub(crate) async fn build_import_pipeline( disable_exec: bool, ) -> eyre::Result<(Pipeline, impl Stream)> where - N: NodeTypesWithDB, + N: NodeTypesWithDB, C: Consensus + 'static, { if !file_client.has_canonical_blocks() { diff --git a/crates/optimism/cli/src/commands/import.rs b/crates/optimism/cli/src/commands/import.rs index b7d2ee13fca6..e5f037c3d5cc 100644 --- a/crates/optimism/cli/src/commands/import.rs +++ b/crates/optimism/cli/src/commands/import.rs @@ -1,7 +1,6 @@ //! Command that initializes the node by importing OP Mainnet chain segment below Bedrock, from a //! file. use clap::Parser; -use reth_chainspec::ChainSpec; use reth_cli::chainspec::ChainSpecParser; use reth_cli_commands::common::{AccessRights, Environment, EnvironmentArgs}; use reth_consensus::noop::NoopConsensus; @@ -12,6 +11,7 @@ use reth_downloaders::file_client::{ }; use reth_node_builder::NodeTypesWithEngine; use reth_node_core::version::SHORT_VERSION; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_primitives::bedrock::is_dup_tx; use reth_provider::StageCheckpointReader; use reth_prune::PruneModes; @@ -40,7 +40,7 @@ pub struct ImportOpCommand { path: PathBuf, } -impl> ImportOpCommand { +impl> ImportOpCommand { /// Execute `import` command pub async fn execute>( self, diff --git a/crates/optimism/cli/src/commands/import_receipts.rs b/crates/optimism/cli/src/commands/import_receipts.rs index 2ec0c9d704a0..838a99818e96 100644 --- a/crates/optimism/cli/src/commands/import_receipts.rs +++ b/crates/optimism/cli/src/commands/import_receipts.rs @@ -4,7 +4,6 @@ use std::path::{Path, PathBuf}; use clap::Parser; -use reth_chainspec::ChainSpec; use reth_cli::chainspec::ChainSpecParser; use reth_cli_commands::common::{AccessRights, Environment, EnvironmentArgs}; use reth_db::tables; @@ -15,12 +14,13 @@ use reth_downloaders::{ use reth_execution_types::ExecutionOutcome; use reth_node_builder::{NodeTypesWithDB, NodeTypesWithEngine}; use reth_node_core::version::SHORT_VERSION; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_primitives::bedrock::is_dup_tx; use reth_primitives::Receipts; use reth_provider::{ - writer::UnifiedStorageWriter, DatabaseProviderFactory, OriginalValuesKnown, ProviderFactory, - StageCheckpointReader, StageCheckpointWriter, StateWriter, StaticFileProviderFactory, - StaticFileWriter, StatsReader, + providers::ProviderNodeTypes, writer::UnifiedStorageWriter, DatabaseProviderFactory, + OriginalValuesKnown, ProviderFactory, StageCheckpointReader, StageCheckpointWriter, + StateWriter, StaticFileProviderFactory, StaticFileWriter, StatsReader, }; use reth_stages::{StageCheckpoint, StageId}; use reth_static_file_types::StaticFileSegment; @@ -46,7 +46,7 @@ pub struct ImportReceiptsOpCommand { path: PathBuf, } -impl> ImportReceiptsOpCommand { +impl> ImportReceiptsOpCommand { /// Execute `import` command pub async fn execute>( self, @@ -88,7 +88,7 @@ pub async fn import_receipts_from_file( filter: F, ) -> eyre::Result<()> where - N: NodeTypesWithDB, + N: NodeTypesWithDB, P: AsRef, F: FnMut(u64, &mut Receipts) -> usize, { @@ -126,7 +126,7 @@ pub async fn import_receipts_from_reader( mut filter: F, ) -> eyre::Result where - N: NodeTypesWithDB, + N: ProviderNodeTypes, F: FnMut(u64, &mut Receipts) -> usize, { let static_file_provider = provider_factory.static_file_provider(); diff --git a/crates/optimism/cli/src/commands/init_state/mod.rs b/crates/optimism/cli/src/commands/init_state/mod.rs index a021e509b64d..3537f89e7519 100644 --- a/crates/optimism/cli/src/commands/init_state/mod.rs +++ b/crates/optimism/cli/src/commands/init_state/mod.rs @@ -1,11 +1,11 @@ //! Command that initializes the node from a genesis file. use clap::Parser; -use reth_chainspec::ChainSpec; use reth_cli::chainspec::ChainSpecParser; use reth_cli_commands::common::{AccessRights, Environment}; use reth_db_common::init::init_from_state_dump; use reth_node_builder::NodeTypesWithEngine; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_primitives::bedrock::BEDROCK_HEADER; use reth_provider::{ BlockNumReader, ChainSpecProvider, DatabaseProviderFactory, StaticFileProviderFactory, @@ -35,7 +35,7 @@ pub struct InitStateCommandOp { without_ovm: bool, } -impl> InitStateCommandOp { +impl> InitStateCommandOp { /// Execute the `init` command pub async fn execute>( self, diff --git a/crates/optimism/cli/src/commands/mod.rs b/crates/optimism/cli/src/commands/mod.rs index 41a19e3ded5e..a7674ec2c9bf 100644 --- a/crates/optimism/cli/src/commands/mod.rs +++ b/crates/optimism/cli/src/commands/mod.rs @@ -2,7 +2,6 @@ use crate::chainspec::OpChainSpecParser; use clap::Subcommand; use import::ImportOpCommand; use import_receipts::ImportReceiptsOpCommand; -use reth_chainspec::ChainSpec; use reth_cli::chainspec::ChainSpecParser; use reth_cli_commands::{ config_cmd, db, dump_genesis, init_cmd, @@ -19,10 +18,8 @@ pub mod init_state; /// Commands to be executed #[derive(Debug, Subcommand)] -pub enum Commands< - Spec: ChainSpecParser = OpChainSpecParser, - Ext: clap::Args + fmt::Debug = NoArgs, -> { +pub enum Commands +{ /// Start the node #[command(name = "node")] Node(Box>), diff --git a/crates/optimism/cli/src/lib.rs b/crates/optimism/cli/src/lib.rs index ea8a77087faf..b17cefa63287 100644 --- a/crates/optimism/cli/src/lib.rs +++ b/crates/optimism/cli/src/lib.rs @@ -28,6 +28,7 @@ pub mod commands; pub mod receipt_file_codec; pub use commands::{import::ImportOpCommand, import_receipts::ImportReceiptsOpCommand}; +use reth_optimism_chainspec::OpChainSpec; use std::{ffi::OsString, fmt, sync::Arc}; @@ -35,7 +36,7 @@ use chainspec::OpChainSpecParser; use clap::{command, value_parser, Parser}; use commands::Commands; use futures_util::Future; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthChainSpec; use reth_cli::chainspec::ChainSpecParser; use reth_cli_commands::node::NoArgs; use reth_cli_runner::CliRunner; @@ -55,10 +56,7 @@ use tracing::info; /// This is the entrypoint to the executable. #[derive(Debug, Parser)] #[command(author, version = SHORT_VERSION, long_version = LONG_VERSION, about = "Reth", long_about = None)] -pub struct Cli< - Spec: ChainSpecParser = OpChainSpecParser, - Ext: clap::Args + fmt::Debug = NoArgs, -> { +pub struct Cli { /// The command to run #[command(subcommand)] command: Commands, @@ -112,9 +110,9 @@ impl Cli { } } -impl Cli +impl Cli where - Spec: ChainSpecParser, + C: ChainSpecParser, Ext: clap::Args + fmt::Debug, { /// Execute the configured cli command. @@ -123,12 +121,12 @@ where /// [`NodeCommand`](reth_cli_commands::node::NodeCommand). pub fn run(mut self, launcher: L) -> eyre::Result<()> where - L: FnOnce(WithLaunchContext, ChainSpec>>, Ext) -> Fut, + L: FnOnce(WithLaunchContext, C::ChainSpec>>, Ext) -> Fut, Fut: Future>, { // add network name to logs dir self.logs.log_file_directory = - self.logs.log_file_directory.join(self.chain.chain.to_string()); + self.logs.log_file_directory.join(self.chain.chain().to_string()); let _guard = self.init_tracing()?; info!(target: "reth::cli", "Initialized tracing, debug log directory: {}", self.logs.log_file_directory); diff --git a/crates/optimism/consensus/Cargo.toml b/crates/optimism/consensus/Cargo.toml index c18eaea50226..f5f061c59929 100644 --- a/crates/optimism/consensus/Cargo.toml +++ b/crates/optimism/consensus/Cargo.toml @@ -21,6 +21,7 @@ reth-trie-common.workspace = true # op-reth reth-optimism-forks.workspace = true +reth-optimism-chainspec.workspace = true # ethereum alloy-primitives.workspace = true diff --git a/crates/optimism/consensus/src/lib.rs b/crates/optimism/consensus/src/lib.rs index d040d32e04d1..fe67ff1bcd9e 100644 --- a/crates/optimism/consensus/src/lib.rs +++ b/crates/optimism/consensus/src/lib.rs @@ -10,7 +10,7 @@ #![cfg(feature = "optimism")] use alloy_primitives::{B64, U256}; -use reth_chainspec::{ChainSpec, EthereumHardforks}; +use reth_chainspec::EthereumHardforks; use reth_consensus::{Consensus, ConsensusError, PostExecutionInput}; use reth_consensus_common::validation::{ validate_against_parent_4844, validate_against_parent_eip1559_base_fee, @@ -18,6 +18,7 @@ use reth_consensus_common::validation::{ validate_header_base_fee, validate_header_extradata, validate_header_gas, validate_shanghai_withdrawals, }; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_forks::OptimismHardforks; use reth_primitives::{ BlockWithSenders, GotExpected, Header, SealedBlock, SealedHeader, EMPTY_OMMER_ROOT_HASH, @@ -36,17 +37,12 @@ pub use validation::validate_block_post_execution; #[derive(Debug, Clone, PartialEq, Eq)] pub struct OptimismBeaconConsensus { /// Configuration - chain_spec: Arc, + chain_spec: Arc, } impl OptimismBeaconConsensus { /// Create a new instance of [`OptimismBeaconConsensus`] - /// - /// # Panics - /// - /// If given chain spec is not optimism [`ChainSpec::is_optimism`] - pub fn new(chain_spec: Arc) -> Self { - assert!(chain_spec.is_optimism(), "optimism consensus only valid for optimism chains"); + pub const fn new(chain_spec: Arc) -> Self { Self { chain_spec } } } diff --git a/crates/optimism/evm/src/execute.rs b/crates/optimism/evm/src/execute.rs index e855b38fbdcf..2f49ce5147dd 100644 --- a/crates/optimism/evm/src/execute.rs +++ b/crates/optimism/evm/src/execute.rs @@ -32,23 +32,20 @@ use tracing::trace; /// Provides executors to execute regular optimism blocks #[derive(Debug, Clone)] pub struct OpExecutorProvider { - chain_spec: Arc, + chain_spec: Arc, evm_config: EvmConfig, } impl OpExecutorProvider { /// Creates a new default optimism executor provider. - pub fn optimism(chain_spec: Arc) -> Self { - Self::new( - chain_spec.clone(), - OptimismEvmConfig::new(Arc::new(OpChainSpec { inner: (*chain_spec).clone() })), - ) + pub fn optimism(chain_spec: Arc) -> Self { + Self::new(chain_spec.clone(), OptimismEvmConfig::new(chain_spec)) } } impl OpExecutorProvider { /// Creates a new executor provider. - pub const fn new(chain_spec: Arc, evm_config: EvmConfig) -> Self { + pub const fn new(chain_spec: Arc, evm_config: EvmConfig) -> Self { Self { chain_spec, evm_config } } } @@ -98,7 +95,7 @@ where #[derive(Debug, Clone)] pub struct OpEvmExecutor { /// The chainspec - chain_spec: Arc, + chain_spec: Arc, /// How to create an EVM. evm_config: EvmConfig, } @@ -240,7 +237,11 @@ pub struct OpBlockExecutor { impl OpBlockExecutor { /// Creates a new Optimism block executor. - pub const fn new(chain_spec: Arc, evm_config: EvmConfig, state: State) -> Self { + pub const fn new( + chain_spec: Arc, + evm_config: EvmConfig, + state: State, + ) -> Self { Self { executor: OpEvmExecutor { chain_spec, evm_config }, state } } @@ -504,12 +505,8 @@ mod tests { } fn executor_provider(chain_spec: Arc) -> OpExecutorProvider { - OpExecutorProvider { - evm_config: OptimismEvmConfig::new(Arc::new(OpChainSpec { - inner: (*chain_spec).clone(), - })), - chain_spec, - } + let chain_spec = Arc::new(OpChainSpec::new(Arc::unwrap_or_clone(chain_spec))); + OpExecutorProvider { evm_config: OptimismEvmConfig::new(chain_spec.clone()), chain_spec } } #[test] diff --git a/crates/optimism/evm/src/l1.rs b/crates/optimism/evm/src/l1.rs index 7bc8cfed1c55..a54bf08ce525 100644 --- a/crates/optimism/evm/src/l1.rs +++ b/crates/optimism/evm/src/l1.rs @@ -4,6 +4,7 @@ use crate::OptimismBlockExecutionError; use alloy_primitives::{address, b256, hex, Address, Bytes, B256, U256}; use reth_chainspec::ChainSpec; use reth_execution_errors::BlockExecutionError; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_forks::OptimismHardfork; use reth_primitives::Block; use revm::{ @@ -260,7 +261,7 @@ impl RethL1BlockInfo for L1BlockInfo { /// deployer contract. This is done by directly setting the code of the create2 deployer account /// prior to executing any transactions on the timestamp activation of the fork. pub fn ensure_create2_deployer( - chain_spec: Arc, + chain_spec: Arc, timestamp: u64, db: &mut revm::State, ) -> Result<(), DB::Error> diff --git a/crates/optimism/node/src/engine.rs b/crates/optimism/node/src/engine.rs index 06059083ff57..a9adadd3068e 100644 --- a/crates/optimism/node/src/engine.rs +++ b/crates/optimism/node/src/engine.rs @@ -14,6 +14,7 @@ use reth_node_api::{ }, validate_version_specific_fields, EngineTypes, EngineValidator, }; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_forks::OptimismHardfork; use reth_optimism_payload_builder::{OptimismBuiltPayload, OptimismPayloadBuilderAttributes}; @@ -25,12 +26,12 @@ pub struct OptimismEngineTypes; /// Validator for Optimism engine API. #[derive(Debug, Clone)] pub struct OptimismEngineValidator { - chain_spec: Arc, + chain_spec: Arc, } impl OptimismEngineValidator { /// Instantiates a new validator. - pub const fn new(chain_spec: Arc) -> Self { + pub const fn new(chain_spec: Arc) -> Self { Self { chain_spec } } } diff --git a/crates/optimism/node/src/node.rs b/crates/optimism/node/src/node.rs index 2a28d44e2a0d..d82cb70a3ffe 100644 --- a/crates/optimism/node/src/node.rs +++ b/crates/optimism/node/src/node.rs @@ -3,7 +3,6 @@ use std::sync::Arc; use reth_basic_payload_builder::{BasicPayloadJobGenerator, BasicPayloadJobGeneratorConfig}; -use reth_chainspec::ChainSpec; use reth_evm::ConfigureEvm; use reth_network::{NetworkHandle, NetworkManager}; use reth_node_api::{EngineValidator, FullNodeComponents, NodeAddOns}; @@ -63,7 +62,7 @@ impl OptimismNode { > where Node: FullNodeTypes< - Types: NodeTypesWithEngine, + Types: NodeTypesWithEngine, >, { let RollupArgs { disable_txpool_gossip, compute_pending_block, discovery_v4, .. } = args; @@ -84,7 +83,7 @@ impl OptimismNode { impl Node for OptimismNode where N: FullNodeTypes< - Types: NodeTypesWithEngine, + Types: NodeTypesWithEngine, >, { type ComponentsBuilder = ComponentsBuilder< @@ -107,7 +106,7 @@ where impl NodeTypes for OptimismNode { type Primitives = (); - type ChainSpec = ChainSpec; + type ChainSpec = OpChainSpec; } impl NodeTypesWithEngine for OptimismNode { @@ -129,7 +128,7 @@ pub struct OptimismExecutorBuilder; impl ExecutorBuilder for OptimismExecutorBuilder where - Node: FullNodeTypes>, + Node: FullNodeTypes>, { type EVM = OptimismEvmConfig; type Executor = OpExecutorProvider; @@ -138,10 +137,8 @@ where self, ctx: &BuilderContext, ) -> eyre::Result<(Self::EVM, Self::Executor)> { - let chain_spec = ctx.chain_spec(); - let evm_config = - OptimismEvmConfig::new(Arc::new(OpChainSpec { inner: (*chain_spec).clone() })); - let executor = OpExecutorProvider::new(chain_spec, evm_config.clone()); + let evm_config = OptimismEvmConfig::new(ctx.chain_spec()); + let executor = OpExecutorProvider::new(ctx.chain_spec(), evm_config.clone()); Ok((evm_config, executor)) } @@ -157,7 +154,7 @@ pub struct OptimismPoolBuilder; impl PoolBuilder for OptimismPoolBuilder where - Node: FullNodeTypes>, + Node: FullNodeTypes>, { type Pool = OpTransactionPool; @@ -165,21 +162,19 @@ where let data_dir = ctx.config().datadir(); let blob_store = DiskFileBlobStore::open(data_dir.blobstore(), Default::default())?; - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.chain_spec()) - .with_head_timestamp(ctx.head().timestamp) - .kzg_settings(ctx.kzg_settings()?) - .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) - .build_with_tasks( - ctx.provider().clone(), - ctx.task_executor().clone(), - blob_store.clone(), - ) - .map(|validator| { - OpTransactionValidator::new(validator) - // In --dev mode we can't require gas fees because we're unable to decode the L1 - // block info - .require_l1_data_gas_fee(!ctx.config().dev.dev) - }); + let validator = TransactionValidationTaskExecutor::eth_builder(Arc::new( + ctx.chain_spec().inner.clone(), + )) + .with_head_timestamp(ctx.head().timestamp) + .kzg_settings(ctx.kzg_settings()?) + .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) + .build_with_tasks(ctx.provider().clone(), ctx.task_executor().clone(), blob_store.clone()) + .map(|validator| { + OpTransactionValidator::new(validator) + // In --dev mode we can't require gas fees because we're unable to decode + // the L1 block info + .require_l1_data_gas_fee(!ctx.config().dev.dev) + }); let transaction_pool = reth_transaction_pool::Pool::new( validator, @@ -256,7 +251,7 @@ impl OptimismPayloadBuilder { ) -> eyre::Result> where Node: FullNodeTypes< - Types: NodeTypesWithEngine, + Types: NodeTypesWithEngine, >, Pool: TransactionPool + Unpin + 'static, Evm: ConfigureEvm
, @@ -292,7 +287,7 @@ impl OptimismPayloadBuilder { impl PayloadServiceBuilder for OptimismPayloadBuilder where Node: FullNodeTypes< - Types: NodeTypesWithEngine, + Types: NodeTypesWithEngine, >, Pool: TransactionPool + Unpin + 'static, { @@ -301,11 +296,7 @@ where ctx: &BuilderContext, pool: Pool, ) -> eyre::Result> { - self.spawn( - OptimismEvmConfig::new(Arc::new(OpChainSpec { inner: (*ctx.chain_spec()).clone() })), - ctx, - pool, - ) + self.spawn(OptimismEvmConfig::new(ctx.chain_spec()), ctx, pool) } } @@ -320,7 +311,7 @@ pub struct OptimismNetworkBuilder { impl NetworkBuilder for OptimismNetworkBuilder where - Node: FullNodeTypes>, + Node: FullNodeTypes>, Pool: TransactionPool + Unpin + 'static, { async fn build_network( @@ -377,7 +368,7 @@ pub struct OptimismConsensusBuilder; impl ConsensusBuilder for OptimismConsensusBuilder where - Node: FullNodeTypes>, + Node: FullNodeTypes>, { type Consensus = Arc; @@ -397,7 +388,7 @@ pub struct OptimismEngineValidatorBuilder; impl EngineValidatorBuilder for OptimismEngineValidatorBuilder where - Types: NodeTypesWithEngine, + Types: NodeTypesWithEngine, Node: FullNodeTypes, OptimismEngineValidator: EngineValidator, { diff --git a/crates/optimism/node/tests/e2e/utils.rs b/crates/optimism/node/tests/e2e/utils.rs index a8dda7b9956b..1e9ffa652f1c 100644 --- a/crates/optimism/node/tests/e2e/utils.rs +++ b/crates/optimism/node/tests/e2e/utils.rs @@ -5,7 +5,7 @@ use alloy_primitives::{Address, B256}; use reth::{rpc::types::engine::PayloadAttributes, tasks::TaskManager}; use reth_chainspec::ChainSpecBuilder; use reth_e2e_test_utils::{transaction::TransactionTestContext, wallet::Wallet, NodeHelperType}; -use reth_optimism_chainspec::BASE_MAINNET; +use reth_optimism_chainspec::{OpChainSpec, BASE_MAINNET}; use reth_optimism_node::{ node::OptimismAddOns, OptimismBuiltPayload, OptimismNode, OptimismPayloadBuilderAttributes, }; @@ -19,13 +19,13 @@ pub(crate) async fn setup(num_nodes: usize) -> eyre::Result<(Vec, TaskMa let genesis: Genesis = serde_json::from_str(include_str!("../assets/genesis.json")).unwrap(); reth_e2e_test_utils::setup( num_nodes, - Arc::new( + Arc::new(OpChainSpec::new( ChainSpecBuilder::default() .chain(BASE_MAINNET.chain) .genesis(genesis) .ecotone_activated() .build(), - ), + )), false, ) .await diff --git a/crates/optimism/node/tests/it/builder.rs b/crates/optimism/node/tests/it/builder.rs index 8d5cc1554e3d..df1dd71fb086 100644 --- a/crates/optimism/node/tests/it/builder.rs +++ b/crates/optimism/node/tests/it/builder.rs @@ -3,12 +3,13 @@ use reth_db::test_utils::create_test_rw_db; use reth_node_api::FullNodeComponents; use reth_node_builder::{NodeBuilder, NodeConfig}; -use reth_optimism_node::node::{OptimismAddOns, OptimismNode}; +use reth_optimism_node::{node::OptimismAddOns, OptimismNode}; +use reth_primitives::BASE_MAINNET; #[test] fn test_basic_setup() { // parse CLI -> config - let config = NodeConfig::test(); + let config = NodeConfig::new(BASE_MAINNET.clone()); let db = create_test_rw_db(); let _builder = NodeBuilder::new(config) .with_database(db) diff --git a/crates/optimism/payload/Cargo.toml b/crates/optimism/payload/Cargo.toml index 047879929be6..e731b50c0767 100644 --- a/crates/optimism/payload/Cargo.toml +++ b/crates/optimism/payload/Cargo.toml @@ -28,6 +28,7 @@ reth-trie.workspace = true reth-chain-state.workspace = true # op-reth +reth-optimism-chainspec.workspace = true reth-optimism-consensus.workspace = true reth-optimism-evm.workspace = true reth-optimism-forks.workspace = true diff --git a/crates/optimism/payload/src/builder.rs b/crates/optimism/payload/src/builder.rs index 878e9cf224de..1c0876b2a726 100644 --- a/crates/optimism/payload/src/builder.rs +++ b/crates/optimism/payload/src/builder.rs @@ -5,12 +5,13 @@ use std::sync::Arc; use alloy_primitives::U256; use reth_basic_payload_builder::*; use reth_chain_state::ExecutedBlock; -use reth_chainspec::{ChainSpec, ChainSpecProvider, EthereumHardforks}; +use reth_chainspec::{ChainSpecProvider, EthereumHardforks}; use reth_evm::{ system_calls::pre_block_beacon_root_contract_call, ConfigureEvm, ConfigureEvmEnv, NextBlockEnvAttributes, }; use reth_execution_types::ExecutionOutcome; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_consensus::calculate_receipt_root_no_memo_optimism; use reth_optimism_forks::OptimismHardfork; use reth_payload_primitives::{PayloadBuilderAttributes, PayloadBuilderError}; @@ -94,7 +95,7 @@ where /// Implementation of the [`PayloadBuilder`] trait for [`OptimismPayloadBuilder`]. impl PayloadBuilder for OptimismPayloadBuilder where - Client: StateProviderFactory + ChainSpecProvider, + Client: StateProviderFactory + ChainSpecProvider, Pool: TransactionPool, EvmConfig: ConfigureEvm
, { @@ -165,7 +166,7 @@ pub(crate) fn optimism_payload( ) -> Result, PayloadBuilderError> where EvmConfig: ConfigureEvm
, - Client: StateProviderFactory + ChainSpecProvider, + Client: StateProviderFactory + ChainSpecProvider, Pool: TransactionPool, { let BuildArguments { client, pool, mut cached_reads, config, cancel, best_payload } = args; diff --git a/crates/optimism/payload/src/payload.rs b/crates/optimism/payload/src/payload.rs index 67eddb8e18b7..ac73f05390ff 100644 --- a/crates/optimism/payload/src/payload.rs +++ b/crates/optimism/payload/src/payload.rs @@ -11,7 +11,8 @@ use op_alloy_rpc_types_engine::{ OptimismExecutionPayloadEnvelopeV3, OptimismExecutionPayloadEnvelopeV4, }; use reth_chain_state::ExecutedBlock; -use reth_chainspec::{ChainSpec, EthereumHardforks}; +use reth_chainspec::EthereumHardforks; +use reth_optimism_chainspec::OpChainSpec; use reth_payload_builder::EthPayloadBuilderAttributes; use reth_payload_primitives::{BuiltPayload, PayloadBuilderAttributes}; use reth_primitives::{ @@ -119,7 +120,7 @@ pub struct OptimismBuiltPayload { /// empty. pub(crate) sidecars: Vec, /// The rollup's chainspec. - pub(crate) chain_spec: Arc, + pub(crate) chain_spec: Arc, /// The payload attributes. pub(crate) attributes: OptimismPayloadBuilderAttributes, } @@ -132,7 +133,7 @@ impl OptimismBuiltPayload { id: PayloadId, block: SealedBlock, fees: U256, - chain_spec: Arc, + chain_spec: Arc, attributes: OptimismPayloadBuilderAttributes, executed_block: Option, ) -> Self { diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index 97ac850c4f06..46967fba262d 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -28,6 +28,7 @@ reth-node-builder.workspace = true reth-chainspec.workspace = true # op-reth +reth-optimism-chainspec.workspace = true reth-optimism-consensus.workspace = true reth-optimism-evm.workspace = true reth-optimism-forks.workspace = true diff --git a/crates/optimism/rpc/src/eth/block.rs b/crates/optimism/rpc/src/eth/block.rs index da799e140d8e..a0565fcc4486 100644 --- a/crates/optimism/rpc/src/eth/block.rs +++ b/crates/optimism/rpc/src/eth/block.rs @@ -3,8 +3,9 @@ use alloy_rpc_types::BlockId; use op_alloy_network::Network; use op_alloy_rpc_types::OpTransactionReceipt; -use reth_chainspec::{ChainSpec, ChainSpecProvider}; +use reth_chainspec::ChainSpecProvider; use reth_node_api::{FullNodeComponents, NodeTypes}; +use reth_optimism_chainspec::OpChainSpec; use reth_primitives::TransactionMeta; use reth_provider::{BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_api::{ @@ -21,7 +22,7 @@ where Error = OpEthApiError, NetworkTypes: Network, >, - N: FullNodeComponents>, + N: FullNodeComponents>, { #[inline] fn provider(&self) -> impl HeaderProvider { diff --git a/crates/optimism/rpc/src/eth/call.rs b/crates/optimism/rpc/src/eth/call.rs index ded4c656b063..3d39b5e22750 100644 --- a/crates/optimism/rpc/src/eth/call.rs +++ b/crates/optimism/rpc/src/eth/call.rs @@ -1,6 +1,6 @@ use alloy_primitives::{Bytes, TxKind, U256}; use alloy_rpc_types_eth::transaction::TransactionRequest; -use reth_chainspec::ChainSpec; +use reth_chainspec::EthereumHardforks; use reth_evm::ConfigureEvm; use reth_node_api::{FullNodeComponents, NodeTypes}; use reth_primitives::{ @@ -18,7 +18,7 @@ use crate::{OpEthApi, OpEthApiError}; impl EthCall for OpEthApi where Self: Call, - N: FullNodeComponents>, + N: FullNodeComponents>, { } diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 403e3b8a73b8..844ea170075b 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -14,7 +14,7 @@ use std::{fmt, sync::Arc}; use alloy_primitives::U256; use derive_more::Deref; use op_alloy_network::Optimism; -use reth_chainspec::{ChainSpec, EthereumHardforks}; +use reth_chainspec::EthereumHardforks; use reth_evm::ConfigureEvm; use reth_network_api::NetworkInfo; use reth_node_api::{BuilderProvider, FullNodeComponents, FullNodeTypes, NodeTypes}; @@ -239,7 +239,7 @@ where impl AddDevSigners for OpEthApi where - N: FullNodeComponents>, + N: FullNodeComponents>, { fn with_dev_accounts(&self) { *self.signers().write() = DevSigner::random_signers(20) diff --git a/crates/optimism/rpc/src/eth/receipt.rs b/crates/optimism/rpc/src/eth/receipt.rs index bfd521635bce..a953d3f3096f 100644 --- a/crates/optimism/rpc/src/eth/receipt.rs +++ b/crates/optimism/rpc/src/eth/receipt.rs @@ -7,6 +7,7 @@ use op_alloy_rpc_types::{ }; use reth_chainspec::ChainSpec; use reth_node_api::{FullNodeComponents, NodeTypes}; +use reth_optimism_chainspec::OpChainSpec; use reth_optimism_evm::RethL1BlockInfo; use reth_optimism_forks::OptimismHardforks; use reth_primitives::{Receipt, TransactionMeta, TransactionSigned, TxType}; @@ -19,7 +20,7 @@ use crate::{OpEthApi, OpEthApiError}; impl LoadReceipt for OpEthApi where Self: Send + Sync, - N: FullNodeComponents>, + N: FullNodeComponents>, { #[inline] fn cache(&self) -> &EthStateCache { @@ -205,7 +206,7 @@ pub struct OpReceiptBuilder { impl OpReceiptBuilder { /// Returns a new builder. pub fn new( - chain_spec: &ChainSpec, + chain_spec: &OpChainSpec, transaction: &TransactionSigned, meta: TransactionMeta, receipt: &Receipt, diff --git a/crates/revm/src/state_change.rs b/crates/revm/src/state_change.rs index bd967a23d31d..a4f5c6cb04a8 100644 --- a/crates/revm/src/state_change.rs +++ b/crates/revm/src/state_change.rs @@ -1,5 +1,5 @@ use alloy_primitives::{map::HashMap, Address}; -use reth_chainspec::{ChainSpec, EthereumHardforks}; +use reth_chainspec::EthereumHardforks; use reth_consensus_common::calc; use reth_primitives::{Block, Withdrawal, Withdrawals, U256}; @@ -8,7 +8,7 @@ use reth_primitives::{Block, Withdrawal, Withdrawals, U256}; /// Balance changes might include the block reward, uncle rewards, withdrawals, or irregular /// state changes (DAO fork). #[inline] -pub fn post_block_balance_increments( +pub fn post_block_balance_increments( chain_spec: &ChainSpec, block: &Block, total_difficulty: U256, @@ -89,6 +89,7 @@ pub fn insert_post_block_withdrawals_balance_increments { } impl DbTool { - /// Get an [`Arc`] to the [`ChainSpec`]. + /// Get an [`Arc`] to the underlying chainspec. pub fn chain(&self) -> Arc { self.provider_factory.chain_spec() } @@ -110,7 +109,7 @@ impl DbTool { } } -impl> DbTool { +impl DbTool { /// Takes a DB where the tables have already been created. pub fn new(provider_factory: ProviderFactory) -> eyre::Result { // Disable timeout because we are entering a TUI which might read for a long time. We diff --git a/crates/storage/db-common/src/init.rs b/crates/storage/db-common/src/init.rs index 6e94677abfc6..83786153312d 100644 --- a/crates/storage/db-common/src/init.rs +++ b/crates/storage/db-common/src/init.rs @@ -2,7 +2,7 @@ use alloy_genesis::GenesisAccount; use alloy_primitives::{Address, B256, U256}; -use reth_chainspec::{ChainSpec, EthChainSpec}; +use reth_chainspec::EthChainSpec; use reth_codecs::Compact; use reth_config::config::EtlConfig; use reth_db::tables; @@ -333,7 +333,7 @@ where Provider: DBProvider + BlockNumReader + BlockHashReader - + ChainSpecProvider + + ChainSpecProvider + StageCheckpointWriter + HistoryWriter + HeaderProvider @@ -366,7 +366,7 @@ where debug!(target: "reth::cli", block, - chain=%provider_rw.chain_spec().chain, + chain=%provider_rw.chain_spec().chain(), "Initializing state at block" ); @@ -582,7 +582,7 @@ struct GenesisAccountWithAddress { mod tests { use super::*; use alloy_genesis::Genesis; - use reth_chainspec::{Chain, HOLESKY, MAINNET, SEPOLIA}; + use reth_chainspec::{Chain, ChainSpec, HOLESKY, MAINNET, SEPOLIA}; use reth_db::DatabaseEnv; use reth_db_api::{ cursor::DbCursorRO, diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index baa35edaf6f4..ce37cb2e7a8d 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -13,7 +13,7 @@ use futures_util::{ FutureExt, Stream, StreamExt, }; use reth_chain_state::CanonStateNotification; -use reth_chainspec::{ChainSpec, ChainSpecProvider}; +use reth_chainspec::{ChainSpecProvider, EthChainSpec}; use reth_execution_types::ChangedAccount; use reth_fs_util::FsPathError; use reth_primitives::{ @@ -74,12 +74,7 @@ pub fn maintain_transaction_pool_future( config: MaintainPoolConfig, ) -> BoxFuture<'static, ()> where - Client: StateProviderFactory - + BlockReaderIdExt - + ChainSpecProvider - + Clone - + Send - + 'static, + Client: StateProviderFactory + BlockReaderIdExt + ChainSpecProvider + Clone + Send + 'static, P: TransactionPoolExt + 'static, St: Stream + Send + Unpin + 'static, Tasks: TaskSpawner + 'static, @@ -100,12 +95,7 @@ pub async fn maintain_transaction_pool( task_spawner: Tasks, config: MaintainPoolConfig, ) where - Client: StateProviderFactory - + BlockReaderIdExt - + ChainSpecProvider - + Clone - + Send - + 'static, + Client: StateProviderFactory + BlockReaderIdExt + ChainSpecProvider + Clone + Send + 'static, P: TransactionPoolExt + 'static, St: Stream + Send + Unpin + 'static, Tasks: TaskSpawner + 'static,