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::{account_key::GenerateAccountKey, EthApi, FrontierBackendType, Sealing};
24
use moonbeam_service::chain_spec;
25
use sc_cli::{Error as CliError, SubstrateCli};
26
use std::path::PathBuf;
27
use std::time::Duration;
28
use url::Url;
29

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

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

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

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

            
54
	/// Export the genesis wasm of the parachain.
55
	#[clap(name = "export-genesis-wasm")]
56
	ExportGenesisWasm(ExportGenesisWasmCommand),
57

            
58
	/// Build a chain specification.
59
	BuildSpec(BuildSpecCommand),
60

            
61
	/// Validate blocks.
62
	CheckBlock(sc_cli::CheckBlockCmd),
63

            
64
	/// Export blocks.
65
	ExportBlocks(sc_cli::ExportBlocksCmd),
66

            
67
	/// Export the state of a given block into a chain spec.
68
	ExportState(sc_cli::ExportStateCmd),
69

            
70
	/// Import blocks.
71
	ImportBlocks(sc_cli::ImportBlocksCmd),
72

            
73
	/// Remove the whole chain.
74
	PurgeChain(cumulus_client_cli::PurgeChainCmd),
75

            
76
	/// Revert the chain to a previous state.
77
	Revert(sc_cli::RevertCmd),
78

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

            
84
	/// Try some command against runtime state.
85
	TryRuntime,
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 state of the parachain
112
#[derive(Debug, Parser)]
113
pub struct ExportGenesisHeadCommand {
114
	/// Output file name or stdout if unspecified.
115
	#[clap(value_parser)]
116
	pub output: Option<PathBuf>,
117

            
118
	/// Id of the parachain this state is for.
119
	#[clap(long)]
120
	pub parachain_id: Option<u32>,
121

            
122
	/// Write output in binary. Default is to write in hex.
123
	#[clap(short, long)]
124
	pub raw: bool,
125

            
126
	/// The name of the chain for that the genesis state should be exported.
127
	#[clap(long)]
128
	pub chain: Option<String>,
129
}
130

            
131
/// Command for exporting the genesis wasm file.
132
#[derive(Debug, Parser)]
133
pub struct ExportGenesisWasmCommand {
134
	/// Output file name or stdout if unspecified.
135
	#[clap(value_parser)]
136
	pub output: Option<PathBuf>,
137

            
138
	/// Write output in binary. Default is to write in hex.
139
	#[clap(short, long)]
140
	pub raw: bool,
141

            
142
	/// The name of the chain for that the genesis wasm file should be exported.
143
	#[clap(long)]
144
	pub chain: Option<String>,
145
}
146

            
147
#[derive(Debug, Parser)]
148
#[group(skip)]
149
pub struct RunCmd {
150
	#[clap(flatten)]
151
	pub base: cumulus_client_cli::RunCmd,
152

            
153
	/// Enable the development service to run without a backing relay chain
154
	#[clap(long)]
155
	pub dev_service: bool,
156

            
157
	/// Enable the legacy block import strategy
158
	#[clap(long)]
159
	pub legacy_block_import_strategy: bool,
160

            
161
	/// Specifies the URL used to fetch chain data via RPC.
162
	///
163
	/// The URL should point to the RPC endpoint of the chain being forked.
164
	/// Ensure that the RPC has sufficient rate limits to handle the expected load.
165
	#[cfg(feature = "lazy-loading")]
166
	#[clap(long)]
167
	#[arg(
168
		long,
169
		value_parser = validate_url,
170
		alias = "fork-chain-from-rpc"
171
	)]
172
	pub lazy_loading_remote_rpc: Option<Url>,
173

            
174
	/// Optional parameter to specify the block hash for lazy loading.
175
	///
176
	/// This parameter allows the user to specify a block hash from which to start loading data.
177
	///
178
	/// If not provided, the latest block will be used.
179
	#[cfg(feature = "lazy-loading")]
180
	#[arg(
181
		long,
182
		value_name = "BLOCK",
183
		value_parser = parse_block_hash,
184
		alias = "block"
185
	)]
186
	pub lazy_loading_block: Option<sp_core::H256>,
187

            
188
	/// Optional parameter to specify state overrides during lazy loading.
189
	///
190
	/// This parameter allows the user to provide a path to a file containing state overrides.
191
	/// The file can contain any custom state modifications that should be applied.
192
	#[cfg(feature = "lazy-loading")]
193
	#[clap(
194
		long,
195
		value_name = "PATH",
196
		value_parser,
197
		alias = "fork-state-overrides"
198
	)]
199
	pub lazy_loading_state_overrides: Option<PathBuf>,
200

            
201
	/// Optional parameter to specify a runtime override when starting the lazy loading.
202
	///
203
	/// If not provided, it will fetch the runtime from the block being forked.
204
	#[cfg(feature = "lazy-loading")]
