stratum-node-core 0.1.0-alpha.1

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
//! Typed identifiers, digests, revisions and timestamps.
//!
//! Each type has one canonical text form. The byte-valued types use lowercase
//! hexadecimal and reject uppercase input, so equal values always print the
//! same way and text comparisons agree with value comparisons.

use std::fmt;
use std::str::FromStr;
use std::time::Duration;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};

use crate::encoding;

/// The longest [`OperationId`] accepted, in characters.
pub const OPERATION_ID_MAX_LEN: usize = 64;

/// The reasons an identifier can fail to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseIdError {
    /// The text is not exactly `expected` lowercase hexadecimal digits.
    #[error("expected {expected} lowercase hex digits")]
    InvalidHex {
        /// The number of hex digits the type requires.
        expected: usize,
    },
    /// An operation identifier is empty.
    #[error("operation id is empty")]
    Empty,
    /// An operation identifier is longer than [`OPERATION_ID_MAX_LEN`].
    #[error("operation id is longer than {OPERATION_ID_MAX_LEN} characters")]
    TooLong,
    /// An operation identifier contains a character outside `[A-Za-z0-9_-]`.
    #[error("operation id may contain only A-Z, a-z, 0-9, '_' and '-'")]
    InvalidCharacter,
}

/// Implements the shared surface of a fixed-size byte identifier rendered as
/// lowercase hex: `from_bytes`, `as_bytes`, `to_hex`, `Display`, `Debug`,
/// `FromStr`, `From<[u8; N]>` and string serde.
macro_rules! hex_bytes_type {
    ($name:ident, $len:literal) => {
        impl $name {
            /// Wraps raw bytes.
            pub const fn from_bytes(bytes: [u8; $len]) -> Self {
                Self(bytes)
            }

            /// Returns the raw bytes.
            pub const fn as_bytes(&self) -> &[u8; $len] {
                &self.0
            }

            /// Returns the lowercase hexadecimal text form.
            pub fn to_hex(&self) -> String {
                hex::encode(self.0)
            }
        }

        impl From<[u8; $len]> for $name {
            fn from(bytes: [u8; $len]) -> Self {
                Self(bytes)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.to_hex())
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, concat!(stringify!($name), "({})"), self.to_hex())
            }
        }

        impl FromStr for $name {
            type Err = ParseIdError;

            /// Parses exactly the lowercase hexadecimal text form.
            fn from_str(text: &str) -> Result<Self, Self::Err> {
                encoding::decode_lower_hex::<$len>(text)
                    .map(Self)
                    .ok_or(ParseIdError::InvalidHex { expected: $len * 2 })
            }
        }

        impl Serialize for $name {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(&self.to_hex())
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let text = String::deserialize(deserializer)?;
                text.parse().map_err(serde::de::Error::custom)
            }
        }
    };
}

/// A Nostr event identifier: the SHA-256 of the NIP-01 serialisation.
///
/// Its text form is 64 lowercase hexadecimal digits. Callers that need replay
/// protection record verified event identifiers durably.
///
/// # Examples
///
/// ```
/// use stratum_node_core::EventId;
///
/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
/// let id: EventId = "00".repeat(32).parse()?;
/// assert_eq!(id.as_bytes(), &[0u8; 32]);
/// assert!("AB".repeat(32).parse::<EventId>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EventId([u8; 32]);
hex_bytes_type!(EventId, 32);

/// A SHA-256 digest, written as 64 lowercase hexadecimal digits.
///
/// # Examples
///
/// ```
/// use stratum_node_core::Sha256Digest;
///
/// let digest = Sha256Digest::of(b"abc");
/// assert_eq!(
///     digest.to_hex(),
///     "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
/// );
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Sha256Digest([u8; 32]);
hex_bytes_type!(Sha256Digest, 32);

impl Sha256Digest {
    /// Computes the SHA-256 digest of `data`.
    pub fn of(data: &[u8]) -> Self {
        Self(Sha256::digest(data).into())
    }
}

