1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Moonbeam CLI Library. Built with clap
18
//!
19
//! This module defines the Moonbeam node's Command Line Interface (CLI)
20
//! It is built using clap and inherits behavior from Substrate's sc_cli crate.
21

            
22
use clap::Parser;
23
use moonbeam_cli_opt::{
24
	account_key::{GenerateAccountKey, Network},
25
	AuthoringPolicy, EthApi, FrontierBackendType, NodeExtraArgs, Sealing,
26
};
27
use moonbeam_service::chain_spec;
28
use sc_cli::{Error as CliError, SubstrateCli};
29
use std::path::PathBuf;
30
use std::time::Duration;
31
use url::Url;
32

            
33
#[cfg(feature = "lazy-loading")]
34
fn parse_block_hash(s: &str) -> Result<sp_core::H256, String> {
35
	use std::str::FromStr;
36
	sp_core::H256::from_str(s).map_err(|err| err.to_string())
37
}
38

            
39
fn validate_url(arg: &str) -> Result<Url, String> {
40
	let url = Url::parse(arg).map_err(|e| e.to_string())?;
41

            
42
	let scheme = url.scheme();
43
	if scheme == "http" || scheme == "https" {
44
		Ok(url)
45
	} else {
46
		Err(format!("'{}' URL scheme not supported.", url.scheme()))
47
	}
48
}
49

            
50
/// Sub-commands supported by the collator.
51
#[derive(Debug, clap::Subcommand)]
52
pub enum Subcommand {
53
	/// Export the genesis state of the parachain.
54
	#[clap(name = "export-genesis-state")]
55
	ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand),
56

            
57
	/// Export the genesis wasm of the parachain.
58
	#[clap(name = "export-genesis-wasm")]
59
	ExportGenesisWasm(ExportGenesisWasmCommand),
60

            
61
	/// Build a chain specification.
62
	BuildSpec(BuildSpecCommand),
63

            
64
	/// Validate blocks.
65
	CheckBlock(sc_cli::CheckBlockCmd),
66

            
67
	/// Export blocks.
68
	ExportBlocks(sc_cli::ExportBlocksCmd),
69

            
70
	/// Export the state of a given block into a chain spec.
71
	ExportState(sc_cli::ExportStateCmd),
72

            
73
	/// Import blocks.
74
	ImportBlocks(sc_cli::ImportBlocksCmd),
75

            
76
	/// Remove the whole chain.
77
	PurgeChain(cumulus_client_cli::PurgeChainCmd),
78

            
79
	/// Revert the chain to a previous state.
80
	Revert(sc_cli::RevertCmd),
81

            
82
	/// Sub-commands concerned with benchmarking.
83
	/// The pallet benchmarking moved to the `pallet` sub-command.
84
	#[clap(subcommand)]
85
	Benchmark(frame_benchmarking_cli::BenchmarkCmd),
86

            
87
	/// Key management cli utilities
88
	#[clap(subcommand)]
89
	Key(KeyCmd),
90

            
91
	/// Precompile the WASM runtime into native code
92
	PrecompileWasm(sc_cli::PrecompileWasmCmd),
