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
//! Text forms: round trips, canonical-form rejection and published NIP-19
//! vectors.

use proptest::prelude::*;
use stratum_node_core::{
    ChallengeId, DidNostr, EventId, NostrSecretKey, OperationId, ParseDidError, ParseIdError,
    ParseKeyError, Revision, Sha256Digest, UnixTime, OPERATION_ID_MAX_LEN,
};

/// NIP-19 published example: public key in hex and as npub.
const NIP19_PUB_HEX: &str = "7e7e9c42a91bfef19fa929e5fda1b72e0ebc1a4c1141673e2794234d86addf4e";
const NIP19_NPUB: &str = "npub10elfcs4fr0l0r8af98jlmgdh9c8tcxjvz9qkw038js35mp4dma8qzvjptg";
/// NIP-19 published example: secret key in hex and as nsec.
const NIP19_SEC_HEX: &str = "67dea2ed018072d675f5415ecfaed7d2597555e202d85b3d65ea4e58d2d92ffa";
const NIP19_NSEC: &str = "nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9laqsnlfe5";

#[test]
fn nip19_public_key_vector() {
    let from_hex = DidNostr::from_hex(NIP19_PUB_HEX).expect("hex parses");
    let from_npub = DidNostr::from_npub(NIP19_NPUB).expect("npub parses");
    assert_eq!(from_hex, from_npub, "same key");
    assert_eq!(from_hex.to_npub(), NIP19_NPUB, "npub encoding");
    assert_eq!(
        from_hex.to_string(),
        format!("did:nostr:{NIP19_PUB_HEX}"),
        "did form"
    );
}

#[test]
fn nip19_secret_key_vector() {
    let from_hex = NostrSecretKey::from_hex(NIP19_SEC_HEX).expect("hex parses");
    let from_nsec = NostrSecretKey::from_nsec(NIP19_NSEC).expect("nsec parses");
    assert_eq!(from_hex.public(), from_nsec.public(), "same key");
    assert_eq!(
        from_hex.public().to_hex(),
        NIP19_PUB_HEX,
        "derived public key"
    );
}

#[test]
fn did_rejects_non_canonical_and_invalid_forms() {
    let upper = format!("did:nostr:{}", NIP19_PUB_HEX.to_uppercase());
    assert_eq!(
        upper.parse::<DidNostr>(),
        Err(ParseDidError::InvalidHex),
        "uppercase"
    );
    assert_eq!(
        NIP19_PUB_HEX.parse::<DidNostr>(),
        Err(ParseDidError::MissingPrefix),
        "bare hex"
    );
    assert_eq!(
        format!("did:nostr:{}", &NIP19_PUB_HEX[2..]).parse::<DidNostr>(),
        Err(ParseDidError::InvalidHex),
        "short"
    );
    // x = 5 is not on the curve (BIP-340 vector 5).
    let off = "eefdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34";
    assert_eq!(
        DidNostr::from_hex(off),
        Err(ParseDidError::NotOnCurve),
        "off curve"
    );
    assert_eq!(
        DidNostr::from_npub(NIP19_NSEC),
        Err(ParseDidError::WrongBech32Prefix),
        "nsec is not npub"
    );
    let mut corrupted = NIP19_NPUB.to_owned();
    corrupted.pop();
    corrupted.push('q');
    assert_eq!(
        DidNostr::from_npub(&corrupted),
        Err(ParseDidError::InvalidBech32),
        "bad checksum"
    );
}

/// The generator point's x-coordinate as a canonical npub.
const GENERATOR_NPUB: &str = "npub10xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqpkge6d";
/// The same 32 bytes with the lowest of the four padding bits set and a valid
/// bech32 checksum (the reviewer's reproducer).
const GENERATOR_NPUB_PADDED: &str =
    "npub10xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vpuquv8l";
/// `NIP19_NSEC` with the lowest padding bit set and a valid checksum.
const NIP19_NSEC_PADDED_LOW: &str =
    "nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9lapd9tuyx";
/// `NIP19_NSEC` with the highest padding bit set and a valid checksum.
const NIP19_NSEC_PADDED_HIGH: &str =
    "nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9lagw8m98f";

#[test]
fn npub_with_non_zero_padding_is_rejected() {
    let canonical = DidNostr::from_npub(GENERATOR_NPUB).expect("canonical npub parses");
    assert_eq!(
        canonical.to_hex(),
        "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
        "generator x-coordinate"
    );
    assert_eq!(
        DidNostr::from_npub(GENERATOR_NPUB_PADDED),
        Err(ParseDidError::InvalidBech32),
        "non-zero padding"
    );
}

#[test]
fn nsec_with_non_zero_padding_is_rejected() {
    assert!(NostrSecretKey::from_nsec(NIP19_NSEC).is_ok(), "canonical");
    for alias in [NIP19_NSEC_PADDED_LOW, NIP19_NSEC_PADDED_HIGH] {
        assert_eq!(
            NostrSecretKey::from_nsec(alias).map(|key| key.public()),
            Err(ParseKeyError::InvalidBech32),
            "{alias}"
        );
    }
}

