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