Skip to main content

zebra_rpc/methods/
hex_data.rs

1//! Deserializes hex-encoded inputs such as the one required
2//! for the `submitblock` RPC method.
3
4use std::fmt;
5
6/// Deserialize hex-encoded strings to bytes.
7#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)]
8pub struct HexData(
9    #[serde(serialize_with = "hex::serialize")]
10    #[schemars(with = "String")]
11    pub Vec<u8>,
12);
13
14impl<'de> serde::Deserialize<'de> for HexData {
15    // The type parameter has the name that serde's derive gave it, so this method's public
16    // signature is the one that the derived implementation had.
17    fn deserialize<__D>(deserializer: __D) -> Result<Self, __D::Error>
18    where
19        __D: serde::Deserializer<'de>,
20    {
21        struct HexDataVisitor;
22
23        impl serde::de::Visitor<'_> for HexDataVisitor {
24            type Value = HexData;
25
26            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
27                formatter.write_str("a hex encoded string")
28            }
29
30            fn visit_str<E>(self, hex: &str) -> Result<Self::Value, E>
31            where
32                E: serde::de::Error,
33            {
34                match decode_hex(hex.as_bytes()) {
35                    Some(bytes) => Ok(HexData(bytes)),
36                    // The `hex` crate reports what is wrong with the string.
37                    None => hex::decode(hex).map(HexData).map_err(E::custom),
38                }
39            }
40        }
41
42        deserializer.deserialize_str(HexDataVisitor)
43    }
44}
45
46/// The entry in [`HEX_DIGITS`] for a byte that isn't a hex digit.
47///
48/// Hex digit values only use the low four bits, so a bitwise OR of entries equals this value if
49/// any of them is invalid.
50const INVALID_HEX_DIGIT: u8 = 0xff;
51
52/// The value of each ASCII hex digit, and [`INVALID_HEX_DIGIT`] for every other byte.
53const HEX_DIGITS: [u8; 256] = {
54    let mut digits = [INVALID_HEX_DIGIT; 256];
55
56    let mut byte = u8::MIN;
57    loop {
58        // Widening a byte to an index can't truncate it.
59        digits[byte as usize] = match byte {
60            b'0'..=b'9' => byte - b'0',
61            b'a'..=b'f' => byte - b'a' + 10,
62            b'A'..=b'F' => byte - b'A' + 10,
63            _ => INVALID_HEX_DIGIT,
64        };
65
66        if byte == u8::MAX {
67            break;
68        }
69        byte += 1;
70    }
71
72    digits
73};
74
75/// Decodes `hex`, or returns `None` if it isn't an even number of hex digits.
76///
77/// Blocks are mostly proofs and ciphertexts, so their hex digits are unpredictable. Comparing
78/// each digit against the digit ranges, like the `hex` crate does, mispredicts a branch for many
79/// of them, which makes decoding a block several times slower than looking the digits up.
80fn decode_hex(hex: &[u8]) -> Option<Vec<u8>> {
81    if !hex.len().is_multiple_of(2) {
82        return None;
83    }
84
85    let mut any_digit = 0;
86    let (pairs, _) = hex.as_chunks::<2>();
87    let bytes = pairs
88        .iter()
89        .map(|[high, low]| {
90            let high = HEX_DIGITS[usize::from(*high)];
91            let low = HEX_DIGITS[usize::from(*low)];
92            any_digit |= high | low;
93
94            (high << 4) | (low & 0x0f)
95        })
96        .collect();
97
98    (any_digit != INVALID_HEX_DIGIT).then_some(bytes)
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    /// Decodes a JSON string as [`HexData`].
106    fn from_json(hex: &str) -> Result<Vec<u8>, String> {
107        serde_json::from_value(serde_json::Value::String(hex.to_string()))
108            .map(|HexData(bytes)| bytes)
109            .map_err(|error| error.to_string())
110    }
111
112    /// Decodes a JSON string with the `hex` crate, like [`HexData`] did before it had its own
113    /// decoder.
114    fn from_json_with_hex_crate(hex: &str) -> Result<Vec<u8>, String> {
115        #[derive(serde::Deserialize)]
116        struct Reference(#[serde(with = "hex")] Vec<u8>);
117
118        serde_json::from_value(serde_json::Value::String(hex.to_string()))
119            .map(|Reference(bytes)| bytes)
120            .map_err(|error| error.to_string())
121    }
122
123    /// Every byte decodes from lowercase and uppercase hex, and encodes back to lowercase hex.
124    #[test]
125    fn hex_data_round_trips_every_byte() {
126        let _init_guard = zebra_test::init();
127
128        let bytes: Vec<u8> = (u8::MIN..=u8::MAX).collect();
129        let lowercase = hex::encode(&bytes);
130
131        assert_eq!(from_json(&lowercase), Ok(bytes.clone()));
132        assert_eq!(from_json(&lowercase.to_uppercase()), Ok(bytes.clone()));
133        assert_eq!(from_json(""), Ok(Vec::new()));
134
135        assert_eq!(
136            serde_json::to_value(HexData(bytes)).expect("hex data serializes to a string"),
137            serde_json::Value::String(lowercase),
138        );
139    }
140
141    /// Strings that aren't hex are rejected with the errors of the `hex` crate, wherever the
142    /// first invalid character is.
143    #[test]
144    fn hex_data_rejects_invalid_strings_like_the_hex_crate() {
145        let _init_guard = zebra_test::init();
146
147        let valid = "00ff10ab";
148        for invalid in [
149            "0", "abc", "0g", "g0", " 0", "0x00", "zz", "é0", "00ff1/", "00:f",
150        ] {
151            assert!(from_json_with_hex_crate(invalid).is_err());
152            assert_eq!(from_json(invalid), from_json_with_hex_crate(invalid));
153
154            // An invalid character after valid digits is still found.
155            let invalid_suffix = format!("{valid}{invalid}");
156            assert!(from_json_with_hex_crate(&invalid_suffix).is_err());
157            assert_eq!(
158                from_json(&invalid_suffix),
159                from_json_with_hex_crate(&invalid_suffix),
160            );
161        }
162
163        // Every byte that isn't a hex digit is rejected in both positions of a pair.
164        for byte in u8::MIN..=u8::MAX {
165            if byte.is_ascii_hexdigit() {
166                continue;
167            }
168
169            assert_eq!(decode_hex(&[byte, b'0']), None);
170            assert_eq!(decode_hex(&[b'0', byte]), None);
171        }
172    }
173}