|
| 1 | +//! Create ENR command implementation. |
| 2 | +//! |
| 3 | +//! This module implements the `pluto create enr` command, which generates a new |
| 4 | +//! Ethereum Node Record (ENR) private key and stores it securely on disk. |
| 5 | +
|
| 6 | +use std::{ |
| 7 | + io::{self, Write}, |
| 8 | + path::{Path, PathBuf}, |
| 9 | +}; |
| 10 | + |
| 11 | +use charon_eth2::enr::Record; |
| 12 | +use charon_p2p::k1; |
| 13 | + |
| 14 | +use crate::error::{CliError, Result}; |
| 15 | + |
| 16 | +/// Arguments for the create enr command |
| 17 | +#[derive(clap::Args)] |
| 18 | +pub struct CreateEnrArgs { |
| 19 | + #[arg( |
| 20 | + long = "data-dir", |
| 21 | + env = "CHARON_DATA_DIR", |
| 22 | + default_value = ".charon", |
| 23 | + help = "The directory where pluto will store all its internal data." |
| 24 | + )] |
| 25 | + pub data_dir: PathBuf, |
| 26 | +} |
| 27 | + |
| 28 | +/// Runs the create enr command |
| 29 | +/// |
| 30 | +/// Stores a new charon-enr-private-key to disk and prints the ENR for the |
| 31 | +/// provided config. It returns an error if the key already exists. |
| 32 | +pub fn run(args: CreateEnrArgs) -> Result<()> { |
| 33 | + if k1::load_priv_key(&args.data_dir).is_ok() { |
| 34 | + let enr_path = k1::key_path(&args.data_dir); |
| 35 | + return Err(CliError::PrivateKeyAlreadyExists { enr_path }); |
| 36 | + } |
| 37 | + |
| 38 | + let key = k1::new_saved_priv_key(&args.data_dir)?; |
| 39 | + |
| 40 | + let record = Record::new(key, Vec::new())?; |
| 41 | + let key_path = k1::key_path(&args.data_dir); |
| 42 | + |
| 43 | + let mut writer = io::stdout(); |
| 44 | + writeln!(writer, "Created ENR private key: {}", key_path.display())?; |
| 45 | + writeln!(writer, "{}", record)?; |
| 46 | + write_enr_warning(&mut writer, &key_path)?; |
| 47 | + |
| 48 | + Ok(()) |
| 49 | +} |
| 50 | + |
| 51 | +/// Writes backup key warning to the terminal |
| 52 | +fn write_enr_warning(w: &mut dyn Write, key_path: &Path) -> Result<()> { |
| 53 | + writeln!(w)?; |
| 54 | + writeln!( |
| 55 | + w, |
| 56 | + "***************** WARNING: Backup key **********************" |
| 57 | + )?; |
| 58 | + writeln!( |
| 59 | + w, |
| 60 | + " PLEASE BACKUP YOUR KEY IMMEDIATELY! IF YOU LOSE YOUR KEY," |
| 61 | + )?; |
| 62 | + writeln!( |
| 63 | + w, |
| 64 | + " YOU WON'T BE ABLE TO PARTICIPATE IN RUNNING A CHARON CLUSTER.\n" |
| 65 | + )?; |
| 66 | + writeln!(w, " YOU CAN FIND YOUR KEY IN {}", key_path.display())?; |
| 67 | + writeln!( |
| 68 | + w, |
| 69 | + "****************************************************************" |
| 70 | + )?; |
| 71 | + writeln!(w)?; |
| 72 | + Ok(()) |
| 73 | +} |
0 commit comments