moonproof-utils 0.2.1

Shared helpers (hex parsing, validation) used across moonproof crates. Mirror of midnight-js/packages/utils.
Documentation
//! Hex parsing + encoding helpers.
//!
//! Replaces the `s.strip_prefix("0x").unwrap_or(s); hex::decode(s)`
//! pattern duplicated across nine sites in the wallet / runtime /
//! cli crates. All parsers accept `0x`-prefixed and bare-hex input.

use thiserror::Error;

#[derive(Debug, Error, PartialEq, Eq)]
pub enum HexError {
    #[error("invalid hex: {0}")]
    Invalid(String),

    #[error("hex byte length mismatch: expected {expected}, got {got}")]
    LengthMismatch { expected: usize, got: usize },
}

/// Parse a hex string (with or without `0x` prefix) into bytes.
///
/// Mirror of TS `parseHex` / `fromHex`.
pub fn parse_hex(input: &str) -> Result<Vec<u8>, HexError> {
    let trimmed = input.strip_prefix("0x").unwrap_or(input);
    ::hex::decode(trimmed).map_err(|e| HexError::Invalid(format!("{e}")))
}

/// Parse a hex string into a fixed-size byte array. Errors when the
/// decoded length doesn't match `N`. Useful for IDs, hashes,
/// public-key bytes that must be exactly N bytes.
pub fn parse_hex_n<const N: usize>(input: &str) -> Result<[u8; N], HexError> {
    let bytes = parse_hex(input)?;
    if bytes.len() != N {
        return Err(HexError::LengthMismatch {
            expected: N,
            got: bytes.len(),
        });
    }
    let mut out = [0u8; N];
    out.copy_from_slice(&bytes);
    Ok(out)
}

/// Lowercase hex without `0x` prefix.
#[must_use]
pub fn to_hex(bytes: &[u8]) -> String {
    ::hex::encode(bytes)
}

/// Lowercase hex with `0x` prefix.
#[must_use]
pub fn to_hex_prefixed(bytes: &[u8]) -> String {
    format!("0x{}", to_hex(bytes))
}

/// `true` iff `s` parses as hex (with or without `0x`). When
/// `byte_len` is `Some(n)`, also requires the decoded length to
/// equal `n` bytes — handy for "is this a valid 32-byte hash" checks.
#[must_use]
pub fn is_hex(s: &str, byte_len: Option<usize>) -> bool {
    match parse_hex(s) {
        Ok(bytes) => byte_len.is_none_or(|n| bytes.len() == n),
        Err(_) => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_hex_strips_prefix() {
        assert_eq!(parse_hex("0xab12").unwrap(), vec![0xab, 0x12]);
        assert_eq!(parse_hex("ab12").unwrap(), vec![0xab, 0x12]);
    }

    #[test]
    fn parse_hex_rejects_invalid() {
        assert!(parse_hex("0xzz").is_err());
        assert!(parse_hex("not hex").is_err());
    }

    #[test]
    fn parse_hex_n_enforces_length() {
        let bytes: [u8; 2] = parse_hex_n("ab12").unwrap();
        assert_eq!(bytes, [0xab, 0x12]);
        let err = parse_hex_n::<3>("ab12").unwrap_err();
        assert!(matches!(err, HexError::LengthMismatch { .. }));
    }

    #[test]
    fn to_hex_round_trips() {
        let bytes = vec![0xde, 0xad, 0xbe, 0xef];
        assert_eq!(to_hex(&bytes), "deadbeef");
        assert_eq!(to_hex_prefixed(&bytes), "0xdeadbeef");
        assert_eq!(parse_hex(&to_hex_prefixed(&bytes)).unwrap(), bytes);
    }

    #[test]
    fn is_hex_validates() {
        assert!(is_hex("0xab12", None));
        assert!(is_hex("ab12", Some(2)));
        assert!(!is_hex("ab12", Some(3)));
        assert!(!is_hex("zz", None));
    }
}