93
}
94

            
95
#[derive(Debug, Parser)]
96
pub struct BuildSpecCommand {
97
	#[clap(flatten)]
98
	pub base: sc_cli::BuildSpecCmd,
99

            
100
	/// Number of accounts to be funded in the genesis
101
	/// Warning: This flag implies a development spec and overrides any explicitly supplied spec
102
	#[clap(long, conflicts_with = "chain")]
103
	pub accounts: Option<u32>,
104

            
105
	/// Mnemonic from which we can derive funded accounts in the genesis
106
	/// Warning: This flag implies a development spec and overrides any explicitly supplied spec
107
	#[clap(long, conflicts_with = "chain")]
108
	pub mnemonic: Option<String>,
109
}
110

            
111
/// Command for exporting the genesis wasm file.
112
#[derive(Debug, Parser)]
113
pub struct ExportGenesisWasmCommand {
114
	/// Output file name or stdout if unspecified.
115
	#[clap(value_parser)]
116
	pub output: Option<PathBuf>,
117

            
118
	/// Write output in binary. Default is to write in hex.
119
	#[clap(short, long)]
120
	pub raw: bool,
121

            
122
	/// The name of the chain for that the genesis wasm file should be exported.
123
	#[clap(long)]
124
	pub chain: Option<String>,
125
}
126

            
127
#[derive(Debug, Parser)]
128
#[group(skip)]
129
pub struct RunCmd {
130
	#[clap(flatten)]
131
	pub base: cumulus_client_cli::RunCmd,
132

            
133
	/// Enable the development service to run without a backing relay chain
134
	#[clap(long)]
135
	pub dev_service: bool,
136

            
137
	/// No-op
138
	/// Deprecated in: https://github.com/moonbeam-foundation/moonbeam/pull/3204
139
	#[clap(long)]
140
	pub experimental_block_import_strategy: bool,
141

            
142
	/// Enable the legacy block import strategy
143
	#[clap(long)]
144
	pub legacy_block_import_strategy: bool,
145

            
146
	/// Specifies the URL used to fetch chain data via RPC.
147
	///
148
	/// The URL should point to the RPC endpoint of the chain being forked.
149
	/// Ensure that the RPC has sufficient rate limits to handle the expected load.
150
	#[cfg(feature = "lazy-loading")]
151
	#[clap(long)]
152
	#[arg(
153
		long,
154
		value_parser = validate_url,
155
		alias = "fork-chain-from-rpc"
156
	)]
157
	pub lazy_loading_remote_rpc: Option<Url>,
158

            
159
	/// Optional parameter to specify the block hash for lazy loading.
160
	///
161
	/// This parameter allows the user to specify a block hash from which to start loading data.
162
	///
163
	/// If not provided, the latest block will be used.
164
	#[cfg(feature = "lazy-loading")]
165
	#[arg(
166
		long,
167
		value_name = "BLOCK",
168
		value_parser = parse_block_hash,
169
		alias = "block"
170
	)]
171
	pub lazy_loading_block: Option<sp_core::H256>,
172

            
173
	/// Optional parameter to specify state overrides during lazy loading.
174
	///
175
	/// This parameter allows the user to provide a path to a file containing state overrides.
176
	/// The file can contain any custom state modifications that should be applied.
177
	#[cfg(feature = "lazy-loading")]
178
	#[clap(
179
		long,
180
		value_name = "PATH",
181
		value_parser,
182
		alias = "fork-state-overrides"
183
	)]
184
	pub lazy_loading_state_overrides: Option<PathBuf>,
185

            
186
	/// Optional parameter to specify a runtime override when starting the lazy loading.
187
	///
188
	/// If not provided, it will fetch the runtime from the block being forked.
189
	#[cfg(feature = "lazy-loading")]
190
	#[clap(long, value_name = "PATH", value_parser, alias = "runtime-override")]
191
	pub lazy_loading_runtime_override: Option<PathBuf>,
192

            
193
	/// The delay (in milliseconds) between RPC requests when using lazy loading.
194
	///
195
	/// This parameter controls the amount of time (in milliseconds) to wait between consecutive
196
	/// RPC requests. This can help manage request rate and avoid overwhelming the server.
197
	///
198
	/// The default value is 100 milliseconds.
199
	#[cfg(feature = "lazy-loading")]
200
	#[clap(long, default_value = "100")]
201
	pub lazy_loading_delay_between_requests: u32,
202

            
203
	/// The maximum number of retries for an RPC request when using lazy loading.
204
	///
205
	/// The default value is 10 retries.
206
	#[cfg(feature = "lazy-loading")]
207
	#[clap(long, default_value = "10")]
208
	pub lazy_loading_max_retries_per_request: u32,
209

            
210
	/// When blocks should be sealed in the dev service.
211
	///
212
	/// Options are "instant", "manual", or timer interval in milliseconds
213
	#[clap(long, default_value = "instant")]
214
	pub sealing: Sealing,
