Skip to main content

did_bio_core/
multikey.rs

1//! Multikey encoding and decoding (Controlled Identifiers v1.0 Section 2.2.2).
2//!
3//! A Multikey `publicKeyMultibase` value is the multibase `z` (base58btc)
4//! encoding of a multicodec varint prefix followed by the raw public key
5//! bytes (spec Section 5.2).
6
7use crate::error::Error;
8
9/// Multicodec key codecs used by `did:bio` verification methods.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum KeyCodec {
13    /// `ed25519-pub`, multicodec `0xed`, a 32 byte key encoded as `z6Mk...`.
14    Ed25519Pub,
15    /// `x25519-pub`, multicodec `0xec`, a 32 byte key encoded as `z6LS...`.
16    X25519Pub,
17    /// `secp256k1-pub`, multicodec `0xe7`, a 33 byte compressed key encoded
18    /// as `zQ3s...`.
19    Secp256k1Pub,
20}
21
22impl KeyCodec {
23    /// The multicodec code point.
24    pub const fn multicodec(self) -> u64 {
25        match self {
26            KeyCodec::Ed25519Pub => 0xed,
27            KeyCodec::X25519Pub => 0xec,
28            KeyCodec::Secp256k1Pub => 0xe7,
29        }
30    }
31
32    /// Required raw key length in bytes.
33    pub const fn key_len(self) -> usize {
34        match self {
35            KeyCodec::Ed25519Pub => 32,
36            KeyCodec::X25519Pub => 32,
37            KeyCodec::Secp256k1Pub => 33,
38        }
39    }
40
41    /// The characteristic multibase prefix of encoded keys. It is
42    /// informative (spec Section 5.2 table).
43    pub const fn multibase_prefix(self) -> &'static str {
44        match self {
45            KeyCodec::Ed25519Pub => "z6Mk",
46            KeyCodec::X25519Pub => "z6LS",
47            KeyCodec::Secp256k1Pub => "zQ3s",
48        }
49    }
50
51    fn from_multicodec(code: u64) -> Option<KeyCodec> {
52        match code {
53            0xed => Some(KeyCodec::Ed25519Pub),
54            0xec => Some(KeyCodec::X25519Pub),
55            0xe7 => Some(KeyCodec::Secp256k1Pub),
56            _ => None,
57        }
58    }
59}
60
61/// Append `value` to `out` as an unsigned varint, the multiformats LEB128
62/// form.
63fn write_uvarint(out: &mut Vec<u8>, mut value: u64) {
64    loop {
65        let byte = (value & 0x7f) as u8;
66        value >>= 7;
67        if value == 0 {
68            out.push(byte);
69            return;
70        }
71        out.push(byte | 0x80);
72    }
73}
74
75/// Read an unsigned varint from the front of `bytes`, returning the value
76/// and the number of bytes consumed. The encoding must be minimal, as
77/// multiformats requires, so a key has exactly one Multikey form.
78fn read_uvarint(bytes: &[u8]) -> Result<(u64, usize), Error> {
79    let mut value: u64 = 0;
80    for (i, &byte) in bytes.iter().enumerate().take(9) {
81        value |= u64::from(byte & 0x7f) << (7 * i);
82        if byte & 0x80 == 0 {
83            if i > 0 && byte == 0 {
84                return Err(Error::InvalidMultikey(
85                    "multicodec varint is not minimally encoded",
86                ));
87            }
88            return Ok((value, i + 1));
89        }
90    }
91    Err(Error::InvalidMultikey("malformed multicodec varint"))
92}
93
94/// Encode raw public key bytes as a Multikey `publicKeyMultibase` string.
95///
96/// Fails with [`Error::InvalidKeyLength`] when `key` does not have the
97/// codec's required length.
98///
99/// ```
100/// use did_bio_core::multikey;
101/// use did_bio_core::multikey::KeyCodec;
102///
103/// let encoded = multikey::encode(KeyCodec::Ed25519Pub, &[0u8; 32]).unwrap();
104/// assert!(encoded.starts_with("z6Mk"));
105/// ```
106pub fn encode(codec: KeyCodec, key: &[u8]) -> Result<String, Error> {
107    if key.len() != codec.key_len() {
108        return Err(Error::InvalidKeyLength {
109            expected: codec.key_len(),
110            actual: key.len(),
111        });
112    }
113    let mut bytes = Vec::with_capacity(2 + key.len());
114    write_uvarint(&mut bytes, codec.multicodec());
115    bytes.extend_from_slice(key);
116    Ok(format!("z{}", bs58::encode(bytes).into_string()))
117}
118
119/// Decode a Multikey `publicKeyMultibase` string to its codec and raw key
120/// bytes.
121///
122/// Rejects non-`z` multibase headers, undecodable base58, unknown
123/// multicodec prefixes, and key material of the wrong length.
124pub fn decode(multikey: &str) -> Result<(KeyCodec, Vec<u8>), Error> {
125    let encoded = multikey.strip_prefix('z').ok_or(Error::InvalidMultikey(
126        "expected multibase `z` (base58btc) header",
127    ))?;
128    let bytes = bs58::decode(encoded)
129        .into_vec()
130        .map_err(|_| Error::InvalidMultikey("invalid base58btc payload"))?;
131    let (code, consumed) = read_uvarint(&bytes)?;
132    let codec = KeyCodec::from_multicodec(code)
133        .ok_or(Error::InvalidMultikey("unknown multicodec key prefix"))?;
134    let key = &bytes[consumed..];
135    if key.len() != codec.key_len() {
136        return Err(Error::InvalidKeyLength {
137            expected: codec.key_len(),
138            actual: key.len(),
139        });
140    }
141    Ok((codec, key.to_vec()))
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn varint_two_byte_prefixes() {
150        let mut out = Vec::new();
151        write_uvarint(&mut out, 0xed);
152        assert_eq!(out, [0xed, 0x01]);
153        assert_eq!(read_uvarint(&[0xed, 0x01]).unwrap(), (0xed, 2));
154        assert_eq!(read_uvarint(&[0x7f]).unwrap(), (0x7f, 1));
155        assert_eq!(read_uvarint(&[0x00]).unwrap(), (0, 1));
156        assert!(read_uvarint(&[0x80]).is_err());
157        // 0xed in three bytes, and 0 in two: valid LEB128, not minimal.
158        assert!(read_uvarint(&[0xed, 0x81, 0x00]).is_err());
159        assert!(read_uvarint(&[0x80, 0x00]).is_err());
160    }
161
162    #[test]
163    fn roundtrip_all_codecs() {
164        for codec in [
165            KeyCodec::Ed25519Pub,
166            KeyCodec::X25519Pub,
167            KeyCodec::Secp256k1Pub,
168        ] {
169            let key = vec![7u8; codec.key_len()];
170            let encoded = encode(codec, &key).unwrap();
171            assert!(encoded.starts_with(codec.multibase_prefix()), "{encoded}");
172            let (decoded_codec, decoded_key) = decode(&encoded).unwrap();
173            assert_eq!(decoded_codec, codec);
174            assert_eq!(decoded_key, key);
175        }
176    }
177
178    #[test]
179    fn rejects_wrong_lengths_and_headers() {
180        assert!(matches!(
181            encode(KeyCodec::Ed25519Pub, &[0u8; 31]),
182            Err(Error::InvalidKeyLength {
183                expected: 32,
184                actual: 31
185            })
186        ));
187        assert!(decode("m6Mk").is_err());
188        assert!(decode("z0OIl").is_err());
189        // an overlong prefix names the same codec, so one key would have
190        // two Multikey strings
191        let mut overlong = vec![0xed, 0x81, 0x00];
192        overlong.extend_from_slice(&[7u8; 32]);
193        let overlong = format!("z{}", bs58::encode(overlong).into_string());
194        assert!(matches!(
195            decode(&overlong),
196            Err(Error::InvalidMultikey(
197                "multicodec varint is not minimally encoded"
198            ))
199        ));
200        // ed25519 prefix but 31 key bytes
201        let mut bytes = vec![0xed, 0x01];
202        bytes.extend_from_slice(&[0u8; 31]);
203        let bad = format!("z{}", bs58::encode(bytes).into_string());
204        assert!(matches!(decode(&bad), Err(Error::InvalidKeyLength { .. })));
205    }
206}