vouch-core 4.1.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
//! Ed25519 key generation, signing, verification, and did:key encoding.
//!
//! Matches the TypeScript reference SDK: the same seed produces the same public
//! key, the same message produces the same 64-byte signature, and did:key uses
//! the Ed25519 multikey (`did:key:z6Mk...`). Interop is asserted against the
//! shared vectors (a seed -> public-key known-answer test).

use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};

use crate::error::{CoreError, Result};
use crate::multikey;

pub const ED25519_SEED_LEN: usize = 32;
pub const ED25519_PUBLIC_LEN: usize = 32;
pub const ED25519_SIGNATURE_LEN: usize = 64;

/// An Ed25519 key pair. The 32-byte seed is the private key (RFC 8032).
pub struct Ed25519KeyPair {
    signing: SigningKey,
}

impl Ed25519KeyPair {
    /// Generate a fresh key pair using the platform CSPRNG (getrandom; on WASM
    /// this is the JS crypto API via the getrandom "js" feature in the wasm
    /// wrapper crate).
    pub fn generate() -> Result<Self> {
        let mut seed = [0u8; ED25519_SEED_LEN];
        getrandom::getrandom(&mut seed).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
        Ok(Self::from_seed(&seed))
    }

    /// Build a key pair from a 32-byte seed (deterministic; used for KATs and
    /// for importing an existing private key).
    pub fn from_seed(seed: &[u8; ED25519_SEED_LEN]) -> Self {
        Self {
            signing: SigningKey::from_bytes(seed),
        }
    }

    /// Build a key pair from a seed slice, validating its length.
    pub fn from_seed_slice(seed: &[u8]) -> Result<Self> {
        let arr: [u8; ED25519_SEED_LEN] =
            seed.try_into().map_err(|_| CoreError::InvalidKeyLength {
                expected: ED25519_SEED_LEN,
                got: seed.len(),
            })?;
        Ok(Self::from_seed(&arr))
    }

    /// The 32-byte private seed.
    pub fn seed(&self) -> [u8; ED25519_SEED_LEN] {
        self.signing.to_bytes()
    }

    /// The 32-byte public key.
    pub fn public_key(&self) -> [u8; ED25519_PUBLIC_LEN] {
        self.signing.verifying_key().to_bytes()
    }

    /// Sign a message, returning the 64-byte signature.
    pub fn sign(&self, message: &[u8]) -> [u8; ED25519_SIGNATURE_LEN] {
        self.signing.sign(message).to_bytes()
    }

    /// The public key as a Multikey string (z-prefixed base58btc).
    pub fn public_multikey(&self) -> String {
        multikey::encode_ed25519_public(&self.public_key()).expect("public key is always 32 bytes")
    }

    /// The did:key form of the public key.
    pub fn did_key(&self) -> String {
        ed25519_to_did_key(&self.public_key()).expect("public key is always 32 bytes")
    }
}

/// The field prime p = 2^255 - 19, little-endian (the byte order of an encoded
/// Ed25519 point).
const FIELD_PRIME_LE: [u8; 32] = [
    0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
];

/// True when a 32-byte Ed25519 point encoding is canonical: its y coordinate
/// (the low 255 bits, little-endian) is below p. An encoding with y >= p names
/// the same point as y - p, so accepting it would give one key two spellings.
pub fn is_canonical_point_encoding(encoded: &[u8; 32]) -> bool {
    let mut y = *encoded;
    y[31] &= 0x7f; // drop the sign bit of x
                   // Compare the little-endian numbers from the most significant byte down.
    for i in (0..32).rev() {
        if y[i] != FIELD_PRIME_LE[i] {
            return y[i] < FIELD_PRIME_LE[i];
        }
    }
    false // y == p
}

