frequency_cli/
command.rs

1// File originally from https://github.com/paritytech/cumulus/blob/master/parachain-template/node/src/command.rs
2
3use crate::{
4	benchmarking::{inherent_benchmark_data, RemarkBuilder},
5	cli::{Cli, RelayChainCli, Subcommand},
6};
7use common_primitives::node::Block;
8use cumulus_client_service::storage_proof_size::HostFunctions as ReclaimHostFunctions;
9use frame_benchmarking_cli::BenchmarkCmd;
10use frequency_service::{
11	chain_spec,
12	service::{frequency_runtime::VERSION, new_partial},
13};
14use sc_cli::{
15	ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,
16	NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,
17};
18use sc_service::config::{BasePath, PrometheusConfig};
19use sp_runtime::traits::HashingFor;
20
21#[derive(Debug)]
22enum ChainIdentity {
23	Frequency,
24	FrequencyPaseo,
25	FrequencyLocal,
26	FrequencyDev,
27	FrequencyWestendLocal,
28	FrequencyWestend,
29}
30
31trait IdentifyChain {
32	fn identify(&self) -> ChainIdentity;
33}
34
35impl IdentifyChain for dyn sc_service::ChainSpec {
36	fn identify(&self) -> ChainIdentity {
37		if self.id() == "frequency" {
38			ChainIdentity::Frequency
39		} else if self.id() == "frequency-paseo" {
40			ChainIdentity::FrequencyPaseo
41		} else if self.id() == "frequency-local" {
42			ChainIdentity::FrequencyLocal
43		} else if self.id() == "dev" {
44			ChainIdentity::FrequencyDev
45		} else if self.id() == "frequency-westend-local" {
46			ChainIdentity::FrequencyWestendLocal
47		} else if self.id() == "frequency-westend" {
48			ChainIdentity::FrequencyWestend
49		} else {
50			panic!("Unknown chain identity")
51		}
52	}
53}
54
55impl PartialEq for ChainIdentity {
56	fn eq(&self, other: &Self) -> bool {
57		#[allow(clippy::match_like_matches_macro)]
58		match (self, other) {
59			(ChainIdentity::Frequency, ChainIdentity::Frequency) => true,
60			(ChainIdentity::FrequencyPaseo, ChainIdentity::FrequencyPaseo) => true,
61			(ChainIdentity::FrequencyLocal, ChainIdentity::FrequencyLocal) => true,
62			(ChainIdentity::FrequencyDev, ChainIdentity::FrequencyDev) => true,
63			(ChainIdentity::FrequencyWestendLocal, ChainIdentity::FrequencyWestendLocal) => true,
64			(ChainIdentity::FrequencyWestend, ChainIdentity::FrequencyWestend) => true,
65			_ => false,
66		}
67	}
68}
69
70impl<T: sc_service::ChainSpec + 'static> IdentifyChain for T {
71	fn identify(&self) -> ChainIdentity {
72		<dyn sc_service::ChainSpec>::identify(self)
73	}
74}
75
76fn load_spec(id: &str) -> std::result::Result<Box<dyn ChainSpec>, String> {
77	match id {
78		#[cfg(feature = "runtime-benchmarks")]
79		"frequency-bench" => Ok(Box::new(chain_spec::frequency::benchmark_mainnet_config())),
80		#[cfg(feature = "frequency")]
81		"frequency" => Ok(Box::new(chain_spec::frequency::load_frequency_spec())),
82		#[cfg(feature = "frequency-no-relay")]
83		"dev" | "frequency-no-relay" => Ok(Box::new(chain_spec::frequency_dev::development_config())),
84		#[cfg(feature = "frequency-local")]
85		"frequency-paseo-local" =>
86			Ok(Box::new(chain_spec::frequency_paseo_local::local_paseo_testnet_config())),
87		#[cfg(feature = "frequency-bridging")]
88		"frequency-westend-local" =>
89			Ok(Box::new(chain_spec::frequency_westend_local::westend_local_config())),
90		#[cfg(feature = "frequency-testnet")]
91		"frequency-testnet" | "frequency-paseo" | "paseo" | "testnet" =>
92			Ok(Box::new(chain_spec::frequency_paseo::load_frequency_paseo_spec())),
93		#[cfg(feature = "frequency-westend")]
94		"frequency-westend" | "westend" =>
95			Ok(Box::new(chain_spec::frequency_westend::load_frequency_westend_spec())),
96		path => {
97			if path.is_empty() {
98				if cfg!(feature = "frequency") {
99					#[cfg(feature = "frequency")]
100					{
101						return Ok(Box::new(chain_spec::frequency::load_frequency_spec()));
102					}
103					#[cfg(not(feature = "frequency"))]
104					return Err("Frequency runtime is not available.".into());
105				} else if cfg!(feature = "frequency-no-relay") {
106					#[cfg(feature = "frequency-no-relay")]
107					{
108						return Ok(Box::new(chain_spec::frequency_dev::development_config()));
109					}
110					#[cfg(not(feature = "frequency-no-relay"))]
111					return Err("Frequency Development (no relay) runtime is not available.".into());
112				} else if cfg!(feature = "frequency-local") {
113					#[cfg(feature = "frequency-local")]
114					{
115						return Ok(Box::new(
116							chain_spec::frequency_paseo_local::local_paseo_testnet_config(),
117						));
118					}
119					#[cfg(not(feature = "frequency-local"))]
120					return Err("Frequency Local runtime is not available.".into());
121				} else if cfg!(feature = "frequency-bridging") {
122					#[cfg(feature = "frequency-bridging")]
123					{
124						return Ok(Box::new(
125							chain_spec::frequency_westend_local::westend_local_config(),
126						));
127					}
128					#[cfg(not(feature = "frequency-bridging"))]
129					return Err("Frequency Westend Local runtime is not available.".into());
130				} else if cfg!(feature = "frequency-testnet") {
131					#[cfg(feature = "frequency-testnet")]
132					{
133						return Ok(Box::new(
134							chain_spec::frequency_paseo::load_frequency_paseo_spec(),
135						));
136					}
137					#[cfg(not(feature = "frequency-testnet"))]
138					return Err("Frequency Paseo runtime is not available.".into());
139				} else if cfg!(feature = "frequency-westend") {
140					#[cfg(feature = "frequency-westend")]
141					{
142						return Ok(Box::new(
143							chain_spec::frequency_westend::load_frequency_westend_spec(),
144						));
145					}
146					#[cfg(not(feature = "frequency-westend"))]
147					return Err("Frequency Westend runtime is not available.".into());
148				} else {
149					return Err("No chain spec is available.".into());
150				}
151			}
152			let path_buf = std::path::PathBuf::from(path);
153			let spec = Box::new(chain_spec::DummyChainSpec::from_json_file(path_buf.clone())?)
154				as Box<dyn ChainSpec>;
155			if ChainIdentity::Frequency == spec.identify() {
156				#[cfg(feature = "frequency")]
157				{
158					Ok(Box::new(chain_spec::frequency::ChainSpec::from_json_file(path_buf)?))
159				}
160				#[cfg(not(feature = "frequency"))]
161				return Err("Frequency runtime is not available.".into());
162			} else if ChainIdentity::FrequencyPaseo == spec.identify() {
163				#[cfg(feature = "frequency-testnet")]
164				{
165					return Ok(Box::new(chain_spec::frequency_paseo::ChainSpec::from_json_file(
166						path_buf,
167					)?));
168				}
169				#[cfg(not(feature = "frequency-testnet"))]
170				return Err("Frequency Paseo runtime is not available.".into());
171			} else if ChainIdentity::FrequencyLocal == spec.identify() {
172				#[cfg(feature = "frequency-local")]
173				{
174					return Ok(Box::new(
175						chain_spec::frequency_paseo_local::ChainSpec::from_json_file(path_buf)?,
176					));
177				}
178				#[cfg(not(feature = "frequency-local"))]
179				return Err("Frequency Local runtime is not available.".into());
180			} else if ChainIdentity::FrequencyWestendLocal == spec.identify() {
181				#[cfg(feature = "frequency-bridging")]
182				{
183					return Ok(Box::new(
184						chain_spec::frequency_westend_local::ChainSpec::from_json_file(path_buf)?,
185					));
186				}
187				#[cfg(not(feature = "frequency-bridging"))]
188				return Err("Frequency Westend Local runtime is not available.".into());
189			} else if ChainIdentity::FrequencyDev == spec.identify() {
190				#[cfg(feature = "frequency-no-relay")]
191				{
192					return Ok(Box::new(
193						chain_spec::frequency_paseo_local::ChainSpec::from_json_file(path_buf)?,
194					));
195				}
196				#[cfg(not(feature = "frequency-no-relay"))]
197				return Err("Frequency Dev (no relay) runtime is not available.".into());
198			} else if ChainIdentity::FrequencyWestend == spec.identify() {
199				#[cfg(feature = "frequency-westend")]
200				{
201					return Ok(Box::new(chain_spec::frequency_westend::ChainSpec::from_json_file(
202						path_buf,
203					)?));
204				}
205				#[cfg(not(feature = "frequency-westend"))]
206				return Err("Frequency Westend runtime is not available.".into());
207			} else {
208				return Err("Unknown chain spec.".into());
209			}
210		},
211	}
212}
213
214fn chain_name() -> String {
215	"Frequency".into()
216}
217
218impl SubstrateCli for Cli {
219	fn impl_name() -> String {
220		format!("{} Node", chain_name())
221	}
222
223	fn impl_version() -> String {
224		env!("SUBSTRATE_CLI_IMPL_VERSION").into()
225	}
226
227	fn description() -> String {
228		"Frequency\n\nThe command-line arguments provided first will be \
229		passed to the parachain node, while the arguments provided after -- will be passed \
230		to the relay chain node.\n\n\
231		frequency <parachain-args> -- <relay-chain-args>"
232			.into()
233	}
234
235	fn author() -> String {
236		env!("CARGO_PKG_AUTHORS").into()
237	}
238
239	fn support_url() -> String {
240		"https://github.com/frequency-chain/frequency/issues/new".into()
241	}
242
243	fn copyright_start_year() -> i32 {
244		2020
245	}
246
247	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
248		load_spec(id)
249	}
250}
251
252impl Cli {
253	/// Returns a reference to the runtime version.
254	fn runtime_version() -> &'static RuntimeVersion {
255		&VERSION
256	}
257}
258
259impl SubstrateCli for RelayChainCli {
260	fn impl_name() -> String {
261		"Frequency".into()
262	}
263
264	fn impl_version() -> String {
265		env!("SUBSTRATE_CLI_IMPL_VERSION").into()
266	}
267
268	fn description() -> String {
269		"Frequency\n\nThe command-line arguments provided first will be \
270		passed to the parachain node, while the arguments provided after -- will be passed \
271		to the relay chain node.\n\n\
272		frequency <parachain-args> -- <relay-chain-args>"
273			.into()
274	}
275
276	fn author() -> String {
277		env!("CARGO_PKG_AUTHORS").into()
278	}
279
280	fn support_url() -> String {
281		"https://github.com/paritytech/cumulus/issues/new".into()
282	}
283
284	fn copyright_start_year() -> i32 {
285		2020
286	}
287
288	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
289		match id {
290			// TODO: Remove once on a Polkadot-SDK with Paseo-Local
291			#[cfg(feature = "frequency-local")]
292			"paseo-local" => Ok(Box::new(chain_spec::frequency_paseo_local::load_paseo_local_spec())),
293			// TODO: Remove once on a Polkadot-SDK with Paseo
294			#[cfg(feature = "frequency-testnet")]
295			"paseo" => Ok(Box::new(chain_spec::frequency_paseo::load_paseo_spec())),
296			_ => polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter())
297				.load_spec(id),
298		}
299	}
300}
301
302macro_rules! construct_async_run {
303	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{
304		let runner = $cli.create_runner($cmd)?;
305		runner.async_run(|$config| {
306				let $components = new_partial(&$config, false, None)?;
307				let task_manager = $components.task_manager;
308				{ $( $code )* }.map(|v| (v, task_manager))
309			})
310	}}
311}
312
313/// Parse command line arguments into service configuration.
314#[allow(clippy::result_large_err)]
315pub fn run() -> Result<()> {
316	let cli = Cli::from_args();
317
318	match &cli.subcommand {
319		Some(Subcommand::Key(cmd)) => cmd.run(&cli),
320		Some(Subcommand::BuildSpec(cmd)) => {
321			let runner = cli.create_runner(cmd)?;
322			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
323		},
324		Some(Subcommand::CheckBlock(cmd)) => {
325			construct_async_run!(|components, cli, cmd, config| {
326				Ok(cmd.run(components.client, components.import_queue))
327			})
328		},
329		Some(Subcommand::ExportBlocks(cmd)) => {
330			construct_async_run!(|components, cli, cmd, config| {
331				Ok(cmd.run(components.client, config.database))
332			})
333		},
334		Some(Subcommand::ExportState(cmd)) => {
335			construct_async_run!(|components, cli, cmd, config| {
336				Ok(cmd.run(components.client, config.chain_spec))
337			})
338		},
339		Some(Subcommand::ImportBlocks(cmd)) => {
340			construct_async_run!(|components, cli, cmd, config| {
341				Ok(cmd.run(components.client, components.import_queue))
342			})
343		},
344		Some(Subcommand::ExportMetadata(cmd)) => {
345			construct_async_run!(|components, cli, cmd, config| Ok(cmd.run(components.client)))
346		},
347		Some(Subcommand::PurgeChain(cmd)) => {
348			let runner = cli.create_runner(cmd)?;
349
350			runner.sync_run(|config| {
351				let polkadot_cli = RelayChainCli::new(
352					&config,
353					[RelayChainCli::executable_name()].iter().chain(cli.relay_chain_args.iter()),
354				);
355
356				let polkadot_config = SubstrateCli::create_configuration(
357					&polkadot_cli,
358					&polkadot_cli,
359					config.tokio_handle.clone(),
360				)
361				.map_err(|err| format!("Relay chain argument error: {err:?}"))?;
362
363				cmd.run(config, polkadot_config)
364			})
365		},
366		Some(Subcommand::Revert(cmd)) => {
367			construct_async_run!(|components, cli, cmd, config| {
368				Ok(cmd.run(components.client, components.backend, None))
369			})
370		},
371		Some(Subcommand::ExportGenesisHead(cmd)) => {
372			let runner = cli.create_runner(cmd)?;
373			runner.sync_run(|config| {
374				let partials = new_partial(&config, false, None)?;
375
376				cmd.run(partials.client)
377			})
378		},
379		Some(Subcommand::ExportGenesisWasm(cmd)) => {
380			let runner = cli.create_runner(cmd)?;
381			runner.sync_run(|_config| {
382				let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
383				cmd.run(&*spec)
384			})
385		},
386		Some(Subcommand::Benchmark(cmd)) => {
387			let runner = cli.create_runner(cmd)?;
388
389			match cmd {
390				BenchmarkCmd::Pallet(cmd) =>
391					if cfg!(feature = "runtime-benchmarks") {
392						runner.sync_run(|config| {
393							cmd.run_with_spec::<HashingFor<Block>, ReclaimHostFunctions>(Some(
394								config.chain_spec,
395							))
396						})
397					} else {
398						Err("Benchmarking wasn't enabled when building the node. \
399									You can enable it with `--features runtime-benchmarks`."
400							.into())
401					},
402				BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {
403					let partials = new_partial(&config, false, None)?;
404					cmd.run(partials.client)
405				}),
406				#[cfg(not(feature = "runtime-benchmarks"))]
407				BenchmarkCmd::Storage(_) =>
408					return Err(sc_cli::Error::Input(
409						"Compile with --features=runtime-benchmarks \
410						to enable storage benchmarks."
411							.into(),
412					)
413					.into()),
414				#[cfg(feature = "runtime-benchmarks")]
415				BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {
416					let partials = new_partial(&config, false, None)?;
417					let db = partials.backend.expose_db();
418					let storage = partials.backend.expose_storage();
419
420					cmd.run(config, partials.client.clone(), db, storage)
421				}),
422				BenchmarkCmd::Overhead(cmd) => runner.sync_run(|config| {
423					let partials = new_partial(&config, false, None)?;
424					let ext_builder = RemarkBuilder::new(partials.client.clone());
425					let should_record_proof = false;
426
427					cmd.run(
428						chain_name(),
429						partials.client,
430						inherent_benchmark_data()?,
431						Vec::new(),
432						&ext_builder,
433						should_record_proof,
434					)
435				}),
436				BenchmarkCmd::Machine(cmd) => runner.sync_run(|config| {
437					cmd.run(&config, frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE.clone())
438				}),
439				BenchmarkCmd::Extrinsic(_cmd) =>
440					Err("Benchmarking command not implemented.".into()),
441			}
442		},
443
444		Some(Subcommand::ExportRuntimeVersion(cmd)) => {
445			let runner = cli.create_runner(cmd)?;
446
447			runner.async_run(|config| {
448				let version = Cli::runtime_version();
449				// grab the task manager.
450				let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry);
451				let task_manager =
452					sc_service::TaskManager::new(config.tokio_handle.clone(), registry)
453						.map_err(|e| format!("Error: {e:?}"))?;
454				Ok((cmd.run(version), task_manager))
455			})
456		},
457		None => run_chain(cli),
458	}
459}
460
461// This appears messy but due to layers of Rust complexity, it's necessary.
462#[allow(clippy::result_large_err)]
463pub fn run_chain(cli: Cli) -> sc_service::Result<(), sc_cli::Error> {
464	#[allow(unused)]
465	let mut result: sc_service::Result<(), polkadot_cli::Error> = Ok(());
466	#[cfg(feature = "frequency-no-relay")]
467	{
468		result = crate::run_as_localchain::run_as_localchain(cli);
469	}
470	#[cfg(not(feature = "frequency-no-relay"))]
471	{
472		result = crate::run_as_parachain::run_as_parachain(cli);
473	}
474
475	result
476}
477
478impl DefaultConfigurationValues for RelayChainCli {
479	fn p2p_listen_port() -> u16 {
480		30334
481	}
482
483	fn rpc_listen_port() -> u16 {
484		9945
485	}
486
487	fn prometheus_listen_port() -> u16 {
488		9616
489	}
490}
491
492impl CliConfiguration<Self> for RelayChainCli {
493	fn shared_params(&self) -> &SharedParams {
494		self.base.base.shared_params()
495	}
496
497	fn import_params(&self) -> Option<&ImportParams> {
498		self.base.base.import_params()
499	}
500
501	fn network_params(&self) -> Option<&NetworkParams> {
502		self.base.base.network_params()
503	}
504
505	fn keystore_params(&self) -> Option<&KeystoreParams> {
506		self.base.base.keystore_params()
507	}
508
509	fn base_path(&self) -> Result<Option<BasePath>> {
510		Ok(self
511			.shared_params()
512			.base_path()?
513			.or_else(|| self.base_path.clone().map(Into::into)))
514	}
515
516	fn prometheus_config(
517		&self,
518		default_listen_port: u16,
519		chain_spec: &Box<dyn ChainSpec>,
520	) -> Result<Option<PrometheusConfig>> {
521		self.base.base.prometheus_config(default_listen_port, chain_spec)
522	}
523
524	fn init<F>(&self, _support_url: &String, _impl_version: &String, _logger_hook: F) -> Result<()>
525	where
526		F: FnOnce(&mut sc_cli::LoggerBuilder),
527	{
528		unreachable!("PolkadotCli is never initialized; qed");
529	}
530
531	fn chain_id(&self, is_dev: bool) -> Result<String> {
532		let chain_id = self.base.base.chain_id(is_dev)?;
533
534		Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id })
535	}
536
537	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {
538		self.base.base.role(is_dev)
539	}
540
541	fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {
542		self.base.base.transaction_pool(is_dev)
543	}
544
545	fn trie_cache_maximum_size(&self) -> Result<Option<usize>> {
546		self.base.base.trie_cache_maximum_size()
547	}
548
549	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {
550		self.base.base.rpc_methods()
551	}
552
553	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {
554		self.base.base.rpc_cors(is_dev)
555	}
556
557	fn default_heap_pages(&self) -> Result<Option<u64>> {
558		self.base.base.default_heap_pages()
559	}
560
561	fn disable_grandpa(&self) -> Result<bool> {
562		self.base.base.disable_grandpa()
563	}
564
565	fn max_runtime_instances(&self) -> Result<Option<usize>> {
566		self.base.base.max_runtime_instances()
567	}
568
569	fn announce_block(&self) -> Result<bool> {
570		self.base.base.announce_block()
571	}
572
573	fn telemetry_endpoints(
574		&self,
575		chain_spec: &Box<dyn ChainSpec>,
576	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {
577		self.base.base.telemetry_endpoints(chain_spec)
578	}
579
580	fn node_name(&self) -> Result<String> {
581		self.base.base.node_name()
582	}
583}