Skip to main content

rings_core/message/payload/
frame.rs

1//! The frame header: the one part of the wire every version decodes alike (#1104).
2//!
3//! ```text
4//!   frame        = MAGIC ‖ wire_version ‖ rest(wire_version)
5//!   MAGIC        = "RINGS\0"                      fixed forever
6//!   wire_version = u16, big-endian                fixed forever, read before any codec
7//!   rest(5)      = kind ‖ body(kind)              kind: 0 payload, 1 link control, 2 compressed payload
8//! ```
9//!
10//! Law (frame header): every version reads `MAGIC ‖ wire_version` the same way, and decodes
11//! `rest` only when the version is its own. A frame of another version is refused before its
12//! body is decoded, with [`Error::IncompatibleWireVersion`] naming both versions. Frames from
13//! before wire versioning opened with `RINGS-PAYLOAD\0` or `RINGS-LINK\0`: they share the first
14//! five bytes of `MAGIC` and differ in the sixth (`-` against `\0`), so such a frame is told
15//! apart and named as from a peer before wire versioning, never read as a version.
16//!
17//! Both join paths carry the header, since both carry frames: the HTTP handshake exchanges
18//! base58-check frames, and the overlay handshake travels in link frames. Every link frame
19//! carries it as well, so two nodes of different wire versions never exchange a frame, and a
20//! connected overlay holds one wire version.
21//!
22//! Bump rule: [`WIRE_VERSION`] goes up by exactly one per release, relative to the last
23//! released wire version, when the release changes anything a node of that version would
24//! reject or misread: a frame, a message, a transport signal, a signature domain, a handshake
25//! rule. Changes between two releases share the one bump; a change no peer can observe never
26//! bumps it, and the crate version moves independently. Every bump is a total cutover, as
27//! every wire change before 1.0 is: no build decodes the `rest` of another version, and
28//! nothing is negotiated.
29//!
30//! Enforcement (#1107): golden vectors pin [`WIRE_VERSION`] together with the hash of the serde
31//! format of every type the frames reach, every variant of every enum included, one canonical
32//! frame per message and link-control variant, the recorded signaling path, the transcript of
33//! every signing domain tag, and the handshake offer string (`test_wire_goldens`). The
34//! formats `rings-node` adds on top (onion cells, sealed mail, descriptors, extension envelopes,
35//! and relay frames) are pinned by `rings-node`'s sibling `test_wire_goldens` test against this
36//! same version (#1141). Bump procedure, when either test fails: the change moved the wire.
37//! If the last release already shipped [`WIRE_VERSION`], add one to it; if the version is
38//! already this release's, keep it. Then set the pinned pair in the affected `test_wire_goldens`
39//! module (or both) to that version and the hash the failure reports, in the same commit. A
40//! change that moves no golden byte never fails it. If only `format/registry` moved, and only
41//! because the tracer or the lockfile changed (the registry is serde reflection's rendering of
42//! the formats, not wire bytes), re-pin the hash without bumping [`WIRE_VERSION`].
43
44use std::fmt;
45
46use bytes::Bytes;
47
48use crate::error::Error;
49use crate::error::Result;
50
51/// The wire version of this build; see the bump rule.
52pub const WIRE_VERSION: u16 = 5;
53
54/// The opening of every frame, fixed forever (the frame-header law).
55const FRAME_MAGIC: &[u8] = b"RINGS\0";
56/// The opening every frame from before wire versioning shares: its markers were
57/// `RINGS-PAYLOAD\0` and `RINGS-LINK\0`.
58const PRE_VERSIONING_OPENING: &[u8] = b"RINGS-";
59/// The length of a wire version on the wire.
60const WIRE_VERSION_LEN: usize = 2;
61
62/// The bytes a frame of this wire version spends before its body: the magic, the version, and
63/// the kind.
64pub(super) const FRAME_HEADER_LEN: usize = FRAME_MAGIC.len() + WIRE_VERSION_LEN + 1;
65
66/// What a frame of this wire version carries.
67#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68pub(super) enum FrameKind {
69    /// A message payload.
70    Payload,
71    /// A link-control frame.
72    LinkControl,
73    /// An LZ4-block-compressed message payload (`MessageCategory::DhtControl | MessageCategory::Storage`).
74    CompressedPayload,
75}
76
77impl FrameKind {
78    /// The byte that names this kind on the wire.
79    const fn byte(self) -> u8 {
80        match self {
81            Self::Payload => 0,
82            Self::LinkControl => 1,
83            Self::CompressedPayload => 2,
84        }
85    }
86
87    /// The kind `byte` names, if any.
88    const fn from_byte(byte: u8) -> Option<Self> {
89        match byte {
90            0 => Some(Self::Payload),
91            1 => Some(Self::LinkControl),
92            2 => Some(Self::CompressedPayload),
93            _ => None,
94        }
95    }
96}
97
98/// A peer's wire version, as its frame or its handshake endpoint states it.
99#[derive(Clone, Copy, Debug, Eq, PartialEq)]
100pub enum PeerWireVersion {
101    /// The versioned wire, at this version.
102    Versioned(u16),
103    /// A peer from before wire versioning, whose frames carry no version.
104    BeforeVersioning,
105}
106
107impl PeerWireVersion {
108    /// The peer's version number; `None` for a peer from before wire versioning.
109    pub const fn number(self) -> Option<u16> {
110        match self {
111            Self::Versioned(version) => Some(version),
112            Self::BeforeVersioning => None,
113        }
114    }
115
116    /// The peer's wire version as an endpoint reports it: a number, or none for a peer from
117    /// before wire versioning.
118    pub const fn reported(number: Option<u16>) -> Self {
119        match number {
120            Some(version) => Self::Versioned(version),
121            None => Self::BeforeVersioning,
122        }
123    }
124
125    /// Admit a peer of this version: `Ok` iff it is [`WIRE_VERSION`], and otherwise
126    /// [`Self::mismatch`].
127    pub fn admit(self) -> std::result::Result<(), WireVersionMismatch> {
128        if self == Self::Versioned(WIRE_VERSION) {
129            Ok(())
130        } else {
131            Err(self.mismatch())
132        }
133    }
134
135    /// This build's wire version against this one.
136    pub const fn mismatch(self) -> WireVersionMismatch {
137        WireVersionMismatch {
138            ours: WIRE_VERSION,
139            theirs: self,
140        }
141    }
142}
143
144impl fmt::Display for PeerWireVersion {
145    /// The version number, or the words for a peer from before wire versioning.
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            Self::Versioned(version) => write!(f, "{version}"),
149            Self::BeforeVersioning => f.write_str("from before wire versioning"),
150        }
151    }
152}
153
154/// Two wire versions that do not meet: this build's and a peer's (#1104).
155#[derive(Clone, Copy, Debug, Eq, PartialEq)]
156pub struct WireVersionMismatch {
157    /// This build's wire version.
158    pub ours: u16,
159    /// The peer's, as its frame or its handshake endpoint states it.
160    pub theirs: PeerWireVersion,
161}
162
163impl fmt::Display for WireVersionMismatch {
164    /// Both versions, ours first.
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        write!(f, "ours is {}, the peer's is {}", self.ours, self.theirs)
167    }
168}
169
170impl From<WireVersionMismatch> for Error {
171    /// The core's refusal of a peer of another wire version.
172    fn from(mismatch: WireVersionMismatch) -> Self {
173        Self::IncompatibleWireVersion(mismatch)
174    }
175}
176
177/// The frame `MAGIC ‖ WIRE_VERSION ‖ kind ‖ body`, with the length sum checked.
178pub(super) fn frame_bytes(kind: FrameKind, body: &[u8]) -> Result<Bytes> {
179    let capacity = FRAME_HEADER_LEN
180        .checked_add(body.len())
181        .ok_or(Error::MessageSizeOverflow)?;
182    let mut wire = Vec::with_capacity(capacity);
183    wire.extend_from_slice(FRAME_MAGIC);
184    wire.extend_from_slice(&WIRE_VERSION.to_be_bytes());
185    wire.push(kind.byte());
186    wire.extend_from_slice(body);
187    Ok(Bytes::from(wire))
188}
189
190/// Read the header of `bytes` (the frame-header law): the kind and body of a frame of this wire
191/// version, and otherwise the refusal.
192///
193/// ```text
194///   bytes ─┬─ MAGIC ‖ WIRE_VERSION ‖ kind ‖ body ─▶ (kind, body)
195///          ├─ MAGIC ‖ v ≠ WIRE_VERSION ‖ …     ─▶ IncompatibleWireVersion { theirs: Versioned(v) }
196///          ├─ "RINGS-" …                       ─▶ IncompatibleWireVersion { theirs: BeforeVersioning }
197///          └─ otherwise, or an unknown kind     ─▶ UnmarkedFrame
198/// ```
199pub(super) fn split_frame(bytes: &[u8]) -> Result<(FrameKind, &[u8])> {
200    let Some(versioned) = bytes.strip_prefix(FRAME_MAGIC) else {
201        return Err(if bytes.starts_with(PRE_VERSIONING_OPENING) {
202            PeerWireVersion::BeforeVersioning.mismatch().into()
203        } else {
204            Error::UnmarkedFrame
205        });
206    };
207    let Some((version, rest)) = versioned.split_first_chunk::<WIRE_VERSION_LEN>() else {
208        return Err(Error::UnmarkedFrame);
209    };
210    PeerWireVersion::Versioned(u16::from_be_bytes(*version)).admit()?;
211    let Some((kind, body)) = rest.split_first() else {
212        return Err(Error::UnmarkedFrame);
213    };
214    let kind = FrameKind::from_byte(*kind).ok_or(Error::UnmarkedFrame)?;
215    Ok((kind, body))
216}
217
218/// Whether `bytes` (or a leading chunk prefix of `bytes`) can open a
219/// [`FrameKind::CompressedPayload`] frame of this wire version.
220pub(crate) fn may_start_compressed_payload(bytes: &[u8]) -> bool {
221    if bytes.len() < FRAME_HEADER_LEN {
222        let prefix_len = bytes.len().min(FRAME_MAGIC.len());
223        return bytes.get(..prefix_len) == FRAME_MAGIC.get(..prefix_len);
224    }
225    matches!(split_frame(bytes), Ok((FrameKind::CompressedPayload, _)))
226}