/// Decode a 32-byte Ed25519 public key strictly: the encoding must be
/// canonical (y < p), must decode to a curve point, and the point must not be
/// of small order (the identity or a torsion point, which lets one signature
/// verify for many messages). Weak keys are refused here, at decode time, so
/// they never reach a verifier.
pub fn strict_verifying_key(public_key: &[u8]) -> Result<VerifyingKey> {
    let pk: [u8; ED25519_PUBLIC_LEN] =
        public_key
            .try_into()
            .map_err(|_| CoreError::InvalidKeyLength {
                expected: ED25519_PUBLIC_LEN,
                got: public_key.len(),
            })?;
    if !is_canonical_point_encoding(&pk) {
        return Err(CoreError::Crypto(
            "bad public key: non-canonical point encoding".into(),
        ));
    }
    let vk = VerifyingKey::from_bytes(&pk)
        .map_err(|e| CoreError::Crypto(format!("bad public key: {e}")))?;
    if vk.is_weak() {
        return Err(CoreError::Crypto(
            "bad public key: small-order point".into(),
        ));
    }
    Ok(vk)
}

/// Verify a 64-byte Ed25519 signature over a message against a 32-byte public key.
///
/// Strict in every part: the public key must pass [`strict_verifying_key`]
/// (an `Err` otherwise), the signature's R must be the canonical encoding of a
/// point that is not of small order, and S must be below the group order.
pub fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool> {
    let sig: [u8; ED25519_SIGNATURE_LEN] =
        signature
            .try_into()
            .map_err(|_| CoreError::InvalidSignatureLength {
                expected: ED25519_SIGNATURE_LEN,
                got: signature.len(),
            })?;
    let vk = strict_verifying_key(public_key)?;
    let mut r = [0u8; 32];
    r.copy_from_slice(&sig[..32]);
    if !is_canonical_point_encoding(&r) {
        return Ok(false);
    }
    // verify_strict (not verify): refuses an R of small order and a small-order
    // public key, and compares R byte for byte with the recomputed (canonical)
    // R; ed25519-dalek also refuses S >= L. Honest signatures are unaffected.
    Ok(vk
        .verify_strict(message, &Signature::from_bytes(&sig))
        .is_ok())
}

/// Encode an Ed25519 public key as a did:key DID.
pub fn ed25519_to_did_key(public_key: &[u8]) -> Result<String> {
    Ok(format!(
        "did:key:{}",
        multikey::encode_ed25519_public(public_key)?
    ))
}

