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
//! Nostr secret keys and signing.

use std::fmt;

use base64::Engine as _;
use k256::schnorr::SigningKey;
use zeroize::Zeroizing;

use crate::did::DidNostr;
use crate::encoding::{self, Bech32Error};
use crate::event::{SignedEvent, UnsignedEvent};
use crate::id::{Sha256Digest, UnixTime};
use crate::request::{ExpectedRequest, AUTHORIZATION_SCHEME, HTTP_AUTH_KIND};
use crate::schnorr::SchnorrSignError;

/// The NIP-19 human-readable prefix for secret keys.
const NSEC_HRP: &str = "nsec";

/// A secp256k1 secret key used to sign Nostr events with BIP-340.
///
/// The key is zeroised when dropped. It does not implement `Clone`,
/// `Serialize` or `Display`, and its `Debug` output shows only the public
/// principal. This crate offers no way to export the secret again. Zeroising
/// is best effort: temporary copies made on the stack while parsing are not
/// all reachable, and memory dumps and swap are outside what it can promise.
///
/// # Examples
///
/// ```
/// use stratum_node_core::NostrSecretKey;
///
/// # fn main() -> Result<(), stratum_node_core::ParseKeyError> {
/// let key = NostrSecretKey::from_hex(&"03".repeat(32))?;
/// let debug = format!("{key:?}");
/// assert!(!debug.contains(&"03".repeat(32)));
/// assert!(debug.contains(&key.public().to_string()));
/// # Ok(())
/// # }
/// ```
///
/// It cannot be cloned or serialised:
///
/// ```compile_fail
/// fn needs_clone<T: Clone>() {}
/// needs_clone::<stratum_node_core::NostrSecretKey>();
/// ```
///
/// ```compile_fail
/// fn needs_serialize<T: serde::Serialize>() {}
/// needs_serialize::<stratum_node_core::NostrSecretKey>();
/// ```
pub struct NostrSecretKey {
    key: SigningKey,
    public: DidNostr,
}

impl NostrSecretKey {
    /// Builds a key from its 32 big-endian bytes.
    ///
    /// The caller remains responsible for zeroising its own copy.
    ///
    /// # Errors
    ///
    /// Returns [`ParseKeyError::OutOfRange`] when the value is zero or not
    /// below the secp256k1 group order.
    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, ParseKeyError> {
        let key = SigningKey::from_slice(bytes).map_err(|_| ParseKeyError::OutOfRange)?;
        let public_bytes: [u8; 32] = key.verifying_key().to_bytes().into();
        let public = DidNostr::from_bytes(public_bytes).map_err(|_| ParseKeyError::OutOfRange)?;
        Ok(Self { key, public })
    }

    /// Parses a key from 64 lowercase hexadecimal digits.
    ///
    /// # Errors
    ///
    /// Returns [`ParseKeyError::InvalidHex`] for anything other than 64
    /// lowercase hex digits, and [`ParseKeyError::OutOfRange`] as for
    /// [`from_bytes`](Self::from_bytes).
    pub fn from_hex(hex: &str) -> Result<Self, ParseKeyError> {
        let mut bytes = Zeroizing::new([0u8; 32]);
        if !encoding::decode_lower_hex_into(hex, bytes.as_mut_slice()) {
            return Err(ParseKeyError::InvalidHex);
        }
        Self::from_bytes(&bytes)
    }

    /// Parses a NIP-19 `nsec1…` bech32 secret key.
    ///
    /// # Errors
    ///
    /// Returns [`ParseKeyError::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), [`ParseKeyError::WrongBech32Prefix`] for a prefix
    /// other than `nsec`, [`ParseKeyError::InvalidLength`] when the payload
    /// is not 32 bytes, and [`ParseKeyError::OutOfRange`] as for
    /// [`from_bytes`](Self::from_bytes).
    pub fn from_nsec(nsec: &str) -> Result<Self, ParseKeyError> {
        let mut bytes = Zeroizing::new([0u8; 32]);
        encoding::decode_bech32(nsec, NSEC_HRP, &mut bytes).map_err(|err| match err {
            Bech32Error::Invalid => ParseKeyError::InvalidBech32,
            Bech32Error::WrongPrefix => ParseKeyError::WrongBech32Prefix,
            Bech32Error::WrongLength => ParseKeyError::InvalidLength,
        })?;
        Self::from_bytes(&bytes)
    }

    /// Returns the public principal for this key.
    pub fn public(&self) -> DidNostr {
        self.public
    }

