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 (multicodec table codes; the prefix on the wire is the
9//! code as an unsigned varint):
10//!   Ed25519     ed25519-pub    0xed    (32-byte public key)
11//!   ML-DSA-44   mldsa-44-pub   0x1210  (1312-byte public key)
12//!
13//! Only public-key codes decode as keys. The private-key codes (ed25519-priv
14//! 0x1300, mldsa-44-priv 0x1317) are recognised only so they can be refused.
15
16use crate::error::{CoreError, Result};
17
18/// Multicodec table codes.
19pub const ED25519_PUB_CODEC: u16 = 0xed;
20pub const ED25519_PRIV_CODEC: u16 = 0x1300;
21pub const MLDSA44_PUB_CODEC: u16 = 0x1210;
22pub const MLDSA44_PRIV_CODEC: u16 = 0x1317;
23
24/// The unsigned-varint encoding of a multicodec code in 0x80..0x3fff (two
25/// bytes: the low 7 bits with the continuation bit set, then the rest).
26const fn varint2(code: u16) -> [u8; 2] {
27    [((code & 0x7f) as u8) | 0x80, (code >> 7) as u8]
28}
29
30/// Multicodec 2-byte varint prefixes.
31pub const ED25519_PUB_PREFIX: [u8; 2] = varint2(ED25519_PUB_CODEC);
32pub const ED25519_PRIV_PREFIX: [u8; 2] = varint2(ED25519_PRIV_CODEC);
33pub const MLDSA44_PUB_PREFIX: [u8; 2] = varint2(MLDSA44_PUB_CODEC);
34pub const MLDSA44_PRIV_PREFIX: [u8; 2] = varint2(MLDSA44_PRIV_CODEC);
35
36const ED25519_PUBLIC_LEN: usize = 32;
37const MLDSA44_PUBLIC_LEN: usize = 1312;
38
39/// Maximum base58btc input length accepted by [`decode_base58_bounded`]. base58
40/// decoding is O(n^2), so an unbounded input is a denial-of-service vector. The
41/// largest legitimate value is a hybrid composite proofValue (about 3400 chars);
42/// 8192 is a safe ceiling well above every real key, signature, and proofValue.
43pub const MAX_BASE58_LEN: usize = 8192;
44
45/// Decode base58btc with a length cap to bound the O(n^2) decode cost. Use this
46/// for any externally-supplied base58 (proofValues, multikeys) instead of
47/// calling `bs58::decode` directly.
48pub fn decode_base58_bounded(s: &str) -> Result<Vec<u8>> {
49    if s.len() > MAX_BASE58_LEN {
50        return Err(CoreError::InvalidMultikey(format!(
51            "base58 input too long: {} > {MAX_BASE58_LEN}",
52            s.len()
53        )));
54    }
55    bs58::decode(s)
56        .into_vec()
57        .map_err(|e| CoreError::InvalidMultikey(format!("bad base58: {e}")))
58}
59
60/// A multikey decoded into its algorithm name and raw key bytes.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct DecodedKey {
63    pub algorithm: String,
64    pub raw_key: Vec<u8>,
65}
66
67fn encode_with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
68    let mut buf = Vec::with_capacity(2 + raw.len());
69    buf.extend_from_slice(&prefix);
70    buf.extend_from_slice(raw);
71    format!("z{}", bs58::encode(buf).into_string())
72}
73
74/// Encode a 32-byte Ed25519 public key as a Multikey string (z-prefixed base58btc).
75pub fn encode_ed25519_public(raw: &[u8]) -> Result<String> {
76    if raw.len() != ED25519_PUBLIC_LEN {
77        return Err(CoreError::InvalidKeyLength {
78            expected: ED25519_PUBLIC_LEN,
79            got: raw.len(),
80        });
81    }
82    Ok(encode_with_prefix(ED25519_PUB_PREFIX, raw))
83}
84
85/// Encode a 1312-byte ML-DSA-44 public key as a Multikey string (hybrid PQ profile).
86pub fn encode_mldsa44_public(raw: &[u8]) -> Result<String> {
87    if raw.len() != MLDSA44_PUBLIC_LEN {
88        return Err(CoreError::InvalidKeyLength {
89            expected: MLDSA44_PUBLIC_LEN,
90            got: raw.len(),
91        });
92    }
93    Ok(encode_with_prefix(MLDSA44_PUB_PREFIX, raw))
94}
95
96/// Decode a Multikey string into algorithm name plus raw key bytes.
97pub fn decode(multikey: &str) -> Result<DecodedKey> {
98    let body = multikey.strip_prefix('z').ok_or_else(|| {
99        CoreError::InvalidMultikey("must use base58btc encoding (z-prefix)".into())
100    })?;
101    let decoded = decode_base58_bounded(body)?;
102    if decoded.len() < 2 {
103        return Err(CoreError::InvalidMultikey("too short".into()));
104    }
105    let prefix = [decoded[0], decoded[1]];
106    // Only public-key codecs decode as keys: a private-key codec in a DID or a
107    // verification method is refused, never read as if it were a public key.
108    let (algorithm, expected_len) = match prefix {
109        ED25519_PUB_PREFIX => ("Ed25519", ED25519_PUBLIC_LEN),
110        MLDSA44_PUB_PREFIX => ("ML-DSA-44", MLDSA44_PUBLIC_LEN),
111        ED25519_PRIV_PREFIX | MLDSA44_PRIV_PREFIX => {
112            return Err(CoreError::InvalidMultikey(
113                "a private-key codec is not a public key".into(),
114            ))
115        }
116        _ => {
117            return Err(CoreError::UnknownMulticodec(format!(
118                "{:02x}{:02x}",
119                prefix[0], prefix[1]
120            )))
121        }
122    };
123    let raw_key = &decoded[2..];
124    if raw_key.len() != expected_len {
125        return Err(CoreError::InvalidKeyLength {
126            expected: expected_len,
127            got: raw_key.len(),
128        });
129    }
130    if algorithm == "Ed25519" {
131        // Refuse non-canonical and small-order (weak) keys at decode time.
132        crate::keys::strict_verifying_key(raw_key)?;
133    }
134    Ok(DecodedKey {
135        algorithm: algorithm.to_string(),
136        raw_key: raw_key.to_vec(),
137    })
138}
139
140/// Return the algorithm name encoded in a Multikey without exposing raw bytes.
141pub fn algorithm_of(multikey: &str) -> Result<String> {
142    Ok(decode(multikey)?.algorithm)
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn ed25519_roundtrip() {
151        let raw = crate::keys::Ed25519KeyPair::from_seed(&[7u8; 32]).public_key();
152        let mk = encode_ed25519_public(&raw).unwrap();
153        assert!(mk.starts_with("z6Mk"));
154        let decoded = decode(&mk).unwrap();
155        assert_eq!(decoded.algorithm, "Ed25519");
156        assert_eq!(decoded.raw_key, raw);
157    }
158
159    #[test]
160    fn varint_prefixes_match_the_multicodec_codes() {
161        // Decode each prefix back as an unsigned varint and compare with the
162        // table code, so the constants cannot drift from the codes.
163        for (prefix, code) in [
164            (ED25519_PUB_PREFIX, ED25519_PUB_CODEC),
165            (ED25519_PRIV_PREFIX, ED25519_PRIV_CODEC),
166            (MLDSA44_PUB_PREFIX, MLDSA44_PUB_CODEC),
167            (MLDSA44_PRIV_PREFIX, MLDSA44_PRIV_CODEC),
168        ] {
169            assert!(prefix[0] & 0x80 != 0 && prefix[1] & 0x80 == 0);
170            let back = u16::from(prefix[0] & 0x7f) | (u16::from(prefix[1]) << 7);
171            assert_eq!(back, code);
172        }
173    }
174
175    fn with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
176        encode_with_prefix(prefix, raw)
177    }
178
179    #[test]
180    fn private_key_codecs_never_decode_as_keys() {
181        let ed = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
182        assert!(decode(&with_prefix(ED25519_PRIV_PREFIX, &ed.seed())).is_err());
183        assert!(decode(&with_prefix(MLDSA44_PRIV_PREFIX, &[0u8; 2560])).is_err());
184        // The codes that were used before the multicodec table assigned
185        // mldsa-44-pub (0x1207 public, 0x1208 private) are no longer read.
186        assert!(decode(&with_prefix(varint2(0x1207), &[0u8; MLDSA44_PUBLIC_LEN])).is_err());
187        assert!(decode(&with_prefix(varint2(0x1208), &[0u8; 2560])).is_err());
188    }
189
190    #[test]
191    fn exact_key_lengths() {
192        let ed = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]).public_key();
193        let mut long = ed.to_vec();
194        long.push(0);
195        assert!(decode(&with_prefix(ED25519_PUB_PREFIX, &long)).is_err());
196        assert!(decode(&with_prefix(ED25519_PUB_PREFIX, &ed[..31])).is_err());
197        assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; 1311])).is_err());
198        assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; 1313])).is_err());
199        assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; MLDSA44_PUBLIC_LEN])).is_ok());
200    }
201
202    #[test]
203    fn weak_ed25519_keys_refused_at_decode() {
204        for hex in crate::keys::tests::SMALL_ORDER_ENCODINGS
205            .iter()
206            .chain(crate::keys::tests::NON_CANONICAL_ENCODINGS.iter())
207        {
208            let raw = crate::keys::tests::unhex32(hex);
209            let mk = with_prefix(ED25519_PUB_PREFIX, &raw);
210            assert!(decode(&mk).is_err(), "{hex} must be refused");
211            assert!(crate::keys::did_key_to_ed25519(&format!("did:key:{mk}")).is_err());
212        }
213    }
214
215    #[test]
216    fn rejects_wrong_length() {
217        assert!(encode_ed25519_public(&[0u8; 31]).is_err());
218    }
219
220    #[test]
221    fn rejects_non_z_prefix() {
222        assert!(decode("Qabc").is_err());
223    }
224
225    #[test]
226    fn rejects_overlong_base58() {
227        // Guards the O(n^2) base58 decode DoS.
228        let overlong = "1".repeat(MAX_BASE58_LEN + 1);
229        assert!(decode_base58_bounded(&overlong).is_err());
230        assert!(decode(&format!("z{overlong}")).is_err());
231    }
232}