1
// Copyright 2019-2022 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 new block import strategy
158
	/// Deprecated in: https://github.com/Moonsong-Labs/moonkit/pull/43
159
	#[clap(long)]
160
	pub experimental_block_import_strategy: bool,
161

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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