referrerpolicy=no-referrer-when-downgrade

polkadot_omni_node_lib/
command.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17use crate::{
18	cli::{Cli, RelayChainCli, Subcommand},
19	common::{
20		chain_spec::LoadSpec,
21		runtime::{
22			AuraConsensusId, Consensus, Runtime, RuntimeResolver as RuntimeResolverT,
23			RuntimeResolver,
24		},
25		spec::DynNodeSpec,
26		types::Block,
27		NodeBlock, NodeExtraArgs,
28	},
29	extra_subcommand::DefaultExtraSubcommands,
30	fake_runtime_api,
31	runtime::BlockNumber,
32};
33use clap::{CommandFactory, FromArgMatches};
34#[cfg(feature = "runtime-benchmarks")]
35use cumulus_client_service::storage_proof_size::HostFunctions as ReclaimHostFunctions;
36use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
37use log::info;
38use sc_cli::{Result, SubstrateCli};
39#[cfg(feature = "runtime-benchmarks")]
40use sp_runtime::traits::HashingFor;
41
42/// Structure that can be used in order to provide customizers for different functionalities of the
43/// node binary that is being built using this library.
44pub struct RunConfig {
45	/// A custom chain spec loader.
46	pub chain_spec_loader: Box<dyn LoadSpec>,
47	/// A custom runtime resolver.
48	pub runtime_resolver: Box<dyn RuntimeResolver>,
49}
50
51impl RunConfig {
52	/// Creates a new `RunConfig` instance.
53	pub fn new(
54		runtime_resolver: Box<dyn RuntimeResolver>,
55		chain_spec_loader: Box<dyn LoadSpec>,
56	) -> Self {
57		RunConfig { runtime_resolver, chain_spec_loader }
58	}
59}
60
61pub fn new_aura_node_spec<Block>(
62	aura_id: AuraConsensusId,
63	extra_args: &NodeExtraArgs,
64) -> Box<dyn DynNodeSpec>
65where
66	Block: NodeBlock,
67{
68	match aura_id {
69		AuraConsensusId::Sr25519 => crate::nodes::aura::new_aura_node_spec::<
70			Block,
71			fake_runtime_api::aura_sr25519::RuntimeApi,
72			sp_consensus_aura::sr25519::AuthorityId,
73		>(extra_args),
74		AuraConsensusId::Ed25519 => crate::nodes::aura::new_aura_node_spec::<
75			Block,
76			fake_runtime_api::aura_ed25519::RuntimeApi,
77			sp_consensus_aura::ed25519::AuthorityId,
78		>(extra_args),
79	}
80}
81
82fn new_node_spec(
83	config: &sc_service::Configuration,
84	runtime_resolver: &Box<dyn RuntimeResolverT>,
85	extra_args: &NodeExtraArgs,
86) -> std::result::Result<Box<dyn DynNodeSpec>, sc_cli::Error> {
87	let runtime = runtime_resolver.runtime(config.chain_spec.as_ref())?;
88
89	Ok(match runtime {
90		Runtime::Omni(block_number, consensus) => match (block_number, consensus) {
91			(BlockNumber::U32, Consensus::Aura(aura_id)) => {
92				new_aura_node_spec::<Block<u32>>(aura_id, extra_args)
93			},
94			(BlockNumber::U64, Consensus::Aura(aura_id)) => {
95				new_aura_node_spec::<Block<u64>>(aura_id, extra_args)
96			},
97		},
98	})
99}
100
101/// Parse command line arguments into service configuration.
102pub fn run<CliConfig: crate::cli::CliConfig>(cmd_config: RunConfig) -> Result<()> {
103	run_with_custom_cli::<CliConfig, DefaultExtraSubcommands>(cmd_config)
104}
105
106/// Parse command‑line arguments into service configuration and inject an
107/// optional extra sub‑command.
108///
109/// `run_with_custom_cli` builds the base CLI for the node binary, then asks the
110/// `Extra` type for an optional extra sub‑command.
111///
112/// When the user actually invokes that extra sub‑command,
113/// `Extra::from_arg_matches` returns a parsed value which is immediately passed
114/// to `extra.handle(&cfg)` and the process exits.  Otherwise control falls
115/// through to the normal node‑startup / utility sub‑command match.
116///
117/// # Type Parameters
118/// * `CliConfig` – customization trait supplying user‑facing info (name, description, version) for
119///   the binary.
120/// * `Extra` – an implementation of `ExtraSubcommand`. Use *`NoExtraSubcommand`* if the binary
121///   should not expose any extra subcommands.
122pub fn run_with_custom_cli<CliConfig, ExtraSubcommand>(cmd_config: RunConfig) -> Result<()>
123where
124	CliConfig: crate::cli::CliConfig,
125	ExtraSubcommand: crate::extra_subcommand::ExtraSubcommand,
126{
127	let cli_command = Cli::<CliConfig>::command();
128	let cli_command = ExtraSubcommand::augment_subcommands(cli_command);
129	let cli_command = Cli::<CliConfig>::setup_command(cli_command);
130
131	// Get matches for all CLI, including extra args.
132	let matches = cli_command.get_matches();
133
134	// Parse only the part corresponding to the extra args.
135	if let Ok(extra) = ExtraSubcommand::from_arg_matches(&matches) {
136		// Handle the extra, and return - subcommands are self contained,
137		// no need to handle the rest of the CLI or node running.
138		extra.handle(&cmd_config)?;
139		return Ok(());
140	}
141
142	// If matching on the extra subcommands fails, match on the rest of the node CLI as usual.
143	let mut cli =
144		Cli::<CliConfig>::from_arg_matches(&matches).map_err(|e| sc_cli::Error::Cli(e.into()))?;
145	cli.chain_spec_loader = Some(cmd_config.chain_spec_loader);
146	sc_network_statement::set_v2dht_enabled(cli.statement_v2_dht);
147
148	match &cli.subcommand {
149		Some(Subcommand::CheckBlock(cmd)) => {
150			let runner = cli.create_runner(cmd)?;
151			runner.async_run(|config| {
152				let node =
153					new_node_spec(&config, &cmd_config.runtime_resolver, &cli.node_extra_args())?;
154				node.prepare_check_block_cmd(config, cmd)
155			})
156		},
157		Some(Subcommand::ExportBlocks(cmd)) => {
158			let runner = cli.create_runner(cmd)?;
159			runner.async_run(|config| {
160				let node =
161					new_node_spec(&config, &cmd_config.runtime_resolver, &cli.node_extra_args())?;
162				node.prepare_export_blocks_cmd(config, cmd)
163			})
164		},
165		Some(Subcommand::ExportState(cmd)) => {
166			let runner = cli.create_runner(cmd)?;
167			runner.async_run(|config| {
168				let node =
169					new_node_spec(&config, &cmd_config.runtime_resolver, &cli.node_extra_args())?;
170				node.prepare_export_state_cmd(config, cmd)
171			})
172		},
173		Some(Subcommand::ImportBlocks(cmd)) => {
174			let runner = cli.create_runner(cmd)?;
175			runner.async_run(|config| {
176				let node =
177					new_node_spec(&config, &cmd_config.runtime_resolver, &cli.node_extra_args())?;
178				node.prepare_import_blocks_cmd(config, cmd)
179			})
180		},
181		Some(Subcommand::Revert(cmd)) => {
182			let runner = cli.create_runner(cmd)?;
183			runner.async_run(|config| {
184				let node =
185					new_node_spec(&config, &cmd_config.runtime_resolver, &cli.node_extra_args())?;
186				node.prepare_revert_cmd(config, cmd)
187			})
188		},
189		Some(Subcommand::ChainSpecBuilder(cmd)) => {
190			cmd.run().map_err(|err| sc_cli::Error::Application(err.into()))
191		},
192
193		Some(Subcommand::PurgeChain(cmd)) => {
194			let runner = cli.create_runner(cmd)?;
195			let polkadot_cli =
196				RelayChainCli::<CliConfig>::new(runner.config(), cli.relay_chain_args.iter());
197
198			runner.sync_run(|config| {
199				let polkadot_config = SubstrateCli::create_configuration(
200					&polkadot_cli,
201					&polkadot_cli,
202					config.tokio_handle.clone(),
203				)
204				.map_err(|err| format!("Relay chain argument error: {}", err))?;
205
206				cmd.run(config, polkadot_config)
207			})
208		},
209		Some(Subcommand::ExportGenesisHead(cmd)) => {
210			let runner = cli.create_runner(cmd)?;
211			runner.sync_run(|config| {
212				let node =
213					new_node_spec(&config, &cmd_config.runtime_resolver, &cli.node_extra_args())?;
214				node.run_export_genesis_head_cmd(config, cmd)
215			})
216		},
217		Some(Subcommand::ExportGenesisWasm(cmd)) => {
218			let runner = cli.create_runner(cmd)?;
219			runner.sync_run(|_config| {
220				let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
221				cmd.run(&*spec)
222			})
223		},
224		Some(Subcommand::Benchmark(cmd)) => {
225			// Switch on the concrete benchmark sub-command-
226			match cmd {
227				#[cfg(feature = "runtime-benchmarks")]
228				BenchmarkCmd::Pallet(cmd) => {
229					let chain = cmd
230						.shared_params
231						.chain
232						.as_ref()
233						.map(|chain| cli.load_spec(&chain))
234						.transpose()?;
235					cmd.run_with_spec::<HashingFor<Block<u32>>, ReclaimHostFunctions>(chain)
236				},
237				BenchmarkCmd::Block(cmd) => {
238					// The command needs the full node configuration because it uses the node
239					// client and the database source, which in its turn has a dependency on the
240					// chain spec, given via the `--chain` flag.
241					let runner = cli.create_runner(cmd)?;
242					runner.sync_run(|config| {
243						let node = new_node_spec(
244							&config,
245							&cmd_config.runtime_resolver,
246							&cli.node_extra_args(),
247						)?;
248						node.run_benchmark_block_cmd(config, cmd)
249					})
250				},
251				#[cfg(feature = "runtime-benchmarks")]
252				BenchmarkCmd::Storage(cmd) => {
253					// The command needs the full node configuration because it uses the node
254					// client and the database API, storage and shared_trie_cache. It requires
255					// the `--chain` flag to be passed.
256					let runner = cli.create_runner(cmd)?;
257					runner.sync_run(|config| {
258						let node = new_node_spec(
259							&config,
260							&cmd_config.runtime_resolver,
261							&cli.node_extra_args(),
262						)?;
263						node.run_benchmark_storage_cmd(config, cmd)
264					})
265				},
266				BenchmarkCmd::Machine(cmd) => {
267					// The command needs the full node configuration, and implicitly a chain
268					// spec to be passed, even if it doesn't use it directly. The `--chain` flag is
269					// relevant in determining the database path, which is used for the disk
270					// benchmark.
271					//
272					// TODO: change `machine` subcommand to take instead a disk path we want to
273					// benchmark?.
274					let runner = cli.create_runner(cmd)?;
275					runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))
276				},
277				#[allow(unreachable_patterns)]
278				_ => Err("Benchmarking sub-command unsupported or compilation feature missing. \
279					Make sure to compile omni-node with --features=runtime-benchmarks \
280					to enable all supported benchmarks."
281					.into()),
282			}
283		},
284		Some(Subcommand::Key(cmd)) => Ok(cmd.run(&cli)?),
285		None => {
286			let runner = cli.create_runner(&cli.run.normalize())?;
287			let polkadot_cli =
288				RelayChainCli::<CliConfig>::new(runner.config(), cli.relay_chain_args.iter());
289			let collator_options = cli.run.collator_options();
290
291			runner.run_node_until_exit(|config| async move {
292				let node_extra_args = cli.node_extra_args();
293				let node_spec =
294					new_node_spec(&config, &cmd_config.runtime_resolver, &node_extra_args)?;
295
296				if let Some(dev_mode) = cli.dev_mode() {
297					return node_spec
298						.start_dev_node(config, dev_mode, node_extra_args)
299						.map_err(Into::into);
300				}
301
302				// If Statemint (Statemine, Westmint, Rockmine) DB exists and we're using the
303				// asset-hub chain spec, then rename the base path to the new chain ID. In the case
304				// that both file paths exist, the node will exit, as the user must decide (by
305				// deleting one path) the information that they want to use as their DB.
306				let old_name = match config.chain_spec.id() {
307					"asset-hub-polkadot" => Some("statemint"),
308					"asset-hub-kusama" => Some("statemine"),
309					"asset-hub-westend" => Some("westmint"),
310					"asset-hub-rococo" => Some("rockmine"),
311					_ => None,
312				};
313
314				if let Some(old_name) = old_name {
315					let new_path = config.base_path.config_dir(config.chain_spec.id());
316					let old_path = config.base_path.config_dir(old_name);
317
318					if old_path.exists() && new_path.exists() {
319						return Err(format!(
320							"Found legacy {} path {} and new Asset Hub path {}. \
321							Delete one path such that only one exists.",
322							old_name,
323							old_path.display(),
324							new_path.display()
325						)
326						.into());
327					}
328
329					if old_path.exists() {
330						std::fs::rename(old_path.clone(), new_path.clone())?;
331						info!(
332							"{} was renamed to Asset Hub. The filepath with associated data on disk \
333							has been renamed from {} to {}.",
334							old_name,
335							old_path.display(),
336							new_path.display()
337						);
338					}
339				}
340
341				let hwbench = (!cli.no_hardware_benchmarks)
342					.then(|| {
343						config.database.path().map(|database_path| {
344							let _ = std::fs::create_dir_all(database_path);
345							sc_sysinfo::gather_hwbench(
346								Some(database_path),
347								&SUBSTRATE_REFERENCE_HARDWARE,
348							)
349						})
350					})
351					.flatten();
352				let tokio_handle = config.tokio_handle.clone();
353				let mut polkadot_config =
354					SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, tokio_handle)
355						.map_err(|err| format!("Relay chain argument error: {}", err))?;
356
357				// The relay chain side of a collator doesn't listen on WebRTC by default;
358				// `--force-enable-webrtc` or explicit `--listen-addr` take precedence.
359				let relay_network_params = &polkadot_cli.base.base.network_params;
360				if config.role.is_authority() &&
361					!relay_network_params.force_enable_webrtc &&
362					relay_network_params.listen_addr.is_empty()
363				{
364					polkadot_config.network.remove_webrtc_addresses();
365				}
366
367				info!("✍️ Is collating: {}", if config.role.is_authority() { "yes" } else { "no" });
368
369				node_spec
370					.start_node(
371						config,
372						polkadot_config,
373						collator_options,
374						hwbench,
375						cli.node_extra_args(),
376					)
377					.await
378					.map_err(Into::into)
379			})
380		},
381	}
382}