215

            
216
	/// Public authoring identity to be inserted in the author inherent
217
	/// This is not currently used, but we may want a way to use it in the dev service.
218
	// #[clap(long)]
219
	// pub author_id: Option<NimbusId>,
220

            
221
	/// Enable EVM tracing module on a non-authority node.
222
	#[clap(long, value_delimiter = ',')]
223
	pub ethapi: Vec<EthApi>,
224

            
225
	/// Number of concurrent tracing tasks. Meant to be shared by both "debug" and "trace" modules.
226
	#[clap(long, default_value = "10")]
227
	pub ethapi_max_permits: u32,
228

            
229
	/// Maximum number of trace entries a single request of `trace_filter` is allowed to return.
230
	/// A request asking for more or an unbounded one going over this limit will both return an
231
	/// error.
232
	#[clap(long, default_value = "500")]
233
	pub ethapi_trace_max_count: u32,
234

            
235
	/// Size in bytes of the LRU cache for trace_filter block traces.
236
	/// Default value is 100MB (104,857,600 bytes).
237
	#[clap(long, default_value = "104857600")]
238
	pub ethapi_trace_cache_size: u64,
239

            
240
	/// Size in bytes of the LRU cache for block data.
241
	#[clap(long, default_value = "300000000")]
242
	pub eth_log_block_cache: usize,
243

            
244
	/// Size in bytes of the LRU cache for transactions statuses data.
245
	#[clap(long, default_value = "300000000")]
246
	pub eth_statuses_cache: usize,
247

            
248
	/// Sets the frontier backend type (KeyValue or Sql)
249
	#[arg(long, value_enum, ignore_case = true, default_value_t = FrontierBackendType::default())]
250
	pub frontier_backend_type: FrontierBackendType,
251

            
252
	// Sets the SQL backend's pool size.
253
	#[arg(long, default_value = "100")]
254
	pub frontier_sql_backend_pool_size: u32,
255

            
256
	/// Sets the SQL backend's query timeout in number of VM ops.
257
	#[arg(long, default_value = "10000000")]
258
	pub frontier_sql_backend_num_ops_timeout: u32,
259

            
260
	/// Sets the SQL backend's auxiliary thread limit.
261
	#[arg(long, default_value = "4")]
262
	pub frontier_sql_backend_thread_count: u32,
263

            
264
	/// Sets the SQL backend's cache size in bytes.
265
	/// Default value is 200MB.
266
	#[arg(long, default_value = "209715200")]
267
	pub frontier_sql_backend_cache_size: u64,
268

            
269
	/// Size in bytes of data a raw tracing request is allowed to use.
270
	/// Bound the size of memory, stack and storage data.
271
	#[clap(long, default_value = "20000000")]
272
	pub tracing_raw_max_memory_usage: usize,
273

            
274
	/// Maximum number of logs in a query.
275
	#[clap(long, default_value = "10000")]
276
	pub max_past_logs: u32,
277

            
278
	/// Maximum block range to query logs from.
279
	#[clap(long, default_value = "1024")]
280
	pub max_block_range: u32,
281

            
282
	/// Force using Moonbase native runtime.
283
	#[clap(long = "force-moonbase")]
284
	pub force_moonbase: bool,
285

            
286
	/// Force using Moonriver native runtime.
287
	#[clap(long = "force-moonriver")]
288
	pub force_moonriver: bool,
289

            
290
	/// Id of the parachain this collator collates for.
291
	#[clap(long)]
292
	pub parachain_id: Option<u32>,
293

            
294
	/// Maximum fee history cache size.
295
	#[clap(long, default_value = "2048")]
296
	pub fee_history_limit: u64,
297

            
298
	/// Disable automatic hardware benchmarks.
299
	///
300
	/// By default these benchmarks are automatically ran at startup and measure
301
	/// the CPU speed, the memory bandwidth and the disk speed.
302
	///
303
	/// The results are then printed out in the logs, and also sent as part of
304
	/// telemetry, if telemetry is enabled.
305
	#[clap(long)]
