Skip to main content

ic_wire/
framing.rs

1use crate::Error;
2
3pub(crate) const HEADER_BYTES: usize = 11;
4
5/// Interpretation of the input byte span.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum Encoding {
8    /// A Postcard payload without a frame header.
9    Payload,
10    /// An 11-byte Wire header followed by a Postcard payload.
11    Frame {
12        /// Expected routing identity.
13        method: u64,
14        /// Expected request or response direction.
15        direction: Direction,
16    },
17}
18
19/// Direction carried by the last header byte.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum Direction {
22    /// Request, encoded as zero.
23    Request,
24    /// Response, encoded as one.
25    Response,
26}
27
28impl Encoding {
29    pub(crate) const fn header_len(self) -> usize {
30        match self {
31            Self::Payload => 0,
32            Self::Frame { .. } => HEADER_BYTES,
33        }
34    }
35
36    pub(crate) fn header(self) -> Option<[u8; HEADER_BYTES]> {
37        match self {
38            Self::Payload => None,
39            Self::Frame { method, direction } => Some(frame_header(method, direction)),
40        }
41    }
42}
43
44fn frame_header(method: u64, direction: Direction) -> [u8; HEADER_BYTES] {
45    let mut header = [0; HEADER_BYTES];
46    header[..2].copy_from_slice(b"IW");
47    header[2..10].copy_from_slice(&method.to_le_bytes());
48    header[10] = match direction {
49        Direction::Request => 0,
50        Direction::Response => 1,
51    };
52    header
53}
54
55pub(crate) fn validate_header(
56    method: u64,
57    direction: Direction,
58    header: &[u8; HEADER_BYTES],
59) -> Result<(), Error> {
60    if *header != frame_header(method, direction) {
61        return Err(Error::Identity);
62    }
63
64    Ok(())
65}
66
67/// Derive a routing ID from the exact exported method name.
68///
69/// Uses FNV-1a-64 over `ic-wire:method:` followed by the name's UTF-8 bytes,
70/// modulo 2^64. No case folding or Unicode normalization is performed.
71/// This is not authentication or a schema fingerprint. Callers must reject
72/// duplicate IDs; explicit IDs remain valid and need not use this derivation.
73#[must_use]
74pub const fn method_id(name: &str) -> u64 {
75    let parts: [&[u8]; 2] = [b"ic-wire:method:", name.as_bytes()];
76    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
77    let mut part = 0;
78    while part < parts.len() {
79        let mut index = 0;
80        while index < parts[part].len() {
81            hash = (hash ^ parts[part][index] as u64).wrapping_mul(0x0100_0000_01b3);
82            index += 1;
83        }
84        part += 1;
85    }
86
87    hash
88}
89
90/// Admit an exact 11-byte request header before copying its payload.
91///
92/// Requires ASCII `IW`, the expected method in little-endian order, and request
93/// direction zero. This allocates nothing and examines no payload bytes.
94/// Success does not authenticate the sender or admit payload resources/schema.
95///
96/// # Errors
97///
98/// Returns [`Error::Identity`] for any marker, method or direction mismatch.
99/// The fixed-size argument excludes truncated headers at this API boundary.
100pub fn validate_request_header(method: u64, header: &[u8; HEADER_BYTES]) -> Result<(), Error> {
101    validate_header(method, Direction::Request, header)
102}