stratum-node-core 0.1.0-alpha.4

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 BIP-340 glue over `k256::schnorr`.
//!
//! Every signature this crate checks goes through [`verify`], and every
//! signature it makes goes through [`sign`]. No curve arithmetic happens here:
//! both delegate to `k256`.

use k256::elliptic_curve::rand_core::{TryCryptoRng, TryRng};
use k256::schnorr::signature::hazmat::RandomizedPrehashSigner;
use k256::schnorr::{Signature, SigningKey, VerifyingKey};

/// Returns `true` when `bytes` is the x-coordinate of a point on secp256k1.
pub(crate) fn is_valid_xonly(bytes: &[u8; 32]) -> bool {
    VerifyingKey::from_bytes(&(*bytes).into()).is_ok()
}

/// Verifies a BIP-340 signature over `message` by the x-only key `public_key`.
///
/// Returns `false` when the key is not a valid point, when the signature is
/// not a valid encoding (`r` not a field element, `s` not below the group
/// order) or when the signature does not verify.
pub(crate) fn verify(public_key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
    let Ok(key) = VerifyingKey::from_bytes(&(*public_key).into()) else {
        return false;
    };
    let Ok(signature) = Signature::from_bytes(signature) else {
        return false;
    };
    key.verify_raw(message, &signature).is_ok()
}

/// Why [`sign`] produced no signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SchnorrSignError {
    /// `k256` drew the auxiliary randomness as expected but refused to sign,
    /// which happens only when the derived nonce is zero. Retrying with fresh
    /// auxiliary randomness is the remedy.
    ZeroNonce,
    /// `k256` did not draw the auxiliary randomness as exactly one 32-byte
    /// request. No signature is returned, because it would not be bound to
    /// the caller's auxiliary data. Retrying cannot help.
    AuxRandNotUsed,
}

/// Signs `message` with BIP-340 using the caller's 32 bytes of auxiliary
/// randomness.
///
/// The signature is returned only when `k256` drew the auxiliary randomness
/// exactly once, as one 32-byte request. Any other pattern of draws (none,
/// a second one, another size, a `u32` or `u64`) gives
/// [`SchnorrSignError::AuxRandNotUsed`], even if `k256` produced a signature,
/// so a dependency change can never silently sign with substitute data.
pub(crate) fn sign(
    key: &SigningKey,
    message: &[u8],
    aux_rand: &[u8; 32],
) -> Result<[u8; 64], SchnorrSignError> {
    let mut rng = AuxRand::new(aux_rand);
    let signature = key
        .sign_prehash_with_rng(&mut rng, message)
        .ok()
        .map(|signature| signature.to_bytes());
    finish(rng.state, signature)
}

/// Decides the outcome of [`sign`] from how the adapter was drawn on and
/// whether `k256` returned a signature.
fn finish(state: DrawState, signature: Option<[u8; 64]>) -> Result<[u8; 64], SchnorrSignError> {
    match (state, signature) {
        (DrawState::Drawn, Some(signature)) => Ok(signature),
        (DrawState::Drawn, None) => Err(SchnorrSignError::ZeroNonce),
        (DrawState::Fresh | DrawState::Refused, _) => Err(SchnorrSignError::AuxRandNotUsed),
    }
}

/// How an [`AuxRand`] has been drawn on so far.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DrawState {
    /// Nothing has been drawn.
    Fresh,
    /// The one expected 32-byte draw happened, and nothing else.
    Drawn,
    /// Some other draw was attempted and refused. This state is final.
    Refused,
}

/// The error an [`AuxRand`] returns for any draw other than the first
/// 32-byte one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("unexpected draw from one-shot auxiliary randomness")]
struct UnexpectedDraw;

/// A one-shot source that hands `k256` the caller's auxiliary randomness.
///
/// `k256` draws exactly 32 bytes of auxiliary data per BIP-340 signature
/// through its public randomised-signer interface. This adapter yields the
/// supplied bytes for the first request if, and only if, it asks for exactly
/// 32 bytes. Every other request fails with [`UnexpectedDraw`] and marks the
/// adapter [`DrawState::Refused`], which [`finish`] turns into an error. The
/// signing-vector tests pin that the supplied bytes are the ones used.
struct AuxRand {
    bytes: [u8; 32],
    state: DrawState,
}

impl AuxRand {
    fn new(bytes: &[u8; 32]) -> Self {
        Self {
            bytes: *bytes,
            state: DrawState::Fresh,
        }
    }
}

impl Drop for AuxRand {
    fn drop(&mut self) {
        zeroize::Zeroize::zeroize(&mut self.bytes);
    }
}

impl TryRng for AuxRand {
    type Error = UnexpectedDraw;

    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
        self.state = DrawState::Refused;
        Err(UnexpectedDraw)
    }

    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
        self.state = DrawState::Refused;
        Err(UnexpectedDraw)
    }

    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
        if self.state == DrawState::Fresh && dst.len() == self.bytes.len() {
            dst.copy_from_slice(&self.bytes);
            self.state = DrawState::Drawn;
            Ok(())
        } else {
            self.state = DrawState::Refused;
            Err(UnexpectedDraw)
        }
    }
}

impl TryCryptoRng for AuxRand {}