306
	pub no_hardware_benchmarks: bool,
307

            
308
	/// Removes moonbeam prefix from Prometheus metrics
309
	#[clap(long)]
310
	pub no_prometheus_prefix: bool,
311

            
312
	/// Maximum duration in milliseconds to produce a block
313
	#[clap(long, default_value = "2000", value_parser=block_authoring_duration_parser)]
314
	pub block_authoring_duration: Duration,
315

            
316
	/// Enable full proof-of-validation mode for Nimbus (deprecated, use --max-pov-percentage instead)
317
	#[clap(long, hide = true)]
318
	pub nimbus_full_pov: bool,
319

            
320
	/// Maximum percentage of POV size to use (0-100)
321
	#[arg(
322
		long,
323
		conflicts_with = "nimbus_full_pov",
324
		default_value = "50",
325
		default_value_if("nimbus_full_pov", "true", "100")
326
	)]
327
	pub max_pov_percentage: u32,
328

            
329
	/// Authoring style to use.
330
	#[arg(long, default_value_t = AuthoringPolicy::Lookahead)]
331
	pub authoring: AuthoringPolicy,
332

            
333
	/// Export all `PoVs` build by this collator to the given folder.
334
	///
335
	/// This is useful for debugging issues that are occurring while validating these `PoVs` on the
336
	/// relay chain.
337
	#[arg(long)]
338
	pub export_pov_to_path: Option<PathBuf>,
339
}
340

            
341
936
fn block_authoring_duration_parser(s: &str) -> Result<Duration, String> {
342
936
	Ok(Duration::from_millis(clap_num::number_range(
343
936
		s, 250, 2_000,
344
	)?))
345
936
}
346

            
347
impl RunCmd {
348
932
	pub fn new_rpc_config(&self) -> moonbeam_cli_opt::RpcConfig {
349
		moonbeam_cli_opt::RpcConfig {
350
932
			ethapi: self.ethapi.clone(),
351
932
			ethapi_max_permits: self.ethapi_max_permits,
352
932
			ethapi_trace_max_count: self.ethapi_trace_max_count,
353
932
			ethapi_trace_cache_size: self.ethapi_trace_cache_size,
354
932
			eth_log_block_cache: self.eth_log_block_cache,
355
932
			eth_statuses_cache: self.eth_statuses_cache,
356
932
			fee_history_limit: self.fee_history_limit,
357
932
			max_past_logs: self.max_past_logs,
358
932
			max_block_range: self.max_block_range,
359
932
			relay_chain_rpc_urls: self.base.relay_chain_rpc_urls.clone(),
360
932
			tracing_raw_max_memory_usage: self.tracing_raw_max_memory_usage,
361
932
			frontier_backend_config: match self.frontier_backend_type {
362
932
				FrontierBackendType::KeyValue => moonbeam_cli_opt::FrontierBackendConfig::KeyValue,
363
				FrontierBackendType::Sql => moonbeam_cli_opt::FrontierBackendConfig::Sql {
364
					pool_size: self.frontier_sql_backend_pool_size,
365
					num_ops_timeout: self.frontier_sql_backend_num_ops_timeout,
366
					thread_count: self.frontier_sql_backend_thread_count,
367
					cache_size: self.frontier_sql_backend_cache_size,
368
				},
369
			},
370
932
			no_prometheus_prefix: self.no_prometheus_prefix,
371
		}
372
932
	}
373
}
374

            
375
impl std::ops::Deref for RunCmd {
376
	type Target = cumulus_client_cli::RunCmd;
377

            
378
1860
	fn deref(&self) -> &Self::Target {
379
1860
		&self.base
380
1860
	}
381
}
382

            
383
#[derive(Debug, clap::Subcommand)]
384
pub enum KeyCmd {
385
	#[clap(flatten)]
386
	BaseCli(sc_cli::KeySubcommand),
387
	/// Generate an Ethereum account.
388
	#[clap(about = "This command is deprecated, please use `generate-moonbeam-key` instead.")]
389
	GenerateAccountKey(GenerateAccountKey),
390
	/// Generate a Moonbeam account.
391
	GenerateMoonbeamKey(GenerateAccountKey),
392
}
393

            
394
impl KeyCmd {
395
	/// run the key subcommands
396
	pub fn run<C: SubstrateCli>(&self, cli: &C) -> Result<(), CliError> {
397
		match self {
398
			KeyCmd::BaseCli(cmd) => cmd.run(cli),
399
			KeyCmd::GenerateAccountKey(cmd) => {
400
				let deprecation_msg = r#"
401

            
402
				Warning: This command is deprecated, please use `generate-moonbeam-key` instead.
403

            
404
				The `generate-account-key` command used Ethereum's derivation path (m/44'/60'/0'/0/n)
405
				while `generate-moonbeam-key` uses Moonbeam's derivation path (m/44'/1284'/0'/0/n).
406
				Furthermore, it supports derivation paths for Moonriver, Moonbase, and Ethereum.
407

            
408
				For more information, see: https://github.com/moonbeam-foundation/moonbeam/pull/3090
409

            
410
				"#;
411
				eprintln!("{}", ansi_term::Colour::Yellow.paint(deprecation_msg));
412

            
413
				// Force ethereum network for deprecated command
414
				let mut cmd = cmd.clone();
415
				cmd.network = Network::Ethereum;
416
				cmd.run();
417
				Ok(())
418
			}
419
			KeyCmd::GenerateMoonbeamKey(cmd) => {
420
				cmd.run();
421
				Ok(())
422
			}
423
		}
