command.rs 14.5 KB
Newer Older
Gavin Wood's avatar
Gavin Wood committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

Bernhard Schuster's avatar
Bernhard Schuster committed
17
use crate::cli::{Cli, Subcommand};
18
use futures::future::TryFutureExt;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
19
20
21
use log::info;
use sc_cli::{Role, RuntimeVersion, SubstrateCli};
use service::{self, IdentifyVariant};
22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#[derive(thiserror::Error, Debug)]
pub enum Error {
	#[error(transparent)]
	PolkadotService(#[from] service::Error),

	#[error(transparent)]
	SubstrateCli(#[from] sc_cli::Error),

	#[error(transparent)]
	SubstrateService(#[from] sc_service::Error),

	#[error("Other: {0}")]
	Other(String),
}

impl std::convert::From<String> for Error {
	fn from(s: String) -> Self {
		Self::Other(s)
	}
}

type Result<T> = std::result::Result<T, Error>;

Gavin Wood's avatar
Gavin Wood committed
46
47
48
49
50
51
52
fn get_exec_name() -> Option<String> {
	std::env::current_exe()
		.ok()
		.and_then(|pb| pb.file_name().map(|s| s.to_os_string()))
		.and_then(|s| s.into_string().ok())
}

53
impl SubstrateCli for Cli {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
54
55
56
	fn impl_name() -> String {
		"Parity Polkadot".into()
	}
57

Shawn Tabrizi's avatar
Shawn Tabrizi committed
58
59
60
	fn impl_version() -> String {
		env!("SUBSTRATE_CLI_IMPL_VERSION").into()
	}
61

Shawn Tabrizi's avatar
Shawn Tabrizi committed
62
63
64
	fn description() -> String {
		env!("CARGO_PKG_DESCRIPTION").into()
	}
65

Shawn Tabrizi's avatar
Shawn Tabrizi committed
66
67
68
	fn author() -> String {
		env!("CARGO_PKG_AUTHORS").into()
	}
69

Shawn Tabrizi's avatar
Shawn Tabrizi committed
70
71
72
	fn support_url() -> String {
		"https://github.com/paritytech/polkadot/issues/new".into()
	}
73

Shawn Tabrizi's avatar
Shawn Tabrizi committed
74
75
76
	fn copyright_start_year() -> i32 {
		2017
	}
77

Shawn Tabrizi's avatar
Shawn Tabrizi committed
78
79
80
	fn executable_name() -> String {
		"polkadot".into()
	}
81
82

	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
Gavin Wood's avatar
Gavin Wood committed
83
84
		let id = if id == "" {
			let n = get_exec_name().unwrap_or_default();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
85
86
			["polkadot", "kusama", "westend", "rococo"]
				.iter()
Gavin Wood's avatar
Gavin Wood committed
87
88
89
				.cloned()
				.find(|&chain| n.starts_with(chain))
				.unwrap_or("polkadot")
Shawn Tabrizi's avatar
Shawn Tabrizi committed
90
91
92
		} else {
			id
		};
93
		Ok(match id {
94
			"kusama" => Box::new(service::chain_spec::kusama_config()?),
95
			#[cfg(feature = "kusama-native")]
Wei Tang's avatar
Wei Tang committed
96
			"kusama-dev" => Box::new(service::chain_spec::kusama_development_config()?),
97
			#[cfg(feature = "kusama-native")]
Wei Tang's avatar
Wei Tang committed
98
			"kusama-local" => Box::new(service::chain_spec::kusama_local_testnet_config()?),
99
			#[cfg(feature = "kusama-native")]
Wei Tang's avatar
Wei Tang committed
100
			"kusama-staging" => Box::new(service::chain_spec::kusama_staging_testnet_config()?),
101
			#[cfg(not(feature = "kusama-native"))]
102
			name if name.starts_with("kusama-") && !name.ends_with(".json") =>
103
				Err(format!("`{}` only supported with `kusama-native` feature enabled.", name))?,
Gavin Wood's avatar
Gavin Wood committed
104
			"polkadot" => Box::new(service::chain_spec::polkadot_config()?),
105
106
107
108
			"polkadot-dev" | "dev" => Box::new(service::chain_spec::polkadot_development_config()?),
			"polkadot-local" => Box::new(service::chain_spec::polkadot_local_testnet_config()?),
			"polkadot-staging" => Box::new(service::chain_spec::polkadot_staging_testnet_config()?),
			"rococo" => Box::new(service::chain_spec::rococo_config()?),
109
			#[cfg(feature = "rococo-native")]
110
			"rococo-dev" => Box::new(service::chain_spec::rococo_development_config()?),
111
			#[cfg(feature = "rococo-native")]
112
			"rococo-local" => Box::new(service::chain_spec::rococo_local_testnet_config()?),
113
			#[cfg(feature = "rococo-native")]
114
			"rococo-staging" => Box::new(service::chain_spec::rococo_staging_testnet_config()?),
115
116
			#[cfg(not(feature = "rococo-native"))]
			name if name.starts_with("rococo-") && !name.ends_with(".json") =>
117
				Err(format!("`{}` only supported with `rococo-native` feature enabled.", name))?,
118
			"westend" => Box::new(service::chain_spec::westend_config()?),
119
			#[cfg(feature = "westend-native")]
Wei Tang's avatar
Wei Tang committed
120
			"westend-dev" => Box::new(service::chain_spec::westend_development_config()?),
121
			#[cfg(feature = "westend-native")]
Wei Tang's avatar
Wei Tang committed
122
			"westend-local" => Box::new(service::chain_spec::westend_local_testnet_config()?),
123
			#[cfg(feature = "westend-native")]
Wei Tang's avatar
Wei Tang committed
124
			"westend-staging" => Box::new(service::chain_spec::westend_staging_testnet_config()?),
125
			#[cfg(not(feature = "westend-native"))]
126
			name if name.starts_with("westend-") && !name.ends_with(".json") =>
127
				Err(format!("`{}` only supported with `westend-native` feature enabled.", name))?,
128
			"wococo" => Box::new(service::chain_spec::wococo_config()?),
129
			#[cfg(feature = "rococo-native")]
130
			"wococo-dev" => Box::new(service::chain_spec::wococo_development_config()?),
131
132
			#[cfg(feature = "rococo-native")]
			"wococo-local" => Box::new(service::chain_spec::wococo_local_testnet_config()?),
133
134
135
			#[cfg(not(feature = "rococo-native"))]
			name if name.starts_with("wococo-") =>
				Err(format!("`{}` only supported with `rococo-native` feature enabled.", name))?,
136
137
138
			path => {
				let path = std::path::PathBuf::from(path);

Shawn Tabrizi's avatar
Shawn Tabrizi committed
139
140
				let chain_spec = Box::new(service::PolkadotChainSpec::from_json_file(path.clone())?)
					as Box<dyn service::ChainSpec>;
141
142
143

				// When `force_*` is given or the file name starts with the name of one of the known chains,
				// we use the chain spec for the specific chain.
144
				if self.run.force_rococo || chain_spec.is_rococo() || chain_spec.is_wococo() {
145
					Box::new(service::RococoChainSpec::from_json_file(path)?)
146
				} else if self.run.force_kusama || chain_spec.is_kusama() {
147
					Box::new(service::KusamaChainSpec::from_json_file(path)?)
148
				} else if self.run.force_westend || chain_spec.is_westend() {
149
150
					Box::new(service::WestendChainSpec::from_json_file(path)?)
				} else {
151
					chain_spec
152
				}
153
154
155
			},
		})
	}
156
157

	fn native_runtime_version(spec: &Box<dyn service::ChainSpec>) -> &'static RuntimeVersion {
158
		#[cfg(feature = "kusama-native")]
159
		if spec.is_kusama() {
160
			return &service::kusama_runtime::VERSION
161
		}
162
163
164
165
166
167
168
169
170
171
172

		#[cfg(feature = "westend-native")]
		if spec.is_westend() {
			return &service::westend_runtime::VERSION
		}

		#[cfg(feature = "rococo-native")]
		if spec.is_rococo() || spec.is_wococo() {
			return &service::rococo_runtime::VERSION
		}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
173
174
175
176
177
		#[cfg(not(all(
			feature = "rococo-native",
			feature = "westend-native",
			feature = "kusama-native"
		)))]
