1// This file is part of Substrate.
23// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
56// 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.
1011// 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.
1516// 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/>.
1819//! Params to configure how a message should be passed into a command.
2021use crate::error::Error;
22use array_bytes::{hex2bytes, hex_bytes2hex_str};
23use clap::Args;
24use std::io::BufRead;
2526/// 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)]
33message: Option<String>,
3435/// The message is hex-encoded data.
36#[arg(long)]
37hex: bool,
38}
3940impl 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.
44pub(crate) fn message_from<F, R>(&self, create_reader: F) -> Result<Vec<u8>, Error>
45where
46R: BufRead,
47 F: FnOnce() -> R,
48 {
49let raw = match &self.message {
50Some(raw) => raw.as_bytes().to_vec(),
51None => {
52let mut raw = vec![];
53 create_reader().read_to_end(&mut raw)?;
54 raw
55 },
56 };
57if self.hex {
58 hex2bytes(hex_bytes2hex_str(&raw)?).map_err(Into::into)
59 } else {
60Ok(raw)
61 }
62 }
63}
6465#[cfg(test)]
66mod tests {
67use super::*;
6869/// Test that decoding an immediate message works.
70#[test]
71fn message_decode_immediate() {
72for (name, input, hex, output) in test_closures() {
73println!("Testing: immediate_{}", name);
74let params = MessageParams { message: Some(input.into()), hex };
75let message = params.message_from(|| std::io::stdin().lock());
7677match output {
78Some(output) => {
79let message = message.expect(&format!("{}: should decode but did not", name));
80assert_eq!(message, output, "{}: decoded a wrong message", name);
81 },
82None => {
83 message.err().expect(&format!("{}: should not decode but did", name));
84 },
85 }
86 }
87 }
8889/// Test that decoding a message from a stream works.
90#[test]
91fn message_decode_stream() {
92for (name, input, hex, output) in test_closures() {
93println!("Testing: stream_{}", name);
94let params = MessageParams { message: None, hex };
95let message = params.message_from(|| input.as_bytes());
9697match output {
98Some(output) => {
99let message = message.expect(&format!("{}: should decode but did not", name));
100assert_eq!(message, output, "{}: decoded a wrong message", name);
101 },
102None => {
103 message.err().expect(&format!("{}: should not decode but did", name));
104 },
105 }
106 }
107 }
108109/// Returns (test_name, input, hex, output).
110fn test_closures() -> Vec<(&'static str, &'static str, bool, Option<&'static [u8]>)> {
111vec![
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}