Skip to main content

hyprstream_crypto/
did_key.rs

1//! Shared `did:key` (Ed25519) ⇄ raw-key codec.
2//!
3//! This is the **single source of truth** for the `ed25519-pub` multicodec
4//! prefix, the base58btc multibase encoding, and DID-URL fragment/query
5//! stripping used to convert between a raw 32-byte Ed25519 public key and its
6//! `did:key:z6Mk…` / Multikey `publicKeyMultibase` forms.
7//!
8//! It is compiled on **all targets** (unlike `did:web` resolution, which is
9//! native-only, and `iroh_peer`, which is wasm32-only) precisely so the native
10//! `did:web` admission resolver and the wasm32 `iroh_peer` browser identity
11//! helpers share one implementation and can never drift (#281/#475).
12//! `hyprstream_rpc::did_web` re-exports `decode_ed25519_multikey`,
13//! `did_key_to_ed25519`, and `ed25519_to_did_key` for source compatibility with
14//! existing callers.
15//!
16//! This module is the **single canonical home** for the multicodec constants
17//! ([`MULTICODEC_ED25519_PUB`], [`MULTICODEC_ML_DSA_65_PUB`]) and the generic
18//! [`decode_multikey`] helper (#916); previously these were duplicated in
19//! `hyprstream::auth::mesh_trust` and `hyprstream-rpc`'s `service_entry`.
20
21use anyhow::{anyhow, bail, Result};
22
23/// Multicodec `ed25519-pub` unsigned-varint prefix (`0xed01` → bytes `0xed 0x01`).
24///
25/// This is the one canonical definition every `did:key` / Multikey codepath
26/// shares across the workspace.
27pub const MULTICODEC_ED25519_PUB: [u8; 2] = [0xed, 0x01];
28
29/// Multicodec `ml-dsa-65-pub` unsigned-varint prefix (`0x1211` → bytes `0x91 0x24`).
30pub const MULTICODEC_ML_DSA_65_PUB: [u8; 2] = [0x91, 0x24];
31
32/// Decode a `Multikey` `publicKeyMultibase` string into raw key bytes, verifying
33/// the base58btc multibase prefix (`z`) and the expected multicodec header.
34///
35/// Returns the payload with the multicodec prefix stripped (variable length; the
36/// caller validates the key length for its algorithm). For the fixed 32-byte
37/// Ed25519 case, prefer [`decode_ed25519_multikey`].
38///
39/// Returns `Err` for a wrong multibase, an undecodable base58, or a multicodec
40/// prefix that does not match `expected_codec`.
41pub fn decode_multikey(multibase: &str, expected_codec: &[u8; 2]) -> Result<Vec<u8>> {
42    let body = multibase
43        .strip_prefix('z')
44        .ok_or_else(|| anyhow!("Multikey must use base58btc multibase ('z') prefix"))?;
45    let decoded = bs58::decode(body)
46        .into_vec()
47        .map_err(|e| anyhow!("invalid base58btc Multikey: {e}"))?;
48    if decoded.len() < 2 || &decoded[..2] != expected_codec {
49        bail!(
50            "unexpected multicodec prefix (expected {expected_codec:02x?}, got {:02x?})",
51            decoded.get(..2).unwrap_or(&decoded)
52        );
53    }
54    Ok(decoded[2..].to_vec())
55}
56
57/// Decode a `Multikey` `publicKeyMultibase` string into raw Ed25519 key bytes.
58///
59/// Verifies the base58btc multibase prefix (`z`) and the `ed25519-pub` multicodec
60/// header, returning the 32-byte payload.
61///
62/// Returns `Err` for a wrong multibase, an undecodable base58, a non-Ed25519
63/// codec, or a payload that is not exactly 32 bytes.
64pub fn decode_ed25519_multikey(multibase: &str) -> Result<[u8; 32]> {
65    let payload = decode_multikey(multibase, &MULTICODEC_ED25519_PUB)?;
66    let len = payload.len();
67    payload
68        .try_into()
69        .map_err(|_| anyhow!("ed25519 Multikey payload is {len} bytes (expected 32)"))
70}
71
72/// Decode a `did:key` (Ed25519) identifier into its raw 32-byte Ed25519 key.
73///
74/// For Ed25519 a `did:key` is *exactly* `"did:key:" + multibase-base58btc(0xed01
75/// ‖ pubkey)` — i.e. the method-specific identifier is the same `Multikey`
76/// `publicKeyMultibase` value [`decode_ed25519_multikey`] decodes. A `did:key`
77/// is therefore **self-contained**: the key *is* the identity, so this is a pure
78/// decode with **no network fetch**.
79///
80/// Returns `Err` for a non-`did:key` identifier, a non-Ed25519 multicodec, a bad
81/// multibase, or a wrong-length payload. A DID URL fragment / query is stripped
82/// (`did:key:z6Mk…#z6Mk…` self-references the same key; we decode the base
83/// method-specific identifier).
84pub fn did_key_to_ed25519(did: &str) -> Result<[u8; 32]> {
85    // Strip any DID URL fragment / query before decoding (a `#fragment` or
86    // `?query` would otherwise corrupt the base58btc body).
87    let did = did.split(['#', '?']).next().unwrap_or(did);
88    let msi = did
89        .strip_prefix("did:key:")
90        .ok_or_else(|| anyhow!("not a did:key identifier: {did}"))?;
91    if msi.is_empty() {
92        bail!("did:key has empty method-specific identifier: {did}");
93    }
94    // The method-specific id IS a Multikey `publicKeyMultibase`; reuse the one
95    // source of truth for the ed25519-pub multicodec (no duplicated 0xed01).
96    decode_ed25519_multikey(msi)
97        .map_err(|e| anyhow!("did:key {did} is not a valid Ed25519 Multikey: {e}"))
98}
99
100/// Encode a raw 32-byte Ed25519 public key as a `did:key` (Ed25519) identifier
101/// (`did:key:z6Mk…`).
102///
103/// The produced string is `"did:key:" + ed25519_to_multibase(key)` and
104/// round-trips with [`did_key_to_ed25519`]; the Multikey body is byte-identical
105/// to the `publicKeyMultibase` our DID documents publish (one multicodec source
106/// of truth over the same `0xed01 ‖ key` payload).
107pub fn ed25519_to_did_key(key: &[u8; 32]) -> String {
108    let mut payload = Vec::with_capacity(2 + 32);
109    payload.extend_from_slice(&MULTICODEC_ED25519_PUB);
110    payload.extend_from_slice(key);
111    format!("did:key:z{}", bs58::encode(payload).into_string())
112}
113
114#[cfg(test)]
115#[allow(clippy::unwrap_used, clippy::expect_used)]
116mod tests {
117    use super::*;
118
119    fn rand_ed25519() -> [u8; 32] {
120        use ed25519_dalek::SigningKey;
121        use rand::rngs::OsRng;
122        SigningKey::generate(&mut OsRng).verifying_key().to_bytes()
123    }
124
125    #[test]
126    fn did_key_roundtrips_random_key() {
127        for _ in 0..16 {
128            let raw = rand_ed25519();
129            assert_eq!(did_key_to_ed25519(&ed25519_to_did_key(&raw)).unwrap(), raw);
130        }
131    }
132
133    #[test]
134    fn did_key_strips_fragment_and_query() {
135        let raw = [3u8; 32];
136        let base = ed25519_to_did_key(&raw);
137        let mb = base.strip_prefix("did:key:").unwrap();
138        // Self-referencing fragment (`#z6Mk…`) — the common DID-URL VM id form.
139        assert_eq!(did_key_to_ed25519(&format!("{base}#{mb}")).unwrap(), raw);
140        // Query parameter.
141        assert_eq!(
142            did_key_to_ed25519(&format!("{base}?versionId=1")).unwrap(),
143            raw
144        );
145    }
146
147    #[test]
148    fn did_key_rejects_malformed() {
149        assert!(did_key_to_ed25519("did:web:example.com").is_err());
150        assert!(did_key_to_ed25519("did:key:").is_err());
151        // ed25519-pub multicodec but a 31-byte payload (wrong length).
152        let mut payload = vec![0xedu8, 0x01];
153        payload.extend_from_slice(&[0u8; 31]);
154        let did = format!("did:key:z{}", bs58::encode(payload).into_string());
155        assert!(did_key_to_ed25519(&did).is_err());
156    }
157}