cli/commands/wallet/
generate.rs

1use mina_node_account::AccountSecretKey;
2use std::path::PathBuf;
3
4#[derive(Debug, clap::Args)]
5pub struct Generate {
6    /// Path where the encrypted key file will be saved
7    #[arg(long)]
8    pub output: PathBuf,
9
10    /// Password to encrypt the key
11    #[arg(
12        env = "MINA_PRIVKEY_PASS",
13        default_value = "",
14        help = "Password to encrypt the key (env: MINA_PRIVKEY_PASS)"
15    )]
16    pub password: String,
17}
18
19impl Generate {
20    pub fn run(self) -> anyhow::Result<()> {
21        // Check if password is provided
22        if self.password.is_empty() {
23            anyhow::bail!(
24                "Password is required. Provide it via --password argument or MINA_PRIVKEY_PASS environment variable"
25            );
26        }
27
28        // Check if output file already exists
29        if self.output.exists() {
30            anyhow::bail!("File already exists: {}", self.output.display());
31        }
32
33        // Generate a new random keypair
34        let secret_key = AccountSecretKey::rand();
35        let public_key = secret_key.public_key();
36
37        // Save the encrypted key to file
38        secret_key.to_encrypted_file(&self.output, &self.password)?;
39
40        // Save the public key to a separate file
41        let pubkey_path = format!("{}.pub", self.output.display());
42        std::fs::write(&pubkey_path, public_key.to_string())?;
43
44        println!("Generated new encrypted key:");
45        println!("  Private key: {}", self.output.display());
46        println!("  Public key:  {}", pubkey_path);
47        println!("  Address:     {}", public_key);
48        println!();
49        println!("Keep your encrypted key file and password secure!");
50
51        Ok(())
52    }
53}