#[test]
fn did_serde_is_the_did_string_and_validates() {
    let did = DidNostr::from_hex(NIP19_PUB_HEX).expect("valid");
    let json = serde_json::to_string(&did).expect("serialises");
    assert_eq!(json, format!("\"did:nostr:{NIP19_PUB_HEX}\""), "json form");
    assert_eq!(
        serde_json::from_str::<DidNostr>(&json).expect("parses"),
        did,
        "round trip"
    );
    let upper = format!("\"did:nostr:{}\"", NIP19_PUB_HEX.to_uppercase());
    assert!(
        serde_json::from_str::<DidNostr>(&upper).is_err(),
        "deserialise validates"
    );
}

#[test]
fn operation_id_rules() {
    assert_eq!("".parse::<OperationId>(), Err(ParseIdError::Empty), "empty");
    let longest = "a".repeat(OPERATION_ID_MAX_LEN);
    assert!(longest.parse::<OperationId>().is_ok(), "64 chars");
    assert_eq!(
        format!("{longest}a").parse::<OperationId>(),
        Err(ParseIdError::TooLong),
        "65 chars"
    );
    for bad in ["a b", "a/b", "é", "a.b"] {
        assert_eq!(
            bad.parse::<OperationId>(),
            Err(ParseIdError::InvalidCharacter),
            "{bad:?}"
        );
    }
    assert!(
        serde_json::from_str::<OperationId>("\"a b\"").is_err(),
        "serde validates"
    );
}

#[test]
fn revision_next_and_serde() {
    assert_eq!(Revision::new(41).next(), Some(Revision::new(42)), "next");
    assert_eq!(Revision::new(u64::MAX).next(), None, "overflow");
    assert_eq!(
        serde_json::to_string(&Revision::new(7)).expect("ser"),
        "7",
        "plain number"
    );
}

#[test]
fn hex_identifiers_reject_uppercase_and_wrong_length() {
    let upper = "AB".repeat(32);
    assert_eq!(
        upper.parse::<EventId>(),
        Err(ParseIdError::InvalidHex { expected: 64 }),
        "event id upper"
    );
    assert_eq!(
        "ab".repeat(15).parse::<ChallengeId>(),
        Err(ParseIdError::InvalidHex { expected: 32 }),
        "challenge short"
    );
    assert!(
        serde_json::from_str::<Sha256Digest>(&format!("\"{upper}\"")).is_err(),
        "serde validates"
    );
}

fn did_strategy() -> impl Strategy<Value = DidNostr> {
    any::<[u8; 32]>().prop_filter_map("valid x-only point", |b| DidNostr::from_bytes(b).ok())
}

proptest! {
    #[test]
    fn did_text_forms_round_trip(did in did_strategy()) {
        prop_assert_eq!(did.to_string().parse::<DidNostr>(), Ok(did));
        prop_assert_eq!(DidNostr::from_hex(&did.to_hex()), Ok(did));
        prop_assert_eq!(DidNostr::from_npub(&did.to_npub()), Ok(did));
        let json = serde_json::to_string(&did).expect("serialises");
        prop_assert_eq!(serde_json::from_str::<DidNostr>(&json).expect("parses"), did);
    }

    #[test]
    fn did_order_matches_text_order(a in did_strategy(), b in did_strategy()) {
        prop_assert_eq!(a.cmp(&b), a.to_string().cmp(&b.to_string()));
    }

    #[test]
    fn byte_identifiers_round_trip(bytes in any::<[u8; 32]>(), short in any::<[u8; 16]>()) {
        let id = EventId::from_bytes(bytes);
        prop_assert_eq!(id.to_string().parse::<EventId>(), Ok(id));
        let digest = Sha256Digest::from_bytes(bytes);
        prop_assert_eq!(digest.to_string().parse::<Sha256Digest>(), Ok(digest));
        let json = serde_json::to_string(&digest).expect("serialises");
        prop_assert_eq!(serde_json::from_str::<Sha256Digest>(&json).expect("parses"), digest);
        let challenge = ChallengeId::from_bytes(short);
        prop_assert_eq!(challenge.to_string().parse::<ChallengeId>(), Ok(challenge));
        prop_assert_eq!(challenge.to_hex().len(), 32);
    }

    #[test]
    fn operation_id_accepts_exactly_its_alphabet(text in "[A-Za-z0-9_-]{1,64}") {
        let op = text.parse::<OperationId>().expect("valid alphabet parses");
        prop_assert_eq!(op.as_str(), text.as_str());
        let json = serde_json::to_string(&op).expect("serialises");
        prop_assert_eq!(serde_json::from_str::<OperationId>(&json).expect("parses"), op);
    }

    #[test]
    fn operation_id_rejects_other_characters(
        prefix in "[a-z]{0,10}",
        bad in "[^A-Za-z0-9_-]",
    ) {
        let text = format!("{prefix}{bad}");
        prop_assert!(text.parse::<OperationId>().is_err());
    }

    #[test]
    fn numeric_newtypes_round_trip(n in any::<u64>()) {
        let revision = Revision::new(n);
        let json = serde_json::to_string(&revision).expect("serialises");
        prop_assert_eq!(serde_json::from_str::<Revision>(&json).expect("parses"), revision);
        let time = UnixTime::from_secs(n);
        let json = serde_json::to_string(&time).expect("serialises");
        prop_assert_eq!(serde_json::from_str::<UnixTime>(&json).expect("parses"), time);
    }
}