178
179
180
		let _ = spec;

		&service::polkadot_runtime::VERSION
181
	}
182
}
Gavin Wood's avatar
Gavin Wood committed
183

184
185
186
187
188
189
190
191
192
193
194
195
196
197
fn set_default_ss58_version(spec: &Box<dyn service::ChainSpec>) {
	use sp_core::crypto::Ss58AddressFormat;

	let ss58_version = if spec.is_kusama() {
		Ss58AddressFormat::KusamaAccount
	} else if spec.is_westend() {
		Ss58AddressFormat::SubstrateAccount
	} else {
		Ss58AddressFormat::PolkadotAccount
	};

	sp_core::crypto::set_default_ss58_version(ss58_version);
}

198
const DEV_ONLY_ERROR_PATTERN: &'static str =
199
	"can only use subcommand with --chain [polkadot-dev, kusama-dev, westend-dev, rococo-dev, wococo-dev], got ";
200
201

fn ensure_dev(spec: &Box<dyn service::ChainSpec>) -> std::result::Result<(), String> {
Kian Paimani's avatar
Kian Paimani committed
202
203
204
205
206
	if spec.is_dev() {
		Ok(())
	} else {
		Err(format!("{}{}", DEV_ONLY_ERROR_PATTERN, spec.id()))
	}
207
208
}

