1use crate::{
4 args::{
5 DatabaseArgs, DatadirArgs, DebugArgs, DevArgs, EngineArgs, NetworkArgs, PayloadBuilderArgs,
6 PruningArgs, RpcServerArgs, StaticFilesArgs, StorageArgs, 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 StorageSettings,
25};
26use reth_storage_errors::provider::ProviderResult;
27use reth_transaction_pool::TransactionPool;
28use serde::{de::DeserializeOwned, Serialize};
29use std::{
30 fs,
31 path::{Path, PathBuf},
32 sync::Arc,
33};
34use tracing::*;
35
36use crate::args::{EraArgs, MetricArgs};
37pub use reth_engine_primitives::{
38 DEFAULT_MEMORY_BLOCK_BUFFER_TARGET, DEFAULT_PERSISTENCE_THRESHOLD, DEFAULT_RESERVED_CPU_CORES,
39};
40
41pub const DEFAULT_CROSS_BLOCK_CACHE_SIZE_MB: usize = 4 * 1024;
43
44#[derive(Debug)]
90pub struct NodeConfig<ChainSpec> {
91 pub datadir: DatadirArgs,
93
94 pub config: Option<PathBuf>,
96
97 pub chain: Arc<ChainSpec>,
101
102 pub metrics: MetricArgs,
104
105 pub instance: Option<u16>,
121
122 pub network: NetworkArgs,
124
125 pub rpc: RpcServerArgs,
127
128 pub txpool: TxPoolArgs,
130
131 pub builder: PayloadBuilderArgs,
133
134 pub debug: DebugArgs,
136
137 pub db: DatabaseArgs,
139
140 pub dev: DevArgs,
142
143 pub pruning: PruningArgs,
145
146 pub engine: EngineArgs,
148
149 pub era: EraArgs,
151
152 pub static_files: StaticFilesArgs,
154
155 pub storage: StorageArgs,
157}
158
159impl NodeConfig<ChainSpec> {
160 pub fn test() -> Self {
162 Self::default()
163 .with_unused_ports()
165 }
166}
167
168impl<ChainSpec> NodeConfig<ChainSpec> {
169 pub fn new(chain: Arc<ChainSpec>) -> Self {
171 Self {
172 config: None,
173 chain,
174 metrics: MetricArgs::default(),
175 instance: None,
176 network: NetworkArgs::default(),
177 rpc: RpcServerArgs::default(),
178 txpool: TxPoolArgs::default(),
179 builder: PayloadBuilderArgs::default(),
180 debug: DebugArgs::default(),
181 db: DatabaseArgs::default(),
182 dev: DevArgs::default(),
183 pruning: PruningArgs::default(),
184 datadir: DatadirArgs::default(),
185 engine: EngineArgs::default(),
186 era: EraArgs::default(),
187 static_files: StaticFilesArgs::default(),
188 storage: StorageArgs::default(),
189 }
190 }
191
192 pub const fn dev(mut self) -> Self {
197 self.dev.dev = true;
198 self.network.discovery.disable_discovery = true;
199 self
200 }
201
202 pub fn apply<F>(self, f: F) -> Self
204 where
205 F: FnOnce(Self) -> Self,
206 {
207 f(self)
208 }
209
210 pub fn try_apply<F, R>(self, f: F) -> Result<Self, R>
212 where
213 F: FnOnce(Self) -> Result<Self, R>,
214 {
215 f(self)
216 }
217
218 pub const fn set_dev(self, dev: bool) -> Self {
220 if dev {
221 self.dev()
222 } else {
223 self
224 }
225 }
226
227 pub fn with_datadir_args(mut self, datadir_args: DatadirArgs) -> Self {
229 self.datadir = datadir_args;
230 self
231 }
232
233 pub fn with_config(mut self, config: impl Into<PathBuf>) -> Self {
235 self.config = Some(config.into());
236 self
237 }
238
239 pub fn with_chain(mut self, chain: impl Into<Arc<ChainSpec>>) -> Self {
241 self.chain = chain.into();
242 self
243 }
244
245 pub fn map_chain<C>(self, chain: impl Into<Arc<C>>) -> NodeConfig<C> {
247 let Self {
248 datadir,
249 config,
250 metrics,
251 instance,
252 network,
253 rpc,
254 txpool,
255 builder,
256 debug,
257 db,
258 dev,
259 pruning,
260 engine,
261 era,
262 static_files,
263 storage,
264 ..
265 } = self;
266 NodeConfig {
267 datadir,
268 config,
269 chain: chain.into(),
270 metrics,
271 instance,
272 network,
273 rpc,
274 txpool,
275 builder,
276 debug,
277 db,
278 dev,
279 pruning,
280 engine,
281 era,
282 static_files,
283 storage,
284 }
285 }
286
287 pub fn with_metrics(mut self, metrics: MetricArgs) -> Self {
289 self.metrics = metrics;
290 self
291 }
292
293 pub const fn with_instance(mut self, instance: u16) -> Self {
295 self.instance = Some(instance);
296 self
297 }
298
299 pub fn get_instance(&self) -> u16 {
301 self.instance.unwrap_or(1)
302 }
303
304 pub fn with_network(mut self, network: NetworkArgs) -> Self {
306 self.network = network;
307 self
308 }
309
310 pub fn with_rpc(mut self, rpc: RpcServerArgs) -> Self {
312 self.rpc = rpc;
313 self
314 }
315
316 pub fn with_txpool(mut self, txpool: TxPoolArgs) -> Self {
318 self.txpool = txpool;
319 self
320 }
321
322 pub fn with_payload_builder(mut self, builder: PayloadBuilderArgs) -> Self {
324 self.builder = builder;
325 self
326 }
327
328 pub fn with_debug(mut self, debug: DebugArgs) -> Self {
330 self.debug = debug;
331 self
332 }
333
334 pub const fn with_db(mut self, db: DatabaseArgs) -> Self {
336 self.db = db;
337 self
338 }
339
340 pub fn with_dev(mut self, dev: DevArgs) -> Self {
342 self.dev = dev;
343 self
344 }
345
346 pub fn with_pruning(mut self, pruning: PruningArgs) -> Self {
348 self.pruning = pruning;
349 self
350 }
351
352 pub const fn with_storage(mut self, storage: StorageArgs) -> Self {
354 self.storage = storage;
355 self
356 }
357
358 pub fn prune_config(&self) -> Option<PruneConfig>
360 where
361 ChainSpec: EthereumHardforks,
362 {
363 self.pruning.prune_config(&self.chain)
364 }
365
366 pub const fn storage_settings(&self) -> StorageSettings {
372 if self.storage.v2 {
373 StorageSettings::v2()
374 } else {
375 StorageSettings::base()
376 }
377 }
378
379 pub async fn max_block<Provider, Client>(
382 &self,
383 network_client: Client,
384 provider: Provider,
385 ) -> eyre::Result<Option<BlockNumber>>
386 where
387 Provider: HeaderProvider,
388 Client: HeadersClient<Header: reth_primitives_traits::BlockHeader>,
389 {
390 let max_block = if let Some(block) = self.debug.max_block {
391 Some(block)
392 } else if let Some(tip) = self.debug.tip {
393 Some(self.lookup_or_fetch_tip(provider, network_client, tip).await?)
394 } else {
395 None
396 };
397
398 Ok(max_block)
399 }
400
401 pub fn lookup_head<Factory>(&self, factory: &Factory) -> ProviderResult<Head>
405 where
406 Factory: DatabaseProviderFactory<
407 Provider: HeaderProvider + StageCheckpointReader + BlockHashReader,
408 >,
409 {
410 let provider = factory.database_provider_ro()?;
411
412 let head = provider.get_stage_checkpoint(StageId::Finish)?.unwrap_or_default().block_number;
413
414 let header = provider
415 .header_by_number(head)?
416 .expect("the header for the latest block is missing, database is corrupt");
417
418 let hash = provider
419 .block_hash(head)?
420 .expect("the hash for the latest block is missing, database is corrupt");
421
422 Ok(Head {
423 number: head,
424 hash,
425 difficulty: header.difficulty(),
426 total_difficulty: U256::ZERO,
427 timestamp: header.timestamp(),
428 })
429 }
430
431 pub async fn lookup_or_fetch_tip<Provider, Client>(
436 &self,
437 provider: Provider,
438 client: Client,
439 tip: B256,
440 ) -> ProviderResult<u64>
441 where
442 Provider: HeaderProvider,
443 Client: HeadersClient<Header: reth_primitives_traits::BlockHeader>,
444 {
445 let header = provider.header_by_hash_or_number(tip.into())?;
446
447 if let Some(header) = header {
449 info!(target: "reth::cli", ?tip, "Successfully looked up tip block in the database");
450 return Ok(header.number())
451 }
452
453 Ok(self.fetch_tip_from_network(client, tip.into()).await.number())
454 }
455
456 pub async fn fetch_tip_from_network<Client>(
460 &self,
461 client: Client,
462 tip: BlockHashOrNumber,
463 ) -> SealedHeader<Client::Header>
464 where
465 Client: HeadersClient<Header: reth_primitives_traits::BlockHeader>,
466 {
467 info!(target: "reth::cli", ?tip, "Fetching tip block from the network.");
468 let mut fetch_failures = 0;
469 loop {
470 match get_single_header(&client, tip).await {
471 Ok(tip_header) => {
472 info!(target: "reth::cli", ?tip, "Successfully fetched tip");
473 return tip_header
474 }
475 Err(error) => {
476 fetch_failures += 1;
477 if fetch_failures % 20 == 0 {
478 error!(target: "reth::cli", ?fetch_failures, %error, "Failed to fetch the tip. Retrying...");
479 }
480 }
481 }
482 }
483 }
484
485 pub fn adjust_instance_ports(&mut self) {
488 self.network.adjust_instance_ports(self.instance);
489 self.rpc.adjust_instance_ports(self.instance);
490 }
491
492 pub fn with_unused_ports(mut self) -> Self {
495 self.rpc = self.rpc.with_unused_ports();
496 self.network = self.network.with_unused_ports();
497 self
498 }
499
500 pub const fn with_disabled_discovery(mut self) -> Self {
502 self.network.discovery.disable_discovery = true;
503 self
504 }
505
506 pub const fn with_disabled_rpc_cache(mut self) -> Self {
511 self.rpc.rpc_state_cache.set_zero_lengths();
512 self
513 }
514
515 pub fn datadir(&self) -> ChainPath<DataDirPath>
517 where
518 ChainSpec: EthChainSpec,
519 {
520 self.datadir.clone().resolve_datadir(self.chain.chain())
521 }
522
523 pub fn load_path<T: Serialize + DeserializeOwned + Default>(
528 path: impl AsRef<Path>,
529 ) -> eyre::Result<T> {
530 let path = path.as_ref();
531 match fs::read_to_string(path) {
532 Ok(cfg_string) => {
533 toml::from_str(&cfg_string).map_err(|e| eyre!("Failed to parse TOML: {e}"))
534 }
535 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
536 if let Some(parent) = path.parent() {
537 fs::create_dir_all(parent)
538 .map_err(|e| eyre!("Failed to create directory: {e}"))?;
539 }
540 let cfg = T::default();
541 let s = toml::to_string_pretty(&cfg)
542 .map_err(|e| eyre!("Failed to serialize to TOML: {e}"))?;
543 fs::write(path, s).map_err(|e| eyre!("Failed to write configuration file: {e}"))?;
544 Ok(cfg)
545 }
546 Err(e) => Err(eyre!("Failed to load configuration: {e}")),
547 }
548 }
549
550 pub fn map_chainspec<F, C>(self, f: F) -> NodeConfig<C>
552 where
553 F: FnOnce(Arc<ChainSpec>) -> C,
554 {
555 let chain = Arc::new(f(self.chain));
556 NodeConfig {
557 chain,
558 datadir: self.datadir,
559 config: self.config,
560 metrics: self.metrics,
561 instance: self.instance,
562 network: self.network,
563 rpc: self.rpc,
564 txpool: self.txpool,
565 builder: self.builder,
566 debug: self.debug,
567 db: self.db,
568 dev: self.dev,
569 pruning: self.pruning,
570 engine: self.engine,
571 era: self.era,
572 static_files: self.static_files,
573 storage: self.storage,
574 }
575 }
576
577 pub fn dev_mining_mode<Pool>(&self, pool: Pool) -> MiningMode<Pool>
579 where
580 Pool: TransactionPool + Unpin,
581 {
582 if let Some(interval) = self.dev.block_time {
583 MiningMode::interval(interval)
584 } else {
585 MiningMode::instant(pool, self.dev.block_max_transactions)
586 }
587 }
588}
589
590impl Default for NodeConfig<ChainSpec> {
591 fn default() -> Self {
592 Self::new(MAINNET.clone())
593 }
594}
595
596impl<ChainSpec> Clone for NodeConfig<ChainSpec> {
597 fn clone(&self) -> Self {
598 Self {
599 chain: self.chain.clone(),
600 config: self.config.clone(),
601 metrics: self.metrics.clone(),
602 instance: self.instance,
603 network: self.network.clone(),
604 rpc: self.rpc.clone(),
605 txpool: self.txpool.clone(),
606 builder: self.builder.clone(),
607 debug: self.debug.clone(),
608 db: self.db,
609 dev: self.dev.clone(),
610 pruning: self.pruning.clone(),
611 datadir: self.datadir.clone(),
612 engine: self.engine.clone(),
613 era: self.era.clone(),
614 static_files: self.static_files,
615 storage: self.storage,
616 }
617 }
618}