# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/what-communication-invariants-prevent-message-replay-in-a-decentralized-agent-swarm.md # Remnant Warrant: https://corpusfetch.com/c/what-communication-invariants-prevent-message-replay-in-a-decentralized-agent-swarm.warrant.json # Markdown SHA-256: 4ca8f3c9be0f99711fb1e257df7486be95b2f8339c0a3f3c9b186ab09927cd9a # Code AST SHA-256: 621fff4a2ab5e017d03a84d2ac14c83f31b12fb49562b235d3b25a4f621872e0 # Verified Classes: ReplayVerdict, SwarmMessage, ReceiverState, ReplayManifest, DecentralizedReplayGuard # Defensive Guards: 0 fail-closed invariants (zero external deps) from dataclasses import dataclass from enum import Enum, auto import hashlib import json class ReplayVerdict(Enum): FRESH_MESSAGE = auto() REPLAY_DETECTED = auto() STALE_MESSAGE = auto() EXPIRED_MESSAGE = auto() @dataclass(frozen=True) class SwarmMessage: message_id: str sender_vector_clock_hash: str timestamp_epoch: float signature: str @dataclass(frozen=True) class ReceiverState: seen_message_hashes: frozenset[str] current_vector_clock_hash: str current_epoch: float freshness_window_sec: float @dataclass(frozen=True) class ReplayManifest: verdict: ReplayVerdict directive: str manifest_digest: str class DecentralizedReplayGuard: @staticmethod def _hash(data: str) -> str: return hashlib.sha256(data.encode("utf-8")).hexdigest() @classmethod def evaluate_message( cls, msg: SwarmMessage, state: ReceiverState ) -> ReplayManifest: # Gate 1: Deduplication if msg.message_id in state.seen_message_hashes: return ReplayManifest( verdict=ReplayVerdict.REPLAY_DETECTED, directive=f"HALT: Message {msg.message_id} already seen. Replay attack.", manifest_digest=cls._hash(f"REPLAY:{msg.message_id}") ) # Gate 2: Freshness window age = state.current_epoch - msg.timestamp_epoch if age > state.freshness_window_sec: return ReplayManifest( verdict=ReplayVerdict.EXPIRED_MESSAGE, directive=f"HALT: Message is {age:.0f}s old, exceeding {state.freshness_window_sec:.0f}s window.", manifest_digest=cls._hash(f"EXPIRED:{msg.message_id}") ) # Gate 3: Vector clock if msg.sender_vector_clock_hash == state.current_vector_clock_hash: # Same clock = likely stale or replayed return ReplayManifest( verdict=ReplayVerdict.STALE_MESSAGE, directive=f"HALT: Message vector clock matches current. Likely stale.", manifest_digest=cls._hash(f"STALE:{msg.message_id}") ) # Gate 4: Fresh digest = cls._hash(json.dumps({ "message": msg.message_id, "timestamp": f"{msg.timestamp_epoch:.0f}", "clock": msg.sender_vector_clock_hash }, sort_keys=True)) return ReplayManifest( verdict=ReplayVerdict.FRESH_MESSAGE, directive="PROCEED: Message is fresh and not a replay.", manifest_digest=digest )