/// Extract the Ed25519 public key bytes from a did:key DID. The multikey must
/// carry the Ed25519 public-key codec and a strict, non-weak 32-byte key (see
/// [`multikey::decode`]).
pub fn did_key_to_ed25519(did: &str) -> Result<Vec<u8>> {
    let mk = did
        .strip_prefix("did:key:")
        .ok_or_else(|| CoreError::InvalidDid("not a did:key".into()))?;
    let decoded = multikey::decode(mk)?;
    if decoded.algorithm != "Ed25519" {
        return Err(CoreError::InvalidDid(format!(
            "did:key is {} not Ed25519",
            decoded.algorithm
        )));
    }
    Ok(decoded.raw_key)
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    /// Every encoding of a small-order Ed25519 point (the 8 torsion points,
    /// with sign-bit and y >= p spellings), computed with exact field
    /// arithmetic over 2^255 - 19 (multiply points by the group order to land
    /// in the torsion subgroup, then enumerate its spellings).
    pub(crate) const SMALL_ORDER_ENCODINGS: [&str; 14] = [
        "0000000000000000000000000000000000000000000000000000000000000000",
        "0000000000000000000000000000000000000000000000000000000000000080",
        "0100000000000000000000000000000000000000000000000000000000000000",
        "0100000000000000000000000000000000000000000000000000000000000080",
        "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
        "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
        "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
        "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
        "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
        "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
        "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
        "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
    ];

    /// y = p + 3 and y = p + 18: points that are on the curve and not of small
    /// order, spelled with y >= p. Their canonical spellings (y = 3, y = 18)
    /// decode fine.
    pub(crate) const NON_CANONICAL_ENCODINGS: [&str; 2] = [
        "f0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
        "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
    ];

    pub(crate) fn unhex32(h: &str) -> [u8; 32] {
        let mut out = [0u8; 32];
        for (i, b) in out.iter_mut().enumerate() {
            *b = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap();
        }
        out
    }

    #[test]
    fn small_order_public_keys_are_refused() {
        for h in SMALL_ORDER_ENCODINGS {
            let k = unhex32(h);
            assert!(strict_verifying_key(&k).is_err(), "{h}");
            // R = the same point and S = 0 is the classic "verifies for any
            // message" signature; it must never verify.
            let mut sig = [0u8; 64];
            sig[..32].copy_from_slice(&k);
            assert!(verify(&k, b"any message", &sig).is_err(), "{h}");
        }
    }

    #[test]
    fn non_canonical_public_keys_are_refused() {
        for h in NON_CANONICAL_ENCODINGS {
            let k = unhex32(h);
            assert!(!is_canonical_point_encoding(&k));
            // ed25519-dalek alone would accept these; the canonical check is
            // what refuses them.
            assert!(VerifyingKey::from_bytes(&k).is_ok(), "{h} is a curve point");
            assert!(strict_verifying_key(&k).is_err(), "{h}");
        }
        let mut three = [0u8; 32];
        three[0] = 3;
        assert!(strict_verifying_key(&three).is_ok());
        // The boundary: y = p - 1 is canonical, y = p is not (sign bit ignored).
        assert!(is_canonical_point_encoding(&unhex32(
            SMALL_ORDER_ENCODINGS[8]
        )));
        assert!(!is_canonical_point_encoding(&unhex32(
            SMALL_ORDER_ENCODINGS[10]
        )));
        assert!(!is_canonical_point_encoding(&unhex32(
            SMALL_ORDER_ENCODINGS[11]
        )));
    }

    #[test]
    fn small_order_or_non_canonical_r_is_refused() {
        let kp = Ed25519KeyPair::from_seed(&[8u8; 32]);
        let msg = b"vouch protocol";
        let good = kp.sign(msg);
        assert!(verify(&kp.public_key(), msg, &good).unwrap());
        for h in SMALL_ORDER_ENCODINGS
            .iter()
            .chain(NON_CANONICAL_ENCODINGS.iter())
        {
            let mut sig = good;
            sig[..32].copy_from_slice(&unhex32(h));
            assert!(!verify(&kp.public_key(), msg, &sig).unwrap(), "R = {h}");
        }
        // S >= L (here S + L) is refused.
        let l: [u8; 32] = [
            0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9,
            0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x10,
        ];
        let mut sig = good;
        let mut carry = 0u16;
        for i in 0..32 {
            let v = u16::from(sig[32 + i]) + u16::from(l[i]) + carry;
            sig[32 + i] = v as u8;
            carry = v >> 8;
        }
        assert!(!verify(&kp.public_key(), msg, &sig).unwrap_or(false));
    }

    #[test]
    fn sign_verify_roundtrip() {
        let kp = Ed25519KeyPair::generate().unwrap();
        let msg = b"vouch protocol";
        let sig = kp.sign(msg);
        assert!(verify(&kp.public_key(), msg, &sig).unwrap());
        assert!(!verify(&kp.public_key(), b"tampered", &sig).unwrap());
    }

    #[test]
    fn did_key_roundtrip() {
        let kp = Ed25519KeyPair::generate().unwrap();
        let did = kp.did_key();
        assert!(did.starts_with("did:key:z6Mk"));
        assert_eq!(did_key_to_ed25519(&did).unwrap(), kp.public_key().to_vec());
    }

    #[test]
    fn seed_determinism() {
        let seed = [3u8; 32];
        let a = Ed25519KeyPair::from_seed(&seed);
        let b = Ed25519KeyPair::from_seed(&seed);
        assert_eq!(a.public_key(), b.public_key());
    }
}