Skip to main content

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