# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-quorum-equivocation-when-auditors-vote-on-divergent-state-roots-in-a-byzantine-agent-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-quorum-equivocation-when-auditors-vote-on-divergent-state-roots-in-a-byzantine-agent-swarm.warrant.json
# Markdown SHA-256:   3baf5ba6d341d24a31a5f88d64271a91fd6e0f82d82393c2d9073151392f6868
# Code AST SHA-256:   9635db22943a6d835afaf0cf07069d9ce6af14e0d62e51b96f2b678e016ed3d2
# Verified Classes:   QuorumEquivocationError, Vote, QuorumCoordinator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumEquivocationError(RuntimeError):
    """Raised when an auditor identity contributes divergent votes to one round."""


@dataclass(frozen=True)
class Vote:
    identity: str
    round_id: str
    state_root: str
    input_digest: str
    signature: str


def _digest(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


class QuorumCoordinator:
    def __init__(self, n: int, f: int):
        if n < 3 * f + 1:
            raise QuorumEquivocationError(
                f"quorum params invalid: n={n} cannot tolerate f={f}"
            )
        self.n, self.f = n, f
        self.quorum = 2 * f + 1
        # (identity, round_id) -> Vote, for fork detection
        self._seen: dict[tuple[str, str], Vote] = {}
        # round_id -> {state_root: set(identity)}
        self._tally: dict[str, dict[str, set[str]]] = {}

    def submit(self, vote: Vote) -> str | None:
        key = (vote.identity, vote.round_id)
        prior = self._seen.get(key)

        if prior is not None:
            if prior.input_digest != vote.input_digest:
                # Same identity, same round, divergent input -> equivocation.
                # Freeze the round; do not count either vote.
                self._tally.pop(vote.round_id, None)
                raise QuorumEquivocationError(
                    f"fork: identity={vote.identity} round={vote.round_id} "
                    f"input_digest {prior.input_digest[:8]}.. != {vote.input_digest[:8]}.."
                )
            if prior.state_root != vote.state_root:
                # Same input, different root -> Byzantine signer.
                raise QuorumEquivocationError(
                    f"byzantine: identity={vote.identity} signed two roots "
                    f"for input_digest={vote.input_digest[:8]}.."
                )
            return None  # benign retry, count once

        self._seen[key] = vote
        roots = self._tally.setdefault(vote.round_id, {})
        roots.setdefault(vote.state_root, set()).add(vote.identity)

        winners = [r for r, ids in roots.items() if len(ids) >= self.quorum]
        if len(winners) > 1:
            raise QuorumEquivocationError(
                f"double-quorum on round={vote.round_id}: roots={winners}"
            )
        return winners[0] if winners else None
