sc_cli/commands/
generate.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Implementation of the `generate` subcommand
19use crate::{
20	utils::print_from_uri, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams,
21	NetworkSchemeFlag, OutputTypeFlag,
22};
23use bip39::Mnemonic;
24use clap::Parser;
25use itertools::Itertools;
26
27/// The `generate` command
28#[derive(Debug, Clone, Parser)]
29#[command(name = "generate", about = "Generate a random account")]
30pub struct GenerateCmd {
31	/// The number of words in the phrase to generate. One of 12 (default), 15, 18, 21 and 24.
32	#[arg(short = 'w', long, value_name = "WORDS")]
33	words: Option<usize>,
34
35	#[allow(missing_docs)]
36	#[clap(flatten)]
37	pub keystore_params: KeystoreParams,
38
39	#[allow(missing_docs)]
40	#[clap(flatten)]
41	pub network_scheme: NetworkSchemeFlag,
42
43	#[allow(missing_docs)]
44	#[clap(flatten)]
45	pub output_scheme: OutputTypeFlag,
46
47	#[allow(missing_docs)]
48	#[clap(flatten)]
49	pub crypto_scheme: CryptoSchemeFlag,
50}
51
52impl GenerateCmd {
53	/// Run the command
54	pub fn run(&self) -> Result<(), Error> {
55		let words = match self.words {
56			Some(words_count) if [12, 15, 18, 21, 24].contains(&words_count) => Ok(words_count),
57			Some(_) => Err(Error::Input(
58				"Invalid number of words given for phrase: must be 12/15/18/21/24".into(),
59			)),
60			None => Ok(12),
61		}?;
62		let mnemonic = Mnemonic::generate(words)
63			.map_err(|e| Error::Input(format!("Mnemonic generation failed: {e}").into()))?;
64		let password = self.keystore_params.read_password()?;
65		let output = self.output_scheme.output_type;
66
67		let phrase = mnemonic.words().join(" ");
68
69		with_crypto_scheme!(
70			self.crypto_scheme.scheme,
71			print_from_uri(&phrase, password, self.network_scheme.network, output)
72		);
73		Ok(())
74	}
75}
76
77#[cfg(test)]
78mod tests {
79	use super::*;
80
81	#[test]
82	fn generate() {
83		let generate = GenerateCmd::parse_from(&["generate", "--password", "12345"]);
84		assert!(generate.run().is_ok())
85	}
86}