# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-quorum-fence-its-own-equivocation-before-byzantine-agreement-can-bind.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-quorum-fence-its-own-equivocation-before-byzantine-agreement-can-bind.warrant.json
# Markdown SHA-256:   ed633004ddd978686208e7bade374636e308d906bb06097665acf3a9337caf48
# Code AST SHA-256:   065dd40bffd83ae262599878275b597e6cb97b3374fc1c93b095d660d1c13262
# Verified Classes:   EquivocationDetected, QuorumCertificateInvalid, Vote, QuorumLedger
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EquivocationDetected(RuntimeError):
    """Raised when a voter emits two distinct values for the same (round, proposal)."""
    pass


class QuorumCertificateInvalid(RuntimeError):
    """Raised when a certificate's vote set does not satisfy the sound-quorum invariant."""
    pass


@dataclass(frozen=True)
class Vote:
    voter_id: str
    round_id: str
    proposal_hash: str
    context_hash: str
    value: str
    commit_hash: str  # hash(value || context_hash || seed), published before reveal


@dataclass
class QuorumLedger:
    n: int
    f: int
    _commits: dict = field(default_factory=dict)   # (round, proposal, voter) -> commit_hash
    _reveals: dict = field(default_factory=dict)   # (round, proposal, voter) -> Vote

    @property
    def threshold(self) -> int:
        return 2 * self.f + 1

    def commit(self, voter_id: str, round_id: str, proposal_hash: str, commit_hash: str) -> None:
        key = (round_id, proposal_hash, voter_id)
        if key in self._commits and self._commits[key] != commit_hash:
            raise EquivocationDetected(
                f"voter {voter_id} committed two distinct hashes in round {round_id}"
            )
        self._commits[key] = commit_hash

    def reveal(self, vote: Vote) -> None:
        key = (vote.round_id, vote.proposal_hash, vote.voter_id)
        if key not in self._commits:
            raise QuorumCertificateInvalid(
                f"voter {vote.voter_id} revealed without prior commit in round {vote.round_id}"
            )
        if self._commits[key] != vote.commit_hash:
            raise EquivocationDetected(
                f"voter {vote.voter_id} reveal does not match commit in round {vote.round_id}"
            )
        prior = self._reveals.get(key)
        if prior is not None and prior.value != vote.value:
            # The core failure: same voter, same round, same proposal, two values.
            raise EquivocationDetected(
                f"voter {vote.voter_id} equivocated in round {vote.round_id}: "
                f"{prior.value!r} vs {vote.value!r}"
            )
        self._reveals[key] = vote

    def certify(self, round_id: str, proposal_hash: str) -> str:
        round_votes = [
            v for (r, p, _), v in self._reveals.items()
            if r == round_id and p == proposal_hash
        ]
        # Invariant 1: certificate is round-local. No cross-round laundering.
        if len(round_votes) < self.threshold:
            raise QuorumCertificateInvalid(
                f"round {round_id}: only {len(round_votes)} round-local votes, "
                f"need {self.threshold}"
            )
        # Invariant 2: every voter in the certificate committed before revealing.
        for v in round_votes:
            if (v.round_id, v.proposal_hash, v.voter_id) not in self._commits:
                raise QuorumCertificateInvalid(
                    f"voter {v.voter_id} in certificate without commit"
                )
        # Invariant 3: certificate value must be internally consistent.
        values = {v.value for v in round_votes}
        if len(values) != 1:
            raise QuorumCertificateInvalid(
                f"round {round_id}: certificate spans values {values}"
            )
        return values.pop()
