soil_cli/commands/
inspect_node_key.rs1use crate::Error;
10use clap::Parser;
11use libp2p_identity::Keypair;
12use std::{
13 fs,
14 io::{self, Read},
15 path::PathBuf,
16};
17
18#[derive(Debug, Parser)]
20#[command(
21 name = "inspect-node-key",
22 about = "Load a node key from a file or stdin and print the corresponding peer-id."
23)]
24pub struct InspectNodeKeyCmd {
25 #[arg(long)]
28 file: Option<PathBuf>,
29
30 #[arg(long)]
33 bin: bool,
34
35 #[deprecated(note = "Network identifier is not used for node-key inspection")]
37 #[arg(short = 'n', long = "network", value_name = "NETWORK", ignore_case = true)]
38 pub network_scheme: Option<String>,
39}
40
41impl InspectNodeKeyCmd {
42 pub fn run(&self) -> Result<(), Error> {
44 let mut file_data = match &self.file {
45 Some(file) => fs::read(&file)?,
46 None => {
47 let mut buf = Vec::with_capacity(64);
48 io::stdin().lock().read_to_end(&mut buf)?;
49 buf
50 },
51 };
52
53 if !self.bin {
54 let keyhex = String::from_utf8_lossy(&file_data);
56 file_data = array_bytes::hex2bytes(keyhex.trim())
57 .map_err(|_| "failed to decode secret as hex")?;
58 }
59
60 let keypair =
61 Keypair::ed25519_from_bytes(&mut file_data).map_err(|_| "Bad node key file")?;
62
63 println!("{}", keypair.public().to_peer_id());
64
65 Ok(())
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use crate::commands::generate_node_key::GenerateNodeKeyCmd;
72
73 use super::*;
74
75 #[test]
76 fn inspect_node_key() {
77 let path = tempfile::tempdir().unwrap().into_path().join("node-id").into_os_string();
78 let path = path.to_str().unwrap();
79 let cmd = GenerateNodeKeyCmd::parse_from(&["generate-node-key", "--file", path]);
80
81 assert!(cmd.run("test", &String::from("test")).is_ok());
82
83 let cmd = InspectNodeKeyCmd::parse_from(&["inspect-node-key", "--file", path]);
84 assert!(cmd.run().is_ok());
85 }
86}