vouch-core 4.0.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
//! Multikey encoding for verification methods.
//!
//! Byte-exact port of the TypeScript SDK `multikey.ts` and `vouch/multikey.py`.
//! A public key is encoded as `publicKeyMultibase = base58btc(multicodec_prefix
//! || raw_public_key_bytes)`, with a leading 'z' marking base58btc. Cross-
//! implementation interop with the other SDKs is REQUIRED.
//!
//! Supported algorithms (multicodec table codes; the prefix on the wire is the
//! code as an unsigned varint):
//!   Ed25519     ed25519-pub    0xed    (32-byte public key)
//!   ML-DSA-44   mldsa-44-pub   0x1210  (1312-byte public key)
//!
//! Only public-key codes decode as keys. The private-key codes (ed25519-priv
//! 0x1300, mldsa-44-priv 0x1317) are recognised only so they can be refused.

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

/// Multicodec table codes.
pub const ED25519_PUB_CODEC: u16 = 0xed;
pub const ED25519_PRIV_CODEC: u16 = 0x1300;
pub const MLDSA44_PUB_CODEC: u16 = 0x1210;
pub const MLDSA44_PRIV_CODEC: u16 = 0x1317;

/// The unsigned-varint encoding of a multicodec code in 0x80..0x3fff (two
/// bytes: the low 7 bits with the continuation bit set, then the rest).
const fn varint2(code: u16) -> [u8; 2] {
    [((code & 0x7f) as u8) | 0x80, (code >> 7) as u8]
}

/// Multicodec 2-byte varint prefixes.
pub const ED25519_PUB_PREFIX: [u8; 2] = varint2(ED25519_PUB_CODEC);
pub const ED25519_PRIV_PREFIX: [u8; 2] = varint2(ED25519_PRIV_CODEC);
pub const MLDSA44_PUB_PREFIX: [u8; 2] = varint2(MLDSA44_PUB_CODEC);
pub const MLDSA44_PRIV_PREFIX: [u8; 2] = varint2(MLDSA44_PRIV_CODEC);

const ED25519_PUBLIC_LEN: usize = 32;
const MLDSA44_PUBLIC_LEN: usize = 1312;

/// Maximum base58btc input length accepted by [`decode_base58_bounded`]. base58
/// decoding is O(n^2), so an unbounded input is a denial-of-service vector. The
/// largest legitimate value is a hybrid composite proofValue (about 3400 chars);
/// 8192 is a safe ceiling well above every real key, signature, and proofValue.
pub const MAX_BASE58_LEN: usize = 8192;

/// Decode base58btc with a length cap to bound the O(n^2) decode cost. Use this
/// for any externally-supplied base58 (proofValues, multikeys) instead of
/// calling `bs58::decode` directly.
pub fn decode_base58_bounded(s: &str) -> Result<Vec<u8>> {
    if s.len() > MAX_BASE58_LEN {
        return Err(CoreError::InvalidMultikey(format!(
            "base58 input too long: {} > {MAX_BASE58_LEN}",
            s.len()
        )));
    }
    bs58::decode(s)
        .into_vec()
        .map_err(|e| CoreError::InvalidMultikey(format!("bad base58: {e}")))
}

/// A multikey decoded into its algorithm name and raw key bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedKey {
    pub algorithm: String,
    pub raw_key: Vec<u8>,
}

fn encode_with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
    let mut buf = Vec::with_capacity(2 + raw.len());
    buf.extend_from_slice(&prefix);
    buf.extend_from_slice(raw);
    format!("z{}", bs58::encode(buf).into_string())
}

/// Encode a 32-byte Ed25519 public key as a Multikey string (z-prefixed base58btc).
pub fn encode_ed25519_public(raw: &[u8]) -> Result<String> {
    if raw.len() != ED25519_PUBLIC_LEN {
        return Err(CoreError::InvalidKeyLength {
            expected: ED25519_PUBLIC_LEN,
            got: raw.len(),
        });
    }
    Ok(encode_with_prefix(ED25519_PUB_PREFIX, raw))
}

/// Encode a 1312-byte ML-DSA-44 public key as a Multikey string (hybrid PQ profile).
pub fn encode_mldsa44_public(raw: &[u8]) -> Result<String> {
    if raw.len() != MLDSA44_PUBLIC_LEN {
        return Err(CoreError::InvalidKeyLength {
            expected: MLDSA44_PUBLIC_LEN,
            got: raw.len(),
        });
    }
    Ok(encode_with_prefix(MLDSA44_PUB_PREFIX, raw))
}

