MatterEx.Protocol.Counter (matter_ex v0.3.1)

Copy Markdown View Source

Message counter management and sliding-window replay protection.

Each session has its own counter for outgoing messages and a per-peer sliding window for incoming replay detection. State is a plain struct — thread it through your session state.

Summary

Functions

Check if an incoming message counter is valid (not a replay).

Create new counter state with a random initial value.

Create counter state with a specific initial value (for testing).

Get the next counter value and advance the counter.

Types

t()

@type t() :: %MatterEx.Protocol.Counter{
  local_counter: non_neg_integer(),
  peer_windows: %{required(term()) => {non_neg_integer(), non_neg_integer()}}
}

Functions

check_and_update(state, peer_id, counter)

@spec check_and_update(t(), term(), non_neg_integer()) ::
  {:ok, t()} | {:error, :duplicate | :too_old}

Check if an incoming message counter is valid (not a replay).

peer_id is any term identifying the sender.

Returns:

  • {:ok, new_state} — counter accepted, window updated
  • {:error, :duplicate} — counter already seen
  • {:error, :too_old} — counter too far behind the window

new()

@spec new() :: t()

Create new counter state with a random initial value.

new(initial)

@spec new(non_neg_integer()) :: t()

Create counter state with a specific initial value (for testing).

next(state)

@spec next(t()) :: {non_neg_integer(), t()}

Get the next counter value and advance the counter.