Skip to main content

matter_kit/platform/
mod.rs

1//! The seams between this crate and the machine it runs on.
2//!
3//! Matter needs sockets, a clock, randomness, storage and cryptography. None of those is
4//! the protocol, and every one of them differs between a Linux bridge, an ESP32 and a
5//! simulator. So they are traits, and the crate names no implementation of them: there is
6//! no `tokio` and no `embassy-time` in its dependency tree, and a consumer who has already
7//! chosen an executor keeps it.
8//!
9//! The traits are deliberately small. A platform is a handful of `async fn`s, not a
10//! framework.
11//!
12//! # What is here
13//!
14//! | Trait | For |
15//! |---|---|
16//! | [`Timer`] | monotonic time and sleeping — every deadline in the specification |
17//! | [`Clock`] | wall-clock UTC, which only the Time Synchronization cluster needs |
18//! | [`Rng`] | cryptographically secure random bytes |
19//! | [`Udp`] | IPv6 datagrams, the transport every Matter node must have |
20//! | [`KvStore`] | opaque, versioned blobs that survive a reboot |
21//!
22//! Each has an implementation in [`sim`] — an in-process network with a virtual clock —
23//! and, with the `std` feature, in [`crate::platform::os`].
24//!
25//! # Why the clock is a trait, and not `Instant::now()`
26//!
27//! Because half of Matter is timers. MRP retransmits on a backoff curve; a fail-safe
28//! expires; an intermittently-connected device sleeps for an hour and wakes to check in; a
29//! subscription dies if no report arrives inside its interval. Testing any of that against
30//! a real clock means *waiting*, which means those paths get tested rarely, shallowly, and
31//! flakily.
32//!
33//! With time as a parameter, [`sim::SimNet`] advances to the next scheduled deadline
34//! instantly, so an hour-long intermittently-connected scenario is a unit test that
35//! finishes in microseconds and fails the same way every time.
36
37use core::future::Future;
38
39pub mod sim;
40
41#[cfg(feature = "std")]
42#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
43pub mod os;
44
45mod time;
46
47pub use time::{Duration, Instant};
48
49use crate::error::Result;
50
51/// Monotonic time, and the ability to wait for it.
52///
53/// "Monotonic" is the whole requirement: it must never go backwards, and it must not jump
54/// when somebody sets the wall clock. Matter's deadlines are all durations from now.
55pub trait Timer {
56    /// How long since some fixed point this timer never changes.
57    fn now(&self) -> Instant;
58
59    /// Completes at `deadline`, or immediately if it has passed.
60    fn sleep_until(&self, deadline: Instant) -> impl Future<Output = ()>;
61
62    /// Completes after `duration`.
63    fn sleep(&self, duration: Duration) -> impl Future<Output = ()> {
64        self.sleep_until(self.now().saturating_add(duration))
65    }
66}
67
68/// Wall-clock time in UTC.
69///
70/// Separate from [`Timer`] because most nodes do not have one: a light with no real-time
71/// clock and no Time Synchronization cluster implements [`NoClock`] and is none the worse.
72/// Matter never uses wall-clock time for protocol deadlines, only for the Time
73/// Synchronization cluster and for certificate validity.
74pub trait Clock {
75    /// Microseconds since the Matter epoch — 2000-01-01 00:00:00 UTC — or `None` when the
76    /// node does not know the time.
77    fn utc(&self) -> Option<u64>;
78
79    /// Sets the current time, if the platform can. A node that cannot returns
80    /// `Err(ErrorCode::Platform)`; the Time Synchronization cluster reports that honestly
81    /// rather than pretending the write worked.
82    fn set_utc(&self, _micros: u64) -> Result<()> {
83        Err(crate::error::Error::new(crate::error::ErrorCode::Platform))
84    }
85
86    /// How precise [`Clock::utc`] is, as the Time Synchronization cluster's
87    /// `Granularity` enumeration.
88    fn granularity(&self) -> Granularity {
89        Granularity::NoTimeGranularity
90    }
91}
92
93/// How precisely a node knows the time (Core §11.17, `GranularityEnum`).
94#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
95#[repr(u8)]
96pub enum Granularity {
97    /// The node does not know the time at all.
98    NoTimeGranularity = 0,
99    /// Accurate to within a minute.
100    MinutesGranularity = 1,
101    /// Accurate to within a second.
102    SecondsGranularity = 2,
103    /// Accurate to within a millisecond.
104    MillisecondsGranularity = 3,
105    /// Accurate to within a microsecond.
106    MicrosecondsGranularity = 4,
107}
108
109/// A node with no real-time clock.
110#[derive(Debug, Clone, Copy, Default)]
111pub struct NoClock;
112
113impl Clock for NoClock {
114    fn utc(&self) -> Option<u64> {
115        None
116    }
117}
118
119/// A cryptographically secure random number generator.
120///
121/// Matter needs random bytes for nonces, ephemeral keys, exchange ids and the initial
122/// message counter. A predictable one breaks the security of every session, so this is not
123/// somewhere to save a few bytes of code: it must be a CSPRNG seeded from real entropy.
124pub trait Rng {
125    /// Fills `out` with random bytes.
126    ///
127    /// Returns `Err` only when the platform's entropy source has failed — which a node
128    /// must treat as fatal rather than continue with predictable values.
129    fn fill(&self, out: &mut [u8]) -> Result<()>;
130
131    /// A random `u32`.
132    fn next_u32(&self) -> Result<u32> {
133        let mut b = [0u8; 4];
134        self.fill(&mut b)?;
135        Ok(u32::from_le_bytes(b))
136    }
137
138    /// A random `u64`.
139    fn next_u64(&self) -> Result<u64> {
140        let mut b = [0u8; 8];
141        self.fill(&mut b)?;
142        Ok(u64::from_le_bytes(b))
143    }
144
145    /// A random `u16`.
146    fn next_u16(&self) -> Result<u16> {
147        let mut b = [0u8; 2];
148        self.fill(&mut b)?;
149        Ok(u16::from_le_bytes(b))
150    }
151}
152
153/// An IPv6 address and port — where a Matter message came from, or goes to.
154///
155/// Matter is IPv6-only for operational communication (Core §2.5.6): "This protocol uses
156/// IPv6 addressing for its operational communication." An IPv4 address cannot be a peer,
157/// which is why this type has no variant for one.
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
159pub struct PeerAddr {
160    /// The 128-bit address, in network byte order.
161    pub addr: [u8; 16],
162    /// The UDP port; [`crate::PORT`] unless the peer announced another.
163    pub port: u16,
164    /// The scope zone for a link-local address, which is meaningless for other scopes.
165    ///
166    /// A link-local address (`fe80::/10`) is ambiguous without the interface it was seen
167    /// on, and Matter uses link-local addresses routinely — a Thread node may have no
168    /// other kind.
169    pub scope_id: u32,
170}
171
172impl PeerAddr {
173    /// Builds an address with the standard Matter port and no scope.
174    #[must_use]
175    pub const fn new(addr: [u8; 16]) -> Self {
176        Self {
177            addr,
178            port: crate::PORT,
179            scope_id: 0,
180        }
181    }
182
183    /// Builds an address with an explicit port.
184    #[must_use]
185    pub const fn with_port(addr: [u8; 16], port: u16) -> Self {
186        Self {
187            addr,
188            port,
189            scope_id: 0,
190        }
191    }
192
193    /// Whether this is a link-local address (`fe80::/10`), for which [`Self::scope_id`]
194    /// is significant.
195    #[must_use]
196    pub const fn is_link_local(&self) -> bool {
197        self.addr[0] == 0xfe && (self.addr[1] & 0xc0) == 0x80
198    }
199
200    /// Whether this is a multicast address (`ff00::/8`).
201    #[must_use]
202    pub const fn is_multicast(&self) -> bool {
203        self.addr[0] == 0xff
204    }
205}
206
207/// Where a Matter message came from, or goes to, whichever transport carried it.
208///
209/// A Matter node speaks more than one at once: during commissioning a device may be answering
210/// BLE on one side and advertising over IPv6 on the other, and the reply to a message has to
211/// go back the way it came.
212///
213/// The distinction is not only routing. Core §4.12.4:
214///
215/// > Reliable messages sent over TCP, PAFTP, or BTP SHALL utilize the underlying reliability
216/// > mechanisms of those transports and SHOULD NOT set the R Flag.
217///
218/// So which transport a peer is on decides whether MRP runs at all, and
219/// [`Messaging`](crate::messaging::Messaging) reads it from here rather than trusting each
220/// caller to remember.
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
222pub enum Peer {
223    /// A UDP peer, addressed by IPv6. MRP supplies the reliability.
224    Udp(PeerAddr),
225    /// A BLE peer, named by whatever handle the platform's stack uses for the connection.
226    /// [`btp`](crate::transport::btp) supplies the reliability.
227    Ble(u16),
228    /// A TCP peer: an address, plus the connection the stream arrived on.
229    ///
230    /// The address alone does not identify it. Core §4.15.2 lets two nodes hold more than one
231    /// connection at a time, and a reply has to go back down the one the request came up, so
232    /// the platform's own handle for the socket travels with the address.
233    /// [`tcp`](crate::transport::tcp) supplies the reliability.
234    Tcp(PeerAddr, u16),
235}
236
237impl Peer {
238    /// Whether the transport is reliable on its own, so §4.12.4 says not to set the R flag.
239    #[must_use]
240    pub const fn is_reliable(&self) -> bool {
241        match self {
242            Self::Udp(_) => false,
243            Self::Ble(_) | Self::Tcp(..) => true,
244        }
245    }
246
247    /// Whether the transport can carry a message larger than the 1280-octet IPv6 minimum
248    /// MTU, so a Large Message command (§4.4.4) may be sent over it.
249    ///
250    /// Only TCP can. §4.4.4: "The maximum size of the payload for messages sent over a TCP
251    /// connection is 1,048,576 octets", against 1280 for everything datagram-shaped. This is
252    /// what an application passes to
253    /// [`InteractionContext::with_large_messages`](crate::im::server::InteractionContext::with_large_messages),
254    /// so the data model's `L` quality is enforced against the transport that is actually
255    /// underneath rather than against a build-time guess.
256    #[must_use]
257    pub const fn supports_large_payloads(&self) -> bool {
258        matches!(self, Self::Tcp(..))
259    }
260
261    /// The IPv6 address, when there is one.
262    #[must_use]
263    pub const fn addr(&self) -> Option<PeerAddr> {
264        match self {
265            Self::Udp(addr) | Self::Tcp(addr, _) => Some(*addr),
266            Self::Ble(_) => None,
267        }
268    }
269}
270
271impl From<PeerAddr> for Peer {
272    fn from(addr: PeerAddr) -> Self {
273        Self::Udp(addr)
274    }
275}
276
277/// Sending and receiving IPv6 datagrams.
278///
279/// This is the one transport every Matter node must have: Core §2.3 puts Matter on "any
280/// IPv6-bearing network", and UDP on port 5540 is where operational traffic lives.
281pub trait Udp {
282    /// Receives one datagram into `buf`, returning how many octets arrived and from where.
283    ///
284    /// A datagram larger than `buf` is truncated or dropped at the platform's discretion;
285    /// `buf` is always at least [`crate::config::MAX_UDP_MESSAGE`] when this crate calls
286    /// it, which Core §4.4.4 makes sufficient.
287    fn recv_from(&self, buf: &mut [u8]) -> impl Future<Output = Result<(usize, PeerAddr)>>;
288
289    /// Sends one datagram.
290    fn send_to(&self, buf: &[u8], addr: PeerAddr) -> impl Future<Output = Result<()>>;
291
292    /// Joins an IPv6 multicast group, so that group messages addressed to it arrive.
293    ///
294    /// Matter needs one membership per operational group (Core §2.11.1.2).
295    fn join_multicast(&self, _group: [u8; 16], _scope_id: u32) -> Result<()> {
296        Err(crate::error::Error::new(crate::error::ErrorCode::Platform))
297    }
298
299    /// Leaves a multicast group.
300    fn leave_multicast(&self, _group: [u8; 16], _scope_id: u32) -> Result<()> {
301        Err(crate::error::Error::new(crate::error::ErrorCode::Platform))
302    }
303}
304
305/// Non-volatile storage, as opaque blobs under string keys.
306///
307/// The store never sees a Matter type: this crate serialises everything itself, prefixes
308/// each blob with a schema version, and treats an unknown newer version as a failure
309/// rather than a value to guess at. That keeps the platform's job to five methods and
310/// keeps migrations in one place.
311pub trait KvStore {
312    /// Reads the value of `key` into `out`, returning how many octets it holds.
313    ///
314    /// Returns `Ok(None)` when the key is absent — which is not an error, it is how a
315    /// factory-fresh node reads every key.
316    fn get(&self, key: &str, out: &mut [u8]) -> impl Future<Output = Result<Option<usize>>>;
317
318    /// Writes `value` to `key`, replacing what was there.
319    fn set(&self, key: &str, value: &[u8]) -> impl Future<Output = Result<()>>;
320
321    /// Removes `key`. Removing an absent key succeeds.
322    fn remove(&self, key: &str) -> impl Future<Output = Result<()>>;
323
324    /// Removes every key with the given prefix.
325    ///
326    /// This is what `RemoveFabric` and a factory reset are built from.
327    fn remove_prefix(&self, prefix: &str) -> impl Future<Output = Result<()>>;
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn link_local_detection() {
336        let mut a = [0u8; 16];
337        a[0] = 0xfe;
338        a[1] = 0x80;
339        assert!(PeerAddr::new(a).is_link_local());
340        a[1] = 0xc0;
341        assert!(!PeerAddr::new(a).is_link_local());
342        assert!(PeerAddr::new([0xff; 16]).is_multicast());
343    }
344
345    #[test]
346    fn default_port_is_5540() {
347        assert_eq!(PeerAddr::new([0; 16]).port, crate::PORT);
348    }
349
350    #[test]
351    fn a_node_without_a_clock_says_so() {
352        assert_eq!(NoClock.utc(), None);
353        assert_eq!(NoClock.granularity(), Granularity::NoTimeGranularity);
354        assert!(NoClock.set_utc(0).is_err());
355    }
356}