Skip to main content

codec_multicodec/
lookup.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use crate::table::{CodecTag, KeyLength, KeyMaterialKind, MULTICODEC_TABLE};
6use crate::validate_public_key_payload::validate_public_key_payload;
7
8/// Failure to strip a public-key multicodec prefix.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
10pub enum CodecPrefixError {
11    /// No supported prefix was found.
12    #[error("invalid multicodec prefix")]
13    InvalidPrefix,
14    /// The prefix identifies private, symmetric, or non-key material.
15    #[error("multicodec does not identify public key material")]
16    NonPublicKeyMaterial,
17    /// A recognized public-key prefix carries an invalid payload length.
18    #[error("invalid multicodec payload length")]
19    InvalidLength,
20    /// A compressed EC payload lacks a compressed SEC1 point tag.
21    #[error("invalid compressed public key point tag")]
22    InvalidCompressedPoint,
23    /// A variable-length public-key payload exceeds its semantic size ceiling.
24    #[error("public key payload exceeds size limit")]
25    KeyTooLarge {
26        /// Maximum accepted payload size.
27        max: usize,
28        /// Received payload size.
29        actual: usize,
30    },
31}
32
33/// Codec metadata resolved from a multicodec prefix.
34#[derive(Debug, Clone)]
35pub struct CodecLookupResult {
36    /// Canonical multicodec name (e.g. `ed25519-pub`).
37    pub name: &'static str,
38    /// Multicodec table tag.
39    pub tag: CodecTag,
40    /// Key-material class for `key` codecs.
41    pub key_material: KeyMaterialKind,
42    /// Human-readable algorithm name (e.g. `Ed25519`).
43    pub alg: &'static str,
44    /// The multicodec varint prefix bytes.
45    pub codec: &'static [u8],
46    /// Expected raw public key length after the prefix.
47    pub key_length: KeyLength,
48}
49
50/// Lookup multicodec prefix → codec metadata
51pub fn lookup_codec_prefix(bytes: &[u8]) -> Option<CodecLookupResult> {
52    for (name, spec) in MULTICODEC_TABLE {
53        let prefix = spec.codec;
54        if bytes.len() >= prefix.len() && bytes.starts_with(prefix) {
55            return Some(CodecLookupResult {
56                name,
57                tag: spec.tag,
58                key_material: spec.key_material,
59                alg: spec.alg,
60                codec: spec.codec,
61                key_length: spec.key_length,
62            });
63        }
64    }
65    None
66}
67
68/// Strip a recognized public-key multicodec prefix from a complete key.
69///
70/// # Errors
71///
72/// Rejects unknown prefixes, non-public key classes, invalid key lengths, and
73/// malformed compressed EC tags. RSA payloads are opaque and bounded to 4 KiB;
74/// callers must still validate DER and cryptographic key properties before use.
75pub fn strip_codec_prefix(bytes: &[u8]) -> Result<&[u8], CodecPrefixError> {
76    let found = lookup_codec_prefix(bytes).ok_or(CodecPrefixError::InvalidPrefix)?;
77    if found.key_material != KeyMaterialKind::PublicKey {
78        return Err(CodecPrefixError::NonPublicKeyMaterial);
79    }
80    let remainder = bytes
81        .get(found.codec.len()..)
82        .ok_or(CodecPrefixError::InvalidLength)?;
83    validate_public_key_payload(found.name, remainder)?;
84    Ok(remainder)
85}
86
87#[cfg(kani)]
88#[path = "lookup_proof_tests.rs"]
89mod proofs;