referrerpolicy=no-referrer-when-downgrade

polkadot_omni_node_lib/
cli.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
17//! CLI options of the omni-node. See [`Command`].
18
19/// Default block time for dev mode when using `--dev` flag.
20const DEFAULT_DEV_BLOCK_TIME_MS: u64 = 3000;
21
22use crate::{
23	chain_spec::DiskChainSpecLoader,
24	common::{
25		chain_spec::{Extensions, LoadSpec},
26		NodeExtraArgs,
27	},
28};
29use chain_spec_builder::ChainSpecBuilder;
30use clap::{Command, CommandFactory, FromArgMatches, ValueEnum};
31use sc_chain_spec::ChainSpec;
32use sc_cli::{
33	CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, NetworkParams,
34	RpcEndpoint, SharedParams, SubstrateCli,
35};
36use sc_service::{config::PrometheusConfig, BasePath};
37use sc_storage_monitor::StorageMonitorParams;
38use std::{
39	fmt::{Display, Formatter},
40	marker::PhantomData,
41	path::PathBuf,
42};
43/// Trait that can be used to customize some of the customer-facing info related to the node binary
44/// that is being built using this library.
45///
46/// The related info is shown to the customer as part of logs or help messages.
47/// It does not impact functionality.
48pub trait CliConfig {
49	/// The version of the resulting node binary.
50	fn impl_version() -> String;
51
52	/// The description of the resulting node binary.
53	fn description(executable_name: String) -> String {
54		format!(
55			"The command-line arguments provided first will be passed to the parachain node, \n\
56			and the arguments provided after -- will be passed to the relay chain node. \n\
57			\n\
58			Example: \n\
59			\n\
60			{} [parachain-args] -- [relay-chain-args]",
61			executable_name
62		)
63	}
64
65	/// The author of the resulting node binary.
66	fn author() -> String;
67
68	/// The support URL for the resulting node binary.
69	fn support_url() -> String;
70
71	/// The starting copyright year of the resulting node binary.
72	fn copyright_start_year() -> u16;
73}
74
75/// Sub-commands supported by the collator.
76#[derive(Debug, clap::Subcommand)]
77pub enum Subcommand {
78	/// Key management CLI utilities
79	#[command(subcommand)]
80	Key(sc_cli::KeySubcommand),
81
82	/// Build a chain specification.
83	///
84	/// The `build-spec` command relies on the chain specification built (hard-coded) into the node
85	/// binary, and may utilize the genesis presets of the runtimes  also embedded in the nodes
86	/// that support  this command. Since `polkadot-omni-node` does not contain any embedded
87	/// runtime, and requires a `chain-spec` path to be passed to its `--chain` flag, the command
88	/// isn't bringing significant value as it does for other node binaries (e.g. the
89	///  `polkadot` binary).
90	///
91	/// For a more versatile `chain-spec` manipulation experience please check out the
92	/// `polkadot-omni-node chain-spec-builder` subcommand.
93	#[deprecated(
94		note = "build-spec will be removed after 1/06/2025. Use chain-spec-builder instead"
95	)]
96	BuildSpec(sc_cli::BuildSpecCmd),
97
98	/// Validate blocks.
99	CheckBlock(sc_cli::CheckBlockCmd),
100
101	/// Export blocks.
102	ExportBlocks(sc_cli::ExportBlocksCmd),
103
104	/// Export the state of a given block into a chain spec.
105	ExportState(sc_cli::ExportStateCmd),
106
107	/// Import blocks.
108	ImportBlocks(sc_cli::ImportBlocksCmd),
109
110	/// Revert the chain to a previous state.
111	Revert(sc_cli::RevertCmd),
112
113	/// Subcommand for generating and managing chain specifications.
114	///
115	/// A `chain-spec-builder` subcommand corresponds to the existing `chain-spec-builder` tool
116	/// (<https://crates.io/crates/staging-chain-spec-builder>), which can be used already standalone.
117	/// It provides the same functionality as the tool but bundled with `polkadot-omni-node` to
118	/// enable easier access to chain-spec generation, patching, converting to raw or validation,
119	/// from a single binary, which can be used as a parachain node tool
120	/// For a detailed usage guide please check out the standalone tool's crates.io or docs.rs
121	/// pages:
122	/// - <https://crates.io/crates/staging-chain-spec-builder>
123	/// - <https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/>
124	ChainSpecBuilder(ChainSpecBuilder),
125
126	/// Remove the whole chain.
127	PurgeChain(cumulus_client_cli::PurgeChainCmd),
128	/// Export the genesis state of the parachain.
129	#[command(alias = "export-genesis-state")]
130	ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand),
131
132	/// Export the genesis wasm of the parachain.
133	ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand),
134
135	/// Sub-commands concerned with benchmarking.
136	/// The pallet benchmarking moved to the `pallet` sub-command.
137	#[command(subcommand)]
138	Benchmark(frame_benchmarking_cli::BenchmarkCmd),
139}
140
141/// CLI Options shipped with `polkadot-omni-node`.
142#[derive(clap::Parser)]
143#[command(
144	propagate_version = true,
145	args_conflicts_with_subcommands = true,
146	subcommand_negates_reqs = true
147)]
148pub struct Cli<Config: CliConfig> {
149	#[arg(skip)]
150	pub(crate) chain_spec_loader: Option<Box<dyn LoadSpec>>,
151
152	/// Possible subcommands. See [`Subcommand`].
153	#[command(subcommand)]
154	pub subcommand: Option<Subcommand>,
155
156	/// The shared parameters with all cumulus-based parachain nodes.
157	#[command(flatten)]
158	pub run: cumulus_client_cli::RunCmd,
159
160	/// Parameters for storage monitoring.
161	#[command(flatten)]
162	pub storage_monitor: StorageMonitorParams,
163
164	/// Start a dev node that produces a block each `dev_block_time` ms.
165	///
166	/// This is a dev option. It enables a manual sealing, meaning blocks are produced manually
167	/// rather than being part of an actual network consensus process. Using the option won't
168	/// result in starting or connecting to a parachain network. The resulting node will work on
169	/// its own, running the wasm blob and artificially producing a block each `dev_block_time` ms,
170	/// as if it was part of a parachain.
171	///
172	/// The `--dev` flag sets the `dev_block_time` to a default value of 3000ms unless explicitly
173	/// provided.
174	#[arg(long, conflicts_with = "instant_seal")]
175	pub dev_block_time: Option<u64>,
176
177	/// Start a dev node with instant seal.
178	///
179	/// This is a dev option that enables instant sealing, meaning blocks are produced
180	/// immediately when transactions are received, rather than at fixed intervals.
181	/// Using this option won't result in starting or connecting to a parachain network.
182	/// The resulting node will work on its own, running the wasm blob and producing blocks
183	/// instantly upon receiving transactions.
184	#[arg(long, conflicts_with = "dev_block_time")]
185	pub instant_seal: bool,
186
187	/// DEPRECATED: This feature has been stabilized, pLease use `--authoring slot-based` instead.
188	///
189	/// Use slot-based collator which can handle elastic scaling.
190	/// Use with care, this flag is unstable and subject to change.
191	#[arg(long, conflicts_with = "authoring")]
192	pub experimental_use_slot_based: bool,
193
194	/// Authoring style to use.
195	#[arg(long, default_value_t = AuthoringPolicy::Lookahead)]
196	pub authoring: AuthoringPolicy,
197
198	/// Disable automatic hardware benchmarks.
199	///
200	/// By default these benchmarks are automatically ran at startup and measure
201	/// the CPU speed, the memory bandwidth and the disk speed.
202	///
203	/// The results are then printed out in the logs, and also sent as part of
204	/// telemetry, if telemetry is enabled.
205	#[arg(long)]
206	pub no_hardware_benchmarks: bool,
207
208	/// Export all `PoVs` build by this collator to the given folder.
209	///
210	/// This is useful for debugging issues that are occurring while validating these `PoVs` on the
211	/// relay chain.
212	#[arg(long)]
213	pub export_pov_to_path: Option<PathBuf>,
214
215	/// Relay chain arguments
216	#[arg(raw = true)]
217	pub relay_chain_args: Vec<String>,
218
219	/// Enable the statement store.
220	///
221	/// The statement store is a store for statements validated using the runtime API
222	/// `validate_statement`. It should be enabled for chains that provide this runtime API.
223	#[arg(long)]
224	pub enable_statement_store: bool,
225
226	#[arg(skip)]
227	pub(crate) _phantom: PhantomData<Config>,
228}
229
230/// Development sealing mode.
231#[derive(Debug, Clone, Copy)]
232pub(crate) enum DevSealMode {
233	/// Produces blocks immediately upon receiving transactions.
234	InstantSeal,
235	/// Produces blocks at fixed time intervals.
236	/// The u64 parameter represents the block time in milliseconds.
237	ManualSeal(u64),
238}
239
240/// Collator implementation to use.
241#[derive(PartialEq, Debug, ValueEnum, Clone, Copy)]
242pub enum AuthoringPolicy {
243	/// Use the lookahead collator. Builds a block once per imported relay chain block and
244	/// on relay chain forks. Default for asynchronous backing chains.
245	Lookahead,
246	/// Use the slot-based collator. Builds a block based on time. Can utilize multiple cores,
247	/// always builds on the best relay chain block available. Should be used with elastic-scaling
248	/// chains.
249	SlotBased,
250}
251
252impl Display for AuthoringPolicy {
253	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
254		match self {
255			AuthoringPolicy::Lookahead => write!(f, "lookahead"),
256			AuthoringPolicy::SlotBased => write!(f, "slot-based"),
257		}
258	}
259}
260
261impl<Config: CliConfig> Cli<Config> {
262	pub(crate) fn node_extra_args(&self) -> NodeExtraArgs {
263		NodeExtraArgs {
264			authoring_policy: self
265				.experimental_use_slot_based
266				.then(|| AuthoringPolicy::SlotBased)
267				.unwrap_or(self.authoring),
268			export_pov: self.export_pov_to_path.clone(),
269			max_pov_percentage: self.run.experimental_max_pov_percentage,
270			enable_statement_store: self.enable_statement_store,
271			storage_monitor: self.storage_monitor.clone(),
272		}
273	}
274
275	/// Returns the dev seal mode if the node is in dev mode.
276	pub(crate) fn dev_mode(&self) -> Option<DevSealMode> {
277		if self.instant_seal {
278			Some(DevSealMode::InstantSeal)
279		} else if let Some(dev_block_time) = self.dev_block_time {
280			Some(DevSealMode::ManualSeal(dev_block_time))
281		} else if self.run.base.is_dev().unwrap_or(false) {
282			Some(DevSealMode::ManualSeal(DEFAULT_DEV_BLOCK_TIME_MS))
283		} else {
284			None
285		}
286	}
287}
288
289impl<Config: CliConfig> SubstrateCli for Cli<Config> {
290	fn impl_name() -> String {
291		Self::executable_name()
292	}
293
294	fn impl_version() -> String {
295		Config::impl_version()
296	}
297
298	fn description() -> String {
299		Config::description(Self::executable_name())
300	}
301
302	fn author() -> String {
303		Config::author()
304	}
305
306	fn support_url() -> String {
307		Config::support_url()
308	}
309
310	fn copyright_start_year() -> i32 {
311		Config::copyright_start_year() as i32
312	}
313
314	fn load_spec(&self, id: &str) -> Result<Box<dyn ChainSpec>, String> {
315		match &self.chain_spec_loader {
316			Some(chain_spec_loader) => chain_spec_loader.load_spec(id),
317			None => DiskChainSpecLoader.load_spec(id),
318		}
319	}
320}
321
322/// The relay chain CLI flags. These are passed in after a `--` at the end.
323#[derive(Debug)]
324pub struct RelayChainCli<Config: CliConfig> {
325	/// The actual relay chain cli object.
326	pub base: polkadot_cli::RunCmd,
327
328	/// Optional chain id that should be passed to the relay chain.
329	pub chain_id: Option<String>,
330
331	/// The base path that should be used by the relay chain.
332	pub base_path: Option<PathBuf>,
333
334	_phantom: PhantomData<Config>,
335}
336
337impl<Config: CliConfig> RelayChainCli<Config> {
338	fn polkadot_cmd() -> Command {
339		let help_template = color_print::cformat!(
340			"The arguments that are passed to the relay chain node. \n\
341			\n\
342			<bold><underline>RELAY_CHAIN_ARGS:</></> \n\
343			{{options}}",
344		);
345
346		polkadot_cli::RunCmd::command()
347			.no_binary_name(true)
348			.help_template(help_template)
349	}
350
351	/// Parse the relay chain CLI parameters using the parachain `Configuration`.
352	pub fn new<'a>(
353		para_config: &sc_service::Configuration,
354		relay_chain_args: impl Iterator<Item = &'a String>,
355	) -> Self {
356		let polkadot_cmd = Self::polkadot_cmd();
357		let matches = polkadot_cmd.get_matches_from(relay_chain_args);
358		let base = FromArgMatches::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
359
360		let extension = Extensions::try_get(&*para_config.chain_spec);
361		let chain_id = extension.map(|e| e.relay_chain());
362
363		let base_path = para_config.base_path.path().join("polkadot");
364		Self { base, chain_id, base_path: Some(base_path), _phantom: Default::default() }
365	}
366}
367
368impl<Config: CliConfig> SubstrateCli for RelayChainCli<Config> {
369	fn impl_name() -> String {
370		Cli::<Config>::impl_name()
371	}
372
373	fn impl_version() -> String {
374		Cli::<Config>::impl_version()
375	}
376
377	fn description() -> String {
378		Cli::<Config>::description()
379	}
380
381	fn author() -> String {
382		Cli::<Config>::author()
383	}
384
385	fn support_url() -> String {
386		Cli::<Config>::support_url()
387	}
388
389	fn copyright_start_year() -> i32 {
390		Cli::<Config>::copyright_start_year()
391	}
392
393	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn ChainSpec>, String> {
394		polkadot_cli::Cli::from_iter([Self::executable_name()].iter()).load_spec(id)
395	}
396}
397
398impl<Config: CliConfig> DefaultConfigurationValues for RelayChainCli<Config> {
399	fn p2p_listen_port() -> u16 {
400		30334
401	}
402
403	fn rpc_listen_port() -> u16 {
404		9945
405	}
406
407	fn prometheus_listen_port() -> u16 {
408		9616
409	}
410}
411
412impl<Config: CliConfig> CliConfiguration<Self> for RelayChainCli<Config> {
413	fn shared_params(&self) -> &SharedParams {
414		self.base.base.shared_params()
415	}
416
417	fn import_params(&self) -> Option<&ImportParams> {
418		self.base.base.import_params()
419	}
420
421	fn network_params(&self) -> Option<&NetworkParams> {
422		self.base.base.network_params()
423	}
424
425	fn keystore_params(&self) -> Option<&KeystoreParams> {
426		self.base.base.keystore_params()
427	}
428
429	fn base_path(&self) -> sc_cli::Result<Option<BasePath>> {
430		Ok(self
431			.shared_params()
432			.base_path()?
433			.or_else(|| self.base_path.clone().map(Into::into)))
434	}
435
436	fn rpc_addr(&self, default_listen_port: u16) -> sc_cli::Result<Option<Vec<RpcEndpoint>>> {
437		self.base.base.rpc_addr(default_listen_port)
438	}
439
440	fn prometheus_config(
441		&self,
442		default_listen_port: u16,
443		chain_spec: &Box<dyn ChainSpec>,
444	) -> sc_cli::Result<Option<PrometheusConfig>> {
445		self.base.base.prometheus_config(default_listen_port, chain_spec)
446	}
447
448	fn init<F>(
449		&self,
450		_support_url: &String,
451		_impl_version: &String,
452		_logger_hook: F,
453	) -> sc_cli::Result<()>
454	where
455		F: FnOnce(&mut sc_cli::LoggerBuilder),
456	{
457		unreachable!("PolkadotCli is never initialized; qed");
458	}
459
460	fn chain_id(&self, is_dev: bool) -> sc_cli::Result<String> {
461		let chain_id = self.base.base.chain_id(is_dev)?;
462
463		Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id })
464	}
465
466	fn role(&self, is_dev: bool) -> sc_cli::Result<sc_service::Role> {
467		self.base.base.role(is_dev)
468	}
469
470	fn transaction_pool(
471		&self,
472		is_dev: bool,
473	) -> sc_cli::Result<sc_service::config::TransactionPoolOptions> {
474		self.base.base.transaction_pool(is_dev)
475	}
476
477	fn trie_cache_maximum_size(&self) -> sc_cli::Result<Option<usize>> {
478		self.base.base.trie_cache_maximum_size()
479	}
480
481	fn rpc_methods(&self) -> sc_cli::Result<sc_service::config::RpcMethods> {
482		self.base.base.rpc_methods()
483	}
484
485	fn rpc_max_connections(&self) -> sc_cli::Result<u32> {
486		self.base.base.rpc_max_connections()
487	}
488
489	fn rpc_cors(&self, is_dev: bool) -> sc_cli::Result<Option<Vec<String>>> {
490		self.base.base.rpc_cors(is_dev)
491	}
492
493	fn default_heap_pages(&self) -> sc_cli::Result<Option<u64>> {
494		self.base.base.default_heap_pages()
495	}
496
497	fn force_authoring(&self) -> sc_cli::Result<bool> {
498		self.base.base.force_authoring()
499	}
500
501	fn disable_grandpa(&self) -> sc_cli::Result<bool> {
502		self.base.base.disable_grandpa()
503	}
504
505	fn max_runtime_instances(&self) -> sc_cli::Result<Option<usize>> {
506		self.base.base.max_runtime_instances()
507	}
508
509	fn announce_block(&self) -> sc_cli::Result<bool> {
510		self.base.base.announce_block()
511	}
512
513	fn telemetry_endpoints(
514		&self,
515		chain_spec: &Box<dyn ChainSpec>,
516	) -> sc_cli::Result<Option<sc_telemetry::TelemetryEndpoints>> {
517		self.base.base.telemetry_endpoints(chain_spec)
518	}
519
520	fn node_name(&self) -> sc_cli::Result<String> {
521		self.base.base.node_name()
522	}
523}