205
	#[clap(long, value_name = "PATH", value_parser, alias = "runtime-override")]
206
	pub lazy_loading_runtime_override: Option<PathBuf>,
207

            
208
	/// The delay (in milliseconds) between RPC requests when using lazy loading.
209
	///
210
	/// This parameter controls the amount of time (in milliseconds) to wait between consecutive
211
	/// RPC requests. This can help manage request rate and avoid overwhelming the server.
212
	///
213
	/// The default value is 100 milliseconds.
214
	#[cfg(feature = "lazy-loading")]
215
	#[clap(long, default_value = "100")]
216
	pub lazy_loading_delay_between_requests: u32,
217

            
218
	/// The maximum number of retries for an RPC request when using lazy loading.
219
	///
220
	/// The default value is 10 retries.
221
	#[cfg(feature = "lazy-loading")]
222
	#[clap(long, default_value = "10")]
223
	pub lazy_loading_max_retries_per_request: u32,
224

            
225
	/// When blocks should be sealed in the dev service.
226
	///
227
	/// Options are "instant", "manual", or timer interval in milliseconds
228
	#[clap(long, default_value = "instant")]
229
	pub sealing: Sealing,
230

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

            
236
	/// Enable EVM tracing module on a non-authority node.
237
	#[clap(long, value_delimiter = ',')]
238
928
	pub ethapi: Vec<EthApi>,
239

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

            
244
	/// Maximum number of trace entries a single request of `trace_filter` is allowed to return.
245
	/// A request asking for more or an unbounded one going over this limit will both return an
246
	/// error.
247
	#[clap(long, default_value = "500")]
248
	pub ethapi_trace_max_count: u32,
249

            
250
	/// Duration (in seconds) after which the cache of `trace_filter` for a given block will be
251
	/// discarded.
252
	#[clap(long, default_value = "300")]
253
	pub ethapi_trace_cache_duration: u64,
254

            
255
	/// Size in bytes of the LRU cache for block data.
256
	#[clap(long, default_value = "300000000")]
257
	pub eth_log_block_cache: usize,
258

            
259
	/// Size in bytes of the LRU cache for transactions statuses data.
260
	#[clap(long, default_value = "300000000")]
261
	pub eth_statuses_cache: usize,
262

            
263
	/// Sets the frontier backend type (KeyValue or Sql)
264
934
	#[arg(long, value_enum, ignore_case = true, default_value_t = FrontierBackendType::default())]
265
	pub frontier_backend_type: FrontierBackendType,
266

            
267
	// Sets the SQL backend's pool size.
268
	#[arg(long, default_value = "100")]
269
	pub frontier_sql_backend_pool_size: u32,
270

            
271
	/// Sets the SQL backend's query timeout in number of VM ops.
272
	#[arg(long, default_value = "10000000")]
273
	pub frontier_sql_backend_num_ops_timeout: u32,
274

            
275
	/// Sets the SQL backend's auxiliary thread limit.
276
	#[arg(long, default_value = "4")]
277
	pub frontier_sql_backend_thread_count: u32,
278

            
279
	/// Sets the SQL backend's query timeout in number of VM ops.
280
	/// Default value is 200MB.
281
	#[arg(long, default_value = "209715200")]
282
	pub frontier_sql_backend_cache_size: u64,
283

            
284
	/// Size in bytes of data a raw tracing request is allowed to use.
285
	/// Bound the size of memory, stack and storage data.
286
	#[clap(long, default_value = "20000000")]
287
	pub tracing_raw_max_memory_usage: usize,
288

            
289
	/// Maximum number of logs in a query.
290
	#[clap(long, default_value = "10000")]
291
	pub max_past_logs: u32,
292

            
293
	/// Force using Moonbase native runtime.
294
	#[clap(long = "force-moonbase")]
295
	pub force_moonbase: bool,
296

            
297
	/// Force using Moonriver native runtime.
298
	#[clap(long = "force-moonriver")]
299
	pub force_moonriver: bool,
300

            
301
	/// Id of the parachain this collator collates for.
302
	#[clap(long)]
303
	pub parachain_id: Option<u32>,
304

            
305
	/// Maximum fee history cache size.
306
	#[clap(long, default_value = "2048")]
307
	pub fee_history_limit: u64,
308

            
309
	/// Disable automatic hardware benchmarks.
310
	///
311
	/// By default these benchmarks are automatically ran at startup and measure
312
	/// the CPU speed, the memory bandwidth and the disk speed.
313
	///
314
	/// The results are then printed out in the logs, and also sent as part of
315
	/// telemetry, if telemetry is enabled.
316
	#[clap(long)]
317
	pub no_hardware_benchmarks: bool,
318

            
319
	/// Removes moonbeam prefix from Prometheus metrics
320
	#[clap(long)]
321
	pub no_prometheus_prefix: bool,
