pub struct MessageCounter { /* private fields */ }Expand description
The initial value is random (§4.6.1.1), which is why MessageCounter::new takes one
rather than starting at zero: a counter that always starts at 1 leaks how many times a
device has rebooted, and makes nonce reuse across a factory reset far too easy.
Implementations§
Source§impl MessageCounter
impl MessageCounter
Sourcepub const fn new(randomness: u32) -> Self
pub const fn new(randomness: u32) -> Self
§4.6.1.1’s initialisation, from randomness — which should come from
crate::platform::Rng.
“All message counters SHALL be initialized with a random value using the
Crypto_DRBG(len = 28) + 1 primitive”, so the starting value is in 1..=2^28 and not
anywhere in u32. The specification gives the reason in the next sentence: the range is
deliberately narrow “in order to maximize initial entropy while still reserving the vast
majority of the range to actual counter values (roughly 2³² - 2²⁸)”.
That reservation is load-bearing rather than decorative. take refuses on
exhaustion instead of rolling over — §4.6.2 has a secure session “discarded and
re-established before any Secure Session Message Counter overflow or repetition occurs”
— so the initial value is also the size of the session’s supply. Seeded from the full
u32 a session begins on average half-way through its own lifetime, and one in four
thousand begins with under a million counters left: it stops working early, and nothing
anywhere says why.
The narrowing lives here rather than at each caller, for the same reason a session
remembers its peer and a subscription its report cursor: per-interaction state belongs
to the thing it describes. at is for an exact value — a persisted
counter, or the end of the range in a test.
Sourcepub const fn at(value: u32) -> Self
pub const fn at(value: u32) -> Self
A counter at exactly value, bypassing §4.6.1.1.
For restoring a counter that was persisted — a group sender’s counters outlive a reboot
— and for tests that need to stand at a particular point in the range. A counter for a
new session comes from new.
Sourcepub fn take(&mut self) -> Result<u32>
pub fn take(&mut self) -> Result<u32>
Takes the next counter.
Returns ErrorCode::InvalidState on exhaustion rather than rolling over: for a
secure unicast session, reusing a counter means reusing a nonce, which is a
catastrophic failure of the encryption rather than a wrap to handle. A session that
reaches 2³² messages must be re-established, and the caller is told so.
Sourcepub fn take_with_rollover(&mut self) -> u32
pub fn take_with_rollover(&mut self) -> u32
Takes the next counter, rolling over at 2³².
For the group counter space, which §4.6.5.2.2 defines as “a free running message counter that monotonically increases, but rolls over to zero when it exceeds the maximum value of the counter”.