sc_cli/commands/
inspect_node_key.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Implementation of the `inspect-node-key` subcommand
19
20use crate::Error;
21use clap::Parser;
22use libp2p_identity::Keypair;
23use std::{
24	fs,
25	io::{self, Read},
26	path::PathBuf,
27};
28
29/// The `inspect-node-key` command
30#[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	/// Name of file to read the secret key from.
37	/// If not given, the secret key is read from stdin (up to EOF).
38	#[arg(long)]
39	file: Option<PathBuf>,
40
41	/// The input is in raw binary format.
42	/// If not given, the input is read as an hex encoded string.
43	#[arg(long)]
44	bin: bool,
45
46	/// This argument is deprecated and has no effect for this command.
47	#[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	/// runs the command
54	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			// With hex input, give to the user a bit of tolerance about whitespaces
66			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}