# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-heterogeneous-peer-when-its-own-vote-is-non-deterministic.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-heterogeneous-peer-when-its-own-vote-is-non-deterministic.warrant.json
# Markdown SHA-256:   f82b5c867ff7daf56d6d7d4303947f926011d40f2eee1d4572c88fcc5f0340d0
# Code AST SHA-256:   501b9e0bba0afd58e143106a11611196c4ef9473faa336543529ded105cad3f4
# Verified Classes:   EquivocationBoundaryError, SignedVote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationBoundaryError(RuntimeError):
    """Raised when the equivocation predicate cannot be soundly evaluated
    because the commitment-binding invariant is not satisfied."""
    pass


@dataclass(frozen=True)
class SignedVote:
    replica_id: str
    round_id: int
    nonce: str          # committed BEFORE sampling
    value_hash: str
    signature: str


def classify_same_round_pair(a: SignedVote, b: SignedVote) -> str:
    """Return 'duplicate' | 'equivocation' | 'resampling'.
    Sound only if nonces were pre-broadcast at round start."""
    if a.replica_id != b.replica_id or a.round_id != b.round_id:
        raise EquivocationBoundaryError(
            f"pair not same-replica same-round: {a.replica_id}/{a.round_id} vs "
            f"{b.replica_id}/{b.round_id}"
        )
    if a.nonce == b.nonce:
        if a.value_hash == b.value_hash:
            return "duplicate"
        # one commitment, two contradictory payloads -> Byzantine
        return "equivocation"
    # two commitments, two payloads -> honest stochastic resampling
    return "resampling"


def audit_round(votes: list[SignedVote], prebroadcast_nonces: dict[str, set[str]]) -> dict:
    """Audit a round. Reject votes whose nonce was never pre-broadcast,
    then classify all same-replica pairs."""
    for v in votes:
        if v.nonce not in prebroadcast_nonces.get(v.replica_id, set()):
            raise EquivocationBoundaryError(
                f"replica {v.replica_id} voted with nonce {v.nonce} that was "
                f"not pre-broadcast at round start; cannot distinguish "
                f"resampling from laundered equivocation"
            )
    by_replica: dict[str, list[SignedVote]] = {}
    for v in votes:
        by_replica.setdefault(v.replica_id, []).append(v)

    result = {"equivocations": [], "resamplings": [], "duplicates": []}
    for rid, vs in by_replica.items():
        for i in range(len(vs)):
            for j in range(i + 1, len(vs)):
                verdict = classify_same_round_pair(vs[i], vs[j])
                if verdict == "equivocation":
                    result["equivocations"].append(rid)
                elif verdict == "resampling":
                    result["resamplings"].append(rid)
                else:
                    result["duplicates"].append(rid)
    return result
