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(cumulus_client_cli::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 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
	/// Enable the new block import strategy
138
	/// Deprecated in: https://github.com/Moonsong-Labs/moonkit/pull/43
139
	#[clap(long)]
140
	pub experimental_block_import_strategy: bool,
141

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

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

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

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

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

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

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

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

            
217
	/// Enable EVM tracing module on a non-authority node.
218
	#[clap(long, value_delimiter = ',')]
219
910
	pub ethapi: Vec<EthApi>,
220

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

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

            
231
	/// Duration (in seconds) after which the cache of `trace_filter` for a given block will be
232
	/// discarded.
233
	#[clap(long, default_value = "300")]
234
	pub ethapi_trace_cache_duration: u64,
235

            
236
	/// Size in bytes of the LRU cache for block data.
237
	#[clap(long, default_value = "300000000")]
238
	pub eth_log_block_cache: usize,
239

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

            
244
	/// Sets the frontier backend type (KeyValue or Sql)
245
916
	#[arg(long, value_enum, ignore_case = true, default_value_t = FrontierBackendType::default())]
246
	pub frontier_backend_type: FrontierBackendType,
247

            
248
	// Sets the SQL backend's pool size.
249
	#[arg(long, default_value = "100")]
250
	pub frontier_sql_backend_pool_size: u32,
251

            
252
	/// Sets the SQL backend's query timeout in number of VM ops.
253
	#[arg(long, default_value = "10000000")]
254
	pub frontier_sql_backend_num_ops_timeout: u32,
255

            
256
	/// Sets the SQL backend's auxiliary thread limit.
257
	#[arg(long, default_value = "4")]
258
	pub frontier_sql_backend_thread_count: u32,
259

            
260
	/// Sets the SQL backend's query timeout in number of VM ops.
261
	/// Default value is 200MB.
262
	#[arg(long, default_value = "209715200")]
263
	pub frontier_sql_backend_cache_size: u64,
264

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

            
270
	/// Maximum number of logs in a query.
271
	#[clap(long, default_value = "10000")]
272
	pub max_past_logs: u32,
273

            
274
	/// Force using Moonbase native runtime.
275
	#[clap(long = "force-moonbase")]
276
	pub force_moonbase: bool,
277

            
278
	/// Force using Moonriver native runtime.
279
	#[clap(long = "force-moonriver")]
280
	pub force_moonriver: bool,
281

            
282
	/// Id of the parachain this collator collates for.
283
	#[clap(long)]
284
	pub parachain_id: Option<u32>,
285

            
286
	/// Maximum fee history cache size.
287
	#[clap(long, default_value = "2048")]
288
	pub fee_history_limit: u64,
289

            
290
	/// Disable automatic hardware benchmarks.
291
	///
292
	/// By default these benchmarks are automatically ran at startup and measure
293
	/// the CPU speed, the memory bandwidth and the disk speed.
294
	///
295
	/// The results are then printed out in the logs, and also sent as part of
296
	/// telemetry, if telemetry is enabled.
297
	#[clap(long)]
298
	pub no_hardware_benchmarks: bool,
299

            
300
	/// Removes moonbeam prefix from Prometheus metrics
301
	#[clap(long)]
302
	pub no_prometheus_prefix: bool,
303

            
304
	/// Maximum duration in milliseconds to produce a block
305
	#[clap(long, default_value = "2000", value_parser=block_authoring_duration_parser)]
306
	pub block_authoring_duration: Duration,
307
}
308

            
309
916
fn block_authoring_duration_parser(s: &str) -> Result<Duration, String> {
310
916
	Ok(Duration::from_millis(clap_num::number_range(
311
916
		s, 250, 2_000,
312
916
	)?))
313
916
}
314

            
315
impl RunCmd {
316
912
	pub fn new_rpc_config(&self) -> moonbeam_cli_opt::RpcConfig {
317
912
		moonbeam_cli_opt::RpcConfig {
318
912
			ethapi: self.ethapi.clone(),
319
912
			ethapi_max_permits: self.ethapi_max_permits,
320
912
			ethapi_trace_max_count: self.ethapi_trace_max_count,
321
912
			ethapi_trace_cache_duration: self.ethapi_trace_cache_duration,
322
912
			eth_log_block_cache: self.eth_log_block_cache,
323
912
			eth_statuses_cache: self.eth_statuses_cache,
324
912
			fee_history_limit: self.fee_history_limit,
325
912
			max_past_logs: self.max_past_logs,
326
912
			relay_chain_rpc_urls: self.base.relay_chain_rpc_urls.clone(),
327
912
			tracing_raw_max_memory_usage: self.tracing_raw_max_memory_usage,
328
912
			frontier_backend_config: match self.frontier_backend_type {
329
912
				FrontierBackendType::KeyValue => moonbeam_cli_opt::FrontierBackendConfig::KeyValue,
330
				FrontierBackendType::Sql => moonbeam_cli_opt::FrontierBackendConfig::Sql {
331
					pool_size: self.frontier_sql_backend_pool_size,
332
					num_ops_timeout: self.frontier_sql_backend_num_ops_timeout,
333
					thread_count: self.frontier_sql_backend_thread_count,
334
					cache_size: self.frontier_sql_backend_cache_size,
335
				},
336
			},
337
912
			no_prometheus_prefix: self.no_prometheus_prefix,
338
912
		}
339
912
	}
340
}
341

            
342
impl std::ops::Deref for RunCmd {
343
	type Target = cumulus_client_cli::RunCmd;
344

            
345
1820
	fn deref(&self) -> &Self::Target {
346
1820
		&self.base
347
1820
	}
348
}
349

            
350
#[derive(Debug, clap::Subcommand)]
351
pub enum KeyCmd {
352
	#[clap(flatten)]
353
	BaseCli(sc_cli::KeySubcommand),
354
	/// Generate an Ethereum account.
355
	GenerateAccountKey(GenerateAccountKey),
356
}
357

            
358
impl KeyCmd {
359
	/// run the key subcommands
360
	pub fn run<C: SubstrateCli>(&self, cli: &C) -> Result<(), CliError> {
361
		match self {
362
			KeyCmd::BaseCli(cmd) => cmd.run(cli),
363
			KeyCmd::GenerateAccountKey(cmd) => {
364
				cmd.run();
365
				Ok(())
366
			}
367
		}
368
	}
369
}
370

            
371
#[derive(Debug, Parser)]
372
#[clap(
373
	propagate_version = true,