    /// Signs an event.
    ///
    /// `aux_rand` is the 32 bytes of BIP-340 auxiliary randomness. It should
    /// come from a secure random source; BIP-340 signatures stay secure with
    /// fixed auxiliary data, but fresh randomness hardens against
    /// side-channel and fault attacks.
    ///
    /// # Errors
    ///
    /// Returns [`SignError::EmptyTag`] when a tag has no elements,
    /// [`SignError::UnsupportedCharacter`] when the content or a tag holds a
    /// control character this crate cannot serialise as NIP-01 requires (see
    /// [`SignedEvent`](crate::SignedEvent#character-restriction)),
    /// [`SignError::ZeroNonce`] in the negligible case that the derived nonce
    /// is zero, and [`SignError::AuxRandNotUsed`] if the BIP-340 backend did
    /// not take `aux_rand` as its single 32-byte auxiliary input. No
    /// signature is ever made with auxiliary data other than `aux_rand`.
    pub fn sign_event(
        &self,
        event: &UnsignedEvent,
        aux_rand: &[u8; 32],
    ) -> Result<SignedEvent, SignError> {
        if event.has_empty_tag() {
            return Err(SignError::EmptyTag);
        }
        if !event.is_supported_text() {
            return Err(SignError::UnsupportedCharacter);
        }
        let id = event.id_for(&self.public);
        let sig =
            crate::schnorr::sign(&self.key, id.as_bytes(), aux_rand).map_err(|err| match err {
                SchnorrSignError::ZeroNonce => SignError::ZeroNonce,
                SchnorrSignError::AuxRandNotUsed => SignError::AuxRandNotUsed,
            })?;
        Ok(event.clone().into_signed(id, self.public, sig))
    }

    /// Builds and signs a kind-27235 request event and returns the complete
    /// `Authorization` header value, `Nostr <base64 of event JSON>`.
    ///
    /// The event carries a `u` tag with `request.url`, a `method` tag with
    /// `request.method` exactly as given (no case folding: HTTP methods are
    /// case-sensitive, and the verifier compares them byte for byte) and, when `request.body` is `Some`
    /// (even if empty), a `payload` tag with the lowercase hex SHA-256 of the
    /// body. Content is empty. The result passes [`verify_request`] for the
    /// same request within the clock-skew window around `created_at`.
    ///
    /// [`verify_request`]: crate::verify_request
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let key = NostrSecretKey::from_hex(&"04".repeat(32))?;
    /// let request = ExpectedRequest::new("POST", "http://127.0.0.1:7070/api/v1/config/apply", Some(b"{}"));
    /// let now = UnixTime::from_secs(1_700_000_000);
    /// let header = key.sign_request(&request, now, &[0u8; 32])?;
    /// let verified = verify_request(&header, &request, now, &RequestPolicy::new())?;
    /// assert_eq!(verified.signer(), key.public());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// As for [`sign_event`](Self::sign_event); a URL containing an
    /// unsupported control character gives [`SignError::UnsupportedCharacter`].
    pub fn sign_request(
        &self,
        request: &ExpectedRequest<'_>,
        created_at: UnixTime,
        aux_rand: &[u8; 32],
    ) -> Result<String, SignError> {
        let mut event = UnsignedEvent::new(HTTP_AUTH_KIND, created_at)
            .with_tag(["u", request.url])
            .with_tag(["method", request.method]);
        if let Some(body) = request.body {
            event = event.with_tag(["payload".to_owned(), Sha256Digest::of(body).to_hex()]);
        }
        let signed = self.sign_event(&event, aux_rand)?;
        let token = base64::engine::general_purpose::STANDARD.encode(signed.to_json());
        Ok(format!("{AUTHORIZATION_SCHEME} {token}"))
    }
}

impl fmt::Debug for NostrSecretKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NostrSecretKey")
            .field("public", &self.public)
            .finish_non_exhaustive()
    }
}

/// The reasons a secret key can fail to parse.
///
/// No variant carries any part of the input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseKeyError {
    /// The text is not exactly 64 lowercase hexadecimal digits.
    #[error("secret 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 secret key")]
    InvalidBech32,
    /// The bech32 prefix is not `nsec`.
    #[error("bech32 prefix is not nsec")]
    WrongBech32Prefix,
    /// The decoded payload is not 32 bytes.
    #[error("secret key is not 32 bytes")]
    InvalidLength,
    /// The value is zero or not below the secp256k1 group order.
    #[error("secret key is out of range")]
    OutOfRange,
}

/// The reasons signing can fail.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SignError {
    /// The content or a tag contains a control character outside the set
    /// NIP-01 escapes by name; see
    /// [`SignedEvent`](crate::SignedEvent#character-restriction).
    #[error("event text contains an unsupported control character")]
    UnsupportedCharacter,
    /// A tag has no elements; NIP-01 requires at least one.
    #[error("event has an empty tag")]
    EmptyTag,
    /// The BIP-340 nonce derived from this key, message and auxiliary
    /// randomness is zero. The probability is negligible; retry with fresh
    /// auxiliary randomness.
    #[error("derived signing nonce is zero; retry with fresh auxiliary randomness")]
    ZeroNonce,
    /// The BIP-340 backend did not take the auxiliary randomness as exactly
    /// one 32-byte draw, so no signature is returned rather than one made
    /// with substitute auxiliary data. This points at an incompatible
    /// dependency version, not at the input; retrying does not help.
    #[error("signing backend did not take the auxiliary randomness as one 32-byte draw")]
    AuxRandNotUsed,
}