1// This file is part of Substrate.
23// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
56// 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.
1011// 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.
1516// 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/>.
1819//! 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;
2728/// 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")]
34words: Option<usize>,
3536#[allow(missing_docs)]
37 #[clap(flatten)]
38pub keystore_params: KeystoreParams,
3940#[allow(missing_docs)]
41 #[clap(flatten)]
42pub network_scheme: NetworkSchemeFlag,
4344#[allow(missing_docs)]
45 #[clap(flatten)]
46pub output_scheme: OutputTypeFlag,
4748#[allow(missing_docs)]
49 #[clap(flatten)]
50pub crypto_scheme: CryptoSchemeFlag,
51}
5253impl GenerateCmd {
54/// Run the command
55pub fn run(&self) -> Result<(), Error> {
56let words = match self.words {
57Some(words_count) if [12, 15, 18, 21, 24].contains(&words_count) => Ok(words_count),
58Some(_) => Err(Error::Input(
59"Invalid number of words given for phrase: must be 12/15/18/21/24".into(),
60 )),
61None => Ok(12),
62 }?;
63let mnemonic = Mnemonic::generate(words)
64 .map_err(|e| Error::Input(format!("Mnemonic generation failed: {e}").into()))?;
65let password = self.keystore_params.read_password()?;
66let output = self.output_scheme.output_type;
6768let phrase = mnemonic.words().join(" ");
6970with_crypto_scheme!(
71self.crypto_scheme.scheme,
72 print_from_uri(&phrase, password, self.network_scheme.network, output)
73 );
74Ok(())
75 }
76}
7778#[cfg(test)]
79mod tests {
80use super::*;
8182#[test]
83fn generate() {
84let generate = GenerateCmd::parse_from(&["generate", "--password", "12345"]);
85assert!(generate.run().is_ok())
86 }
87}