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.
314pub fn run() -> Result<()> {
315	let cli = Cli::from_args();
316
317	match &cli.subcommand {
318		Some(Subcommand::Key(cmd)) => cmd.run(&cli),
319		Some(Subcommand::BuildSpec(cmd)) => {
320			let runner = cli.create_runner(cmd)?;
321			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
322		},
323		Some(Subcommand::CheckBlock(cmd)) => {
324			construct_async_run!(|components, cli, cmd, config| {
325				Ok(cmd.run(components.client, components.import_queue))
326			})
327		},
328		Some(Subcommand::ExportBlocks(cmd)) => {
329			construct_async_run!(|components, cli, cmd, config| {
330				Ok(cmd.run(components.client, config.database))
331			})
332		},
333		Some(Subcommand::ExportState(cmd)) => {
334			construct_async_run!(|components, cli, cmd, config| {
335				Ok(cmd.run(components.client, config.chain_spec))
336			})
337		},
338		Some(Subcommand::ImportBlocks(cmd)) => {
339			construct_async_run!(|components, cli, cmd, config| {
340				Ok(cmd.run(components.client, components.import_queue))
341			})
342		},
343		Some(Subcommand::ExportMetadata(cmd)) => {
344			construct_async_run!(|components, cli, cmd, config| Ok(cmd.run(components.client)))
345		},
346		Some(Subcommand::PurgeChain(cmd)) => {
347			let runner = cli.create_runner(cmd)?;
348
349			runner.sync_run(|config| {
350				let polkadot_cli = RelayChainCli::new(
351					&config,
352					[RelayChainCli::executable_name()].iter().chain(cli.relay_chain_args.iter()),
353				);
354
355				let polkadot_config = SubstrateCli::create_configuration(
356					&polkadot_cli,
357					&polkadot_cli,
358					config.tokio_handle.clone(),
359				)
360				.map_err(|err| format!("Relay chain argument error: {err:?}"))?;
361
362				cmd.run(config, polkadot_config)
363			})
364		},
365		Some(Subcommand::Revert(cmd)) => {
366			construct_async_run!(|components, cli, cmd, config| {
367				Ok(cmd.run(components.client, components.backend, None))
368			})
369		},
370		Some(Subcommand::ExportGenesisHead(cmd)) => {
371			let runner = cli.create_runner(cmd)?;
372			runner.sync_run(|config| {
373				let partials = new_partial(&config, false, None)?;
374
375				cmd.run(partials.client)
376			})
377		},
378		Some(Subcommand::ExportGenesisWasm(cmd)) => {
379			let runner = cli.create_runner(cmd)?;
380			runner.sync_run(|_config| {
381				let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
382				cmd.run(&*spec)
383			})
384		},
385		Some(Subcommand::Benchmark(cmd)) => {
386			let runner = cli.create_runner(cmd)?;
387
388			match cmd {
389				BenchmarkCmd::Pallet(cmd) =>
390					if cfg!(feature = "runtime-benchmarks") {
391						runner.sync_run(|config| {
392							cmd.run_with_spec::<HashingFor<Block>, ReclaimHostFunctions>(Some(
393								config.chain_spec,
394							))
395						})
396					} else {
397						Err("Benchmarking wasn't enabled when building the node. \
398									You can enable it with `--features runtime-benchmarks`."
399							.into())
400					},
401				BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {
402					let partials = new_partial(&config, false, None)?;
403					cmd.run(partials.client)
404				}),
405				#[cfg(not(feature = "runtime-benchmarks"))]
406				BenchmarkCmd::Storage(_) =>
407					return Err(sc_cli::Error::Input(
408						"Compile with --features=runtime-benchmarks \
409						to enable storage benchmarks."
410							.into(),
411					)
412					.into()),
413				#[cfg(feature = "runtime-benchmarks")]
414				BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {
415					let partials = new_partial(&config, false, None)?;
416					let db = partials.backend.expose_db();
417					let storage = partials.backend.expose_storage();
418					let shared_cache = partials.backend.expose_shared_trie_cache();
419					cmd.run(config, partials.client.clone(), db, storage, shared_cache)
420				}),
421				BenchmarkCmd::Overhead(cmd) => runner.sync_run(|config| {
422					let partials = new_partial(&config, false, None)?;
423					let ext_builder = RemarkBuilder::new(partials.client.clone());
424					let should_record_proof = false;
425
426					cmd.run(
427						chain_name(),
428						partials.client,
429						inherent_benchmark_data()?,
430						Vec::new(),
431						&ext_builder,
432						should_record_proof,
433					)
434				}),
435				BenchmarkCmd::Machine(cmd) => runner.sync_run(|config| {
436					cmd.run(&config, frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE.clone())
437				}),
438				BenchmarkCmd::Extrinsic(_cmd) =>
439					Err("Benchmarking command not implemented.".into()),
440			}
441		},
442
443		Some(Subcommand::ExportRuntimeVersion(cmd)) => {
444			let runner = cli.create_runner(cmd)?;
445
446			runner.async_run(|config| {
447				let version = Cli::runtime_version();
448				// grab the task manager.
449				let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry);
450				let task_manager =
451					sc_service::TaskManager::new(config.tokio_handle.clone(), registry)
452						.map_err(|e| format!("Error: {e:?}"))?;
453				Ok((cmd.run(version), task_manager))
454			})
455		},
456		None => run_chain(cli),
457	}
458}
459
460// This appears messy but due to layers of Rust complexity, it's necessary.
461pub fn run_chain(cli: Cli) -> sc_service::Result<(), sc_cli::Error> {
462	#[allow(unused)]
463	let mut result: sc_service::Result<(), polkadot_cli::Error> = Ok(());
464	#[cfg(feature = "frequency-no-relay")]
465	{
466		result = crate::run_as_localchain::run_as_localchain(cli);
467	}
468	#[cfg(not(feature = "frequency-no-relay"))]
469	{
470		result = crate::run_as_parachain::run_as_parachain(cli);
471	}
472
473	result
474}
475
476impl DefaultConfigurationValues for RelayChainCli {
477	fn p2p_listen_port() -> u16 {
478		30334
479	}
480
481	fn rpc_listen_port() -> u16 {
482		9945
483	}
484
485	fn prometheus_listen_port() -> u16 {
486		9616
487	}
488}
489
490impl CliConfiguration<Self> for RelayChainCli {
491	fn shared_params(&self) -> &SharedParams {
492		self.base.base.shared_params()
493	}
494
495	fn import_params(&self) -> Option<&ImportParams> {
496		self.base.base.import_params()
497	}
498
499	fn network_params(&self) -> Option<&NetworkParams> {
500		self.base.base.network_params()
501	}
502
503	fn keystore_params(&self) -> Option<&KeystoreParams> {
504		self.base.base.keystore_params()
505	}
506
507	fn base_path(&self) -> Result<Option<BasePath>> {
508		Ok(self
509			.shared_params()
510			.base_path()?
511			.or_else(|| self.base_path.clone().map(Into::into)))
512	}
513
514	fn prometheus_config(
515		&self,
516		default_listen_port: u16,
517		chain_spec: &Box<dyn ChainSpec>,
518	) -> Result<Option<PrometheusConfig>> {
519		self.base.base.prometheus_config(default_listen_port, chain_spec)
520	}
521
522	fn init<F>(&self, _support_url: &String, _impl_version: &String, _logger_hook: F) -> Result<()>
523	where
524		F: FnOnce(&mut sc_cli::LoggerBuilder),
525	{
526		unreachable!("PolkadotCli is never initialized; qed");
527	}
528
529	fn chain_id(&self, is_dev: bool) -> Result<String> {
530		let chain_id = self.base.base.chain_id(is_dev)?;
531
532		Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id })
533	}
534
535	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {
536		self.base.base.role(is_dev)
537	}
538
539	fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {
540		self.base.base.transaction_pool(is_dev)
541	}
542
543	fn trie_cache_maximum_size(&self) -> Result<Option<usize>> {
544		self.base.base.trie_cache_maximum_size()
545	}
546
547	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {
548		self.base.base.rpc_methods()
549	}
550
551	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {
552		self.base.base.rpc_cors(is_dev)
553	}
554
555	fn default_heap_pages(&self) -> Result<Option<u64>> {
556		self.base.base.default_heap_pages()
557	}
558
559	fn disable_grandpa(&self) -> Result<bool> {
560		self.base.base.disable_grandpa()
561	}
562
563	fn max_runtime_instances(&self) -> Result<Option<usize>> {
564		self.base.base.max_runtime_instances()
565	}
566
567	fn announce_block(&self) -> Result<bool> {
568		self.base.base.announce_block()
569	}
570
571	fn telemetry_endpoints(
572		&self,
573		chain_spec: &Box<dyn ChainSpec>,
574	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {
575		self.base.base.telemetry_endpoints(chain_spec)
576	}
577
578	fn node_name(&self) -> Result<String> {
579		self.base.base.node_name()
580	}
581}