Skip to main content

soil_cli/commands/
inspect_node_key.rs

1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
6
7//! Implementation of the `inspect-node-key` subcommand
8
9use crate::Error;
10use clap::Parser;
11use libp2p_identity::Keypair;
12use std::{
13	fs,
14	io::{self, Read},
15	path::PathBuf,
16};
17
18/// The `inspect-node-key` command
19#[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	/// Name of file to read the secret key from.
26	/// If not given, the secret key is read from stdin (up to EOF).
27	#[arg(long)]
28	file: Option<PathBuf>,
29
30	/// The input is in raw binary format.
31	/// If not given, the input is read as an hex encoded string.
32	#[arg(long)]
33	bin: bool,
34
35	/// This argument is deprecated and has no effect for this command.
36	#[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	/// runs the command
43	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			// With hex input, give to the user a bit of tolerance about whitespaces
55			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}