referrerpolicy=no-referrer-when-downgrade

sc_cli/commands/
generate.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//! Implementation of the `generate` subcommand
20use crate::{
21	utils::print_from_uri, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams,
22	NetworkSchemeFlag, OutputTypeFlag,
23};
24use bip39::Mnemonic;
25use clap::Parser;
26use itertools::Itertools;
27
28/// The `generate` command
29#[derive(Debug, Clone, Parser)]
30#[command(name = "generate", about = "Generate a random account")]
31pub struct GenerateCmd {
32	/// The number of words in the phrase to generate. One of 12 (default), 15, 18, 21 and 24.
33	#[arg(short = 'w', long, value_name = "WORDS")]
34	words: Option<usize>,
35
36	#[allow(missing_docs)]
37	#[clap(flatten)]
38	pub keystore_params: KeystoreParams,
39
40	#[allow(missing_docs)]
41	#[clap(flatten)]
42	pub network_scheme: NetworkSchemeFlag,
43
44	#[allow(missing_docs)]
45	#[clap(flatten)]
46	pub output_scheme: OutputTypeFlag,
47
48	#[allow(missing_docs)]
49	#[clap(flatten)]
50	pub crypto_scheme: CryptoSchemeFlag,
51}
52
53impl GenerateCmd {
54	/// Run the command
55	pub fn run(&self) -> Result<(), Error> {
56		let words = match self.words {
57			Some(words_count) if [12, 15, 18, 21, 24].contains(&words_count) => Ok(words_count),
58			Some(_) => Err(Error::Input(
59				"Invalid number of words given for phrase: must be 12/15/18/21/24".into(),
60			)),
61			None => Ok(12),
62		}?;
63		let mnemonic = Mnemonic::generate(words)
64			.map_err(|e| Error::Input(format!("Mnemonic generation failed: {e}").into()))?;
65		let password = self.keystore_params.read_password()?;
66		let output = self.output_scheme.output_type;
67
68		let phrase = mnemonic.words().join(" ");
69
70		with_crypto_scheme!(
71			self.crypto_scheme.scheme,
72			print_from_uri(&phrase, password, self.network_scheme.network, output)
73		);
74		Ok(())
75	}
76}
77
78#[cfg(test)]
79mod tests {
80	use super::*;
81
82	#[test]
83	fn generate() {
84		let generate = GenerateCmd::parse_from(&["generate", "--password", "12345"]);
85		assert!(generate.run().is_ok())
86	}
87}