374
	args_conflicts_with_subcommands = true,
375
	subcommand_negates_reqs = true
376
)]
377
pub struct Cli {
378
	#[clap(subcommand)]
379
	pub subcommand: Option<Subcommand>,
380

            
381
	#[clap(flatten)]
382
	pub run: RunCmd,
383

            
384
	/// Relaychain arguments
385
	#[clap(raw = true)]
386
	pub relaychain_args: Vec<String>,
387
}
388

            
389
#[derive(Debug)]
390
pub struct RelayChainCli {
391
	/// The actual relay chain cli object.
392
	pub base: polkadot_cli::RunCmd,
393

            
394
	/// Optional chain id that should be passed to the relay chain.
395
	pub chain_id: Option<String>,
396

            
397
	/// The base path that should be used by the relay chain.
398
	pub base_path: PathBuf,
399
}
400

            
401
impl RelayChainCli {
402
	/// Parse the relay chain CLI parameters using the para chain `Configuration`.
403
	pub fn new<'a>(
404
		para_config: &sc_service::Configuration,
405
		relay_chain_args: impl Iterator<Item = &'a String>,
406
	) -> Self {
407
		let extension = chain_spec::Extensions::try_get(&*para_config.chain_spec);
408
		let chain_id = extension.map(|e| e.relay_chain.clone());
409
		let base_path = para_config.base_path.path().join("polkadot");
410
		Self {
411
			base_path,
412
			chain_id,
413
			base: polkadot_cli::RunCmd::parse_from(relay_chain_args),
414
		}
415
	}
416
}