# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-when-committing-a-multi-agent-plan-under-bft-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-when-committing-a-multi-agent-plan-under-bft-consensus.warrant.json
# Markdown SHA-256:   f37bb1c28c4d86df87f755bba30a3cb1ac8c8ed386f7cee524b2637addd1a256
# Code AST SHA-256:   6076899b3eb64c5acc662556c5581325e7484aa9b67c6a7961f2b974a278423a
# Verified Classes:   EquivocationDetected, UnresolvedHearsayDispute, SignedVote, VoteCache
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when two signed votes from the same key conflict on (round, hash)."""
    pass


class UnresolvedHearsayDispute(RuntimeError):
    """Raised when peers accuse each other of equivocation without signed proof."""
    pass


@dataclass(frozen=True)
class SignedVote:
    round: int
    proposal_hash: str
    value: str          # "COMMIT" | "ABORT"
    signer: str
    signature: str      # signature over (round, proposal_hash, value)


def _sig_payload(v: SignedVote) -> str:
    return f"{v.round}|{v.proposal_hash}|{v.value}"


def _verify(v: SignedVote, pubkey: str) -> bool:
    # Placeholder for real Ed25519 verification.
    expected = hashlib.sha256((_sig_payload(v) + pubkey).encode()).hexdigest()
    return v.signature == expected


class VoteCache:
    """Write-once cache keyed by (round, proposal_hash). Enforces vote uniqueness."""

    def __init__(self) -> None:
        self._store: Dict[Tuple[int, str], SignedVote] = {}

    def record_or_reuse(self, candidate: SignedVote) -> SignedVote:
        key = (candidate.round, candidate.proposal_hash)
        if key in self._store:
            prior = self._store[key]
            if prior.value != candidate.value:
                raise EquivocationDetected(
                    f"local equivocation at round={candidate.round} "
                    f"hash={candidate.proposal_hash}: cached={prior.value} "
                    f"new={candidate.value}"
                )
            return prior  # reuse the original signed vote
        self._store[key] = candidate
        return candidate


def check_certificate(votes: list[SignedVote], pubkeys: Dict[str, str],
                      quorum: int, round_no: int, proposal_hash: str) -> str:
    """Validate a quorum certificate: value-bound, signature-checked, equivocation-free."""
    by_signer: Dict[str, SignedVote] = {}
    for v in votes:
        if v.round != round_no or v.proposal_hash != proposal_hash:
            raise EquivocationDetected(
                f"vote for wrong round/hash: got ({v.round},{v.proposal_hash}) "
                f"expected ({round_no},{proposal_hash})"
            )
        if v.signer not in pubkeys or not _verify(v, pubkeys[v.signer]):
            raise EquivocationDetected(f"bad signature from {v.signer}")
        if v.signer in by_signer:
            prior = by_signer[v.signer]
            if prior.value != v.value:
                raise EquivocationDetected(
                    f"equivocation proof: {v.signer} signed {prior.value} and {v.value} "
                    f"on round={round_no} hash={proposal_hash}"
                )
        by_signer[v.signer] = v

    values = {v.value for v in by_signer.values()}
    if len(values) != 1:
        raise EquivocationDetected(
            f"certificate spans multiple values {values} on round={round_no}"
        )
    if len(by_signer) < quorum:
        raise EquivocationDetected(
            f"insufficient quorum: {len(by_signer)} < {quorum}"
        )
    return values.pop()


def resolve_hearsay(accuser_a: SignedVote | None, accuser_b: SignedVote | None,
                    pubkeys: Dict[str, str]) -> None:
    """Hearsay without signed transcripts is indeterminate; refuse to advance."""
    if accuser_a is None or accuser_b is None:
        raise UnresolvedHearsayDispute(
            "conflicting accusations without signed vote transcripts; "
            "cannot attribute equivocation, refusing to advance round"
        )
    if accuser_a.value == accuser_b.value:
        raise UnresolvedHearsayDispute("accusations agree; no equivocation proven")
    # Both transcripts present and conflicting: this IS proof.
    raise EquivocationDetected(
        f"equivocation confirmed via transcripts from {accuser_a.signer}"
    )
