# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-a2a-signed-envelopes-when-the-nonce-is-bound-to-the-sender-s-replay-window-rather-than-the-receiver-s.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-a2a-signed-envelopes-when-the-nonce-is-bound-to-the-sender-s-replay-window-rather-than-the-receiver-s.warrant.json
# Markdown SHA-256:   135e3abf5129b2dd40df7fe8717f20cc47d260f2e3ed7146c8c70bdbe6486203
# Code AST SHA-256:   7e5f0e8412cd64c82535dbdc3dd1941c4351398506273d0d813ece5ca5724daf
# Verified Classes:   NonceEpochViolation, Envelope, ReceiverReplayGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class NonceEpochViolation(RuntimeError):
    """Raised when an A2A envelope's nonce cannot be bound to a receiver-verifiable epoch."""
    pass


class Envelope:
    def __init__(self, sender_id, boot_id, epoch_id, seq, nonce, payload, sig):
        self.sender_id = sender_id
        self.boot_id = boot_id
        self.epoch_id = epoch_id
        self.seq = seq
        self.nonce = nonce
        self.payload = payload
        self.sig = sig


class ReceiverReplayGuard:
    def __init__(self, known_epochs, max_rewind_window):
        self.known_epochs = known_epochs          # epoch_id -> issuer signature, set by receiver
        self.max_rewind_window = max_rewind_window
        self.last_boot_id = {}                    # sender_id -> boot_id
        self.high_water_seq = {}                  # sender_id -> int
        self.seen_nonces = {}                     # (sender_id, nonce) -> epoch_id

    def accept(self, env: Envelope, sig_ok: bool) -> bool:
        if not sig_ok:
            raise NonceEpochViolation(f"bad signature from {env.sender_id}")

        # Invariant: nonce must be bound to a receiver-issued epoch.
        if env.epoch_id not in self.known_epochs:
            raise NonceEpochViolation(
                f"epoch {env.epoch_id} for sender {env.sender_id} not issued by this receiver"
            )

        prev_boot = self.last_boot_id.get(env.sender_id)
        if prev_boot is not None and prev_boot != env.boot_id:
            # Sender restarted: local counter may have rewound. Force re-handshake.
            raise NonceEpochViolation(
                f"sender {env.sender_id} boot_id changed {prev_boot}->{env.boot_id}; "
                f"require epoch re-establishment before accepting seq={env.seq}"
            )

        key = (env.sender_id, env.nonce)
        if key in self.seen_nonces:
            return False  # genuine duplicate within live epoch

        hw = self.high_water_seq.get(env.sender_id, -1)
        if env.seq <= hw and prev_boot == env.boot_id:
            # Same boot, seq went backwards: replay or corruption.
            return False

        self.seen_nonces[key] = env.epoch_id
        self.high_water_seq[env.sender_id] = max(hw, env.seq)
        self.last_boot_id[env.sender_id] = env.boot_id
        return True

    def prune(self, sender_id, up_to_nonce_seq, attested_by_sender: bool):
        # Only prune when the sender has attested its counter has advanced past
        # the pruned range within the current epoch. Otherwise the TTL hole reopens.
        if not attested_by_sender:
            raise NonceEpochViolation(
                f"refusing to prune nonces for {sender_id} without sender attestation"
            )
        for (sid, nonce) in list(self.seen_nonces):
            if sid == sender_id and nonce <= up_to_nonce_seq:
                del self.seen_nonces[(sid, nonce)]
