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