Skip to content

Commit

Permalink
feat: make NodeConfig generic over ChainSpec (#11039)
Browse files Browse the repository at this point in the history
  • Loading branch information
klkvr committed Sep 19, 2024
1 parent 65fb29c commit c3d090a
Show file tree
Hide file tree
Showing 16 changed files with 185 additions and 105 deletions.
2 changes: 1 addition & 1 deletion bin/reth/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl<C: ChainSpecParser<ChainSpec = ChainSpec>, Ext: clap::Args + fmt::Debug> Cl
/// ````
pub fn run<L, Fut>(mut self, launcher: L) -> eyre::Result<()>
where
L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>>>, Ext) -> Fut,
L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>, C::ChainSpec>>, Ext) -> Fut,
Fut: Future<Output = eyre::Result<()>>,
{
// add network name to logs dir
Expand Down
24 changes: 23 additions & 1 deletion crates/chainspec/src/api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::ChainSpec;
use crate::{ChainSpec, DepositContract};
use alloy_chains::Chain;
use alloy_eips::eip1559::BaseFeeParams;
use alloy_primitives::B256;
use core::fmt::Debug;

/// Trait representing type configuring a chain spec.
Expand All @@ -14,6 +15,15 @@ pub trait EthChainSpec: Send + Sync + Unpin + Debug + 'static {

/// Get the [`BaseFeeParams`] for the chain at the given timestamp.
fn base_fee_params_at_timestamp(&self, timestamp: u64) -> BaseFeeParams;

/// Returns the deposit contract data for the chain, if it's present
fn deposit_contract(&self) -> Option<&DepositContract>;

/// The genesis hash.
fn genesis_hash(&self) -> B256;

/// The delete limit for pruner, per run.
fn prune_delete_limit(&self) -> usize;
}