/// The identifier of a single-use challenge, written as 32 lowercase hex
/// digits.
///
/// This crate performs no I/O, so the caller supplies the 16 bytes; they must
/// come from a cryptographically secure random source.
///
/// # Examples
///
/// ```
/// use stratum_node_core::ChallengeId;
///
/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
/// let id = ChallengeId::from_bytes([7; 16]);
/// assert_eq!(id.to_string().parse::<ChallengeId>()?, id);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChallengeId([u8; 16]);
hex_bytes_type!(ChallengeId, 16);

/// A configuration revision number.
///
/// Revisions count up from zero; [`next`](Self::next) refuses to wrap.
///
/// # Examples
///
/// ```
/// use stratum_node_core::Revision;
///
/// let first = Revision::new(0);
/// assert_eq!(first.next(), Some(Revision::new(1)));
/// assert_eq!(Revision::new(u64::MAX).next(), None);
/// ```
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct Revision(u64);

impl Revision {
    /// Wraps a revision number.
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the revision number.
    pub const fn get(self) -> u64 {
        self.0
    }

    /// Returns the following revision, or `None` if this is `u64::MAX`.
    pub const fn next(self) -> Option<Self> {
        match self.0.checked_add(1) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }
}

impl From<u64> for Revision {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl From<Revision> for u64 {
    fn from(revision: Revision) -> Self {
        revision.0
    }
}

impl fmt::Display for Revision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// A point in time as whole seconds since the Unix epoch.
///
/// This crate never reads a clock; callers pass the current time in.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use stratum_node_core::UnixTime;
///
/// let now = UnixTime::from_secs(1_700_000_000);
/// let later = now.checked_add(Duration::from_secs(300));
/// assert_eq!(later, Some(UnixTime::from_secs(1_700_000_300)));
/// ```
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct UnixTime(u64);

impl UnixTime {
    /// Wraps a number of seconds since the Unix epoch.
    pub const fn from_secs(secs: u64) -> Self {
        Self(secs)
    }

    /// Returns the number of seconds since the Unix epoch.
    pub const fn as_secs(self) -> u64 {
        self.0
    }

    /// Adds a duration, ignoring sub-second precision, or returns `None` on
    /// overflow.
    pub const fn checked_add(self, duration: Duration) -> Option<Self> {
        match self.0.checked_add(duration.as_secs()) {
            Some(secs) => Some(Self(secs)),
            None => None,
        }
    }

    /// Returns the absolute distance between two times, in seconds.
    pub const fn abs_diff(self, other: Self) -> u64 {
        self.0.abs_diff(other.0)
    }
}

impl From<u64> for UnixTime {
    fn from(secs: u64) -> Self {
        Self(secs)
    }
}

impl From<UnixTime> for u64 {
    fn from(time: UnixTime) -> Self {
        time.0
    }
}

impl fmt::Display for UnixTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// A caller-chosen identifier for a mutating operation.
///
/// It is 1 to [`OPERATION_ID_MAX_LEN`] characters drawn from `[A-Za-z0-9_-]`,
/// and is compared exactly (case matters).
///
/// # Examples
///
/// ```
/// use stratum_node_core::OperationId;
///
/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
/// let op: OperationId = "apply-2026_12_03".parse()?;
/// assert_eq!(op.as_str(), "apply-2026_12_03");
/// assert!("has space".parse::<OperationId>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OperationId(String);

impl OperationId {
    /// Returns the identifier text.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Checks the length and character set.
    fn validate(text: &str) -> Result<(), ParseIdError> {
        if text.is_empty() {
            return Err(ParseIdError::Empty);
        }
        if text.len() > OPERATION_ID_MAX_LEN {
            return Err(ParseIdError::TooLong);
        }
        if !text
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
        {
            return Err(ParseIdError::InvalidCharacter);
        }
        Ok(())
    }
}

impl FromStr for OperationId {
    type Err = ParseIdError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        Self::validate(text)?;
        Ok(Self(text.to_owned()))
    }
}

impl TryFrom<String> for OperationId {
    type Error = ParseIdError;

    fn try_from(text: String) -> Result<Self, Self::Error> {
        Self::validate(&text)?;
        Ok(Self(text))
    }
}

impl AsRef<str> for OperationId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for OperationId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Serialize for OperationId {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for OperationId {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        Self::try_from(text).map_err(serde::de::Error::custom)
    }
}