Skip to main content

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