209
210
211
212
/// Launch a node, accepting arguments just like a regular node,
/// accepts an alternative overseer generator, to adjust behavior
/// for integration tests as needed.
#[cfg(feature = "malus")]
Bernhard Schuster's avatar
Bernhard Schuster committed
213
pub fn run_node(run: crate::cli::RunCmd, overseer_gen: impl service::OverseerGen) -> Result<()> {
Bernhard Schuster's avatar
Bernhard Schuster committed
214
	run_node_inner(Cli { subcommand: None, run }, overseer_gen)
215
216
217
}

fn run_node_inner(cli: Cli, overseer_gen: impl service::OverseerGen) -> Result<()> {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
218
	let runner = cli.create_runner(&cli.run.base).map_err(Error::from)?;
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
	let chain_spec = &runner.config().chain_spec;

	set_default_ss58_version(chain_spec);

	let grandpa_pause = if cli.run.grandpa_pause.is_empty() {
		None
	} else {
		Some((cli.run.grandpa_pause[0], cli.run.grandpa_pause[1]))
	};

	if chain_spec.is_kusama() {
		info!("----------------------------");
		info!("This chain is not in any way");
		info!("      endorsed by the       ");
		info!("     KUSAMA FOUNDATION      ");
		info!("----------------------------");
	}

	let jaeger_agent = cli.run.jaeger_agent;

	runner.run_node_until_exit(move |config| async move {
		let role = config.role.clone();

		match role {
			Role::Light => Err(Error::Other("Light client not enabled".into())),
			_ => service::build_full(
				config,
				service::IsCollator::No,
				grandpa_pause,
				cli.run.no_beefy,
				jaeger_agent,
				None,
				overseer_gen,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
252
253
254
			)
			.map(|full| full.task_manager)
			.map_err(Into::into),
255
256
257
258
		}
	})
}

