reth_node_core/
node_config.rs

1//! Support for customizing the node
2
3use crate::{
4    args::{
5        DatabaseArgs, DatadirArgs, DebugArgs, DevArgs, EngineArgs, NetworkArgs, PayloadBuilderArgs,
6        PruningArgs, RpcServerArgs, TxPoolArgs,
7    },
8    dirs::{ChainPath, DataDirPath},
9    utils::get_single_header,
10};
11use alloy_consensus::BlockHeader;
12use alloy_eips::BlockHashOrNumber;
13use alloy_primitives::{BlockNumber, B256, U256};
14use eyre::eyre;
15use reth_chainspec::{ChainSpec, EthChainSpec, MAINNET};
16use reth_config::config::PruneConfig;
17use reth_engine_local::MiningMode;
18use reth_ethereum_forks::{EthereumHardforks, Head};
19use reth_network_p2p::headers::client::HeadersClient;
20use reth_primitives_traits::SealedHeader;
21use reth_stages_types::StageId;
22use reth_storage_api::{
23    BlockHashReader, DatabaseProviderFactory, HeaderProvider, StageCheckpointReader,
24};
25use reth_storage_errors::provider::ProviderResult;
26use reth_transaction_pool::TransactionPool;
27use serde::{de::DeserializeOwned, Serialize};
28use std::{
29    fs,
30    path::{Path, PathBuf},
31    sync::Arc,
32};
33use tracing::*;
34
35use crate::args::{EraArgs, MetricArgs};
36pub use reth_engine_primitives::{
37    DEFAULT_MEMORY_BLOCK_BUFFER_TARGET, DEFAULT_PERSISTENCE_THRESHOLD, DEFAULT_RESERVED_CPU_CORES,
38};
39
40/// Default size of cross-block cache in megabytes.
41pub const DEFAULT_CROSS_BLOCK_CACHE_SIZE_MB: u64 = 4 * 1024;
42
43/// This includes all necessary configuration to launch the node.
44/// The individual configuration options can be overwritten before launching the node.
45///
46/// # Example
47/// ```rust
48/// # use reth_node_core::{
49/// #     node_config::NodeConfig,
50/// #     args::RpcServerArgs,
51/// # };
52/// # use reth_rpc_server_types::RpcModuleSelection;
53/// # use tokio::runtime::Handle;
54///
55/// async fn t() {
56///     // create the builder
57///     let builder = NodeConfig::default();
58///
59///     // configure the rpc apis
60///     let mut rpc = RpcServerArgs::default().with_http().with_ws();
61///     rpc.http_api = Some(RpcModuleSelection::All);
62///     let builder = builder.with_rpc(rpc);
63/// }
64/// ```
65///
66/// This can also be used to launch a node with a temporary test database. This can be done with
67/// the [`NodeConfig::test`] method.
68///
69/// # Example
70/// ```rust
71/// # use reth_node_core::{
72/// #     node_config::NodeConfig,
73/// #     args::RpcServerArgs,
74/// # };
75/// # use reth_rpc_server_types::RpcModuleSelection;
76/// # use tokio::runtime::Handle;
77///
78/// async fn t() {
79///     // create the builder with a test database, using the `test` method
80///     let builder = NodeConfig::test();
81///
82///     // configure the rpc apis
83///     let mut rpc = RpcServerArgs::default().with_http().with_ws();
84///     rpc.http_api = Some(RpcModuleSelection::All);
85///     let builder = builder.with_rpc(rpc);
86/// }
87/// ```
88#[derive(Debug)]
89pub struct NodeConfig<ChainSpec> {
90    /// All data directory related arguments
91    pub datadir: DatadirArgs,
92
93    /// The path to the configuration file to use.
94    pub config: Option<PathBuf>,
95
96    /// The chain this node is running.
97    ///
98    /// Possible values are either a built-in chain or the path to a chain specification file.
99    pub chain: Arc<ChainSpec>,
100
101    /// Enable to configure metrics export to endpoints
102    pub metrics: MetricArgs,
103
104    /// Add a new instance of a node.
105    ///
106    /// Configures the ports of the node to avoid conflicts with the defaults.
107    /// This is useful for running multiple nodes on the same machine.
108    ///
109    /// Max number of instances is 200. It is chosen in a way so that it's not possible to have
110    /// port numbers that conflict with each other.
111    ///
112    /// Changes to the following port numbers:
113    /// - `DISCOVERY_PORT`: default + `instance` - 1
114    /// - `DISCOVERY_V5_PORT`: default + `instance` - 1
115    /// - `AUTH_PORT`: default + `instance` * 100 - 100
116    /// - `HTTP_RPC_PORT`: default - `instance` + 1
117    /// - `WS_RPC_PORT`: default + `instance` * 2 - 2
118    /// - `IPC_PATH`: default + `instance`
119    pub instance: Option<u16>,
120
121    /// All networking related arguments
122    pub network: NetworkArgs,
123
124    /// All rpc related arguments
125    pub rpc: RpcServerArgs,
126
127    /// All txpool related arguments with --txpool prefix
128    pub txpool: TxPoolArgs,
129
130    /// All payload builder related arguments
131    pub builder: PayloadBuilderArgs,
132
133    /// All debug related arguments with --debug prefix
134    pub debug: DebugArgs,
135
136    /// All database related arguments
137    pub db: DatabaseArgs,
138
139    /// All dev related arguments with --dev prefix
140    pub dev: DevArgs,
141
142    /// All pruning related arguments
143    pub pruning: PruningArgs,
144
145    /// All engine related arguments
146    pub engine: EngineArgs,
147
148    /// All ERA import related arguments with --era prefix
149    pub era: EraArgs,
150}
151
152impl NodeConfig<ChainSpec> {
153    /// Creates a testing [`NodeConfig`], causing the database to be launched ephemerally.
154    pub fn test() -> Self {
155        Self::default()
156            // set all ports to zero by default for test instances
157            .with_unused_ports()
158    }
159}
160
161impl<ChainSpec> NodeConfig<ChainSpec> {
162    /// Creates a new config with given chain spec, setting all fields to default values.
163    pub fn new(chain: Arc<ChainSpec>) -> Self {
164        Self {
165            config: None,
166            chain,
167            metrics: MetricArgs::default(),
168            instance: None,
169            network: NetworkArgs::default(),
170            rpc: RpcServerArgs::default(),
171            txpool: TxPoolArgs::default(),
172            builder: PayloadBuilderArgs::default(),
173            debug: DebugArgs::default(),
174            db: DatabaseArgs::default(),
175            dev: DevArgs::default(),
176            pruning: PruningArgs::default(),
177            datadir: DatadirArgs::default(),
178            engine: EngineArgs::default(),
179            era: EraArgs::default(),
180        }
181    }
182
183    /// Sets --dev mode for the node.
184    ///
185    /// In addition to setting the `--dev` flag, this also:
186    ///   - disables discovery in [`NetworkArgs`].
187    pub const fn dev(mut self) -> Self {
188        self.dev.dev = true;
189        self.network.discovery.disable_discovery = true;
190        self
191    }
192
193    /// Apply a function to the config.
194    pub fn apply<F>(self, f: F) -> Self
195    where
196        F: FnOnce(Self) -> Self,
197    {
198        f(self)
199    }
200
201    /// Applies a fallible function to the config.
202    pub fn try_apply<F, R>(self, f: F) -> Result<Self, R>
203    where
204        F: FnOnce(Self) -> Result<Self, R>,
205    {
206        f(self)
207    }
208
209    /// Sets --dev mode for the node [`NodeConfig::dev`], if `dev` is true.
210    pub const fn set_dev(self, dev: bool) -> Self {
211        if dev {
212            self.dev()
213        } else {
214            self
215        }
216    }
217
218    /// Set the data directory args for the node
219    pub fn with_datadir_args(mut self, datadir_args: DatadirArgs) -> Self {
220        self.datadir = datadir_args;
221        self
222    }
223
224    /// Set the config file for the node
225    pub fn with_config(mut self, config: impl Into<PathBuf>) -> Self {
226        self.config = Some(config.into());
227        self
228    }
229
230    /// Set the [`ChainSpec`] for the node
231    pub fn with_chain(mut self, chain: impl Into<Arc<ChainSpec>>) -> Self {
232        self.chain = chain.into();
233        self
234    }
235
236    /// Set the metrics address for the node
237    pub fn with_metrics(mut self, metrics: MetricArgs) -> Self {
238        self.metrics = metrics;
239        self
240    }
241
242    /// Set the instance for the node
243    pub const fn with_instance(mut self, instance: u16) -> Self {
244        self.instance = Some(instance);
245        self
246    }
247
248    /// Returns the instance value, defaulting to 1 if not set.
249    pub fn get_instance(&self) -> u16 {
250        self.instance.unwrap_or(1)
251    }
252
253    /// Set the network args for the node
254    pub fn with_network(mut self, network: NetworkArgs) -> Self {
255        self.network = network;
256        self
257    }
258
259    /// Set the rpc args for the node
260    pub fn with_rpc(mut self, rpc: RpcServerArgs) -> Self {
261        self.rpc = rpc;
262        self
263    }
264
265    /// Set the txpool args for the node
266    pub fn with_txpool(mut self, txpool: TxPoolArgs) -> Self {
267        self.txpool = txpool;
268        self
269    }
270
271    /// Set the builder args for the node
272    pub fn with_payload_builder(mut self, builder: PayloadBuilderArgs) -> Self {
273        self.builder = builder;
274        self
275    }
276
277    /// Set the debug args for the node
278    pub fn with_debug(mut self, debug: DebugArgs) -> Self {
279        self.debug = debug;
280        self
281    }
282
283    /// Set the database args for the node
284    pub const fn with_db(mut self, db: DatabaseArgs) -> Self {
285        self.db = db;
286        self
287    }
288
289    /// Set the dev args for the node
290    pub fn with_dev(mut self, dev: DevArgs) -> Self {
291        self.dev = dev;
292        self
293    }
294
295    /// Set the pruning args for the node
296    pub fn with_pruning(mut self, pruning: PruningArgs) -> Self {
297        self.pruning = pruning;
298        self
299    }
300
301    /// Returns pruning configuration.
302    pub fn prune_config(&self) -> Option<PruneConfig>
303    where
304        ChainSpec: EthereumHardforks,
305    {
306        self.pruning.prune_config(&self.chain)
307    }
308
309    /// Returns the max block that the node should run to, looking it up from the network if
310    /// necessary
311    pub async fn max_block<Provider, Client>(
312        &self,
313        network_client: Client,
314        provider: Provider,
315    ) -> eyre::Result<Option<BlockNumber>>
316    where
317        Provider: HeaderProvider,
318        Client: HeadersClient<Header: reth_primitives_traits::BlockHeader>,
319    {
320        let max_block = if let Some(block) = self.debug.max_block {
321            Some(block)
322        } else if let Some(tip) = self.debug.tip {
323            Some(self.lookup_or_fetch_tip(provider, network_client, tip).await?)
324        } else {
325            None
326        };
327
328        Ok(max_block)
329    }
330
331    /// Fetches the head block from the database.
332    ///
333    /// If the database is empty, returns the genesis block.
334    pub fn lookup_head<Factory>(&self, factory: &Factory) -> ProviderResult<Head>
335    where
336        Factory: DatabaseProviderFactory<
337            Provider: HeaderProvider + StageCheckpointReader + BlockHashReader,
338        >,
339    {
340        let provider = factory.database_provider_ro()?;
341
342        let head = provider.get_stage_checkpoint(StageId::Finish)?.unwrap_or_default().block_number;
343
344        let header = provider
345            .header_by_number(head)?
346            .expect("the header for the latest block is missing, database is corrupt");
347
348        let hash = provider
349            .block_hash(head)?
350            .expect("the hash for the latest block is missing, database is corrupt");
351
352        Ok(Head {
353            number: head,
354            hash,
355            difficulty: header.difficulty(),
356            total_difficulty: U256::ZERO,
357            timestamp: header.timestamp(),
358        })
359    }
360
361    /// Attempt to look up the block number for the tip hash in the database.
362    /// If it doesn't exist, download the header and return the block number.
363    ///
364    /// NOTE: The download is attempted with infinite retries.
365    pub async fn lookup_or_fetch_tip<Provider, Client>(
366        &self,
367        provider: Provider,
368        client: Client,
369        tip: B256,
370    ) -> ProviderResult<u64>
371    where
372        Provider: HeaderProvider,
373        Client: HeadersClient<Header: reth_primitives_traits::BlockHeader>,
374    {
375        let header = provider.header_by_hash_or_number(tip.into())?;
376
377        // try to look up the header in the database
378        if let Some(header) = header {
379            info!(target: "reth::cli", ?tip, "Successfully looked up tip block in the database");
380            return Ok(header.number())
381        }
382
383        Ok(self.fetch_tip_from_network(client, tip.into()).await.number())
384    }
385
386    /// Attempt to look up the block with the given number and return the header.
387    ///
388    /// NOTE: The download is attempted with infinite retries.
389    pub async fn fetch_tip_from_network<Client>(
390        &self,
391        client: Client,
392        tip: BlockHashOrNumber,
393    ) -> SealedHeader<Client::Header>
394    where
395        Client: HeadersClient<Header: reth_primitives_traits::BlockHeader>,
396    {
397        info!(target: "reth::cli", ?tip, "Fetching tip block from the network.");
398        let mut fetch_failures = 0;
399        loop {
400            match get_single_header(&client, tip).await {
401                Ok(tip_header) => {
402                    info!(target: "reth::cli", ?tip, "Successfully fetched tip");
403                    return tip_header
404                }
405                Err(error) => {
406                    fetch_failures += 1;
407                    if fetch_failures % 20 == 0 {
408                        error!(target: "reth::cli", ?fetch_failures, %error, "Failed to fetch the tip. Retrying...");
409                    }
410                }
411            }
412        }
413    }
414
415    /// Change rpc port numbers based on the instance number, using the inner
416    /// [`RpcServerArgs::adjust_instance_ports`] method.
417    pub fn adjust_instance_ports(&mut self) {
418        self.network.adjust_instance_ports(self.instance);
419        self.rpc.adjust_instance_ports(self.instance);
420    }
421
422    /// Sets networking and RPC ports to zero, causing the OS to choose random unused ports when
423    /// sockets are bound.
424    pub fn with_unused_ports(mut self) -> Self {
425        self.rpc = self.rpc.with_unused_ports();
426        self.network = self.network.with_unused_ports();
427        self
428    }
429
430    /// Effectively disables the RPC state cache by setting the cache sizes to `0`.
431    ///
432    /// By setting the cache sizes to 0, caching of newly executed or fetched blocks will be
433    /// effectively disabled.
434    pub const fn with_disabled_rpc_cache(mut self) -> Self {
435        self.rpc.rpc_state_cache.set_zero_lengths();
436        self
437    }
438
439    /// Resolve the final datadir path.
440    pub fn datadir(&self) -> ChainPath<DataDirPath>
441    where
442        ChainSpec: EthChainSpec,
443    {
444        self.datadir.clone().resolve_datadir(self.chain.chain())
445    }
446
447    /// Load an application configuration from a specified path.
448    ///
449    /// A new configuration file is created with default values if none
450    /// exists.
451    pub fn load_path<T: Serialize + DeserializeOwned + Default>(
452        path: impl AsRef<Path>,
453    ) -> eyre::Result<T> {
454        let path = path.as_ref();
455        match fs::read_to_string(path) {
456            Ok(cfg_string) => {
457                toml::from_str(&cfg_string).map_err(|e| eyre!("Failed to parse TOML: {e}"))
458            }
459            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
460                if let Some(parent) = path.parent() {
461                    fs::create_dir_all(parent)
462                        .map_err(|e| eyre!("Failed to create directory: {e}"))?;
463                }
464                let cfg = T::default();
465                let s = toml::to_string_pretty(&cfg)
466                    .map_err(|e| eyre!("Failed to serialize to TOML: {e}"))?;
467                fs::write(path, s).map_err(|e| eyre!("Failed to write configuration file: {e}"))?;
468                Ok(cfg)
469            }
470            Err(e) => Err(eyre!("Failed to load configuration: {e}")),
471        }
472    }
473
474    /// Modifies the [`ChainSpec`] generic of the config using the provided closure.
475    pub fn map_chainspec<F, C>(self, f: F) -> NodeConfig<C>
476    where
477        F: FnOnce(Arc<ChainSpec>) -> C,
478    {
479        let chain = Arc::new(f(self.chain));
480        NodeConfig {
481            chain,
482            datadir: self.datadir,
483            config: self.config,
484            metrics: self.metrics,
485            instance: self.instance,
486            network: self.network,
487            rpc: self.rpc,
488            txpool: self.txpool,
489            builder: self.builder,
490            debug: self.debug,
491            db: self.db,
492            dev: self.dev,
493            pruning: self.pruning,
494            engine: self.engine,
495            era: self.era,
496        }
497    }
498
499    /// Returns the [`MiningMode`] intended for --dev mode.
500    pub fn dev_mining_mode<Pool>(&self, pool: Pool) -> MiningMode<Pool>
501    where
502        Pool: TransactionPool + Unpin,
503    {
504        if let Some(interval) = self.dev.block_time {
505            MiningMode::interval(interval)
506        } else {
507            MiningMode::instant(pool, self.dev.block_max_transactions)
508        }
509    }
510}
511
512impl Default for NodeConfig<ChainSpec> {
513    fn default() -> Self {
514        Self::new(MAINNET.clone())
515    }
516}
517
518impl<ChainSpec> Clone for NodeConfig<ChainSpec> {
519    fn clone(&self) -> Self {
520        Self {
521            chain: self.chain.clone(),
522            config: self.config.clone(),
523            metrics: self.metrics.clone(),
524            instance: self.instance,
525            network: self.network.clone(),
526            rpc: self.rpc.clone(),
527            txpool: self.txpool.clone(),
528            builder: self.builder.clone(),
529            debug: self.debug.clone(),
530            db: self.db,
531            dev: self.dev.clone(),
532            pruning: self.pruning.clone(),
533            datadir: self.datadir.clone(),
534            engine: self.engine.clone(),
535            era: self.era.clone(),
536        }
537    }
538}