Skip to main content

codec_multikey/
parse.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use codec_multibase::multibase_to_bytes;
6use codec_multicodec::{
7    lookup_codec_prefix, validate_public_key_payload, KeyLength, KeyMaterialKind,
8};
9
10use crate::error::MultikeyError;
11use crate::map_public_key_error::map_public_key_error;
12use zeroize::Zeroizing;
13
14/// A multikey decoded into its codec metadata and raw public key bytes.
15///
16/// Its metadata cannot be replaced after parsing: binding validation relies
17/// on the codec and algorithm being the ones established by the parser.
18///
19/// ```compile_fail
20/// use codec_multikey::parse_multikey;
21///
22/// if let Ok(mut parsed) = parse_multikey("invalid") {
23///     parsed.alg = "Ed25519";
24/// }
25/// ```
26pub struct ParsedMultikey {
27    /// Canonical multicodec name of the key type (e.g. `ed25519-pub`).
28    codec_name: &'static str,
29    /// Human-readable algorithm name implied by the codec (e.g. `Ed25519`).
30    alg: &'static str,
31    /// Raw public key bytes with the multicodec prefix stripped.
32    public_key: Vec<u8>,
33    /// Expected public key length for the codec.
34    key_length: KeyLength,
35}
36
37impl ParsedMultikey {
38    /// Returns the canonical multicodec name established by parsing.
39    #[must_use]
40    pub const fn codec_name(&self) -> &'static str {
41        self.codec_name
42    }
43
44    /// Returns the algorithm name associated with the parsed codec.
45    #[must_use]
46    pub const fn algorithm_name(&self) -> &'static str {
47        self.alg
48    }
49
50    /// Borrows the validated public key bytes.
51    #[must_use]
52    pub fn public_key(&self) -> &[u8] {
53        &self.public_key
54    }
55
56    /// Returns the length policy associated with the parsed codec.
57    #[must_use]
58    pub const fn key_length(&self) -> KeyLength {
59        self.key_length
60    }
61
62    /// Transfers ownership of the validated public key bytes.
63    #[must_use]
64    pub fn into_public_key(self) -> Vec<u8> {
65        self.public_key
66    }
67}
68
69/// Parses a multibase-encoded multikey string into its codec and key bytes.
70///
71/// Fails closed on non-canonical multibase, unknown prefixes, incorrect lengths,
72/// invalid compressed EC tags, or RSA payloads beyond the shared size ceiling.
73pub fn parse_multikey(multibase_key: &str) -> Result<ParsedMultikey, MultikeyError> {
74    if multibase_key.len() < 2 {
75        return Err(MultikeyError::InvalidMultibase);
76    }
77    // Multikey has a single canonical string form: base58btc (`z`).
78    // Rejecting alternate multibase alphabets prevents duplicate encodings of
79    // the same key from bypassing string-based blocklists or deduplication.
80    if !multibase_key.starts_with('z') {
81        return Err(MultikeyError::InvalidMultibase);
82    }
83
84    // 1) multibase decode
85    let raw = Zeroizing::new(
86        multibase_to_bytes(multibase_key).map_err(|_| MultikeyError::InvalidMultibase)?,
87    );
88
89    if raw.len() < 2 {
90        return Err(MultikeyError::DecodedTooShort(raw.len()));
91    }
92
93    // 2) multicodec prefix lookup
94    let found = lookup_codec_prefix(&raw).ok_or(MultikeyError::UnknownCodecPrefix)?;
95
96    if found.key_material != KeyMaterialKind::PublicKey {
97        return Err(MultikeyError::NonPublicKeyMaterial);
98    }
99
100    let public_key = raw
101        .get(found.codec.len()..)
102        .ok_or(MultikeyError::UnknownCodecPrefix)?;
103
104    validate_public_key_payload(found.name, public_key).map_err(|error| {
105        map_public_key_error(found.name, found.key_length, public_key.len(), error)
106    })?;
107
108    Ok(ParsedMultikey {
109        codec_name: found.name,
110        alg: found.alg,
111        public_key: public_key.to_vec(),
112        key_length: found.key_length,
113    })
114}