matter_kit/lib.rs
1//! A Matter implementation in Rust: one crate, `no_std`, no allocation, and no runtime of
2//! its own.
3//!
4//! [Matter](https://csa-iot.org/all-solutions/matter/) is the CSA's smart-home standard —
5//! the protocol behind Apple Home, Google Home, Alexa and SmartThings. This crate targets
6//! **specification 1.6** (approved 2026-06-16) and is built to be *certifiable* rather
7//! than merely interoperable: the same data model the certification Test Harness reads is
8//! the data model this crate is generated from.
9//!
10//! # Status
11//!
12//! Under construction and pre-1.0. A device can be commissioned into a fabric end to end — over
13//! IPv6, BLE, Wi-Fi PAF or NFC — answer Reads, Writes and Invokes against a `const` data model,
14//! hold subscriptions, enforce §6.6's access control, take part in groupcast, move a firmware
15//! image over BDX and advertise itself over DNS-SD, with [`messaging`] composing the layers so
16//! that a datagram finds its session, exchange and protocol. The CHIP SDK's own `chip-tool`
17//! commissions the `light` example through the whole of §5.5, and eleven of the CSA Test
18//! Harness's certification cases pass against it.
19//!
20//! What is missing is most of the application clusters' *behaviour* behind the generated
21//! descriptors, and the facades — `Node::builder`, `Controller` — that would turn the examples'
22//! hand-assembly into three lines. The
23//! [README](https://github.com/hupe1980/matter-kit#status) carries the layer-by-layer table;
24//! each module here states which sections it implements.
25//!
26//! # Three things that shape the whole crate
27//!
28//! **A capacity is declared once, and the specification checks it.** Every table in the stack
29//! — fabrics, sessions, exchanges, subscriptions, access-control entries — is a fixed-capacity
30//! array whose length is its own const parameter, and each one carries a `const` assertion that
31//! the length can keep the promises [`Config`] makes to each fabric. A node that could not pass
32//! certification does not compile, and the failing rule is named in the build error. Two
33//! libraries in one binary cannot fight over it the way they fight over a Cargo feature.
34//!
35//! ```compile_fail
36//! use matter_kit::{Config, DefaultConfig, acl::Acl};
37//!
38//! // Core §2.11.1.1 wants four access-control entries for each of five fabrics.
39//! let too_small: Acl<DefaultConfig, 4, 4, 3> = Acl::new();
40//! ```
41//!
42//! ```
43//! use matter_kit::{Capacity, Config, DefaultConfig, acl::Acl};
44//!
45//! // The defaults are the specification's own minima, so naming none of them is conformant.
46//! let acl: Acl<DefaultConfig> = Acl::new();
47//! assert_eq!(<Acl<DefaultConfig> as Capacity>::PER_FABRIC, DefaultConfig::ACL_ENTRIES_PER_FABRIC);
48//! ```
49//!
50//! **No runtime is chosen for you.** The crate is `async` over [`core::future`] and talks
51//! to the outside world through the traits in [`platform`]: sockets, timers, randomness,
52//! storage, cryptography. No executor crate is in the dependency tree at all; `examples/`
53//! run on a `block_on` of their own. One consequence worth having: every timeout in the
54//! specification — MRP backoff, the fail-safe, an intermittently-connected device's idle
55//! period — is driven by a [`platform::Timer`], so [`platform::sim`] runs an hour-long
56//! scenario in microseconds.
57//!
58//! **Nothing panics on network input.** `unwrap`, `expect`, `panic!` and slice indexing
59//! are denied crate-wide; every parser returns [`Error`]. Resource exhaustion is a value
60//! ([`ErrorCode::NoSpace`], [`ErrorCode::Busy`]), so a device that runs out of exchanges
61//! answers rather than aborts.
62//!
63//! # Commissioning, in miniature
64//!
65//! The whole of PASE: a printed passcode becomes three shared keys, without the passcode
66//! ever crossing the wire. Needs the `rustcrypto` feature, which is on by default.
67//!
68//! The salt and iteration count below are the CHIP test vectors, so that this example is the
69//! protocol and nothing else. A product's are neither: §3.9 allows 1 000 to 100 000 iterations
70//! and the floor is what an offline attack on leaked verifier material is priced at, and a salt
71//! shared between devices shares its pre-computation with all of them. Draw the salt per device
72//! at manufacture and put the iteration count well above the minimum — `examples/light` does
73//! both.
74//!
75//! ```
76//! # #[cfg(feature = "rustcrypto")]
77//! # fn demo() -> Result<(), matter_kit::Error> {
78//! use matter_kit::crypto::Spake2pVerifierData;
79//! use matter_kit::msg::SessionId;
80//! use matter_kit::sc::{PaseInitiator, PaseResponder, PbkdfParameters, ResponderConfig};
81//!
82//! // What a factory burns into the device. The passcode itself is never stored.
83//! let parameters = PbkdfParameters::new(1_000, b"SPAKE2P Key Salt")?;
84//! let verifier =
85//! Spake2pVerifierData::from_passcode(20_202_021, ¶meters.salt, parameters.iterations)?;
86//!
87//! let mut device = PaseResponder::new(
88//! ResponderConfig { verifier, parameters: parameters.clone(), session_params: None },
89//! SessionId(1),
90//! );
91//! let mut commissioner =
92//! PaseInitiator::new(20_202_021, SessionId(2), Some(parameters), None);
93//!
94//! let (mut a, mut b) = ([0u8; 512], [0u8; 512]);
95//! let n = commissioner.start(&[0x11; 32], &mut a)?;
96//! let n = device.on_pbkdf_param_request(&a[..n], &[0x22; 32], &mut b)?;
97//! let n = commissioner.on_pbkdf_param_response(&b[..n], &[0x33; 32], &mut a)?;
98//! let n = device.on_pake1(&a[..n], &[0x44; 32], &mut b)?;
99//! let n = commissioner.on_pake2(&b[..n], &mut a)?;
100//! let (n, device_keys) = device.on_pake3(&a[..n], &mut b)?;
101//! let commissioner_keys = commissioner.on_pake_finished(&b[..n])?;
102//!
103//! // Both ends now hold the same three keys.
104//! assert_eq!(commissioner_keys.i2r, device_keys.i2r);
105//! # Ok(())
106//! # }
107//! # fn main() {
108//! # #[cfg(feature = "rustcrypto")]
109//! # demo().expect("the exchange completes");
110//! # }
111//! ```
112//!
113//! # Matching on an event
114//!
115//! Enums this crate *reports* through are `#[non_exhaustive]`; enums the **specification**
116//! closes are not. So a `match` on a protocol state is still checked for completeness —
117//! which is where you want to be told about a new variant — and a `match` on a stream of
118//! events does not break when a new one is worth reporting.
119//!
120//! ---
121//!
122//! Matter® is a registered trademark of the Connectivity Standards Alliance. This project
123//! is not affiliated with or endorsed by the Alliance, and nothing here is a certified
124//! implementation.
125
126#![cfg_attr(not(feature = "std"), no_std)]
127#![cfg_attr(docsrs, feature(doc_cfg))]
128// The crate-wide `deny` list in `Cargo.toml` is aimed at code that faces the network.
129// Test code faces a test: `unwrap` there is a legible assertion, and writing
130// `let Some(x) = .. else { panic!() }` around every fixture buys nothing and hides the
131// intent. The denials stay in force for everything that ships.
132#![cfg_attr(
133 test,
134 allow(
135 clippy::unwrap_used,
136 clippy::expect_used,
137 clippy::panic,
138 clippy::indexing_slicing,
139 clippy::arithmetic_side_effects,
140 clippy::cast_possible_truncation,
141 clippy::cast_possible_wrap,
142 clippy::cast_sign_loss,
143 )
144)]
145
146#[cfg(feature = "alloc")]
147extern crate alloc;
148
149mod bytes;
150
151pub mod acl;
152#[cfg(feature = "rustcrypto")]
153pub mod attestation;
154pub mod bdx;
155/// The fabric's certificate authority needs [`cert`] and [`crypto`]'s signing.
156#[cfg(feature = "rustcrypto")]
157#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
158pub mod ca;
159#[cfg(feature = "rustcrypto")]
160pub mod cert;
161pub mod clusters;
162pub mod commissioning;
163pub mod config;
164pub mod crypto;
165#[cfg(feature = "rustcrypto")]
166pub mod der;
167pub mod discovery;
168pub mod dm;
169pub mod error;
170pub mod exchange;
171#[cfg(feature = "rustcrypto")]
172pub mod fabric;
173#[cfg(feature = "rustcrypto")]
174#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
175pub mod group;
176#[cfg(feature = "rustcrypto")]
177#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
178pub mod icd;
179pub mod im;
180#[cfg(feature = "rustcrypto")]
181#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
182pub mod jf;
183#[cfg(feature = "rustcrypto")]
184#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
185pub mod messaging;
186pub mod msg;
187pub mod platform;
188pub mod sc;
189#[cfg(feature = "rustcrypto")]
190pub mod session;
191pub mod sync;
192pub mod tlv;
193pub mod transport;
194
195pub use config::{Capacity, Config, DefaultConfig, SubscriptionCapacity};
196pub use error::{Error, ErrorCode, Result};
197
198/// The Matter specification version this crate implements, in the encoding of the Basic
199/// Information cluster's `SpecificationVersion` attribute (Core §11.1.5.22).
200///
201/// The four component bytes are major, minor, patch and reserved: `0x01_06_00_00` is
202/// 1.6.0. A larger value is newer.
203pub const SPECIFICATION_VERSION: u32 = 0x0106_0000;
204
205/// The Data Model revision this crate implements — §7.1.1's revision 21, "Added Revision
206/// conformance".
207///
208/// §11.1.5.1 requires a node to report "the revision number of the Data Model against which
209/// the Node is certified", and "one of the valid values listed in Section 7.1.1". The table
210/// grew by one between releases and the split is easy to miss: 1.5.1 ends at
211/// `20 — Removed P quality and added Revision conformance`, and 1.6 divides that single row
212/// into `20 — Removed P quality` and `21 — Added Revision conformance`. A 1.6 node reports
213/// 21; carrying 20 forward advertises a 1.5.1 data model.
214///
215/// It lives here rather than in the Basic Information cluster because it is also
216/// `DATA_MODEL_REVISION` in the `session-parameter-struct` of §4.13.1, which is exchanged
217/// long before any cluster is readable. `clusters::basic_information` re-exports it.
218pub const DATA_MODEL_REVISION: u16 = 21;
219
220/// The IANA-assigned UDP port for Matter (Core §2.5.6.3).
221pub const PORT: u16 = 5540;
222
223/// The README's `rust` blocks, compiled as doctests.
224///
225/// Under `cfg(doctest)` only, so the README is not pulled into the crate's own
226/// documentation — this exists so a landing-page example cannot quietly stop compiling.
227#[cfg(doctest)]
228#[doc = include_str!("../README.md")]
229struct Readme;
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn specification_version_is_1_6_0() {
237 assert_eq!(SPECIFICATION_VERSION.to_be_bytes(), [1, 6, 0, 0]);
238 }
239
240 /// The three revisions a peer reads out of `session-parameter-struct` (§4.13.1) move
241 /// independently of each other and of the crate version, and each is a number taken from
242 /// a table in a PDF. Asserting them here is what makes a spec uplift that forgets one
243 /// fail loudly: 1.6 split §7.1.1's last row and `DATA_MODEL_REVISION` silently stayed at
244 /// its 1.5.1 value until this test existed.
245 #[test]
246 fn the_revision_constants_are_the_1_6_values() {
247 // Core §7.1.1, last row: "21 — Added Revision conformance".
248 assert_eq!(DATA_MODEL_REVISION, 21);
249 // Core §8.1.1, last row: "13 — Added WildcardFilterConfigurationVersion (Matter 1.3)".
250 assert_eq!(crate::im::INTERACTION_MODEL_REVISION, 13);
251 // Core §11.1.5.22, as four component bytes.
252 assert_eq!(SPECIFICATION_VERSION, 0x0106_0000);
253 }
254}