referrerpolicy=no-referrer-when-downgrade

sc_cli/commands/
verify.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! implementation of the `verify` subcommand
20
21use crate::{error, params::MessageParams, utils, with_crypto_scheme, CryptoSchemeFlag};
22use clap::Parser;
23use sp_core::crypto::{ByteArray, Ss58Codec};
24use std::io::BufRead;
25
26/// The `verify` command
27#[derive(Debug, Clone, Parser)]
28#[command(
29	name = "verify",
30	about = "Verify a signature for a message, provided on STDIN, with a given (public or secret) key"
31)]
32pub struct VerifyCmd {
33	/// Signature, hex-encoded.
34	sig: String,
35
36	/// The public or secret key URI.
37	/// If the value is a file, the file content is used as URI.
38	/// If not given, you will be prompted for the URI.
39	uri: Option<String>,
40
41	#[allow(missing_docs)]
42	#[clap(flatten)]
43	pub message_params: MessageParams,
44
45	#[allow(missing_docs)]
46	#[clap(flatten)]
47	pub crypto_scheme: CryptoSchemeFlag,
48}
49
50impl VerifyCmd {
51	/// Run the command
52	pub fn run(&self) -> error::Result<()> {
53		self.verify(|| std::io::stdin().lock())
54	}
55
56	/// Verify a signature for a message.
57	///
58	/// The message can either be provided as immediate argument via CLI or otherwise read from the
59	/// reader created by `create_reader`. The reader will only be created in case that the message
60	/// is not passed as immediate.
61	pub(crate) fn verify<F, R>(&self, create_reader: F) -> error::Result<()>
62	where
63		R: BufRead,
64		F: FnOnce() -> R,
65	{
66		let message = self.message_params.message_from(create_reader)?;
67		let sig_data = array_bytes::hex2bytes(&self.sig)?;
68		let uri = utils::read_uri(self.uri.as_ref())?;
69		let uri = if let Some(uri) = uri.strip_prefix("0x") { uri } else { &uri };
70
71		with_crypto_scheme!(self.crypto_scheme.scheme, verify(sig_data, message, uri))
72	}
73}
74
75fn verify<Pair>(sig_data: Vec<u8>, message: Vec<u8>, uri: &str) -> error::Result<()>
76where
77	Pair: sp_core::Pair,
78	Pair::Signature: for<'a> TryFrom<&'a [u8]>,
79{
80	let signature =
81		Pair::Signature::try_from(&sig_data).map_err(|_| error::Error::SignatureFormatInvalid)?;
82
83	let pubkey = if let Ok(pubkey_vec) = array_bytes::hex2bytes(uri) {
84		Pair::Public::from_slice(pubkey_vec.as_slice())
85			.map_err(|_| error::Error::KeyFormatInvalid)?
86	} else {
87		Pair::Public::from_string(uri)?
88	};
89
90	if Pair::verify(&signature, &message, &pubkey) {
91		println!("Signature verifies correctly.");
92	} else {
93		return Err(error::Error::SignatureInvalid)
94	}
95
96	Ok(())
97}
98
99#[cfg(test)]
100mod test {
101	use super::*;
102
103	const ALICE: &str = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY";
104	const SIG1: &str = "0x4eb25a2285a82374888880af0024eb30c3a21ce086eae3862888d345af607f0ad6fb081312f11730932564f24a9f8ebcee2d46861413ae61307eca58db2c3e81";
105	const SIG2: &str = "0x026342225155056ea797118c1c8c8b3cc002aa2020c36f4217fa3c302783a572ad3dcd38c231cbaf86cadb93984d329c963ceac0685cc1ee4c1ed50fa443a68f";
106
107	// Verify work with `--message` argument.
108	#[test]
109	fn verify_immediate() {
110		let cmd = VerifyCmd::parse_from(&["verify", SIG1, ALICE, "--message", "test message"]);
111		assert!(cmd.run().is_ok(), "Alice' signature should verify");
112	}
113
114	// Verify work without `--message` argument.
115	#[test]
116	fn verify_stdin() {
117		let cmd = VerifyCmd::parse_from(&["verify", SIG1, ALICE]);
118		let message = "test message";
119		assert!(cmd.verify(|| message.as_bytes()).is_ok(), "Alice' signature should verify");
120	}
121
122	// Verify work with `--message` argument for hex message.
123	#[test]
124	fn verify_immediate_hex() {
125		let cmd = VerifyCmd::parse_from(&["verify", SIG2, ALICE, "--message", "0xaabbcc", "--hex"]);
126		assert!(cmd.run().is_ok(), "Alice' signature should verify");
127	}
128
129	// Verify work without `--message` argument for hex message.
130	#[test]
131	fn verify_stdin_hex() {
132		let cmd = VerifyCmd::parse_from(&["verify", SIG2, ALICE, "--hex"]);
133		assert!(cmd.verify(|| "0xaabbcc".as_bytes()).is_ok());
134		assert!(cmd.verify(|| "aabbcc".as_bytes()).is_ok());
135		assert!(cmd.verify(|| "0xaABBcC".as_bytes()).is_ok());
136	}
137}