1use crate::{
4 app::{run_commands_with, CliApp},
5 chainspec::EthereumChainSpecParser,
6};
7use clap::{Parser, Subcommand};
8use reth_chainspec::{ChainSpec, EthChainSpec, Hardforks};
9use reth_cli::chainspec::ChainSpecParser;
10use reth_cli_commands::{
11 common::{CliComponentsBuilder, CliNodeTypes, HeaderMut},
12 config_cmd, db, download, dump_genesis, export_era, import, import_era, init_cmd, init_state,
13 launcher::FnLauncher,
14 node::{self, NoArgs},
15 p2p, prune, re_execute, stage,
16};
17use reth_cli_runner::CliRunner;
18use reth_db::DatabaseEnv;
19use reth_node_api::NodePrimitives;
20use reth_node_builder::{NodeBuilder, WithLaunchContext};
21use reth_node_core::{
22 args::{LogArgs, OtlpInitStatus, TraceArgs},
23 version::version_metadata,
24};
25use reth_node_metrics::recorder::install_prometheus_recorder;
26use reth_rpc_server_types::{DefaultRpcModuleValidator, RpcModuleValidator};
27use reth_tracing::{FileWorkerGuard, Layers};
28use std::{ffi::OsString, fmt, future::Future, marker::PhantomData, sync::Arc};
29use tracing::{info, warn};
30
31#[derive(Debug, Parser)]
35#[command(author, name = version_metadata().name_client.as_ref(), version = version_metadata().short_version.as_ref(), long_version = version_metadata().long_version.as_ref(), about = "Reth", long_about = None)]
36pub struct Cli<
37 C: ChainSpecParser = EthereumChainSpecParser,
38 Ext: clap::Args + fmt::Debug = NoArgs,
39 Rpc: RpcModuleValidator = DefaultRpcModuleValidator,
40> {
41 #[command(subcommand)]
43 pub command: Commands<C, Ext>,
44
45 #[command(flatten)]
47 pub logs: LogArgs,
48
49 #[command(flatten)]
51 pub traces: TraceArgs,
52
53 #[arg(skip)]
55 pub _phantom: PhantomData<Rpc>,
56}
57
58impl Cli {
59 pub fn parse_args() -> Self {
61 Self::parse()
62 }
63
64 pub fn try_parse_args_from<I, T>(itr: I) -> Result<Self, clap::error::Error>
66 where
67 I: IntoIterator<Item = T>,
68 T: Into<OsString> + Clone,
69 {
70 Self::try_parse_from(itr)
71 }
72}
73
74impl<C: ChainSpecParser, Ext: clap::Args + fmt::Debug, Rpc: RpcModuleValidator> Cli<C, Ext, Rpc> {
75 pub fn configure(self) -> CliApp<C, Ext, Rpc>
80 where
81 C: ChainSpecParser<ChainSpec = ChainSpec>,
82 {
83 CliApp::new(self)
84 }
85
86 pub fn run<L, Fut>(self, launcher: L) -> eyre::Result<()>
129 where
130 L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>, C::ChainSpec>>, Ext) -> Fut,
131 Fut: Future<Output = eyre::Result<()>>,
132 C: ChainSpecParser<ChainSpec = ChainSpec>,
133 {
134 self.with_runner(CliRunner::try_default_runtime()?, launcher)
135 }
136
137 pub fn run_with_components<N>(
144 self,
145 components: impl CliComponentsBuilder<N>,
146 launcher: impl AsyncFnOnce(
147 WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>, C::ChainSpec>>,
148 Ext,
149 ) -> eyre::Result<()>,
150 ) -> eyre::Result<()>
151 where
152 N: CliNodeTypes<Primitives: NodePrimitives<BlockHeader: HeaderMut>, ChainSpec: Hardforks>,
153 C: ChainSpecParser<ChainSpec = N::ChainSpec>,
154 {
155 self.with_runner_and_components(CliRunner::try_default_runtime()?, components, launcher)
156 }
157
158 pub fn with_runner<L, Fut>(self, runner: CliRunner, launcher: L) -> eyre::Result<()>
178 where
179 L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>, C::ChainSpec>>, Ext) -> Fut,
180 Fut: Future<Output = eyre::Result<()>>,
181 C: ChainSpecParser<ChainSpec = ChainSpec>,
182 {
183 let mut app = self.configure();
184 app.set_runner(runner);
185 app.run(FnLauncher::new::<C, Ext>(async move |builder, ext| launcher(builder, ext).await))
186 }
187
188 pub fn with_runner_and_components<N>(
191 mut self,
192 runner: CliRunner,
193 components: impl CliComponentsBuilder<N>,
194 launcher: impl AsyncFnOnce(
195 WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>, C::ChainSpec>>,
196 Ext,
197 ) -> eyre::Result<()>,
198 ) -> eyre::Result<()>
199 where
200 N: CliNodeTypes<Primitives: NodePrimitives<BlockHeader: HeaderMut>, ChainSpec: Hardforks>,
201 C: ChainSpecParser<ChainSpec = N::ChainSpec>,
202 {
203 if let Some(chain_spec) = self.command.chain_spec() {
205 self.logs.log_file_directory =
206 self.logs.log_file_directory.join(chain_spec.chain().to_string());
207 }
208 let _guard = self.init_tracing(&runner, Layers::new())?;
209
210 let _ = install_prometheus_recorder();
212
213 run_commands_with::<C, Ext, Rpc, N>(self, runner, components, launcher)
215 }
216
217 pub fn init_tracing(
224 &mut self,
225 runner: &CliRunner,
226 mut layers: Layers,
227 ) -> eyre::Result<Option<FileWorkerGuard>> {
228 let otlp_status = runner.block_on(self.traces.init_otlp_tracing(&mut layers))?;
229
230 let guard = self.logs.init_tracing_with_layers(layers)?;
231 info!(target: "reth::cli", "Initialized tracing, debug log directory: {}", self.logs.log_file_directory);
232 match otlp_status {
233 OtlpInitStatus::Started(endpoint) => {
234 info!(target: "reth::cli", "Started OTLP {:?} tracing export to {endpoint}", self.traces.protocol);
235 }
236 OtlpInitStatus::NoFeature => {
237 warn!(target: "reth::cli", "Provided OTLP tracing arguments do not have effect, compile with the `otlp` feature")
238 }
239 OtlpInitStatus::Disabled => {}
240 }
241
242 Ok(guard)
243 }
244}
245
246#[derive(Debug, Subcommand)]
248pub enum Commands<C: ChainSpecParser, Ext: clap::Args + fmt::Debug> {
249 #[command(name = "node")]
251 Node(Box<node::NodeCommand<C, Ext>>),
252 #[command(name = "init")]
254 Init(init_cmd::InitCommand<C>),
255 #[command(name = "init-state")]
257 InitState(init_state::InitStateCommand<C>),
258 #[command(name = "import")]
260 Import(import::ImportCommand<C>),
261 #[command(name = "import-era")]
263 ImportEra(import_era::ImportEraCommand<C>),
264 #[command(name = "export-era")]
266 ExportEra(export_era::ExportEraCommand<C>),
267 DumpGenesis(dump_genesis::DumpGenesisCommand<C>),
269 #[command(name = "db")]
271 Db(Box<db::Command<C>>),
272 #[command(name = "download")]
274 Download(download::DownloadCommand<C>),
275 #[command(name = "stage")]
277 Stage(stage::Command<C>),
278 #[command(name = "p2p")]
280 P2P(Box<p2p::Command<C>>),
281 #[cfg(feature = "dev")]
283 #[command(name = "test-vectors")]
284 TestVectors(reth_cli_commands::test_vectors::Command),
285 #[command(name = "config")]
287 Config(config_cmd::Command),
288 #[command(name = "prune")]
290 Prune(prune::PruneCommand<C>),
291 #[command(name = "re-execute")]
293 ReExecute(re_execute::Command<C>),
294}
295
296impl<C: ChainSpecParser, Ext: clap::Args + fmt::Debug> Commands<C, Ext> {
297 pub fn chain_spec(&self) -> Option<&Arc<C::ChainSpec>> {
299 match self {
300 Self::Node(cmd) => cmd.chain_spec(),
301 Self::Init(cmd) => cmd.chain_spec(),
302 Self::InitState(cmd) => cmd.chain_spec(),
303 Self::Import(cmd) => cmd.chain_spec(),
304 Self::ExportEra(cmd) => cmd.chain_spec(),
305 Self::ImportEra(cmd) => cmd.chain_spec(),
306 Self::DumpGenesis(cmd) => cmd.chain_spec(),
307 Self::Db(cmd) => cmd.chain_spec(),
308 Self::Download(cmd) => cmd.chain_spec(),
309 Self::Stage(cmd) => cmd.chain_spec(),
310 Self::P2P(cmd) => cmd.chain_spec(),
311 #[cfg(feature = "dev")]
312 Self::TestVectors(_) => None,
313 Self::Config(_) => None,
314 Self::Prune(cmd) => cmd.chain_spec(),
315 Self::ReExecute(cmd) => cmd.chain_spec(),
316 }
317 }
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323 use crate::chainspec::SUPPORTED_CHAINS;
324 use clap::CommandFactory;
325 use reth_chainspec::SEPOLIA;
326 use reth_node_core::args::ColorMode;
327
328 #[test]
329 fn parse_color_mode() {
330 let reth = Cli::try_parse_args_from(["reth", "node", "--color", "always"]).unwrap();
331 assert_eq!(reth.logs.color, ColorMode::Always);
332 }
333
334 #[test]
338 fn test_parse_help_all_subcommands() {
339 let reth = Cli::<EthereumChainSpecParser, NoArgs>::command();
340 for sub_command in reth.get_subcommands() {
341 let err = Cli::try_parse_args_from(["reth", sub_command.get_name(), "--help"])
342 .err()
343 .unwrap_or_else(|| {
344 panic!("Failed to parse help message {}", sub_command.get_name())
345 });
346
347 assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
350 }
351 }
352
353 #[test]
356 fn parse_logs_path_node() {
357 let mut reth = Cli::try_parse_args_from(["reth", "node"]).unwrap();
358 if let Some(chain_spec) = reth.command.chain_spec() {
359 reth.logs.log_file_directory =
360 reth.logs.log_file_directory.join(chain_spec.chain.to_string());
361 }
362 let log_dir = reth.logs.log_file_directory;
363 let end = format!("reth/logs/{}", SUPPORTED_CHAINS[0]);
364 assert!(log_dir.as_ref().ends_with(end), "{log_dir:?}");
365
366 let mut iter = SUPPORTED_CHAINS.iter();
367 iter.next();
368 for chain in iter {
369 let mut reth = Cli::try_parse_args_from(["reth", "node", "--chain", chain]).unwrap();
370 let chain =
371 reth.command.chain_spec().map(|c| c.chain.to_string()).unwrap_or(String::new());
372 reth.logs.log_file_directory = reth.logs.log_file_directory.join(chain.clone());
373 let log_dir = reth.logs.log_file_directory;
374 let end = format!("reth/logs/{chain}");
375 assert!(log_dir.as_ref().ends_with(end), "{log_dir:?}");
376 }
377 }
378
379 #[test]
382 fn parse_logs_path_init() {
383 let mut reth = Cli::try_parse_args_from(["reth", "init"]).unwrap();
384 if let Some(chain_spec) = reth.command.chain_spec() {
385 reth.logs.log_file_directory =
386 reth.logs.log_file_directory.join(chain_spec.chain.to_string());
387 }
388 let log_dir = reth.logs.log_file_directory;
389 let end = format!("reth/logs/{}", SUPPORTED_CHAINS[0]);
390 println!("{log_dir:?}");
391 assert!(log_dir.as_ref().ends_with(end), "{log_dir:?}");
392 }
393
394 #[test]
396 fn parse_empty_logs_path() {
397 let mut reth = Cli::try_parse_args_from(["reth", "config"]).unwrap();
398 if let Some(chain_spec) = reth.command.chain_spec() {
399 reth.logs.log_file_directory =
400 reth.logs.log_file_directory.join(chain_spec.chain.to_string());
401 }
402 let log_dir = reth.logs.log_file_directory;
403 let end = "reth/logs".to_string();
404 println!("{log_dir:?}");
405 assert!(log_dir.as_ref().ends_with(end), "{log_dir:?}");
406 }
407
408 #[test]
409 fn parse_env_filter_directives() {
410 let temp_dir = tempfile::tempdir().unwrap();
411
412 unsafe { std::env::set_var("RUST_LOG", "info,evm=debug") };
413 let reth = Cli::try_parse_args_from([
414 "reth",
415 "init",
416 "--datadir",
417 temp_dir.path().to_str().unwrap(),
418 "--log.file.filter",
419 "debug,net=trace",
420 ])
421 .unwrap();
422 assert!(reth.run(async move |_, _| Ok(())).is_ok());
423 }
424
425 #[test]
426 fn test_rpc_module_validation() {
427 use reth_rpc_server_types::RethRpcModule;
428
429 let cli =
431 Cli::try_parse_args_from(["reth", "node", "--http.api", "eth,admin,debug"]).unwrap();
432
433 if let Commands::Node(command) = &cli.command {
434 if let Some(http_api) = &command.rpc.http_api {
435 let modules = http_api.to_selection();
437 assert!(modules.contains(&RethRpcModule::Eth));
438 assert!(modules.contains(&RethRpcModule::Admin));
439 assert!(modules.contains(&RethRpcModule::Debug));
440 } else {
441 panic!("Expected http.api to be set");
442 }
443 } else {
444 panic!("Expected Node command");
445 }
446
447 let cli =
449 Cli::try_parse_args_from(["reth", "node", "--http.api", "eth,customrpc"]).unwrap();
450
451 if let Commands::Node(command) = &cli.command {
452 if let Some(http_api) = &command.rpc.http_api {
453 let modules = http_api.to_selection();
454 assert!(modules.contains(&RethRpcModule::Eth));
455 assert!(modules.contains(&RethRpcModule::Other("customrpc".to_string())));
456 } else {
457 panic!("Expected http.api to be set");
458 }
459 } else {
460 panic!("Expected Node command");
461 }
462 }
463
464 #[test]
465 fn test_rpc_module_unknown_rejected() {
466 use reth_cli_runner::CliRunner;
467
468 let cli =
470 Cli::try_parse_args_from(["reth", "node", "--http.api", "unknownmodule"]).unwrap();
471
472 let runner = CliRunner::try_default_runtime().unwrap();
474 let result = cli.with_runner(runner, |_, _| async { Ok(()) });
475
476 assert!(result.is_err());
477 let err = result.unwrap_err();
478 let err_msg = err.to_string();
479
480 assert!(
482 err_msg.contains("Unknown RPC module"),
483 "Error should mention unknown module: {}",
484 err_msg
485 );
486 assert!(
487 err_msg.contains("'unknownmodule'"),
488 "Error should mention the module name: {}",
489 err_msg
490 );
491 }
492
493 #[test]
494 fn parse_unwind_chain() {
495 let cli = Cli::try_parse_args_from([
496 "reth", "stage", "unwind", "--chain", "sepolia", "to-block", "100",
497 ])
498 .unwrap();
499 match cli.command {
500 Commands::Stage(cmd) => match cmd.command {
501 stage::Subcommands::Unwind(cmd) => {
502 assert_eq!(cmd.chain_spec().unwrap().chain_id(), SEPOLIA.chain_id());
503 }
504 _ => panic!("Expected Unwind command"),
505 },
506 _ => panic!("Expected Stage command"),
507 };
508 }
509
510 #[test]
511 fn parse_empty_supported_chains() {
512 #[derive(Debug, Clone, Default)]
513 struct FileChainSpecParser;
514
515 impl ChainSpecParser for FileChainSpecParser {
516 type ChainSpec = ChainSpec;
517
518 const SUPPORTED_CHAINS: &'static [&'static str] = &[];
519
520 fn parse(s: &str) -> eyre::Result<Arc<Self::ChainSpec>> {
521 EthereumChainSpecParser::parse(s)
522 }
523 }
524
525 let cli = Cli::<FileChainSpecParser>::try_parse_from([
526 "reth", "stage", "unwind", "--chain", "sepolia", "to-block", "100",
527 ])
528 .unwrap();
529 match cli.command {
530 Commands::Stage(cmd) => match cmd.command {
531 stage::Subcommands::Unwind(cmd) => {
532 assert_eq!(cmd.chain_spec().unwrap().chain_id(), SEPOLIA.chain_id());
533 }
534 _ => panic!("Expected Unwind command"),
535 },
536 _ => panic!("Expected Stage command"),
537 };
538 }
539}