/// Decode a Multikey string into algorithm name plus raw key bytes.
pub fn decode(multikey: &str) -> Result<DecodedKey> {
    let body = multikey.strip_prefix('z').ok_or_else(|| {
        CoreError::InvalidMultikey("must use base58btc encoding (z-prefix)".into())
    })?;
    let decoded = decode_base58_bounded(body)?;
    if decoded.len() < 2 {
        return Err(CoreError::InvalidMultikey("too short".into()));
    }
    let prefix = [decoded[0], decoded[1]];
    // Only public-key codecs decode as keys: a private-key codec in a DID or a
    // verification method is refused, never read as if it were a public key.
    let (algorithm, expected_len) = match prefix {
        ED25519_PUB_PREFIX => ("Ed25519", ED25519_PUBLIC_LEN),
        MLDSA44_PUB_PREFIX => ("ML-DSA-44", MLDSA44_PUBLIC_LEN),
        ED25519_PRIV_PREFIX | MLDSA44_PRIV_PREFIX => {
            return Err(CoreError::InvalidMultikey(
                "a private-key codec is not a public key".into(),
            ))
        }
        _ => {
            return Err(CoreError::UnknownMulticodec(format!(
                "{:02x}{:02x}",
                prefix[0], prefix[1]
            )))
        }
    };
    let raw_key = &decoded[2..];
    if raw_key.len() != expected_len {
        return Err(CoreError::InvalidKeyLength {
            expected: expected_len,
            got: raw_key.len(),
        });
    }
    if algorithm == "Ed25519" {
        // Refuse non-canonical and small-order (weak) keys at decode time.
        crate::keys::strict_verifying_key(raw_key)?;
    }
    Ok(DecodedKey {
        algorithm: algorithm.to_string(),
        raw_key: raw_key.to_vec(),
    })
}

/// Return the algorithm name encoded in a Multikey without exposing raw bytes.
pub fn algorithm_of(multikey: &str) -> Result<String> {
    Ok(decode(multikey)?.algorithm)
}

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

    #[test]
    fn ed25519_roundtrip() {
        let raw = crate::keys::Ed25519KeyPair::from_seed(&[7u8; 32]).public_key();
        let mk = encode_ed25519_public(&raw).unwrap();
        assert!(mk.starts_with("z6Mk"));
        let decoded = decode(&mk).unwrap();
        assert_eq!(decoded.algorithm, "Ed25519");
        assert_eq!(decoded.raw_key, raw);
    }

    #[test]
    fn varint_prefixes_match_the_multicodec_codes() {
        // Decode each prefix back as an unsigned varint and compare with the
        // table code, so the constants cannot drift from the codes.
        for (prefix, code) in [
            (ED25519_PUB_PREFIX, ED25519_PUB_CODEC),
            (ED25519_PRIV_PREFIX, ED25519_PRIV_CODEC),
            (MLDSA44_PUB_PREFIX, MLDSA44_PUB_CODEC),
            (MLDSA44_PRIV_PREFIX, MLDSA44_PRIV_CODEC),
        ] {
            assert!(prefix[0] & 0x80 != 0 && prefix[1] & 0x80 == 0);
            let back = u16::from(prefix[0] & 0x7f) | (u16::from(prefix[1]) << 7);
            assert_eq!(back, code);
        }
    }

    fn with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
        encode_with_prefix(prefix, raw)
    }

    #[test]
    fn private_key_codecs_never_decode_as_keys() {
        let ed = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
        assert!(decode(&with_prefix(ED25519_PRIV_PREFIX, &ed.seed())).is_err());
        assert!(decode(&with_prefix(MLDSA44_PRIV_PREFIX, &[0u8; 2560])).is_err());
        // The codes that were used before the multicodec table assigned
        // mldsa-44-pub (0x1207 public, 0x1208 private) are no longer read.
        assert!(decode(&with_prefix(varint2(0x1207), &[0u8; MLDSA44_PUBLIC_LEN])).is_err());
        assert!(decode(&with_prefix(varint2(0x1208), &[0u8; 2560])).is_err());
    }

    #[test]
    fn exact_key_lengths() {
        let ed = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]).public_key();
        let mut long = ed.to_vec();
        long.push(0);
        assert!(decode(&with_prefix(ED25519_PUB_PREFIX, &long)).is_err());
        assert!(decode(&with_prefix(ED25519_PUB_PREFIX, &ed[..31])).is_err());
        assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; 1311])).is_err());
        assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; 1313])).is_err());
        assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; MLDSA44_PUBLIC_LEN])).is_ok());
    }

    #[test]
    fn weak_ed25519_keys_refused_at_decode() {
        for hex in crate::keys::tests::SMALL_ORDER_ENCODINGS
            .iter()
            .chain(crate::keys::tests::NON_CANONICAL_ENCODINGS.iter())
        {
            let raw = crate::keys::tests::unhex32(hex);
            let mk = with_prefix(ED25519_PUB_PREFIX, &raw);
            assert!(decode(&mk).is_err(), "{hex} must be refused");
            assert!(crate::keys::did_key_to_ed25519(&format!("did:key:{mk}")).is_err());
        }
    }

    #[test]
    fn rejects_wrong_length() {
        assert!(encode_ed25519_public(&[0u8; 31]).is_err());
    }

    #[test]
    fn rejects_non_z_prefix() {
        assert!(decode("Qabc").is_err());
    }

    #[test]
    fn rejects_overlong_base58() {
        // Guards the O(n^2) base58 decode DoS.
        let overlong = "1".repeat(MAX_BASE58_LEN + 1);
        assert!(decode_base58_bounded(&overlong).is_err());
        assert!(decode(&format!("z{overlong}")).is_err());
    }
}