#[cfg(test)]
mod tests {
    //! The official BIP-340 test vectors, run through [`verify`] and [`sign`].

    use super::*;

    /// The vectors file, with its provenance recorded beside it.
    const VECTORS: &str = include_str!("../tests/vectors/bip340-test-vectors.csv");

    struct Vector<'a> {
        index: &'a str,
        secret_key: &'a str,
        public_key: &'a str,
        aux_rand: &'a str,
        message: &'a str,
        signature: &'a str,
        expected: bool,
    }

    fn vectors() -> Vec<Vector<'static>> {
        VECTORS
            .lines()
            .skip(1)
            .filter(|line| !line.trim().is_empty())
            .map(|line| {
                let fields: Vec<&str> = line.splitn(8, ',').collect();
                assert_eq!(fields.len(), 8, "malformed vector line {line:?}");
                Vector {
                    index: fields[0],
                    secret_key: fields[1],
                    public_key: fields[2],
                    aux_rand: fields[3],
                    message: fields[4],
                    signature: fields[5],
                    expected: match fields[6] {
                        "TRUE" => true,
                        "FALSE" => false,
                        other => panic!("unexpected verification result {other:?}"),
                    },
                }
            })
            .collect()
    }

    fn fixed<const N: usize>(hex_text: &str) -> [u8; N] {
        let bytes = hex::decode(hex_text).expect("vector field is hex");
        bytes
            .try_into()
            .unwrap_or_else(|b: Vec<u8>| panic!("expected {N} bytes, got {}", b.len()))
    }

    #[test]
    fn all_verification_vectors() {
        let vectors = vectors();
        assert_eq!(vectors.len(), 19, "the published file has 19 vectors");
        for v in &vectors {
            let public_key: [u8; 32] = fixed(v.public_key);
            let message = hex::decode(v.message).expect("message is hex");
            let signature: [u8; 64] = fixed(v.signature);
            assert_eq!(
                verify(&public_key, &message, &signature),
                v.expected,
                "vector {}",
                v.index
            );
        }
    }

    #[test]
    fn aux_rand_yields_the_bytes_once_for_a_32_byte_draw() {
        let mut rng = AuxRand::new(&[7; 32]);
        let mut first = [0u8; 32];
        assert!(rng.try_fill_bytes(&mut first).is_ok(), "first draw");
        assert_eq!(first, [7; 32], "the supplied bytes");
        let mut second = [0u8; 32];
        assert!(
            rng.try_fill_bytes(&mut second).is_err(),
            "second draw fails"
        );
    }

    #[test]
    fn aux_rand_refuses_every_other_draw() {
        for len in [0usize, 1, 16, 31, 33, 64] {
            let mut rng = AuxRand::new(&[7; 32]);
            let mut buf = vec![0u8; len];
            assert!(rng.try_fill_bytes(&mut buf).is_err(), "{len}-byte draw");
        }
        assert!(AuxRand::new(&[7; 32]).try_next_u32().is_err(), "next_u32");
        assert!(AuxRand::new(&[7; 32]).try_next_u64().is_err(), "next_u64");
    }

    #[test]
    fn aux_rand_refusal_is_final() {
        let mut rng = AuxRand::new(&[7; 32]);
        let mut short = [0u8; 16];
        assert!(rng.try_fill_bytes(&mut short).is_err(), "16-byte draw");
        let mut full = [0u8; 32];
        assert!(rng.try_fill_bytes(&mut full).is_err(), "later 32-byte draw");
        assert_eq!(full, [0; 32], "nothing written");
        assert_eq!(rng.state, DrawState::Refused, "state");
    }

    #[test]
    fn signing_requires_exactly_the_one_expected_draw() {
        let sig = [3u8; 64];
        assert_eq!(finish(DrawState::Drawn, Some(sig)), Ok(sig), "drawn once");
        assert_eq!(
            finish(DrawState::Drawn, None),
            Err(SchnorrSignError::ZeroNonce),
            "drawn, no signature"
        );
        for state in [DrawState::Fresh, DrawState::Refused] {
            for signature in [Some(sig), None] {
                assert_eq!(
                    finish(state, signature),
                    Err(SchnorrSignError::AuxRandNotUsed),
                    "{state:?} with {:?}",
                    signature.is_some()
                );
            }
        }
    }

    #[test]
    fn all_signing_vectors() {
        let mut signed = 0;
        for v in vectors().iter().filter(|v| !v.secret_key.is_empty()) {
            let secret: [u8; 32] = fixed(v.secret_key);
            let key = SigningKey::from_bytes(&secret.into()).expect("vector secret key is valid");
            let public_key: [u8; 32] = fixed(v.public_key);
            assert_eq!(
                <[u8; 32]>::from(key.verifying_key().to_bytes()),
                public_key,
                "vector {} public key",
                v.index
            );
            let message = hex::decode(v.message).expect("message is hex");
            let aux: [u8; 32] = fixed(v.aux_rand);
            let signature = sign(&key, &message, &aux).expect("vector signs");
            let want: [u8; 64] = fixed(v.signature);
            assert_eq!(signature, want, "vector {} signature", v.index);
            signed += 1;
        }
        assert_eq!(signed, 8, "the published file has 8 signing vectors");
    }
}