322

            
323
	/// Maximum duration in milliseconds to produce a block
324
	#[clap(long, default_value = "2000", value_parser=block_authoring_duration_parser)]
325
	pub block_authoring_duration: Duration,
326
}
327

            
328
934
fn block_authoring_duration_parser(s: &str) -> Result<Duration, String> {
329
934
	Ok(Duration::from_millis(clap_num::number_range(
330
934
		s, 250, 2_000,
331
934
	)?))
332
934
}
333

            
334
impl RunCmd {
335
930
	pub fn new_rpc_config(&self) -> moonbeam_cli_opt::RpcConfig {
336
930
		moonbeam_cli_opt::RpcConfig {
337
930
			ethapi: self.ethapi.clone(),
338
930
			ethapi_max_permits: self.ethapi_max_permits,
339
930
			ethapi_trace_max_count: self.ethapi_trace_max_count,
340
930
			ethapi_trace_cache_duration: self.ethapi_trace_cache_duration,
341
930
			eth_log_block_cache: self.eth_log_block_cache,
342
930
			eth_statuses_cache: self.eth_statuses_cache,
343
930
			fee_history_limit: self.fee_history_limit,
344
930
			max_past_logs: self.max_past_logs,
345
930
			relay_chain_rpc_urls: self.base.relay_chain_rpc_urls.clone(),
346
930
			tracing_raw_max_memory_usage: self.tracing_raw_max_memory_usage,
347
930
			frontier_backend_config: match self.frontier_backend_type {
348
930
				FrontierBackendType::KeyValue => moonbeam_cli_opt::FrontierBackendConfig::KeyValue,
349
				FrontierBackendType::Sql => moonbeam_cli_opt::FrontierBackendConfig::Sql {
350
					pool_size: self.frontier_sql_backend_pool_size,
351
					num_ops_timeout: self.frontier_sql_backend_num_ops_timeout,
352
					thread_count: self.frontier_sql_backend_thread_count,
353
					cache_size: self.frontier_sql_backend_cache_size,
354
				},
355
			},
356
930
			no_prometheus_prefix: self.no_prometheus_prefix,
357
930
		}
358
930
	}
359
}
360

            
361
impl std::ops::Deref for RunCmd {
362
	type Target = cumulus_client_cli::RunCmd;
363

            
364
1856
	fn deref(&self) -> &Self::Target {
365
1856
		&self.base
366
1856
	}
367
}
368

            
369
#[derive(Debug, clap::Subcommand)]
370
pub enum KeyCmd {
371
	#[clap(flatten)]
372
	BaseCli(sc_cli::KeySubcommand),
373
	/// Generate an Ethereum account.
374
	GenerateAccountKey(GenerateAccountKey),
375
}
376

            
377
impl KeyCmd {
378
	/// run the key subcommands
379
	pub fn run<C: SubstrateCli>(&self, cli: &C) -> Result<(), CliError> {
380
		match self {
381
			KeyCmd::BaseCli(cmd) => cmd.run(cli),
382
			KeyCmd::GenerateAccountKey(cmd) => {
383
				cmd.run();
384
				Ok(())
385
			}
386
		}
387
	}
388
}
389

            
390
#[derive(Debug, Parser)]
391
#[clap(
392
	propagate_version = true,
393
	args_conflicts_with_subcommands = true,
394
	subcommand_negates_reqs = true
395
)]
396
pub struct Cli {
397
	#[clap(subcommand)]
398
	pub subcommand: Option<Subcommand>,
399

            
400
	#[clap(flatten)]
401
	pub run: RunCmd,
402

            
403
	/// Relaychain arguments
404
	#[clap(raw = true)]
405
	pub relaychain_args: Vec<String>,
406
}
407

            
408
#[derive(Debug)]
409
pub struct RelayChainCli {
410
	/// The actual relay chain cli object.
411
	pub base: polkadot_cli::RunCmd,
412

            
413
	/// Optional chain id that should be passed to the relay chain.
414
	pub chain_id: Option<String>,
415

            
416
	/// The base path that should be used by the relay chain.
417
	pub base_path: PathBuf,
418
}
419

            
420
impl RelayChainCli {
421
	/// Parse the relay chain CLI parameters using the para chain `Configuration`.
422
	pub fn new<'a>(
423
		para_config: &sc_service::Configuration,
424
		relay_chain_args: impl Iterator<Item = &'a String>,
425
	) -> Self {
426
		let extension = chain_spec::Extensions::try_get(&*para_config.chain_spec);
427
		let chain_id = extension.map(|e| e.relay_chain.clone());
428
		let base_path = para_config.base_path.path().join("polkadot");
429
		Self {
430
			base_path,
431
			chain_id,
432
			base: polkadot_cli::RunCmd::parse_from(relay_chain_args),
433
		}
434
	}
435
}