# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-quorum-before-committing-shared-agent-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-quorum-before-committing-shared-agent-state.warrant.json
# Markdown SHA-256:   b6f5f331a6a5c7c737d0c3bb0196c0ab0b87e1ecce1aee9a1befd098d3b11530
# Code AST SHA-256:   319e3b0f2bab8f4efb13afe0ccbb85bf25227969fcc21ef6cdc4eb06de29dd03
# Verified Classes:   EquivocationDetected, SignedProposal, CommitmentLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when one identity signed two conflicting proposals in one view."""
    pass


@dataclass(frozen=True)
class SignedProposal:
    signer: str
    view: int
    proposal_hash: str
    signature: str  # assumed already verified against signer's key


class CommitmentLedger:
    def __init__(self, quorum_size: int):
        self.quorum_size = quorum_size
        # Retain raw envelopes per (signer, view) so conflicting pairs can be assembled.
        self._envelopes: Dict[Tuple[str, int], List[SignedProposal]] = {}
        self._committed: Dict[int, str] = {}

    def record(self, env: SignedProposal) -> None:
        key = (env.signer, env.view)
        seen = self._envelopes.setdefault(key, [])
        if env not in seen:
            seen.append(env)
        # Equivocation invariant: same signer, same view, differing hashes.
        hashes = {e.proposal_hash for e in seen}
        if len(hashes) > 1:
            proof = tuple(seen)
            raise EquivocationDetected(
                f"signer={env.signer} view={env.view} signed conflicting "
                f"proposals {sorted(hashes)}; broadcast proof={proof}"
            )

    def try_commit(self, view: int, proposal_hash: str,
                   cert: List[SignedProposal]) -> None:
        # Proposal-binding: every signature must bind the identical tuple.
        if any(e.view != view or e.proposal_hash != proposal_hash for e in cert):
            raise EquivocationDetected(
                f"certificate for view={view} hash={proposal_hash} is not "
                f"proposal-bound; mixed signatures detected"
            )
        distinct = {e.signer for e in cert}
        if len(distinct) < self.quorum_size:
            return  # insufficient quorum; remain uncommitted
        # Provisional commit: valid only until epoch closes without fault proof.
        self._committed[view] = proposal_hash
