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    /// The group this Node ID names, if it is a Group Node ID.
67    #[must_use]
68    pub const fn group(self) -> Option<GroupId> {
69        match self.kind() {
70            NodeIdKind::Group => Some(GroupId(self.0 as u16)),
71            _ => None,
72        }
73    }
74
75    /// The Group Node ID for a group (§2.5.5.2).
76    #[must_use]
77    pub const fn from_group(group: GroupId) -> Self {
78        Self(0xFFFF_FFFF_FFFF_0000 | group.0 as u64)
79    }
80}
81
82/// A CASE Authenticated Tag: an access-control subject shared by a group of nodes
83/// (Core §6.6.2.1.2).
84///
85/// A CAT is carried in a node's operational certificate, so "the administrative root of
86/// trust does chain back through the individual source Node to the Fabric's trusted root".
87/// That is what makes it unlike a group key: group-*like* addressing, with per-node
88/// attribution intact.
89///
90/// The 32 bits are two halves. The upper 16 name the tag; the lower 16 are a version an
91/// administrator bumps whenever the set of nodes holding the tag changes, so that an
92/// access-control entry written against version 3 does not silently admit a node that was
93/// granted version 2 and has since been removed.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
95pub struct CaseAuthenticatedTag(pub u32);
96
97impl CaseAuthenticatedTag {
98    /// `0xFFFF` — the Administrator identifier, reserved to the Joint Fabric (§12.2.4.1).
99    pub const ADMINISTRATOR_IDENTIFIER: u16 = 0xFFFF;
100    /// `0xFFFE` — the Anchor identifier, reserved to the Joint Fabric (§12.2.4.2).
101    pub const ANCHOR_IDENTIFIER: u16 = 0xFFFE;
102    /// The last identifier "generally available"; `0xF000..=0xFFFD` is reserved.
103    pub const GENERAL_IDENTIFIER_MAX: u16 = 0xEFFF;
104
105    /// Builds a tag from its two halves.
106    #[must_use]
107    pub const fn new(identifier: u16, version: u16) -> Self {
108        Self(((identifier as u32) << 16) | version as u32)
109    }
110
111    /// The upper 16 bits, which "uniquely identifies a CAT".
112    #[must_use]
113    pub const fn identifier(self) -> u16 {
114        (self.0 >> 16) as u16
115    }
116
117    /// The lower 16 bits.
118    #[must_use]
119    pub const fn version(self) -> u16 {
120        self.0 as u16
121    }
122
123    /// Whether the version is usable: "Version number is a monotonically increasing
124    /// natural number in the range of 1 to 65535. A version number of 0 is invalid."
125    #[must_use]
126    pub const fn is_valid(self) -> bool {
127        self.version() != 0
128    }
129
130    /// The Node ID sub-encoding a CAT takes in an access-control entry's `Subjects` list:
131    /// the tag with `0xFFFF_FFFD` above it (§6.6.2.1.2).
132    ///
133    /// "Note that this encoding cannot appear as an operational Node ID."
134    #[must_use]
135    pub const fn to_node_id(self) -> NodeId {
136        NodeId(0xFFFF_FFFD_0000_0000 | self.0 as u64)
137    }
138
139    /// Recovers a CAT from that sub-encoding, or `None` if the Node ID is not one.
140    #[must_use]
141    pub const fn from_node_id(node_id: NodeId) -> Option<Self> {
142        match node_id.kind() {
143            NodeIdKind::CaseAuthenticatedTag => Some(Self(node_id.0 as u32)),
144            _ => None,
145        }
146    }
147}
148
149/// A 16-bit Group ID (Core §2.5.4).
150#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
151pub struct GroupId(pub u16);
152
153impl GroupId {
154    /// Group ID 0 is reserved as the "null" group and never addresses anything.
155    pub const UNSPECIFIED: Self = Self(0);
156
157    /// Whether this group can be addressed — everything but zero.
158    #[must_use]
159    pub const fn is_valid(self) -> bool {
160        self.0 != 0
161    }
162}
163
164/// A 64-bit Fabric ID (Core §2.5.1).
165#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
166pub struct FabricId(pub u64);
167
168/// A local index into a node's own fabric table (Core §7.5).
169///
170/// One octet, `1..=254`; zero means "no fabric", and the value is local to one node — the
171/// same fabric has different indices on different nodes.
172#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
173pub struct FabricIndex(pub u8);
174
175impl FabricIndex {
176    /// The absent index.
177    pub const NONE: Self = Self(0);
178
179    /// Whether this names a fabric.
180    #[must_use]
181    pub const fn is_some(self) -> bool {
182        self.0 != 0
183    }
184}
185
186/// A 16-bit session identifier (Core §4.4.1.2).
187///
188/// Identifies "the particular key used to encrypt a message out of the set of available
189/// keys". Zero with a unicast session type means the unsecured session.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
191pub struct SessionId(pub u16);
192
193impl SessionId {
194    /// The unsecured session: session type unicast and session id zero (§4.4.1.3).
195    pub const UNSECURED: Self = Self(0);
196}
197
198/// A 16-bit exchange identifier (Core §4.4.3.3).
199#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
200pub struct ExchangeId(pub u16);
201
202/// A 16-bit Vendor ID (Core §2.5.2).
203#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
204pub struct VendorId(pub u16);
205
206impl VendorId {
207    /// The Common Vendor ID, under which Matter's own protocols are defined.
208    pub const COMMON: Self = Self(0x0000);
209    /// `0xFFF1` — the first of the Vendor IDs "allocated for testing purposes".
210    pub const TEST_1: Self = Self(0xFFF1);
211}
212
213/// A protocol identifier, which is a Vendor ID and a 16-bit protocol number
214/// (Core §4.4.3.5).
215#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
216pub struct ProtocolId {
217    /// Whose protocol this is; [`VendorId::COMMON`] for Matter's own.
218    pub vendor: VendorId,
219    /// The protocol number within that vendor's space.
220    pub id: u16,
221}
222
223impl ProtocolId {
224    /// Builds a protocol id under the Common Vendor ID.
225    #[must_use]
226    pub const fn common(id: u16) -> Self {
227        Self {
228            vendor: VendorId::COMMON,
229            id,
230        }
231    }
232
233    /// `0x0000` — Secure Channel: PASE, CASE, MRP standalone acknowledgements, status
234    /// reports and the check-in message (Core §4.11).
235    pub const SECURE_CHANNEL: Self = Self::common(0x0000);
236    /// `0x0001` — the Interaction Model (Core ch. 8).
237    pub const INTERACTION_MODEL: Self = Self::common(0x0001);
238    /// `0x0002` — the Bulk Data Exchange Protocol (Core §11.22).
239    pub const BDX: Self = Self::common(0x0002);
240    /// `0x0003` — User Directed Commissioning (Core §5.3).
241    pub const USER_DIRECTED_COMMISSIONING: Self = Self::common(0x0003);
242    /// `0x0004` — reserved for testing.
243    pub const FOR_TESTING: Self = Self::common(0x0004);
244
245    /// Whether this protocol belongs to the Common Vendor ID, and so needs no Protocol
246    /// Vendor ID field on the wire.
247    #[must_use]
248    pub const fn is_common(self) -> bool {
249        self.vendor.0 == VendorId::COMMON.0
250    }
251}
252
253impl Default for ProtocolId {
254    fn default() -> Self {
255        Self::SECURE_CHANNEL
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn node_id_ranges_follow_2_5_5() {
265        assert_eq!(NodeId(0).kind(), NodeIdKind::Unspecified);
266        assert_eq!(NodeId(1).kind(), NodeIdKind::Operational);
267        assert_eq!(
268            NodeId(0xFFFF_FFEF_FFFF_FFFF).kind(),
269            NodeIdKind::Operational
270        );
271        assert_eq!(
272            NodeId(0xFFFF_FFF0_0000_0000).kind(),
273            NodeIdKind::Reserved,
274            "one past the operational range"
275        );
276        assert_eq!(
277            NodeId(0xFFFF_FFFB_0000_0001).kind(),
278            NodeIdKind::PakeKeyIdentifier
279        );
280        assert_eq!(
281            NodeId(0xFFFF_FFFD_0000_0001).kind(),
282            NodeIdKind::CaseAuthenticatedTag
283        );
284        assert_eq!(
285            NodeId(0xFFFF_FFFE_0000_0001).kind(),
286            NodeIdKind::TemporaryLocal
287        );
288        assert_eq!(NodeId(0xFFFF_FFFF_FFFF_0001).kind(), NodeIdKind::Group);
289    }
290
291    #[test]
292    fn group_node_ids_round_trip() {
293        let g = GroupId(0x1234);
294        let n = NodeId::from_group(g);
295        assert_eq!(n.0, 0xFFFF_FFFF_FFFF_1234);
296        assert_eq!(n.group(), Some(g));
297        assert_eq!(NodeId(1).group(), None);
298    }
299
300    #[test]
301    fn the_unspecified_node_id_is_not_operational() {
302        assert!(!NodeId::UNSPECIFIED.is_operational());
303        assert!(NodeId(1).is_operational());
304    }
305
306    #[test]
307    fn group_zero_is_not_addressable() {
308        assert!(!GroupId::UNSPECIFIED.is_valid());
309        assert!(GroupId(1).is_valid());
310    }
311
312    #[test]
313    fn common_protocols_need_no_vendor_field() {
314        assert!(ProtocolId::SECURE_CHANNEL.is_common());
315        assert!(ProtocolId::INTERACTION_MODEL.is_common());
316        assert!(
317            !ProtocolId {
318                vendor: VendorId::TEST_1,
319                id: 1
320            }
321            .is_common()
322        );
323    }
324}