Skip to main content

vouch_core/
multikey.rs

1//! Multikey encoding for verification methods.
2//!
3//! Byte-exact port of the TypeScript SDK `multikey.ts` and `vouch/multikey.py`.
4//! A public key is encoded as `publicKeyMultibase = base58btc(multicodec_prefix
5//! || raw_public_key_bytes)`, with a leading 'z' marking base58btc. Cross-
6//! implementation interop with the other SDKs is REQUIRED.
7//!
8//! Supported algorithms:
9//!   Ed25519     multicodec prefix 0xed01  (32-byte public key)
10//!   ML-DSA-44   multicodec prefix 0x8724  (1312-byte public key, provisional)
11
12use crate::error::{CoreError, Result};
13
14/// Multicodec 2-byte prefixes.
15pub const ED25519_PUB_PREFIX: [u8; 2] = [0xed, 0x01];
16pub const ED25519_PRIV_PREFIX: [u8; 2] = [0x80, 0x26];
17pub const MLDSA44_PUB_PREFIX: [u8; 2] = [0x87, 0x24];
18pub const MLDSA44_PRIV_PREFIX: [u8; 2] = [0x88, 0x24];
19
20const ED25519_PUBLIC_LEN: usize = 32;
21const MLDSA44_PUBLIC_LEN: usize = 1312;
22
23/// Maximum base58btc input length accepted by [`decode_base58_bounded`]. base58
24/// decoding is O(n^2), so an unbounded input is a denial-of-service vector. The
25/// largest legitimate value is a hybrid composite proofValue (about 3400 chars);
26/// 8192 is a safe ceiling well above every real key, signature, and proofValue.
27pub const MAX_BASE58_LEN: usize = 8192;
28
29/// Decode base58btc with a length cap to bound the O(n^2) decode cost. Use this
30/// for any externally-supplied base58 (proofValues, multikeys) instead of
31/// calling `bs58::decode` directly.
32pub fn decode_base58_bounded(s: &str) -> Result<Vec<u8>> {
33    if s.len() > MAX_BASE58_LEN {
34        return Err(CoreError::InvalidMultikey(format!(
35            "base58 input too long: {} > {MAX_BASE58_LEN}",
36            s.len()
37        )));
38    }
39    bs58::decode(s)
40        .into_vec()
41        .map_err(|e| CoreError::InvalidMultikey(format!("bad base58: {e}")))
42}
43
44/// A multikey decoded into its algorithm name and raw key bytes.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct DecodedKey {
47    pub algorithm: String,
48    pub raw_key: Vec<u8>,
49}
50
51fn encode_with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
52    let mut buf = Vec::with_capacity(2 + raw.len());
53    buf.extend_from_slice(&prefix);
54    buf.extend_from_slice(raw);
55    format!("z{}", bs58::encode(buf).into_string())
56}
57
58/// Encode a 32-byte Ed25519 public key as a Multikey string (z-prefixed base58btc).
59pub fn encode_ed25519_public(raw: &[u8]) -> Result<String> {
60    if raw.len() != ED25519_PUBLIC_LEN {
61        return Err(CoreError::InvalidKeyLength {
62            expected: ED25519_PUBLIC_LEN,
63            got: raw.len(),
64        });
65    }
66    Ok(encode_with_prefix(ED25519_PUB_PREFIX, raw))
67}
68
69/// Encode a 1312-byte ML-DSA-44 public key as a Multikey string (hybrid PQ profile).
70pub fn encode_mldsa44_public(raw: &[u8]) -> Result<String> {
71    if raw.len() != MLDSA44_PUBLIC_LEN {
72        return Err(CoreError::InvalidKeyLength {
73            expected: MLDSA44_PUBLIC_LEN,
74            got: raw.len(),
75        });
76    }
77    Ok(encode_with_prefix(MLDSA44_PUB_PREFIX, raw))
78}
79
80/// Decode a Multikey string into algorithm name plus raw key bytes.
81pub fn decode(multikey: &str) -> Result<DecodedKey> {
82    let body = multikey.strip_prefix('z').ok_or_else(|| {
83        CoreError::InvalidMultikey("must use base58btc encoding (z-prefix)".into())
84    })?;
85    let decoded = decode_base58_bounded(body)?;
86    if decoded.len() < 2 {
87        return Err(CoreError::InvalidMultikey("too short".into()));
88    }
89    let prefix = [decoded[0], decoded[1]];
90    let algorithm = match prefix {
91        ED25519_PUB_PREFIX | ED25519_PRIV_PREFIX => "Ed25519",
92        MLDSA44_PUB_PREFIX | MLDSA44_PRIV_PREFIX => "ML-DSA-44",
93        _ => {
94            return Err(CoreError::UnknownMulticodec(format!(
95                "{:02x}{:02x}",
96                prefix[0], prefix[1]
97            )))
98        }
99    };
100    Ok(DecodedKey {
101        algorithm: algorithm.to_string(),
102        raw_key: decoded[2..].to_vec(),
103    })
104}
105
106/// Return the algorithm name encoded in a Multikey without exposing raw bytes.
107pub fn algorithm_of(multikey: &str) -> Result<String> {
108    Ok(decode(multikey)?.algorithm)
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn ed25519_roundtrip() {
117        let raw = [7u8; 32];
118        let mk = encode_ed25519_public(&raw).unwrap();
119        assert!(mk.starts_with('z'));
120        let decoded = decode(&mk).unwrap();
121        assert_eq!(decoded.algorithm, "Ed25519");
122        assert_eq!(decoded.raw_key, raw);
123    }
124
125    #[test]
126    fn rejects_wrong_length() {
127        assert!(encode_ed25519_public(&[0u8; 31]).is_err());
128    }
129
130    #[test]
131    fn rejects_non_z_prefix() {
132        assert!(decode("Qabc").is_err());
133    }
134
135    #[test]
136    fn rejects_overlong_base58() {
137        // Guards the O(n^2) base58 decode DoS.
138        let overlong = "1".repeat(MAX_BASE58_LEN + 1);
139        assert!(decode_base58_bounded(&overlong).is_err());
140        assert!(decode(&format!("z{overlong}")).is_err());
141    }
142}