Skip to main content

matter_kit/msg/
ids.rs

1//! The identifiers that appear in a message header (Core §2.5).
2//!
3//! Each is a newtype over the integer the wire carries, because a `u64` that is sometimes
4//! a Node ID, sometimes a Fabric ID and sometimes a compressed Fabric ID is a `u64` that
5//! will eventually be the wrong one.
6
7/// A 64-bit Node ID (Core §2.5.5).
8///
9/// The value space is carved into ranges with different meanings, which [`NodeId::kind`]
10/// reports. Not every 64-bit value is a legal operational Node ID.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
12pub struct NodeId(pub u64);
13
14/// What range of the Node ID space a value falls in (Core §2.5.5).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum NodeIdKind {
17    /// `0x0000_0000_0000_0000` — "a reserved value that never appears in messages or
18    /// protocol usage. It exists to mark or detect the presence of uninitialized,
19    /// missing, or invalid Node IDs" (§2.5.5.6).
20    Unspecified,
21    /// `0x0000_0000_0000_0001` … `0xFFFF_FFEF_FFFF_FFFF` — a node on a fabric (§2.5.5.1).
22    Operational,
23    /// `0xFFFF_FFFB_xxxx_xxxx` — identifies the PAKE passcode a PASE session used
24    /// (§2.5.5.4).
25    PakeKeyIdentifier,
26    /// `0xFFFF_FFFD_xxxx_xxxx` — a CASE Authenticated Tag, an access-control subject
27    /// shared by a group of peers (§2.5.5.5).
28    CaseAuthenticatedTag,
29    /// `0xFFFF_FFFE_xxxx_xxxx` — a temporary local Node ID (§2.5.5.3).
30    TemporaryLocal,
31    /// `0xFFFF_FFFF_FFFF_xxxx` — a group, addressed by the low 16 bits (§2.5.5.2).
32    Group,
33    /// Inside the reserved span but matching no defined range.
34    Reserved,
35}
36
37impl NodeId {
38    /// The Unspecified Node ID (§2.5.5.6).
39    pub const UNSPECIFIED: Self = Self(0);
40
41    /// The first operational Node ID.
42    pub const OPERATIONAL_MIN: u64 = 0x0000_0000_0000_0001;
43    /// The last operational Node ID.
44    pub const OPERATIONAL_MAX: u64 = 0xFFFF_FFEF_FFFF_FFFF;
45
46    /// Which range this value falls in.
47    #[must_use]
48    pub const fn kind(self) -> NodeIdKind {
49        match self.0 {
50            0 => NodeIdKind::Unspecified,
51            Self::OPERATIONAL_MIN..=Self::OPERATIONAL_MAX => NodeIdKind::Operational,
52            0xFFFF_FFFB_0000_0000..=0xFFFF_FFFB_FFFF_FFFF => NodeIdKind::PakeKeyIdentifier,
53            0xFFFF_FFFD_0000_0000..=0xFFFF_FFFD_FFFF_FFFF => NodeIdKind::CaseAuthenticatedTag,
54            0xFFFF_FFFE_0000_0000..=0xFFFF_FFFE_FFFF_FFFF => NodeIdKind::TemporaryLocal,
55            0xFFFF_FFFF_FFFF_0000..=0xFFFF_FFFF_FFFF_FFFF => NodeIdKind::Group,
56            _ => NodeIdKind::Reserved,
57        }
58    }
59
60    /// Whether this is a usable operational Node ID.
61    #[must_use]
62    pub const fn is_operational(self) -> bool {
63        matches!(self.kind(), NodeIdKind::Operational)
64    }
65
66    /// An Ephemeral Initiator Node ID for an Unsecured Session Context (§4.13.2.1).
67    ///
68    /// > Initiators SHALL select a new random ephemeral node ID for each unsecured session, and
69    /// > SHALL select an ID that does not conflict with any ephemeral node IDs for any other
70    /// > ongoing unsecured sessions opened by the initiator.
71    ///
72    /// The value is drawn from the caller's [`Rng`](crate::platform::Rng) and folded into the
73    /// Operational Node ID range, which is where §4.13.2.1 says it has to come from. Folding
74    /// rather than rejecting is deliberate: a constructor that could fail would make the caller
75    /// choose what to do about randomness that fell outside a range, and the only correct answer
76    /// is to draw again — which this does arithmetically and without a loop.
77    #[must_use]
78    pub const fn ephemeral(randomness: u64) -> Self {
79        // `OPERATIONAL_MAX` is `0xFFFF_FFEF_FFFF_FFFF`, so the top byte is the only part that
80        // can land outside the range; clearing its high nibble keeps the value inside it, and
81        // `| 1` keeps it away from `Unspecified`.
82        Self((randomness & 0x0FFF_FFFF_FFFF_FFFF) | 1)
83    }
84
85    /// The group this Node ID names, if it is a Group Node ID.
86    #[must_use]
87    #[expect(
88        clippy::cast_possible_truncation,
89        reason = "a Group Node ID is 0xFFFF_FFFF_FFFF_xxxx, so the group id is exactly the low 16 bits"
90    )]
91    pub const fn group(self) -> Option<GroupId> {
92        match self.kind() {
93            NodeIdKind::Group => Some(GroupId(self.0 as u16)),
94            _ => None,
95        }
96    }
97
98    /// The Group Node ID for a group (§2.5.5.2).
99    #[must_use]
100    pub const fn from_group(group: GroupId) -> Self {
101        Self(0xFFFF_FFFF_FFFF_0000 | group.0 as u64)
102    }
103}
104
105/// A CASE Authenticated Tag: an access-control subject shared by a group of nodes
106/// (Core §6.6.2.1.2).
107///
108/// A CAT is carried in a node's operational certificate, so "the administrative root of
109/// trust does chain back through the individual source Node to the Fabric's trusted root".
110/// That is what makes it unlike a group key: group-*like* addressing, with per-node
111/// attribution intact.
112///
113/// The 32 bits are two halves. The upper 16 name the tag; the lower 16 are a version an
114/// administrator bumps whenever the set of nodes holding the tag changes, so that an
115/// access-control entry written against version 3 does not silently admit a node that was
116/// granted version 2 and has since been removed.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
118pub struct CaseAuthenticatedTag(pub u32);
119
120impl CaseAuthenticatedTag {
121    /// `0xFFFF` — the Administrator identifier, reserved to the Joint Fabric (§12.2.4.1).
122    pub const ADMINISTRATOR_IDENTIFIER: u16 = 0xFFFF;
123    /// `0xFFFE` — the Anchor identifier, reserved to the Joint Fabric (§12.2.4.2).
124    pub const ANCHOR_IDENTIFIER: u16 = 0xFFFE;
125    /// The last identifier "generally available"; `0xF000..=0xFFFD` is reserved.
126    pub const GENERAL_IDENTIFIER_MAX: u16 = 0xEFFF;
127
128    /// Builds a tag from its two halves.
129    #[must_use]
130    pub const fn new(identifier: u16, version: u16) -> Self {
131        Self(((identifier as u32) << 16) | version as u32)
132    }
133
134    /// The upper 16 bits, which "uniquely identifies a CAT".
135    #[must_use]
136    pub const fn identifier(self) -> u16 {
137        (self.0 >> 16) as u16
138    }
139
140    /// The lower 16 bits.
141    #[must_use]
142    #[expect(
143        clippy::cast_possible_truncation,
144        reason = "a CAT's version is defined as the low 16 bits of the identifier (§6.5.6.3)"
145    )]
146    pub const fn version(self) -> u16 {
147        self.0 as u16
148    }
149
150    /// Whether the version is usable: "Version number is a monotonically increasing
151    /// natural number in the range of 1 to 65535. A version number of 0 is invalid."
152    #[must_use]
153    pub const fn is_valid(self) -> bool {
154        self.version() != 0
155    }
156
157    /// The Node ID sub-encoding a CAT takes in an access-control entry's `Subjects` list:
158    /// the tag with `0xFFFF_FFFD` above it (§6.6.2.1.2).
159    ///
160    /// "Note that this encoding cannot appear as an operational Node ID."
161    #[must_use]
162    pub const fn to_node_id(self) -> NodeId {
163        NodeId(0xFFFF_FFFD_0000_0000 | self.0 as u64)
164    }
165
166    /// Recovers a CAT from that sub-encoding, or `None` if the Node ID is not one.
167    #[must_use]
168    #[expect(
169        clippy::cast_possible_truncation,
170        reason = "a CASE Authenticated Tag Node ID carries the tag in its low 32 bits"
171    )]
172    pub const fn from_node_id(node_id: NodeId) -> Option<Self> {
173        match node_id.kind() {
174            NodeIdKind::CaseAuthenticatedTag => Some(Self(node_id.0 as u32)),
175            _ => None,
176        }
177    }
178}
179
180/// A 16-bit Group ID (Core §2.5.4).
181#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
182pub struct GroupId(pub u16);
183
184impl GroupId {
185    /// Group ID 0 is reserved as the "null" group and never addresses anything.
186    pub const UNSPECIFIED: Self = Self(0);
187
188    /// Whether this group can be addressed — everything but zero.
189    #[must_use]
190    pub const fn is_valid(self) -> bool {
191        self.0 != 0
192    }
193}
194
195/// A 64-bit Fabric ID (Core §2.5.1).
196#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
197pub struct FabricId(pub u64);
198
199/// A local index into a node's own fabric table (Core §7.5).
200///
201/// One octet, `1..=254`; zero means "no fabric", and the value is local to one node — the
202/// same fabric has different indices on different nodes.
203#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
204pub struct FabricIndex(pub u8);
205
206impl FabricIndex {
207    /// The absent index.
208    pub const NONE: Self = Self(0);
209
210    /// Whether this names a fabric.
211    #[must_use]
212    pub const fn is_some(self) -> bool {
213        self.0 != 0
214    }
215}
216
217/// A 16-bit session identifier (Core §4.4.1.2).
218///
219/// Identifies "the particular key used to encrypt a message out of the set of available
220/// keys". Zero with a unicast session type means the unsecured session.
221#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
222pub struct SessionId(pub u16);
223
224impl SessionId {
225    /// The unsecured session: session type unicast and session id zero (§4.4.1.3).
226    pub const UNSECURED: Self = Self(0);
227}
228
229/// A 16-bit exchange identifier (Core §4.4.3.3).
230#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
231pub struct ExchangeId(pub u16);
232
233/// A 16-bit Vendor ID (Core §2.5.2).
234#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
235pub struct VendorId(pub u16);
236
237impl VendorId {
238    /// The Common Vendor ID, under which Matter's own protocols are defined.
239    pub const COMMON: Self = Self(0x0000);
240    /// `0xFFF1` — the first of the Vendor IDs "allocated for testing purposes".
241    pub const TEST_1: Self = Self(0xFFF1);
242}
243
244/// A protocol identifier, which is a Vendor ID and a 16-bit protocol number
245/// (Core §4.4.3.5).
246#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
247pub struct ProtocolId {
248    /// Whose protocol this is; [`VendorId::COMMON`] for Matter's own.
249    pub vendor: VendorId,
250    /// The protocol number within that vendor's space.
251    pub id: u16,
252}
253
254impl ProtocolId {
255    /// Builds a protocol id under the Common Vendor ID.
256    #[must_use]
257    pub const fn common(id: u16) -> Self {
258        Self {
259            vendor: VendorId::COMMON,
260            id,
261        }
262    }
263
264    /// `0x0000` — Secure Channel: PASE, CASE, MRP standalone acknowledgements, status
265    /// reports and the check-in message (Core §4.11).
266    pub const SECURE_CHANNEL: Self = Self::common(0x0000);
267    /// `0x0001` — the Interaction Model (Core ch. 8).
268    pub const INTERACTION_MODEL: Self = Self::common(0x0001);
269    /// `0x0002` — the Bulk Data Exchange Protocol (Core §11.22).
270    pub const BDX: Self = Self::common(0x0002);
271    /// `0x0003` — User Directed Commissioning (Core §5.3).
272    pub const USER_DIRECTED_COMMISSIONING: Self = Self::common(0x0003);
273    /// `0x0004` — reserved for testing.
274    pub const FOR_TESTING: Self = Self::common(0x0004);
275
276    /// Whether this protocol belongs to the Common Vendor ID, and so needs no Protocol
277    /// Vendor ID field on the wire.
278    #[must_use]
279    pub const fn is_common(self) -> bool {
280        self.vendor.0 == VendorId::COMMON.0
281    }
282}
283
284impl Default for ProtocolId {
285    fn default() -> Self {
286        Self::SECURE_CHANNEL
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn node_id_ranges_follow_2_5_5() {
296        assert_eq!(NodeId(0).kind(), NodeIdKind::Unspecified);
297        assert_eq!(NodeId(1).kind(), NodeIdKind::Operational);
298        assert_eq!(
299            NodeId(0xFFFF_FFEF_FFFF_FFFF).kind(),
300            NodeIdKind::Operational
301        );
302        assert_eq!(
303            NodeId(0xFFFF_FFF0_0000_0000).kind(),
304            NodeIdKind::Reserved,
305            "one past the operational range"
306        );
307        assert_eq!(
308            NodeId(0xFFFF_FFFB_0000_0001).kind(),
309            NodeIdKind::PakeKeyIdentifier
310        );
311        assert_eq!(
312            NodeId(0xFFFF_FFFD_0000_0001).kind(),
313            NodeIdKind::CaseAuthenticatedTag
314        );
315        assert_eq!(
316            NodeId(0xFFFF_FFFE_0000_0001).kind(),
317            NodeIdKind::TemporaryLocal
318        );
319        assert_eq!(NodeId(0xFFFF_FFFF_FFFF_0001).kind(), NodeIdKind::Group);
320    }
321
322    #[test]
323    fn group_node_ids_round_trip() {
324        let g = GroupId(0x1234);
325        let n = NodeId::from_group(g);
326        assert_eq!(n.0, 0xFFFF_FFFF_FFFF_1234);
327        assert_eq!(n.group(), Some(g));
328        assert_eq!(NodeId(1).group(), None);
329    }
330
331    #[test]
332    fn the_unspecified_node_id_is_not_operational() {
333        assert!(!NodeId::UNSPECIFIED.is_operational());
334        assert!(NodeId(1).is_operational());
335    }
336
337    #[test]
338    fn group_zero_is_not_addressable() {
339        assert!(!GroupId::UNSPECIFIED.is_valid());
340        assert!(GroupId(1).is_valid());
341    }
342
343    #[test]
344    fn common_protocols_need_no_vendor_field() {
345        assert!(ProtocolId::SECURE_CHANNEL.is_common());
346        assert!(ProtocolId::INTERACTION_MODEL.is_common());
347        assert!(
348            !ProtocolId {
349                vendor: VendorId::TEST_1,
350                id: 1
351            }
352            .is_common()
353        );
354    }
355}