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
//! The `did:nostr` principal: a DID over a BIP-340 x-only public key.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::encoding::{self, Bech32Error};

/// The method prefix every `did:nostr` identifier starts with.
const DID_PREFIX: &str = "did:nostr:";

/// The NIP-19 human-readable prefix for public keys.
const NPUB_HRP: &str = "npub";

/// A `did:nostr` principal over a 32-byte x-only secp256k1 public key.
///
/// Every value holds a key that is a valid BIP-340 x-only point, so a
/// `DidNostr` can always be used to verify a signature. The canonical text
/// form is `did:nostr:` followed by 64 lowercase hexadecimal digits, which is
/// what [`Display`](fmt::Display), [`FromStr`] and serde use. Ordering and
/// hashing follow the key bytes, which agrees with the order of the hex text.
///
/// # Examples
///
/// ```
/// use stratum_node_core::DidNostr;
///
/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
/// let did: DidNostr =
///     "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
/// assert_eq!(DidNostr::from_npub(&did.to_npub())?, did);
/// assert_eq!(DidNostr::from_hex(&did.to_hex())?, did);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DidNostr([u8; 32]);

impl DidNostr {
    /// Builds a principal from the raw 32-byte x-only public key.
    ///
    /// # Errors
    ///
    /// Returns [`ParseDidError::NotOnCurve`] when the bytes are not the
    /// x-coordinate of a point on secp256k1.
    pub fn from_bytes(bytes: [u8; 32]) -> Result<Self, ParseDidError> {
        if crate::schnorr::is_valid_xonly(&bytes) {
            Ok(Self(bytes))
        } else {
            Err(ParseDidError::NotOnCurve)
        }
    }

    /// Parses the key from 64 lowercase hexadecimal digits, with no prefix.
    ///
    /// Uppercase digits are rejected so that each key has one text form.
    ///
    /// # Errors
    ///
    /// Returns [`ParseDidError::InvalidHex`] for anything other than 64
    /// lowercase hex digits, and [`ParseDidError::NotOnCurve`] for a value
    /// that is not a valid point.
    pub fn from_hex(hex: &str) -> Result<Self, ParseDidError> {
        let bytes = encoding::decode_lower_hex::<32>(hex).ok_or(ParseDidError::InvalidHex)?;
        Self::from_bytes(bytes)
    }

    /// Parses a NIP-19 `npub1…` bech32 public key.
    ///
    /// # Errors
    ///
    /// Returns [`ParseDidError::InvalidBech32`] for a malformed string, a
    /// bech32m checksum or non-zero padding bits (so each key has exactly
    /// one accepted encoding, up to letter case), [`ParseDidError::WrongBech32Prefix`] for a prefix
    /// other than `npub`, [`ParseDidError::InvalidLength`] when the payload
    /// is not 32 bytes, and [`ParseDidError::NotOnCurve`] for a value that is
    /// not a valid point.
    pub fn from_npub(npub: &str) -> Result<Self, ParseDidError> {
        let mut bytes = [0u8; 32];
        encoding::decode_bech32(npub, NPUB_HRP, &mut bytes).map_err(|err| match err {
            Bech32Error::Invalid => ParseDidError::InvalidBech32,
            Bech32Error::WrongPrefix => ParseDidError::WrongBech32Prefix,
            Bech32Error::WrongLength => ParseDidError::InvalidLength,
        })?;
        Self::from_bytes(bytes)
    }

    /// Returns the raw 32-byte x-only public key.
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Returns the key as 64 lowercase hexadecimal digits, as used in the
    /// `pubkey` field of a Nostr event.
    pub fn to_hex(&self) -> String {
        hex::encode(self.0)
    }

    /// Returns the key as a NIP-19 `npub1…` string.
    pub fn to_npub(&self) -> String {
        encoding::encode_bech32(NPUB_HRP, &self.0)
    }
}

impl fmt::Display for DidNostr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{DID_PREFIX}{}", self.to_hex())
    }
}

impl fmt::Debug for DidNostr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "DidNostr({self})")
    }
}

impl FromStr for DidNostr {
    type Err = ParseDidError;

    /// Parses `did:nostr:<64 lowercase hex>`.
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let hex = text
            .strip_prefix(DID_PREFIX)
            .ok_or(ParseDidError::MissingPrefix)?;
        Self::from_hex(hex)
    }
}

impl TryFrom<[u8; 32]> for DidNostr {
    type Error = ParseDidError;

    fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
        Self::from_bytes(bytes)
    }
}

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

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

/// The reasons a `did:nostr` principal can fail to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseDidError {
    /// The text does not start with `did:nostr:`.
    #[error("missing did:nostr: prefix")]
    MissingPrefix,
    /// The key is not exactly 64 lowercase hexadecimal digits.
    #[error("public key is not 64 lowercase hex digits")]
    InvalidHex,
    /// The string is not valid bech32 with a bech32 (not bech32m) checksum
    /// and zero padding bits.
    #[error("invalid bech32 public key")]
    InvalidBech32,
    /// The bech32 prefix is not `npub`.
    #[error("bech32 prefix is not npub")]
    WrongBech32Prefix,
    /// The decoded payload is not 32 bytes.
    #[error("public key is not 32 bytes")]
    InvalidLength,
    /// The bytes are not the x-coordinate of a point on secp256k1.
    #[error("public key is not a valid x-only secp256k1 point")]
    NotOnCurve,
}