# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-byzantine-equivocation-in-agent-swarms-when-signed-votes-are-replayed-across-rotated-quorum-epochs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-byzantine-equivocation-in-agent-swarms-when-signed-votes-are-replayed-across-rotated-quorum-epochs.warrant.json
# Markdown SHA-256:   c8dc3bdc86046c1a21a2ba1898241c877ee54d6d77ff33507fb6ecbc7c2171be
# Code AST SHA-256:   8a93b1097f19878b082e7c2c09c166ed850cce268b2db52e1a36f8424a7d44e9
# Verified Classes:   EpochBindingViolation, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EpochBindingViolation(RuntimeError):
    """Raised when a vote's epoch does not match the verifier's current epoch
    in a way that indicates replay, forgery, or detector misconfiguration."""
    pass


@dataclass(frozen=True)
class Vote:
    signer: str
    epoch: int
    decision: str
    signature: bytes


def derive_epoch_key(identity_secret: bytes, epoch: int) -> bytes:
    # Epoch-scoped key: the admissibility primitive.
    return hashlib.sha256(identity_secret + epoch.to_bytes(8, "big")).digest()


def verify_vote(vote: Vote, current_epoch: int,
                epoch_key_commitments: dict) -> bool:
    # 1. Monotonicity: reject stale and future votes before any tally.
    if vote.epoch < current_epoch:
        raise EpochBindingViolation(
            f"stale vote from {vote.signer}: epoch {vote.epoch} < {current_epoch}"
        )
    if vote.epoch > current_epoch:
        raise EpochBindingViolation(
            f"future-epoch vote from {vote.signer}: epoch {vote.epoch} > {current_epoch}"
        )
    # 2. Epoch-scoped signature check. The commitment for (signer, epoch)
    #    must exist; absence means the verifier cannot bind the vote.
    expected = epoch_key_commitments.get((vote.signer, vote.epoch))
    if expected is None:
        raise EpochBindingViolation(
            f"no epoch-key commitment for ({vote.signer}, {vote.epoch})"
        )
    return vote.signature == expected


def detect_equivocation(votes: list[Vote], current_epoch: int) -> set[str]:
    # Epoch-bucketed detector: only same-epoch conflicts count.
    by_signer_epoch: dict[tuple[str, int], set[str]] = {}
    for v in votes:
        if v.epoch != current_epoch:
            continue  # stale/future votes never enter the detector
        by_signer_epoch.setdefault((v.signer, v.epoch), set()).add(v.decision)
    return {s for (s, _e), decisions in by_signer_epoch.items() if len(decisions) > 1}
