matter_kit/config.rs
1//! How big everything is.
2//!
3//! A Matter node is a set of tables: fabrics it belongs to, sessions it holds, exchanges
4//! in flight, subscriptions it serves, access-control entries it enforces. On a
5//! microcontroller every one of those is a fixed-capacity array, and its length has to be
6//! known at compile time.
7//!
8//! The obvious way to express that is Cargo features — `fabrics-5`, `fabrics-32`,
9//! `sessions-16` — which is what the other Rust implementation does, with seventy-odd of
10//! them. It has two problems. Cargo features are *additive and global*: two crates in one
11//! binary that want different sizes silently get the union, and there is no way to say so.
12//! And nothing checks the result against the specification, so a build that cannot pass
13//! certification compiles happily.
14//!
15//! So sizing is a **trait**. A consumer writes one type, the numbers travel with it
16//! through every generic in the crate, and the specification's minima are `const`
17//! assertions that fail the build rather than the certification laboratory.
18//!
19//! **Every constant here is read by the crate.** A sizing knob nothing reads is worse than
20//! no knob at all: it reads as a promise, it can carry an assertion that looks like
21//! enforcement, and the table it claims to size is whatever length somebody else picked. So
22//! `Config` carries what the protocol core allocates — fabrics, sessions, exchanges,
23//! subscriptions, access control — and no more. Capacities that belong to one instance of one
24//! table are const parameters on that table (`GroupKeys<K, M>`, `SceneTable<N, EFS, F>`,
25//! `Binding<C, N>`), chosen where it is constructed, because that is where the device knows
26//! how many it wants. `GROUPS` and `GROUP_KEYS` stay because §2.11.1.2's per-fabric minima
27//! are checked against them and a device passes them straight to those tables.
28//!
29//! ```
30//! use matter_kit::Config;
31//!
32//! /// A Thread light: one ecosystem plus room for a second, and not much else.
33//! struct Light;
34//! impl Config for Light {
35//! const FABRICS: usize = 5;
36//! const SESSIONS: usize = 16;
37//! const SUBSCRIPTIONS: usize = 15;
38//! }
39//! ```
40//!
41//! Everything not named takes the value in [`DefaultConfig`], which is a device-sized
42//! profile that satisfies every minimum.
43//!
44//! # What is checked
45//!
46//! | Constant | Rule | Section |
47//! |---|---|---|
48//! | `FABRICS` | 5 ..= 254 — the `SupportedFabrics` constraint | §11.18.5.3 |
49//! | `ACL_ENTRIES` | at least 4 per fabric | §2.11.1.1 |
50//! | `GROUP_KEYS` | at least 3 per fabric | §2.11.1.2 |
51//! | `SESSIONS` | at least 3 CASE sessions per fabric | §4.14.2.8 |
52//! | `SUBSCRIPTIONS` | at least 3 per fabric | §2.11.2.2 |
53//! | `SUB_PATHS` | at least 3 per subscription | §2.11.2.2 |
54//! | `READ_PATHS` | at least 9 | §2.11.2.1 |
55//! | `EXCHANGES_PER_SESSION` | at least 1 | — |
56//!
57//! The assertions are in [`assert_valid`], which every generic entry point in the crate
58//! instantiates. A `Config` that breaks a rule therefore fails to compile at the first
59//! place it is used, with the failing rule named in the panic message.
60
61/// The sizes a Matter node is built to.
62///
63/// Implement this on a zero-sized type and pass it as the `C` parameter. Every constant
64/// has a default from [`DefaultConfig`], so a minimal implementation is `impl Config for
65/// MyNode {}`.
66pub trait Config {
67 /// How many fabrics — commissioned ecosystems — the node can belong to.
68 ///
69 /// Reported as `SupportedFabrics` (Core §11.18.5.3), whose constraint is `5 to 254`:
70 /// a node that supports fewer than five cannot be commissioned into the number of
71 /// ecosystems the specification requires.
72 const FABRICS: usize = 5;
73
74 /// How many secure sessions can exist at once, across all fabrics.
75 ///
76 /// Core §4.14.2.8: "A node SHALL support at least 3 CASE session contexts per fabric."
77 const SESSIONS: usize = 16;
78
79 /// How many exchanges can be open on one session at once.
80 const EXCHANGES_PER_SESSION: usize = 4;
81
82 /// How many subscriptions the node can serve, across all fabrics.
83 ///
84 /// Core §2.11.2.2: at least three per fabric.
85 const SUBSCRIPTIONS: usize = 15;
86
87 /// How many subscriptions any one fabric may hold.
88 ///
89 /// §2.11.2.2 states the rule as a *guarantee*, not a cap: "A publisher SHALL ensure that
90 /// every fabric the node is commissioned into can support at least three Subscribe
91 /// Interactions to the publisher." A table with only a global limit cannot make that
92 /// promise — the first administrator to ask fills it, and every fabric commissioned
93 /// afterwards is told the node is out of resources by a node that is, from its own point
94 /// of view, working perfectly.
95 ///
96 /// So the guarantee is kept the way [`Config::ACL_ENTRIES_PER_FABRIC`] keeps §6.6's: a
97 /// fixed share each, refusing a fabric that is at its quota even when the table has room.
98 /// That is the strict reading, it is always conformant, and it cannot surprise an
99 /// administrator by granting a subscription one day and refusing it the next when what
100 /// changed was somebody else's fabric.
101 const SUBSCRIPTIONS_PER_FABRIC: usize = 3;
102
103 /// How many attribute or event paths one subscription can carry.
104 ///
105 /// Core §2.11.2.2: at least three.
106 const SUB_PATHS: usize = 3;
107
108 /// How many paths one read interaction can carry.
109 ///
110 /// Core §2.11.2.1: "a single Read Interaction from a client on that fabric containing
111 /// up to 9 paths".
112 const READ_PATHS: usize = 9;
113
114 /// How many access-control entries the node stores, across all fabrics.
115 ///
116 /// Core §2.11.1.1: "at least four Access Control Entries available for every fabric".
117 const ACL_ENTRIES: usize = 4 * Self::FABRICS;
118
119 /// How many access-control entries **one fabric** may hold — §9.10.6.7's
120 /// `AccessControlEntriesPerFabric`, constrained to `4 to 65534`.
121 ///
122 /// A per-fabric quota, not just a total: §2.11.1.1 requires "at least four Access Control
123 /// Entries available for every fabric supported by the node", and without a quota the
124 /// first fabric to fill the table would lock every later administrator out of granting
125 /// itself anything.
126 ///
127 /// §2.11.1.1 permits over-subscription — "if it supports N entries must enforce that any K
128 /// fabrics together do not use more than N - 4*(5-K) entries" — which would let one fabric
129 /// borrow the unused quota of another. This is the strict reading instead: a fixed share
130 /// each. It is always conformant and it cannot surprise an administrator by granting a
131 /// quota one day and refusing it the next, when what changed was another fabric.
132 const ACL_ENTRIES_PER_FABRIC: usize = 4;
133
134 /// How many subjects one access-control entry can name.
135 ///
136 /// §9.10.6.5's `SubjectsPerAccessControlEntry`, constrained to `4 to 65534`.
137 const ACL_SUBJECTS: usize = 4;
138
139 /// How many targets one access-control entry can name.
140 ///
141 /// §9.10.6.6's `TargetsPerAccessControlEntry`, constrained to `3 to 65534`.
142 const ACL_TARGETS: usize = 3;
143
144 /// Whether §9.10.4.3's Auxiliary feature is implemented.
145 ///
146 /// It changes an access decision: with it, §6.6.6.2 stops a wildcard Group entry from
147 /// reaching endpoint 0, whose clusters administer the node itself.
148 const ACL_AUXILIARY: bool = false;
149
150 /// How many group memberships the node keeps, across all fabrics.
151 const GROUPS: usize = 4 * Self::FABRICS;
152
153 /// How many group key sets the node keeps, across all fabrics.
154 ///
155 /// Core §2.11.1.2: "at least three group keys per fabric".
156 const GROUP_KEYS: usize = 3 * Self::FABRICS;
157
158 /// The largest message the node will accept over a stream transport.
159 ///
160 /// Core §4.15.2.3 calls this the "Maximum Message Size", and a peer that announces a
161 /// larger one gets `MESSAGE_TOO_LARGE` and a closed connection. It is the `N` of
162 /// [`tcp::Framer`](crate::transport::tcp::Framer), and the specification sets no figure:
163 /// "The system platform MAY configure a Maximum Message Size for the payload that it is
164 /// capable of receiving", so a device that cannot spare 64 KiB says so here.
165 const MAX_TCP_MSG: usize = 64 * 1024;
166}
167
168/// A device-sized profile that satisfies every minimum: five fabrics, sixteen sessions,
169/// fifteen subscriptions.
170///
171/// This is the configuration the crate's own tests and examples use.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct DefaultConfig;
174
175impl Config for DefaultConfig {}
176
177/// The largest message that fits the IPv6 minimum MTU (Core §4.4.4).
178///
179/// "Support for IPv6 fragmentation is not mandatory in Matter, and the expected supported
180/// MTU is 1280 bytes … all messages, including transport headers, SHALL fit within that
181/// minimal IPv6 MTU. This message size limit SHALL apply to the UDP transport."
182pub const MAX_UDP_MESSAGE: usize = 1280;
183
184/// The largest framing a secured unicast message can carry, in octets.
185///
186/// Message header: flags, session id, security flags and counter (8), a source node id (8) and
187/// a destination node id (8) — [`MessageHeader::encoded_len`](crate::msg::MessageHeader::encoded_len)'s
188/// worst case. Protocol header: flags, opcode, exchange id and protocol id (6), a vendor id (2)
189/// and an acknowledged counter (4) — [`ProtocolHeader::encoded_len`](crate::msg::ProtocolHeader::encoded_len)'s.
190/// Then §4.8's AEAD tag (16).
191pub const MAX_MESSAGE_FRAMING: usize = (8 + 8 + 8) + (6 + 2 + 4) + 16;
192
193/// The largest protocol payload that is **certain** to fit a UDP datagram once framed.
194///
195/// A node builds its reply in a payload buffer and hands it to the messaging layer, which adds
196/// the headers and the AEAD tag. So the payload bound is the datagram bound *minus the framing*,
197/// and sizing that buffer by anything else is guesswork that fails as `buffer too small` — from
198/// this node, about its own reply, with nothing on the wire to explain it.
199///
200/// It is a floor rather than an exact figure: a message with no source node id, or on a common
201/// protocol, or with nothing to acknowledge, has room to spare. Sizing to the worst case is what
202/// makes "it fits" independent of which of those happens to be true.
203pub const MAX_UDP_PAYLOAD: usize = MAX_UDP_MESSAGE.saturating_sub(MAX_MESSAGE_FRAMING);
204
205/// Compile-time proof that a [`Config`] satisfies the specification's minima.
206///
207/// Instantiating this type evaluates its assertions; every generic entry point in the
208/// crate does so, which is what makes a bad `Config` a build failure at its first use.
209pub struct AssertValid<C: Config>(core::marker::PhantomData<C>);
210
211impl<C: Config> AssertValid<C> {
212 /// The assertions themselves. Referencing this constant is what runs them.
213 pub const CHECK: () = {
214 assert!(
215 C::FABRICS >= 5,
216 "Config::FABRICS: Core §11.18.5.3 constrains SupportedFabrics to 5..=254"
217 );
218 assert!(
219 C::FABRICS <= 254,
220 "Config::FABRICS: Core §11.18.5.3 constrains SupportedFabrics to 5..=254"
221 );
222 assert!(
223 C::ACL_ENTRIES >= 4 * C::FABRICS,
224 "Config::ACL_ENTRIES: Core §2.11.1.1 requires at least 4 entries per fabric"
225 );
226 assert!(
227 C::GROUP_KEYS >= 3 * C::FABRICS,
228 "Config::GROUP_KEYS: Core §2.11.1.2 requires at least 3 group keys per fabric"
229 );
230 assert!(
231 C::SESSIONS >= 3 * C::FABRICS,
232 "Config::SESSIONS: Core §4.14.2.8 requires at least 3 CASE sessions per fabric"
233 );
234 assert!(
235 C::SUBSCRIPTIONS_PER_FABRIC >= 3,
236 "Config::SUBSCRIPTIONS_PER_FABRIC: Core §2.11.2.2 requires at least 3 per fabric"
237 );
238 assert!(
239 C::SUBSCRIPTIONS >= C::SUBSCRIPTIONS_PER_FABRIC * C::FABRICS,
240 "Config::SUBSCRIPTIONS: every fabric must be able to reach SUBSCRIPTIONS_PER_FABRIC"
241 );
242 assert!(
243 C::SUBSCRIPTIONS >= 3 * C::FABRICS,
244 "Config::SUBSCRIPTIONS: Core §2.11.2.2 requires at least 3 subscriptions per fabric"
245 );
246 assert!(
247 C::SUB_PATHS >= 3,
248 "Config::SUB_PATHS: Core §2.11.2.2 requires at least 3 paths per subscription"
249 );
250 assert!(
251 C::READ_PATHS >= 9,
252 "Config::READ_PATHS: Core §2.11.2.1 requires a read of up to 9 paths"
253 );
254 assert!(
255 C::EXCHANGES_PER_SESSION >= 1,
256 "Config::EXCHANGES_PER_SESSION: a session with no exchange can do nothing"
257 );
258 };
259}
260
261/// Runs [`AssertValid::CHECK`] for `C`.
262///
263/// Call it from any `const` context — or just let the crate's generic types do it.
264pub const fn assert_valid<C: Config>() {
265 #[allow(clippy::let_unit_value)]
266 let () = AssertValid::<C>::CHECK;
267}
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272
273 // The real check is a `const` one: `assert_valid` evaluates `AssertValid::CHECK`,
274 // which fails the *build* rather than a test run. Naming it in a `const` context is
275 // what proves that, so these are `const` blocks and not runtime assertions.
276 const _: () = assert_valid::<DefaultConfig>();
277
278 #[test]
279 fn the_default_config_satisfies_every_minimum() {
280 // Reaching this line at all means the `const` above compiled.
281 assert_valid::<DefaultConfig>();
282 }
283
284 #[test]
285 fn derived_defaults_follow_the_fabric_count() {
286 #[derive(Debug)]
287 struct Big;
288 impl Config for Big {
289 const FABRICS: usize = 16;
290 const SESSIONS: usize = 64;
291 const SUBSCRIPTIONS: usize = 48;
292 }
293 const _: () = assert_valid::<Big>();
294 // ACL_ENTRIES and GROUP_KEYS default off FABRICS, so they scale with it.
295 assert_eq!(Big::ACL_ENTRIES, 64);
296 assert_eq!(Big::GROUP_KEYS, 48);
297 }
298
299 #[test]
300 fn max_udp_message_is_the_ipv6_minimum_mtu() {
301 assert_eq!(MAX_UDP_MESSAGE, 1280);
302 }
303}
304
305#[cfg(test)]
306mod payload_bound {
307 use super::{MAX_MESSAGE_FRAMING, MAX_UDP_MESSAGE, MAX_UDP_PAYLOAD};
308 use crate::msg::{
309 Destination, MessageHeader, NodeId, ProtocolHeader, ProtocolId, SessionId, SessionType,
310 };
311
312 /// `MAX_MESSAGE_FRAMING` is the worst case the encoders can actually produce.
313 ///
314 /// Derived by hand from two `encoded_len` implementations, which is exactly the kind of
315 /// arithmetic that is right when written and wrong after the next field is added. So it is
316 /// checked against the encoders rather than against itself.
317 #[test]
318 fn the_framing_bound_is_what_the_headers_encode() {
319 // Every optional field present: a source node id, a destination node id, a vendor
320 // protocol and an acknowledgement.
321 let message = MessageHeader {
322 session_id: SessionId(0x1234),
323 session_type: SessionType::Unicast,
324 privacy: false,
325 control: false,
326 message_counter: 0xDEAD_BEEF,
327 source: Some(NodeId(0x0102_0304_0506_0708)),
328 destination: Destination::Node(NodeId(0x1112_1314_1516_1718)),
329 };
330 let protocol = ProtocolHeader {
331 acknowledged_counter: Some(0x0BAD_F00D),
332 protocol: ProtocolId {
333 vendor: crate::msg::VendorId(0xFFF1),
334 id: 0x0001,
335 },
336 ..ProtocolHeader::default()
337 };
338 let encoded = message.encoded_len() + protocol.encoded_len();
339 let mic = crate::crypto::AEAD_MIC_LENGTH_BYTES;
340 assert_eq!(
341 encoded + mic,
342 MAX_MESSAGE_FRAMING,
343 "the framing bound no longer matches what the headers encode"
344 );
345 assert_eq!(MAX_UDP_PAYLOAD + MAX_MESSAGE_FRAMING, MAX_UDP_MESSAGE);
346 }
347}