Skip to main content

moonproof_utils/
hex.rs

1//! Hex parsing + encoding helpers.
2//!
3//! Replaces the `s.strip_prefix("0x").unwrap_or(s); hex::decode(s)`
4//! pattern duplicated across nine sites in the wallet / runtime /
5//! cli crates. All parsers accept `0x`-prefixed and bare-hex input.
6
7use thiserror::Error;
8
9#[derive(Debug, Error, PartialEq, Eq)]
10pub enum HexError {
11    #[error("invalid hex: {0}")]
12    Invalid(String),
13
14    #[error("hex byte length mismatch: expected {expected}, got {got}")]
15    LengthMismatch { expected: usize, got: usize },
16}
17
18/// Parse a hex string (with or without `0x` prefix) into bytes.
19///
20/// Mirror of TS `parseHex` / `fromHex`.
21pub fn parse_hex(input: &str) -> Result<Vec<u8>, HexError> {
22    let trimmed = input.strip_prefix("0x").unwrap_or(input);
23    ::hex::decode(trimmed).map_err(|e| HexError::Invalid(format!("{e}")))
24}
25
26/// Parse a hex string into a fixed-size byte array. Errors when the
27/// decoded length doesn't match `N`. Useful for IDs, hashes,
28/// public-key bytes that must be exactly N bytes.
29pub fn parse_hex_n<const N: usize>(input: &str) -> Result<[u8; N], HexError> {
30    let bytes = parse_hex(input)?;
31    if bytes.len() != N {
32        return Err(HexError::LengthMismatch {
33            expected: N,
34            got: bytes.len(),
35        });
36    }
37    let mut out = [0u8; N];
38    out.copy_from_slice(&bytes);
39    Ok(out)
40}
41
42/// Lowercase hex without `0x` prefix.
43#[must_use]
44pub fn to_hex(bytes: &[u8]) -> String {
45    ::hex::encode(bytes)
46}
47
48/// Lowercase hex with `0x` prefix.
49#[must_use]
50pub fn to_hex_prefixed(bytes: &[u8]) -> String {
51    format!("0x{}", to_hex(bytes))
52}
53
54/// `true` iff `s` parses as hex (with or without `0x`). When
55/// `byte_len` is `Some(n)`, also requires the decoded length to
56/// equal `n` bytes — handy for "is this a valid 32-byte hash" checks.
57#[must_use]
58pub fn is_hex(s: &str, byte_len: Option<usize>) -> bool {
59    match parse_hex(s) {
60        Ok(bytes) => byte_len.is_none_or(|n| bytes.len() == n),
61        Err(_) => false,
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn parse_hex_strips_prefix() {
71        assert_eq!(parse_hex("0xab12").unwrap(), vec![0xab, 0x12]);
72        assert_eq!(parse_hex("ab12").unwrap(), vec![0xab, 0x12]);
73    }
74
75    #[test]
76    fn parse_hex_rejects_invalid() {
77        assert!(parse_hex("0xzz").is_err());
78        assert!(parse_hex("not hex").is_err());
79    }
80
81    #[test]
82    fn parse_hex_n_enforces_length() {
83        let bytes: [u8; 2] = parse_hex_n("ab12").unwrap();
84        assert_eq!(bytes, [0xab, 0x12]);
85        let err = parse_hex_n::<3>("ab12").unwrap_err();
86        assert!(matches!(err, HexError::LengthMismatch { .. }));
87    }
88
89    #[test]
90    fn to_hex_round_trips() {
91        let bytes = vec![0xde, 0xad, 0xbe, 0xef];
92        assert_eq!(to_hex(&bytes), "deadbeef");
93        assert_eq!(to_hex_prefixed(&bytes), "0xdeadbeef");
94        assert_eq!(parse_hex(&to_hex_prefixed(&bytes)).unwrap(), bytes);
95    }
96
97    #[test]
98    fn is_hex_validates() {
99        assert!(is_hex("0xab12", None));
100        assert!(is_hex("ab12", Some(2)));
101        assert!(!is_hex("ab12", Some(3)));
102        assert!(!is_hex("zz", None));
103    }
104}