Gavin Wood's avatar
Gavin Wood committed
259
/// Parses polkadot specific CLI arguments and run the service.
260
261
262
263
pub fn run() -> Result<()> {
	let cli = Cli::from_args();

	match &cli.subcommand {
264
		None => run_node_inner(cli, service::RealOverseerGen),
265
266
		Some(Subcommand::BuildSpec(cmd)) => {
			let runner = cli.create_runner(cmd)?;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
267
			Ok(runner.sync_run(|config| cmd.run(config.chain_spec, config.network))?)
268
269
		},
		Some(Subcommand::CheckBlock(cmd)) => {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
270
			let runner = cli.create_runner(cmd).map_err(Error::SubstrateCli)?;
271
272
273
274
275
			let chain_spec = &runner.config().chain_spec;

			set_default_ss58_version(chain_spec);

			runner.async_run(|mut config| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
276
277
				let (client, _, import_queue, task_manager) =
					service::new_chain_ops(&mut config, None)?;
278
				Ok((cmd.run(client, import_queue).map_err(Error::SubstrateCli), task_manager))
279
280
281
282
			})
		},
		Some(Subcommand::ExportBlocks(cmd)) => {
			let runner = cli.create_runner(cmd)?;
283
			let chain_spec = &runner.config().chain_spec;
284
285

			set_default_ss58_version(chain_spec);
Gavin Wood's avatar
Gavin Wood committed
286

287
			Ok(runner.async_run(|mut config| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
288
289
				let (client, _, _, task_manager) =
					service::new_chain_ops(&mut config, None).map_err(Error::PolkadotService)?;
290
291
				Ok((cmd.run(client, config.database).map_err(Error::SubstrateCli), task_manager))
			})?)
292
293
294
295
296
297
298
		},
		Some(Subcommand::ExportState(cmd)) => {
			let runner = cli.create_runner(cmd)?;
			let chain_spec = &runner.config().chain_spec;

			set_default_ss58_version(chain_spec);

299
300
301
302
			Ok(runner.async_run(|mut config| {
				let (client, _, _, task_manager) = service::new_chain_ops(&mut config, None)?;
				Ok((cmd.run(client, config.chain_spec).map_err(Error::SubstrateCli), task_manager))
			})?)
303
304
305
306
307
308
309
		},
		Some(Subcommand::ImportBlocks(cmd)) => {
			let runner = cli.create_runner(cmd)?;
			let chain_spec = &runner.config().chain_spec;

			set_default_ss58_version(chain_spec);

310
			Ok(runner.async_run(|mut config| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
311
312
				let (client, _, import_queue, task_manager) =
					service::new_chain_ops(&mut config, None)?;
313
314
				Ok((cmd.run(client, import_queue).map_err(Error::SubstrateCli), task_manager))
			})?)
315
316
317
		},
		Some(Subcommand::PurgeChain(cmd)) => {
			let runner = cli.create_runner(cmd)?;
318
			Ok(runner.sync_run(|config| cmd.run(config.database))?)
319
320
321
322
323
324
325
		},
		Some(Subcommand::Revert(cmd)) => {
			let runner = cli.create_runner(cmd)?;
			let chain_spec = &runner.config().chain_spec;

			set_default_ss58_version(chain_spec);

326
327
			Ok(runner.async_run(|mut config| {
				let (client, backend, _, task_manager) = service::new_chain_ops(&mut config, None)?;
Kian Paimani's avatar
Kian Paimani committed
328
				Ok((cmd.run(client, backend).map_err(Error::SubstrateCli), task_manager))
329
			})?)
Gavin Wood's avatar
Gavin Wood committed
330
		},
331
		Some(Subcommand::PvfPrepareWorker(cmd)) => {
Cecile Tonglet's avatar
Cecile Tonglet committed
332
			let mut builder = sc_cli::LoggerBuilder::new("");
333
334
			builder.with_colors(false);
			let _ = builder.init();
Gavin Wood's avatar
Gavin Wood committed
335

336
			#[cfg(target_os = "android")]
337
			{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
338
339
340
341
				return Err(sc_cli::Error::Input(
					"PVF preparation workers are not supported under this platform".into(),
				)
				.into())
342
343
			}

344
			#[cfg(not(target_os = "android"))]
345
346
347
348
349
350
351
352
353
354
			{
				polkadot_node_core_pvf::prepare_worker_entrypoint(&cmd.socket_path);
				Ok(())
			}
		},
		Some(Subcommand::PvfExecuteWorker(cmd)) => {
			let mut builder = sc_cli::LoggerBuilder::new("");
			builder.with_colors(false);
			let _ = builder.init();

355
			#[cfg(target_os = "android")]
356
			{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
357
358
359
360
				return Err(sc_cli::Error::Input(
					"PVF execution workers are not supported under this platform".into(),
				)
				.into())
361
362
			}

363
			#[cfg(not(target_os = "android"))]
364
365
			{
				polkadot_node_core_pvf::execute_worker_entrypoint(&cmd.socket_path);
Gavin Wood's avatar
Gavin Wood committed
366
367
368
				Ok(())
			}
		},
