referrerpolicy=no-referrer-when-downgrade

sc_cli/params/
message_params.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//! Params to configure how a message should be passed into a command.
20
21use crate::error::Error;
22use array_bytes::{hex2bytes, hex_bytes2hex_str};
23use clap::Args;
24use std::io::BufRead;
25
26/// Params to configure how a message should be passed into a command.
27#[derive(Debug, Clone, Args)]
28pub struct MessageParams {
29	/// Message to process. Will be read from STDIN otherwise.
30	/// The message is assumed to be raw bytes per default. Use `--hex` for hex input. Can
31	/// optionally be prefixed with `0x` in the hex case.
32	#[arg(long)]
33	message: Option<String>,
34
35	/// The message is hex-encoded data.
36	#[arg(long)]
37	hex: bool,
38}
39
40impl MessageParams {
41	/// Produces the message by either using its immediate value or reading from stdin.
42	///
43	/// This function should only be called once and the result cached.
44	pub(crate) fn message_from<F, R>(&self, create_reader: F) -> Result<Vec<u8>, Error>
45	where
46		R: BufRead,
47		F: FnOnce() -> R,
48	{
49		let raw = match &self.message {
50			Some(raw) => raw.as_bytes().to_vec(),
51			None => {
52				let mut raw = vec![];
53				create_reader().read_to_end(&mut raw)?;
54				raw
55			},
56		};
57		if self.hex {
58			hex2bytes(hex_bytes2hex_str(&raw)?).map_err(Into::into)
59		} else {
60			Ok(raw)
61		}
62	}
63}
64
65#[cfg(test)]
66mod tests {
67	use super::*;
68
69	/// Test that decoding an immediate message works.
70	#[test]
71	fn message_decode_immediate() {
72		for (name, input, hex, output) in test_closures() {
73			println!("Testing: immediate_{}", name);
74			let params = MessageParams { message: Some(input.into()), hex };
75			let message = params.message_from(|| std::io::stdin().lock());
76
77			match output {
78				Some(output) => {
79					let message = message.expect(&format!("{}: should decode but did not", name));
80					assert_eq!(message, output, "{}: decoded a wrong message", name);
81				},
82				None => {
83					message.err().expect(&format!("{}: should not decode but did", name));
84				},
85			}
86		}
87	}
88
89	/// Test that decoding a message from a stream works.
90	#[test]
91	fn message_decode_stream() {
92		for (name, input, hex, output) in test_closures() {
93			println!("Testing: stream_{}", name);
94			let params = MessageParams { message: None, hex };
95			let message = params.message_from(|| input.as_bytes());
96
97			match output {
98				Some(output) => {
99					let message = message.expect(&format!("{}: should decode but did not", name));
100					assert_eq!(message, output, "{}: decoded a wrong message", name);
101				},
102				None => {
103					message.err().expect(&format!("{}: should not decode but did", name));
104				},
105			}
106		}
107	}
108
109	/// Returns (test_name, input, hex, output).
110	fn test_closures() -> Vec<(&'static str, &'static str, bool, Option<&'static [u8]>)> {
111		vec![
112			("decode_no_hex_works", "Hello this is not hex", false, Some(b"Hello this is not hex")),
113			("decode_no_hex_with_hex_string_works", "0xffffffff", false, Some(b"0xffffffff")),
114			("decode_hex_works", "0x00112233", true, Some(&[0, 17, 34, 51])),
115			("decode_hex_without_prefix_works", "00112233", true, Some(&[0, 17, 34, 51])),
116			("decode_hex_uppercase_works", "0xaAbbCCDd", true, Some(&[170, 187, 204, 221])),
117			("decode_hex_wrong_len_errors", "0x0011223", true, None),
118		]
119	}
120}