424
	}
425
}
426

            
427
#[derive(Debug, Parser)]
428
#[clap(
429
	propagate_version = true,
430
	args_conflicts_with_subcommands = true,
431
	subcommand_negates_reqs = true
432
)]
433
pub struct Cli {
434
	#[clap(subcommand)]
435
	pub subcommand: Option<Subcommand>,
436

            
437
	#[clap(flatten)]
438
	pub run: RunCmd,
439

            
440
	/// Relaychain arguments
441
	#[clap(raw = true)]
442
	pub relaychain_args: Vec<String>,
443
}
444

            
445
impl Cli {
446
932
	pub(crate) fn node_extra_args(&self) -> NodeExtraArgs {
447
932
		NodeExtraArgs {
448
932
			authoring_policy: self.run.authoring,
449
932
			export_pov: self.run.export_pov_to_path.clone(),
450
932
			max_pov_percentage: Some(self.run.max_pov_percentage),
451
932
			legacy_block_import_strategy: self.run.legacy_block_import_strategy,
452
932
		}
453
932
	}
454
}
455

            
456
#[derive(Debug)]
457
pub struct RelayChainCli {
458
	/// Implementation version.
459
	///
460
	/// By default, it will look like this:
461
	///
462
	/// `2.0.0-b950f731c`
463
	///
464
	/// Where the hash is the short hash of the commit in the Git repository.
465
	pub impl_version: String,
466

            
467
	/// The actual relay chain cli object.
468
	pub base: polkadot_cli::RunCmd,
469

            
470
	/// Optional chain id that should be passed to the relay chain.
471
	pub chain_id: Option<String>,
472

            
473
	/// The base path that should be used by the relay chain.
474
	pub base_path: PathBuf,
475
}
476

            
477
impl RelayChainCli {
478
	/// Parse the relay chain CLI parameters using the para chain `Configuration`.
479
	pub fn new<'a>(
480
		para_config: &sc_service::Configuration,
481
		relay_chain_args: impl Iterator<Item = &'a String>,
482
	) -> Self {
483
		let extension = chain_spec::Extensions::try_get(&*para_config.chain_spec);
484
		let chain_id = extension.map(|e| e.relay_chain.clone());
485
		let base_path = para_config.base_path.path().join("polkadot");
486
		Self {
487
			impl_version: polkadot_cli::Cli::impl_version(),
488
			base_path,
489
			chain_id,
490
			base: polkadot_cli::RunCmd::parse_from(relay_chain_args),
491
		}
492
	}
493
}