stratum-node-core 0.1.0-alpha.2

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
Documentation
//! Private text-encoding helpers shared by the identifier and key types.

/// Decodes exactly `N` bytes from lowercase hexadecimal.
///
/// Returns `None` when the text is not `2 * N` characters of `[0-9a-f]`.
/// Uppercase digits are rejected so that every value has one text form.
pub(crate) fn decode_lower_hex<const N: usize>(text: &str) -> Option<[u8; N]> {
    let mut out = [0u8; N];
    decode_lower_hex_into(text, &mut out).then_some(out)
}

/// Decodes lowercase hexadecimal into `out`, returning `false` unless the
/// text is exactly `2 * out.len()` characters of `[0-9a-f]`.
///
/// Writing into a caller buffer lets secret-key parsing decode straight into
/// memory that zeroises itself.
pub(crate) fn decode_lower_hex_into(text: &str, out: &mut [u8]) -> bool {
    text.len() == out.len() * 2 && is_lower_hex(text) && hex::decode_to_slice(text, out).is_ok()
}

/// Returns `true` when every byte of `text` is in `[0-9a-f]`.
pub(crate) fn is_lower_hex(text: &str) -> bool {
    text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// Errors from [`decode_bech32`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Bech32Error {
    /// Not a valid bech32 string with a bech32 (not bech32m) checksum, or
    /// its padding bits are non-zero or more than four.
    Invalid,
    /// Valid bech32, but with a different human-readable prefix.
    WrongPrefix,
    /// Valid bech32 with the right prefix, but not exactly 32 data bytes.
    WrongLength,
}

/// Decodes a NIP-19 bech32 string with prefix `hrp` into 32 bytes.
///
/// The checks run in this order: checksum, prefix, payload length, padding.
/// A 32-byte payload always leaves exactly four padding bits, so over-long
/// padding always shows up first as [`Bech32Error::WrongLength`]; non-zero
/// padding on a 32-byte payload is [`Bech32Error::Invalid`].
///
/// The output is written into `out` so that callers decoding secret material
/// can supply a buffer that zeroises itself.
pub(crate) fn decode_bech32(text: &str, hrp: &str, out: &mut [u8; 32]) -> Result<(), Bech32Error> {
    use bech32::primitives::decode::CheckedHrpstring;
    use bech32::Bech32;

    let parsed = CheckedHrpstring::new::<Bech32>(text).map_err(|_| Bech32Error::Invalid)?;
    if !parsed.hrp().as_str().eq_ignore_ascii_case(hrp) {
        return Err(Bech32Error::WrongPrefix);
    }
    let mut len = 0usize;
    for byte in parsed.byte_iter() {
        let slot = out.get_mut(len).ok_or(Bech32Error::WrongLength)?;
        *slot = byte;
        len += 1;
    }
    if len != out.len() {
        return Err(Bech32Error::WrongLength);
    }
    // `byte_iter` drops the trailing bits that do not fill a byte, so two
    // strings differing only there would decode to the same key. BIP-173
    // requires those bits to number at most four and to be zero. The
    // "segwit" in the name is historical: the check reads only the data part,
    // which here has no witness version to strip.
    parsed
        .validate_segwit_padding()
        .map_err(|_| Bech32Error::Invalid)
}

/// Encodes 32 bytes as a lowercase NIP-19 bech32 string with prefix `hrp`.
///
/// `hrp` is one of this crate's fixed four-letter prefixes and the payload is
/// 32 bytes, so the 63-character result is well inside bech32's 90-character
/// limit and encoding cannot fail.
pub(crate) fn encode_bech32(hrp: &'static str, data: &[u8; 32]) -> String {
    use bech32::{Bech32, Hrp};

    let hrp = Hrp::parse_unchecked(hrp);
    bech32::encode::<Bech32>(hrp, data)
        .expect("a 4-letter prefix and 32 data bytes always fit in a bech32 string")
}