# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-equivocation-in-byzantine-multi-agent-consensus-when-signed-votes-are-valid-but-the-proposal-hash-diverges.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-equivocation-in-byzantine-multi-agent-consensus-when-signed-votes-are-valid-but-the-proposal-hash-diverges.warrant.json
# Markdown SHA-256:   ec93a57204bdea2b1ecb70c6200ef886b44a200d9b3ef4470d5b510fcdba7191
# Code AST SHA-256:   7d663eda659a2fbaf3e7f1d98c1d30faa55b611c20ecb643e501b14cf76bd4ea
# Verified Classes:   EquivocationDetected, Vote, QuorumTally
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple, List


class EquivocationDetected(RuntimeError):
    """Raised when a voter signs two different proposal hashes for the same (view, height)."""
    pass


@dataclass(frozen=True)
class Vote:
    voter: str
    view: int
    height: int
    proposal_hash: str
    signature: bytes  # assumed already verified


@dataclass
class QuorumTally:
    threshold: int
    # (voter, view, height) -> set of hashes that voter signed for that slot
    seen: Dict[Tuple[str, int, int], set] = field(default_factory=dict)
    # (view, height) -> hash -> set of voters
    counts: Dict[Tuple[int, int], Dict[str, set]] = field(default_factory=dict)

    def ingest(self, vote: Vote) -> None:
        slot = (vote.voter, vote.view, vote.height)
        hashes = self.seen.setdefault(slot, set())
        hashes.add(vote.proposal_hash)

        if len(hashes) > 1:
            # Provable equivocation: same voter, same slot, conflicting hashes.
            # The whole vote set for this height is now untrustworthy.
            raise EquivocationDetected(
                f"voter {vote.voter} signed {sorted(hashes)} at "
                f"view={vote.view} height={vote.height}; "
                f"quarantine height and roll back to last certified checkpoint"
            )

        slot_counts = self.counts.setdefault((vote.view, vote.height), {})
        slot_counts.setdefault(vote.proposal_hash, set()).add(vote.voter)

    def certified_hash(self, view: int, height: int) -> str:
        slot_counts = self.counts.get((view, height), {})
        winners = [h for h, voters in slot_counts.items() if len(voters) >= self.threshold]
        if len(winners) > 1:
            # Two hashes each reached threshold: the vote set was forked.
            raise EquivocationDetected(
                f"forked quorum at view={view} height={height}: "
                f"multiple hashes reached threshold {self.threshold}: {winners}"
            )
        if not winners:
            raise EquivocationDetected(
                f"no quorum at view={view} height={height}"
            )
        return winners[0]