369
		Some(Subcommand::Benchmark(cmd)) => {
370
371
			let runner = cli.create_runner(cmd)?;
			let chain_spec = &runner.config().chain_spec;
372
			set_default_ss58_version(chain_spec);
373

374
			ensure_dev(chain_spec).map_err(Error::Other)?;
375
376

			#[cfg(feature = "kusama-native")]
Kian Paimani's avatar
Kian Paimani committed
377
			if chain_spec.is_kusama() {
378
				return Ok(runner.sync_run(|config| {
379
380
381
382
					cmd.run::<service::kusama_runtime::Block, service::KusamaExecutorDispatch>(
						config,
					)
					.map_err(|e| Error::SubstrateCli(e))
383
				})?)
384
385
386
387
388
			}

			#[cfg(feature = "westend-native")]
			if chain_spec.is_westend() {
				return Ok(runner.sync_run(|config| {
389
390
391
392
					cmd.run::<service::westend_runtime::Block, service::WestendExecutorDispatch>(
						config,
					)
					.map_err(|e| Error::SubstrateCli(e))
393
394
				})?)
			}
395
396
397

			// else we assume it is polkadot.
			Ok(runner.sync_run(|config| {
398
399
400
401
				cmd.run::<service::polkadot_runtime::Block, service::PolkadotExecutorDispatch>(
					config,
				)
				.map_err(|e| Error::SubstrateCli(e))
402
			})?)
403
		},
404
		Some(Subcommand::Key(cmd)) => Ok(cmd.run(&cli)?),
Kian Paimani's avatar
Kian Paimani committed
405
406
407
408
409
410
		#[cfg(feature = "try-runtime")]
		Some(Subcommand::TryRuntime(cmd)) => {
			let runner = cli.create_runner(cmd)?;
			let chain_spec = &runner.config().chain_spec;
			set_default_ss58_version(chain_spec);

411
412
			use sc_service::TaskManager;
			let registry = &runner.config().prometheus_config.as_ref().map(|cfg| &cfg.registry);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
413
414
415
			let task_manager =
				TaskManager::new(runner.config().task_executor.clone(), *registry)
					.map_err(|e| Error::SubstrateService(sc_service::Error::Prometheus(e)))?;
416
417

			ensure_dev(chain_spec).map_err(Error::Other)?;
418
419

			#[cfg(feature = "kusama-native")]
Kian Paimani's avatar
Kian Paimani committed
420
			if chain_spec.is_kusama() {
421
				return runner.async_run(|config| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
422
					Ok((
ferrell-code's avatar
ferrell-code committed
423
424
425
426
						cmd.run::<service::kusama_runtime::Block, service::KusamaExecutorDispatch>(
							config,
						)
						.map_err(Error::SubstrateCli),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
427
428
						task_manager,
					))
429
				})
430
431
432
433
434
			}

			#[cfg(feature = "westend-native")]
			if chain_spec.is_westend() {
				return runner.async_run(|config| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
435
					Ok((
ferrell-code's avatar
ferrell-code committed
436
						cmd.run::<service::westend_runtime::Block, service::WestendExecutorDispatch>(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
437
438
439
440
441
							config,
						)
						.map_err(Error::SubstrateCli),
						task_manager,
					))
442
443
				})
			}
444
445
			// else we assume it is polkadot.
			runner.async_run(|config| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
446
				Ok((
ferrell-code's avatar
ferrell-code committed
447
448
449
450
					cmd.run::<service::polkadot_runtime::Block, service::PolkadotExecutorDispatch>(
						config,
					)
					.map_err(Error::SubstrateCli),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
451
452
					task_manager,
				))
453
			})
Zeke Mostov's avatar
Zeke Mostov committed
454
455
		},
		#[cfg(not(feature = "try-runtime"))]
Shawn Tabrizi's avatar
Shawn Tabrizi committed
456
457
458
459
460
461
		Some(Subcommand::TryRuntime) => Err(Error::Other(
			"TryRuntime wasn't enabled when building the node. \
				You can enable it with `--features try-runtime`."
				.into(),
		)
		.into()),
462
463
	}?;
	Ok(())
Gavin Wood's avatar
Gavin Wood committed
464
}