Skip to main content

sc_cli/
arg_enums.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Definitions of [`ValueEnum`] types.
20
21use clap::ValueEnum;
22use std::str::FromStr;
23
24/// The instantiation strategy to use in compiled mode.
25#[derive(Debug, Clone, Copy, ValueEnum)]
26#[value(rename_all = "kebab-case")]
27pub enum WasmtimeInstantiationStrategy {
28	/// Pool the instances to avoid initializing everything from scratch
29	/// on each instantiation. Use copy-on-write memory when possible.
30	PoolingCopyOnWrite,
31
32	/// Recreate the instance from scratch on every instantiation.
33	/// Use copy-on-write memory when possible.
34	RecreateInstanceCopyOnWrite,
35
36	/// Pool the instances to avoid initializing everything from scratch
37	/// on each instantiation.
38	Pooling,
39
40	/// Recreate the instance from scratch on every instantiation. Very slow.
41	RecreateInstance,
42}
43
44/// The default [`WasmtimeInstantiationStrategy`].
45pub const DEFAULT_WASMTIME_INSTANTIATION_STRATEGY: WasmtimeInstantiationStrategy =
46	WasmtimeInstantiationStrategy::PoolingCopyOnWrite;
47
48/// How to execute Wasm runtime code.
49#[derive(Debug, Clone, Copy, ValueEnum)]
50#[value(rename_all = "kebab-case")]
51pub enum WasmExecutionMethod {
52	/// Uses an interpreter which now is deprecated.
53	#[clap(name = "interpreted-i-know-what-i-do")]
54	Interpreted,
55	/// Uses a compiled runtime.
56	Compiled,
57}
58
59impl std::fmt::Display for WasmExecutionMethod {
60	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61		match self {
62			Self::Interpreted => write!(f, "Interpreted"),
63			Self::Compiled => write!(f, "Compiled"),
64		}
65	}
66}
67
68/// Converts the execution method and instantiation strategy command line arguments
69/// into an execution method which can be used internally.
70pub fn execution_method_from_cli(
71	execution_method: WasmExecutionMethod,
72	instantiation_strategy: WasmtimeInstantiationStrategy,
73) -> sc_service::config::WasmExecutionMethod {
74	if let WasmExecutionMethod::Interpreted = execution_method {
75		log::warn!(
76			"`interpreted-i-know-what-i-do` is deprecated and will be removed in the future. Defaults to `compiled` execution mode."
77		);
78	}
79
80	sc_service::config::WasmExecutionMethod::Compiled {
81		instantiation_strategy: match instantiation_strategy {
82			WasmtimeInstantiationStrategy::PoolingCopyOnWrite => {
83				sc_service::config::WasmtimeInstantiationStrategy::PoolingCopyOnWrite
84			},
85			WasmtimeInstantiationStrategy::RecreateInstanceCopyOnWrite => {
86				sc_service::config::WasmtimeInstantiationStrategy::RecreateInstanceCopyOnWrite
87			},
88			WasmtimeInstantiationStrategy::Pooling => {
89				sc_service::config::WasmtimeInstantiationStrategy::Pooling
90			},
91			WasmtimeInstantiationStrategy::RecreateInstance => {
92				sc_service::config::WasmtimeInstantiationStrategy::RecreateInstance
93			},
94		},
95	}
96}
97
98/// The default [`WasmExecutionMethod`].
99pub const DEFAULT_WASM_EXECUTION_METHOD: WasmExecutionMethod = WasmExecutionMethod::Compiled;
100
101#[allow(missing_docs)]
102#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
103#[value(rename_all = "kebab-case")]
104pub enum TracingReceiver {
105	/// Output the tracing records using the log.
106	Log,
107}
108
109impl Into<sc_tracing::TracingReceiver> for TracingReceiver {
110	fn into(self) -> sc_tracing::TracingReceiver {
111		match self {
112			TracingReceiver::Log => sc_tracing::TracingReceiver::Log,
113		}
114	}
115}
116
117/// The type of the node key.
118#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
119#[value(rename_all = "kebab-case")]
120pub enum NodeKeyType {
121	/// Use ed25519.
122	Ed25519,
123}
124
125/// The crypto scheme to use.
126#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
127#[value(rename_all = "kebab-case")]
128pub enum CryptoScheme {
129	/// Use ed25519.
130	Ed25519,
131	/// Use sr25519.
132	Sr25519,
133	/// Use ecdsa.
134	Ecdsa,
135}
136
137/// The type of the output format.
138#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
139#[value(rename_all = "kebab-case")]
140pub enum OutputType {
141	/// Output as json.
142	Json,
143	/// Output as text.
144	Text,
145}
146
147/// How to execute blocks
148#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
149#[value(rename_all = "kebab-case")]
150pub enum ExecutionStrategy {
151	/// Execute with native build (if available, WebAssembly otherwise).
152	Native,
153	/// Only execute with the WebAssembly build.
154	Wasm,
155	/// Execute with both native (where available) and WebAssembly builds.
156	Both,
157	/// Execute with the native build if possible; if it fails, then execute with WebAssembly.
158	NativeElseWasm,
159}
160
161/// Available RPC methods.
162#[allow(missing_docs)]
163#[derive(Debug, Copy, Clone, PartialEq, ValueEnum)]
164#[value(rename_all = "kebab-case")]
165pub enum RpcMethods {
166	/// Expose every RPC method only when RPC is listening on `localhost`,
167	/// otherwise serve only safe RPC methods.
168	Auto,
169	/// Allow only a safe subset of RPC methods.
170	Safe,
171	/// Expose every RPC method (even potentially unsafe ones).
172	Unsafe,
173}
174
175impl FromStr for RpcMethods {
176	type Err = String;
177
178	fn from_str(s: &str) -> Result<Self, Self::Err> {
179		match s {
180			"safe" => Ok(RpcMethods::Safe),
181			"unsafe" => Ok(RpcMethods::Unsafe),
182			"auto" => Ok(RpcMethods::Auto),
183			invalid => Err(format!("Invalid rpc methods {invalid}")),
184		}
185	}
186}
187
188impl Into<sc_service::config::RpcMethods> for RpcMethods {
189	fn into(self) -> sc_service::config::RpcMethods {
190		match self {
191			RpcMethods::Auto => sc_service::config::RpcMethods::Auto,
192			RpcMethods::Safe => sc_service::config::RpcMethods::Safe,
193			RpcMethods::Unsafe => sc_service::config::RpcMethods::Unsafe,
194		}
195	}
196}
197
198/// CORS setting
199///
200/// The type is introduced to overcome `Option<Option<T>>` handling of `clap`.
201#[derive(Clone, Debug)]
202pub enum Cors {
203	/// All hosts allowed.
204	All,
205	/// Only hosts on the list are allowed.
206	List(Vec<String>),
207}
208
209impl From<Cors> for Option<Vec<String>> {
210	fn from(cors: Cors) -> Self {
211		match cors {
212			Cors::All => None,
213			Cors::List(list) => Some(list),
214		}
215	}
216}
217
218impl FromStr for Cors {
219	type Err = crate::Error;
220
221	fn from_str(s: &str) -> Result<Self, Self::Err> {
222		let mut is_all = false;
223		let mut origins = Vec::new();
224		for part in s.split(',') {
225			match part {
226				"all" | "*" => {
227					is_all = true;
228					break;
229				},
230				other => origins.push(other.to_owned()),
231			}
232		}
233
234		if is_all {
235			Ok(Cors::All)
236		} else {
237			Ok(Cors::List(origins))
238		}
239	}
240}
241
242/// Database backend
243#[derive(Debug, Clone, PartialEq, Copy, clap::ValueEnum)]
244#[value(rename_all = "lower")]
245pub enum Database {
246	/// Facebooks RocksDB
247	#[cfg(feature = "rocksdb")]
248	RocksDb,
249	/// ParityDb. <https://github.com/paritytech/parity-db/>
250	ParityDb,
251	/// Detect whether there is an existing database. Use it, if there is, if not, create new
252	/// instance of ParityDb
253	Auto,
254	/// ParityDb. <https://github.com/paritytech/parity-db/>
255	#[value(name = "paritydb-experimental")]
256	ParityDbDeprecated,
257}
258
259impl Database {
260	/// Returns all the variants of this enum to be shown in the cli.
261	pub const fn variants() -> &'static [&'static str] {
262		&[
263			#[cfg(feature = "rocksdb")]
264			"rocksdb",
265			"paritydb",
266			"paritydb-experimental",
267			"auto",
268		]
269	}
270}
271
272/// Whether off-chain workers are enabled.
273#[allow(missing_docs)]
274#[derive(Debug, Clone, ValueEnum)]
275#[value(rename_all = "kebab-case")]
276pub enum OffchainWorkerEnabled {
277	/// Always have offchain worker enabled.
278	Always,
279	/// Never enable the offchain worker.
280	Never,
281	/// Only enable the offchain worker when running as a validator (or collator, if this is a
282	/// parachain node).
283	WhenAuthority,
284}
285
286/// Syncing mode.
287#[derive(Debug, Clone, Copy, ValueEnum, PartialEq)]
288#[value(rename_all = "kebab-case")]
289pub enum SyncMode {
290	/// Full sync. Download and verify all blocks.
291	Full,
292	/// Download blocks without executing them. Download latest state with proofs.
293	Fast,
294	/// Download blocks without executing them. Download latest state without proofs.
295	FastUnsafe,
296	/// Prove finality and download the latest state.
297	/// After warp sync completes, the node will have block headers but not bodies for historical
298	/// blocks (unless `blocks-pruning` is set to archive mode). This saves bandwidth while still
299	/// allowing the node to serve as a warp sync source for other nodes.
300	Warp,
301}
302
303impl Into<sc_network::config::SyncMode> for SyncMode {
304	fn into(self) -> sc_network::config::SyncMode {
305		match self {
306			SyncMode::Full => sc_network::config::SyncMode::Full,
307			SyncMode::Fast => sc_network::config::SyncMode::LightState {
308				skip_proofs: false,
309				storage_chain_mode: false,
310			},
311			SyncMode::FastUnsafe => sc_network::config::SyncMode::LightState {
312				skip_proofs: true,
313				storage_chain_mode: false,
314			},
315			SyncMode::Warp => sc_network::config::SyncMode::Warp,
316		}
317	}
318}
319
320/// Network backend type.
321#[derive(Debug, Clone, Copy, ValueEnum, PartialEq)]
322#[value(rename_all = "lower")]
323pub enum NetworkBackendType {
324	/// Use libp2p for P2P networking.
325	Libp2p,
326
327	/// Use litep2p for P2P networking.
328	Litep2p,
329}
330
331impl Into<sc_network::config::NetworkBackendType> for NetworkBackendType {
332	fn into(self) -> sc_network::config::NetworkBackendType {
333		match self {
334			Self::Libp2p => sc_network::config::NetworkBackendType::Libp2p,
335			Self::Litep2p => sc_network::config::NetworkBackendType::Litep2p,
336		}
337	}
338}