# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-replayed-a2a-envelopes-from-silently-rebinding-to-a-fresh-sender-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-replayed-a2a-envelopes-from-silently-rebinding-to-a-fresh-sender-identity.warrant.json
# Markdown SHA-256:   c1de3ddf3d3b01eb3803c32bc36d3953bdd1494537dc76d002a31adb46c5e4c5
# Code AST SHA-256:   48b4424ead46441407ed1c380fa841796a871bf7067668f826454b7da44d1a9a
# Verified Classes:   EnvelopeBindingError, Envelope, ReplayGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EnvelopeBindingError(RuntimeError):
    """Raised when a signed envelope's identity binding cannot be proven."""
    pass


@dataclass(frozen=True)
class Envelope:
    sender_id: str
    key_id: str
    seq: int
    nonce: bytes
    ciphertext: bytes
    signature: bytes


class ReplayGuard:
    def __init__(self, trust_sets, watermarks):
        # trust_sets: {sender_id: {key_id: pubkey_bytes}}
        # watermarks: {sender_id: int}  -- persists across key rotation
        self.trust_sets = trust_sets
        self.watermarks = watermarks
        self.seen_nonces = {}

    def _resolve_key(self, env: Envelope) -> bytes:
        # Invariant 2: resolve key ONLY within the signed sender's namespace.
        sender_keys = self.trust_sets.get(env.sender_id)
        if sender_keys is None:
            raise EnvelopeBindingError(
                f"unknown sender identity {env.sender_id!r}; refusing global key fallback"
            )
        pub = sender_keys.get(env.key_id)
        if pub is None:
            raise EnvelopeBindingError(
                f"key_id {env.key_id!r} not bound to sender {env.sender_id!r}"
            )
        return pub

    def _dedup_key(self, env: Envelope) -> bytes:
        # Invariant 1: dedup key derived from signed fields only.
        h = hashlib.sha256()
        h.update(env.sender_id.encode())
        h.update(env.seq.to_bytes(8, "big"))
        h.update(env.nonce)
        return h.digest()

    def accept(self, env: Envelope, verify) -> bool:
        pub = self._resolve_key(env)  # hard reject on binding failure
        if not verify(pub, env):
            raise EnvelopeBindingError("signature invalid under bound key")
        # Invariant 3: watermark is per-identity, monotonic across key_id.
        wm = self.watermarks.get(env.sender_id, 0)
        if env.seq <= wm:
            return False
        nonces = self.seen_nonces.setdefault(env.sender_id, set())
        if env.nonce in nonces:
            return False
        nonces.add(env.nonce)
        self.watermarks[env.sender_id] = env.seq
        return True
