Expand description
UMSH MAC-layer coordinator and supporting state types.
Note: This reference implementation is a work in progress and was developed with the assistance of an LLM. It should be considered experimental.
This crate is the central runtime for the UMSH mesh protocol. It owns every piece of radio-facing state and drives the full MAC lifecycle: receiving and authenticating inbound frames, forwarding eligible frames as a repeater, issuing and verifying transport ACKs, retransmitting unacknowledged sends, suppressing duplicates, enforcing replay windows, managing frame-counter persistence, and servicing the outbound transmit queue.
The crate is no_std compatible. All data structures are backed by
heapless fixed-capacity collections; capacity is controlled
by const-generic parameters on Mac so the compiler enforces sizing at build time with
zero heap allocation.
§Architecture overview
┌────────────────────────────────────────────────────────────────┐
│ Application / upper layers │
│ queue_broadcast / queue_unicast / queue_multicast / … │
└──────────────────────────┬─────────────────────────────────────┘
│ SendOptions → SendReceipt
▼
┌────────────────────────────────────────────────────────────────┐
│ Mac<P> (coordinator.rs) │
│ │
│ ┌─────────────────┐ ┌────────────────┐ ┌────────────────┐ │
│ │ IdentitySlot[N] │ │ PeerRegistry │ │ ChannelTable │ │
│ │ frame counters │ │ public keys │ │ channel keys │ │
│ │ pending ACKs │ │ cached routes │ │ derived keys │ │
│ │ pairwise keys │ └────────────────┘ └────────────────┘ │
│ └─────────────────┘ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ TxQueue (priority-ordered outbound frame buffer) │ │
│ └──────────────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ DuplicateCache │ ReplayWindow (per peer, per identity) │ │
│ └──────────────────────────────────────────────────────────┘ │
└──────────────────────────┬─────────────────────────────────────┘
│ async next_event()
▼
┌────────────────────────────────────────────────────────────────┐
│ Platform (umsh-hal + umsh-crypto) │
│ Radio · Clock · Rng · Aes/Sha · CounterStore · KeyValueStore │
└────────────────────────────────────────────────────────────────┘§Modules and key types
§[coordinator]—the top-level state machine
Mac<P> is the single top-level type. Create one with Mac::new, register
identities and peers, then drive it with Mac::run, Mac::run_quiet, or
Mac::next_event depending on whether you want a long-lived driver loop or manual
multiplexing with other async work. Everything else in this crate exists to support
Mac.
Supporting types in this module:
LocalIdentityId—opaque slot index returned when registering a local keypair.LocalIdentity—either a long-term platform identity or an ephemeral software identity for PFS sessions.IdentitySlot—per-identity runtime state: keys, frame counter, pending ACKs.OperatingPolicy—transmission-time rules for the local node (amateur-radio mode, operator callsign, per-channel overrides).RepeaterConfig—controls whether and how inbound frames are forwarded.AmateurRadioMode—shared enum governing encryption and identification requirements under ham-radio law.ChannelPolicy—per-channel overrides within anOperatingPolicy.SendError,MacError,CounterPersistenceError—error types for queuing, runtime event processing, and frame-counter store operations respectively.
§[send]—outbound transmission types
SendOptions—high-level parameters for a single send: MIC size, encryption, flood hops, ACK request, source route, salt, etc.SendReceipt—opaque token returned for ACK-requested sends; matched against inbound MAC ACKs to confirm delivery.TxQueue—priority-ordered, fixed-capacity queue of sealed frames waiting for radio transmission.QueuedTx—one entry in the transmit queue; includes frame bytes, priority, not-before timestamp, and CAD retry count.TxPriority—priority classes from highest (ImmediateAck) to lowest (Application).AckState—ACK lifecycle state machine covering queued sends, forwarding confirmation, retry scheduling, and final destination ACK waiting.PendingAck—full tracking record for one in-flight ACK-requested send, stored in the identity slot until delivery is confirmed or the deadline expires.ResendRecord—verbatim sealed frame bytes retained for retransmission without re-sealing.
§[cache]—duplicate suppression and replay protection
DuplicateCache—a fixed-size FIFO ring that records recently-seenDupCacheKeyvalues. Before forwarding or delivering any received frame, the coordinator checks this cache; matching entries are silently dropped. Prevents re-delivery of frames that echoed back via multiple repeater paths. Entries leave afterDUP_CACHE_TTL_MSor when the ring recycles, whichever is first; a hashed key repeats for the life of the sender, so age is what releases it.DupCacheKey—keyed on the truncated MIC for authenticated packets (unforgeable and compact) or a 32-bit hash of the frame body for unauthenticated ones (broadcast).ReplayWindow—per-peer, per-identity sliding window over frame counters. Rejects exact counter replays and frames older than the backtrack window, while tolerating a small amount of out-of-order delivery. Backed by aRecentMicring for backward-window disambiguation.ReplayVerdict—outcome of a replay check:Accept,Duplicate, orReplay.
§[peers]—remote peer and channel registries
PeerRegistry—a flat list ofPeerInforecords (public key + last-seen time + cached route). Looked up by hint or full key when matching inbound packets and routing outbound sends.PeerId—opaque index into the peer registry.CachedRoute—a direct link, an explicit source route, or a flood-distance estimate, learned from successfully received packets and used to route future sends without unnecessary flooding.PeerCryptoMap—per-identity map fromPeerIdtoPeerCryptoState(established pairwise keys + replay window). One map perIdentitySlot.ChannelTable—flat list of registered multicast channels. Each entry stores the raw channel key, the derivedk_enc/k_mickeys (precomputed at registration time), and the 2-byte channel ID (also precomputed). Looked up by channel ID when authenticating inbound multicast and blind-unicast frames.
§[handle]—shared-ownership coordinator access
MacHandle—aCopy-able, lifetime-bounded reference to aRefCell<Mac<P>>. Designed for multi-task environments (e.g.,tokioor RTOS task pairs) where one task runs thenext_eventloop while another enqueues sends or updates configuration without holding a long-lived mutable borrow.
§Platform trait
Platform is the single integration point. Implement it once per deployment target to
supply concrete driver types for all hardware abstractions:
struct MyPlatform;
impl umsh_mac::Platform for MyPlatform {
type Identity = MyHsmIdentity;
type Aes = MyAesDriver;
type Sha = MyShaDriver;
type Radio = MySx1262Driver;
type Delay = MyDelay;
type Clock = MyMonotonicClock;
type Rng = MyTrng;
type CounterStore = MyFlashStore;
type KeyValueStore = MyNvmStore;
}The umsh workspace crate provides a std/tokio-backed implementation
(tokio_support::StdPlatform) suitable for desktop development and testing.
§Frame-counter persistence
UMSH uses a monotonic frame counter (not a timestamp) for replay protection. Because the counter must never reuse a value, it must be committed to non-volatile storage before the corresponding value is used on-air, or after a power cycle the counter could reset to a previously-seen value, allowing old ciphertexts to replay. The coordinator manages this automatically:
- On startup, call
Mac::load_persisted_counterfor each long-term identity to read the last-committed boundary from the [umsh_hal::CounterStore] and set the live counter to the next safe starting point. - At runtime, the coordinator schedules a persist whenever the live counter crosses a
block boundary (every [
COUNTER_PERSIST_BLOCK_SIZE] frames, default 128). While a persist is pending, sends will eventually block withSendError::CounterPersistenceLagif the store is not flushed in time. - The application calls
Mac::service_counter_persistence(typically from thenext_eventcallback or a background task) to drain the pending write queue.
§no_std usage
Enable default-features = false in Cargo.toml. The crate compiles without the
standard library. All capacity limits are compile-time const generics. The std feature
enables test_support, which provides software-backed driver stubs for unit testing.
Modules§
- forward_
id - Routing identity of a packet as seen by a forwarder.
- test_
support - Std-only simulated radio network and dummy platform components for tests.
Structs§
- Bearer
Id - Which of a node’s bearers a frame crossed.
- Capacity
Error - Error returned when a fixed-capacity MAC data structure is full.
- Channel
Info Ref - Borrowing view of an inbound MAC event.
- Channel
Policy - Per-channel operating-policy overrides enforced on outgoing traffic.
- Channel
State - Shared state for one multicast channel.
- Channel
Table - Fixed-capacity channel table shared by the MAC coordinator.
- Duplicate
Cache - Fixed-capacity cache of recently observed duplicate keys.
- Hint
Replay State - Replay state for a sender known only by hint.
- Identity
Slot - Per-identity runtime state owned by the
Maccoordinator. - Local
Identity Id - Opaque handle that identifies a locally registered identity within the
Maccoordinator. - Mac
- MacCounters
- Central MAC coordinator that owns and drives the full UMSH radio-facing state machine.
- MacHandle
- Lightweight, cloneable handle for queuing MAC operations against shared state.
- Operating
Policy - Local transmission policy enforced by the
Maccoordinator on all outgoing frames. - Peer
Crypto Map - Fixed-capacity map of per-peer secure transport state.
- Peer
Crypto State - Per-peer secure transport state.
- PeerId
- Opaque identifier for one remote peer.
- Peer
Info - Shared metadata tracked for a remote peer.
- Peer
Registry - Fixed-capacity registry of remote peers.
- Peer
Removal - Outcome of removing a peer from the registry.
- Peer
Route Status - A snapshot of the route to one peer, for an application to present.
- Pending
Ack - Complete tracking state for one in-flight tracked transmission.
- Queued
Tx - One entry in the
TxQueuewaiting to be transmitted by theMaccoordinator. - Received
Packet Ref - Borrowed view of one accepted inbound packet together with parsed on-wire metadata.
- Recent
Mic - Recently accepted MIC tracked for backward-window replay handling.
- Repeater
Config - Configuration governing whether and how the node forwards received frames.
- Repeater
Hints - Iterator over the packed two-byte repeater hints of a source-route or trace-route option. Each hint names one repeater, so a route yields one fewer entry than the path has hops.
- Replay
Window - Replay-detection window for secure traffic from one sender.
- Resend
Record - Sealed frame bytes and optional source route retained for retransmission.
- Route
Candidate - A learned path waiting beside a held route; see
RouteHold::candidate. - Route
Evidence - What a sender knows about the far end of the route it is about to use.
- Route
Hold - A route the application chose for a peer, kept in place until a deadline.
- RxMetadata
- Local physical-layer observations captured when a frame was received.
- Send
Options - High-level transmission options passed to
Macsend helpers. - Send
Receipt - Opaque tracking token for delivery or local transmission completion.
- Snr
- Signal-to-noise ratio represented in centibels (0.1 dB units).
- Transmitter
Observation - The most recent reception from one neighboring repeater.
- Transmitter
Observations - A bounded, least-recently-heard table of repeater observations.
- TxQueue
- Fixed-capacity, priority-ordered transmit queue owned by the
Maccoordinator.
Enums§
- AckState
- Tracks which phase of the two-stage ACK lifecycle a pending transmission is in.
- AddChannel
Error - Error returned when adding a named channel to the MAC channel table.
- AddPeer
Error - Error returned when adding a peer to the MAC peer registry.
- Amateur
Radio Mode - Controls how the coordinator and optional repeater handle amateur-radio legal requirements.
- Cached
Route - Learned routing information for a remote peer.
- Completion
Signal - The signal that completes a tracked in-flight transmission.
- Counter
Persistence Error - Errors returned while loading persisted frame-counter boundaries via
Mac::load_persisted_counter. - DupCache
Key - Duplicate-suppression key derived from an accepted packet.
- Local
Identity - A local node identity that the
Maccoordinator owns and acts on behalf of. - MacError
- Runtime errors produced by the
Maccoordinator’s async event loop. - MacEvent
Ref - Borrowing view of an inbound MAC event.
- Packet
Family - Coarser grouping of on-wire packet types.
- Pending
AckError - Errors returned when recording pending-ACK state in an identity slot.
- Replay
Verdict - Result of checking a packet against a replay window.
- Send
Error - Errors returned by the
Maccoordinator when queueing an outbound send. - TxPriority
- Priority class assigned to entries in the
TxQueue. - Wake
Reason - Why
Mac::poll_wait_for_wakereturned ready.
Constants§
- DEFAULT_
ACKS - Default pending-ACK capacity for the common
Mac<P>configuration. - DEFAULT_
CHANNELS - Default shared-channel capacity for the common
Mac<P>configuration. - DEFAULT_
CHANNEL_ HINT_ REPLAY - Default per-channel hint-only replay-window capacity.
- DEFAULT_
CHANNEL_ REPLAY - Default per-channel full-key replay-window capacity (senders tracked per channel). Each window retains up to nine MICs, so these two capacities dominate the MAC’s channel-table footprint; small targets shrink them. A full map fail-closes: frames from additional senders are dropped, never accepted unchecked.
- DEFAULT_
DUP - Default duplicate-cache capacity for the common
Mac<P>configuration. - DEFAULT_
FRAME - Default frame-buffer capacity for the common
Mac<P>configuration. - DEFAULT_
IDENTITIES - Default identity-slot capacity for the common
Mac<P>configuration. - DEFAULT_
PEERS - Default remote-peer capacity for the common
Mac<P>configuration. - DEFAULT_
ROUTE_ HOLDS - Default capacity for routes held against learning (see
PeerRegistry::hold_route). None: holding a route is something an application with a person choosing paths opts into. - DEFAULT_
TX - Default transmit-queue depth for the common
Mac<P>configuration. - DUP_
CACHE_ TTL_ MS - How long a duplicate key stays suppressed.
- ESTABLISHED_
ROUTE_ EXTRA_ FLOOD_ HOPS - The slack the policy grants, in flood hops, when it grants any.
- MAX_
CAD_ ATTEMPTS - CAD attempts a frame gets before it is dropped, from Channel Access § Backoff Procedure: one initial attempt and fifteen retries. Public because every UMSH transmitter shares the procedure—a host relaying frames onto a segment contends with the same neighbors as the MAC does, and a second opinion about how long to persist would just be a second, wrong answer.
- MAX_
FLOOD_ HOPS - Largest value the
FHOPS_REMnibble can carry. - MAX_
TRANSMITTER_ OBSERVATIONS - How many repeaters the table remembers.
- STRONG_
DIRECT_ RSSI_ DBM - A destination heard directly above this RSSI has enough link budget that the reverse direction can be trusted without a repeater backstop.
- TRACE_
ROUTE_ REFRESH_ MS - How long a packet that reached us from a peer without flooding vouches for the peer’s path here. Past it, the next packet to the peer carries a trace route so the peer can learn a fresh one.
- WEAK_
LAST_ HOP_ RSSI_ DBM - A last hop measured at or below this RSSI is weak enough that the destination may already be out of that repeater’s reach.
Traits§
- Platform
- Bundle of platform-specific associated types used by the higher layers.
Functions§
- established_
route_ slack - The flood hops a send along an established route carries past the
route’s end:
ESTABLISHED_ROUTE_EXTRA_FLOOD_HOPSor none.