impl EthChainSpec for ChainSpec {
Expand All @@ -24,4 +34,16 @@ impl EthChainSpec for ChainSpec {
fn base_fee_params_at_timestamp(&self, timestamp: u64) -> BaseFeeParams {
self.base_fee_params_at_timestamp(timestamp)
}

fn deposit_contract(&self) -> Option<&DepositContract> {
self.deposit_contract.as_ref()
}

fn genesis_hash(&self) -> B256 {
self.genesis_hash()
}

fn prune_delete_limit(&self) -> usize {
self.prune_delete_limit
}
}
2 changes: 1 addition & 1 deletion crates/cli/commands/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ impl<C: ChainSpecParser<ChainSpec = ChainSpec>, Ext: clap::Args + fmt::Debug> No
/// closure.
pub async fn execute<L, Fut>(self, ctx: CliContext, launcher: L) -> eyre::Result<()>
where
L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>>>, Ext) -> Fut,
L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>, C::ChainSpec>>, Ext) -> Fut,
Fut: Future<Output = eyre::Result<()>>,
{
tracing::info!(target: "reth::cli", version = ?version::SHORT_VERSION, "Starting reth");
Expand Down
2 changes: 1 addition & 1 deletion crates/ethereum/node/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ pub struct EthereumNetworkBuilder {

impl<Node, Pool> NetworkBuilder<Node, Pool> for EthereumNetworkBuilder
where
Node: FullNodeTypes,
Node: FullNodeTypes<Types: NodeTypes<ChainSpec = ChainSpec>>,
Pool: TransactionPool + Unpin + 'static,
{
async fn build_network(
Expand Down
4 changes: 2 additions & 2 deletions crates/exex/exex/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::Debug;

use reth_node_api::{FullNodeComponents, NodeTypesWithEngine};
use reth_node_api::{FullNodeComponents, NodeTypes, NodeTypesWithEngine};
use reth_node_core::node_config::NodeConfig;
use reth_primitives::Head;
use reth_tasks::TaskExecutor;
Expand All @@ -13,7 +13,7 @@ pub struct ExExContext<Node: FullNodeComponents> {
/// The current head of the blockchain at launch.
pub head: Head,
/// The config of the node
pub config: NodeConfig,
pub config: NodeConfig<<Node::Types as NodeTypes>::ChainSpec>,
/// The loaded node config
pub reth_config: reth_config::Config,
/// Channel used to send [`ExExEvent`]s to the rest of the node.
Expand Down
95 changes: 51 additions & 44 deletions crates/node/builder/src/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub use states::*;
use std::sync::Arc;

use futures::Future;
use reth_chainspec::ChainSpec;
use reth_chainspec::{ChainSpec, EthChainSpec};
use reth_cli_util::get_secret_key;
use reth_db_api::{
database::Database,
Expand Down Expand Up @@ -154,28 +154,30 @@ pub type RethFullAdapter<DB, Types> = FullNodeTypesAdapter<
/// configured by the builder itself during launch. This might change in the future.
///
/// [builder]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
pub struct NodeBuilder<DB> {
pub struct NodeBuilder<DB, ChainSpec> {
/// All settings for how the node should be configured.
config: NodeConfig,
config: NodeConfig<ChainSpec>,
/// The configured database for the node.
database: DB,
}

impl NodeBuilder<()> {
impl<ChainSpec> NodeBuilder<(), ChainSpec> {
/// Create a new [`NodeBuilder`].
pub const fn new(config: NodeConfig) -> Self {
pub const fn new(config: NodeConfig<ChainSpec>) -> Self {
Self { config, database: () }
}
}

impl<DB> NodeBuilder<DB> {
impl<DB, ChainSpec> NodeBuilder<DB, ChainSpec> {
/// Returns a reference to the node builder's config.
pub const fn config(&self) -> &NodeConfig {
pub const fn config(&self) -> &NodeConfig<ChainSpec> {
&self.config
}
}

impl<DB, ChainSpec: EthChainSpec> NodeBuilder<DB, ChainSpec> {
/// Configures the underlying database that the node will use.
pub fn with_database<D>(self, database: D) -> NodeBuilder<D> {
pub fn with_database<D>(self, database: D) -> NodeBuilder<D, ChainSpec> {
NodeBuilder { config: self.config, database }
}

Expand All @@ -191,8 +193,9 @@ impl<DB> NodeBuilder<DB> {
pub fn testing_node(
mut self,
task_executor: TaskExecutor,
) -> WithLaunchContext<NodeBuilder<Arc<reth_db::test_utils::TempDatabase<reth_db::DatabaseEnv>>>>
{
) -> WithLaunchContext<
NodeBuilder<Arc<reth_db::test_utils::TempDatabase<reth_db::DatabaseEnv>>, ChainSpec>,
> {
let path = reth_node_core::dirs::MaybePlatformPath::<DataDirPath>::from(
reth_db::test_utils::tempdir_path(),
);
Expand All @@ -202,15 +205,15 @@ impl<DB> NodeBuilder<DB> {
});

let data_dir =
path.unwrap_or_chain_default(self.config.chain.chain, self.config.datadir.clone());
path.unwrap_or_chain_default(self.config.chain.chain(), self.config.datadir.clone());

let db = reth_db::test_utils::create_test_rw_db_with_path(data_dir.db());

WithLaunchContext { builder: self.with_database(db), task_executor }
}
}

impl<DB> NodeBuilder<DB>
impl<DB> NodeBuilder<DB, ChainSpec>
where
DB: Database + DatabaseMetrics + DatabaseMetadata + Clone + Unpin + 'static,
{
Expand Down Expand Up @@ -263,15 +266,17 @@ impl<Builder> WithLaunchContext<Builder> {
}
}

impl<DB> WithLaunchContext<NodeBuilder<DB>>
where
DB: Database + DatabaseMetrics + DatabaseMetadata + Clone + Unpin + 'static,
{
impl<DB, ChainSpec> WithLaunchContext<NodeBuilder<DB, ChainSpec>> {
/// Returns a reference to the node builder's config.
pub const fn config(&self) -> &NodeConfig {
pub const fn config(&self) -> &NodeConfig<ChainSpec> {
self.builder.config()
}
}

impl<DB> WithLaunchContext<NodeBuilder<DB, ChainSpec>>
where
DB: Database + DatabaseMetrics + DatabaseMetadata + Clone + Unpin + 'static,
{
/// Configures the types of the node.
pub fn with_types<T>(self) -> WithLaunchContext<NodeBuilderWithTypes<RethFullAdapter<DB, T>>>
where
Expand Down Expand Up @@ -395,7 +400,7 @@ where
AO: NodeAddOns<NodeAdapter<T, CB::Components>, EthApi: FullEthApiServer + AddDevSigners>,
{
/// Returns a reference to the node builder's config.
pub const fn config(&self) -> &NodeConfig {
pub const fn config(&self) -> &NodeConfig<<T::Types as NodeTypes>::ChainSpec> {
&self.builder.config
}

Expand Down Expand Up @@ -520,7 +525,7 @@ pub struct BuilderContext<Node: FullNodeTypes> {
/// The executor of the node.
pub(crate) executor: TaskExecutor,
/// Config container
pub(crate) config_container: WithConfigs,
pub(crate) config_container: WithConfigs<<Node::Types as NodeTypes>::ChainSpec>,
}

impl<Node: FullNodeTypes> BuilderContext<Node> {
Expand All @@ -529,7 +534,7 @@ impl<Node: FullNodeTypes> BuilderContext<Node> {
head: Head,
provider: Node::Provider,
executor: TaskExecutor,
config_container: WithConfigs,
config_container: WithConfigs<<Node::Types as NodeTypes>::ChainSpec>,
) -> Self {
Self { head, provider, executor, config_container }
}
Expand All @@ -545,7 +550,7 @@ impl<Node: FullNodeTypes> BuilderContext<Node> {
}

/// Returns the config of the node.
pub const fn config(&self) -> &NodeConfig {
pub const fn config(&self) -> &NodeConfig<<Node::Types as NodeTypes>::ChainSpec> {
&self.config_container.config
}

Expand Down Expand Up @@ -586,13 +591,6 @@ impl<Node: FullNodeTypes> BuilderContext<Node> {
self.config().builder.clone()
}

/// Creates the [`NetworkBuilder`] for the node.
pub async fn network_builder(&self) -> eyre::Result<NetworkBuilder<(), ()>> {
let network_config = self.network_config()?;
let builder = NetworkManager::builder(network_config).await?;
Ok(builder)
}

/// Convenience function to start the network.
///
/// Spawns the configured network and associated tasks and returns the [`NetworkHandle`]
Expand Down Expand Up @@ -634,6 +632,31 @@ impl<Node: FullNodeTypes> BuilderContext<Node> {
handle
}

/// Get the network secret from the given data dir
fn network_secret(&self, data_dir: &ChainPath<DataDirPath>) -> eyre::Result<SecretKey> {
let network_secret_path =
self.config().network.p2p_secret_key.clone().unwrap_or_else(|| data_dir.p2p_secret());
let secret_key = get_secret_key(&network_secret_path)?;
Ok(secret_key)
}

/// Builds the [`NetworkConfig`].
pub fn build_network_config(
&self,
network_builder: NetworkConfigBuilder,
) -> NetworkConfig<Node::Provider> {
network_builder.build(self.provider.clone())
}
}

impl<Node: FullNodeTypes<Types: NodeTypes<ChainSpec = ChainSpec>>> BuilderContext<Node> {
/// Creates the [`NetworkBuilder`] for the node.
pub async fn network_builder(&self) -> eyre::Result<NetworkBuilder<(), ()>> {
let network_config = self.network_config()?;
let builder = NetworkManager::builder(network_config).await?;
Ok(builder)
}

/// Returns the default network config for the node.
pub fn network_config(&self) -> eyre::Result<NetworkConfig<Node::Provider>> {
let network_builder = self.network_config_builder();
Expand All @@ -658,22 +681,6 @@ impl<Node: FullNodeTypes> BuilderContext<Node> {

Ok(builder)
}

/// Get the network secret from the given data dir
fn network_secret(&self, data_dir: &ChainPath<DataDirPath>) -> eyre::Result<SecretKey> {
let network_secret_path =
self.config().network.p2p_secret_key.clone().unwrap_or_else(|| data_dir.p2p_secret());
let secret_key = get_secret_key(&network_secret_path)?;
Ok(secret_key)
}

/// Builds the [`NetworkConfig`].
pub fn build_network_config(
&self,
network_builder: NetworkConfigBuilder,
) -> NetworkConfig<Node::Provider> {
network_builder.build(self.provider.clone())
}
}

impl<Node: FullNodeTypes> std::fmt::Debug for BuilderContext<Node> {
Expand Down
11 changes: 7 additions & 4 deletions crates/node/builder/src/builder/states.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{fmt, future::Future, marker::PhantomData};

use reth_exex::ExExContext;
use reth_node_api::{
FullNodeComponents, FullNodeTypes, NodeAddOns, NodeTypesWithDB, NodeTypesWithEngine,
FullNodeComponents, FullNodeTypes, NodeAddOns, NodeTypes, NodeTypesWithDB, NodeTypesWithEngine,
};
use reth_node_core::{
node_config::NodeConfig,
Expand All @@ -29,14 +29,17 @@ use crate::{
/// A node builder that also has the configured types.
pub struct NodeBuilderWithTypes<T: FullNodeTypes> {
/// All settings for how the node should be configured.
config: NodeConfig,
config: NodeConfig<<T::Types as NodeTypes>::ChainSpec>,
/// The configured database for the node.
adapter: NodeTypesAdapter<T>,
}

impl<T: FullNodeTypes> NodeBuilderWithTypes<T> {
/// Creates a new instance of the node builder with the given configuration and types.
pub const fn new(config: NodeConfig, database: <T::Types as NodeTypesWithDB>::DB) -> Self {
pub const fn new(
config: NodeConfig<<T::Types as NodeTypes>::ChainSpec>,
database: <T::Types as NodeTypesWithDB>::DB,
) -> Self {
Self { config, adapter: NodeTypesAdapter::new(database) }
}

Expand Down Expand Up @@ -149,7 +152,7 @@ pub struct NodeBuilderWithComponents<
AO: NodeAddOns<NodeAdapter<T, CB::Components>>,
> {
/// All settings for how the node should be configured.
pub config: NodeConfig,
pub config: NodeConfig<<T::Types as NodeTypes>::ChainSpec>,
/// Adapter for the underlying node types and database
pub adapter: NodeTypesAdapter<T>,
/// container for type specific components
Expand Down
Loading

0 comments on commit c3d090a

Please sign in to comment.