# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-tool-call-commitment-quorum-before-committing-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-tool-call-commitment-quorum-before-committing-side-effects.warrant.json
# Markdown SHA-256:   fe1035302e88b32e4a155ee8b0c15d3910c5c66d9fdb9aea2d6a2d8e63747d32
# Code AST SHA-256:   f1a481b4e567b872961c444566e5c19caa2ba5a9d2731e04422b766af2e0cc7d
# Verified Classes:   Commitment, Prepare, EquivocationDetected, InsufficientCertificate, CommitGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Tuple, Optional

@dataclass(frozen=True)
class Commitment:
    batch_id: str
    slot: int
    view: int
    hash: str

@dataclass
class Prepare:
    commitment: Commitment
    signer: str          # replica id
    signature: bytes     # binds (batch_id, slot, view, hash)

class EquivocationDetected(RuntimeError):
    """Raised when a leader has signed conflicting commitments for one slot."""
    pass

class InsufficientCertificate(RuntimeError):
    """Raised when a commit is attempted without 2f+1 distinct signers."""
    pass

class CommitGuard:
    def __init__(self, n: int, f: int, local_view: int):
        self.n, self.f = n, f
        self.local_view = local_view
        self.prepares: Dict[Tuple[str, int], Dict[str, Prepare]] = {}
        self.conflicts: Set[Tuple[str, int]] = set()

    def _key(self, c: Commitment) -> Tuple[str, int]:
        return (c.batch_id, c.slot)

    def on_prepare(self, p: Prepare) -> None:
        c = p.commitment
        if c.view < self.local_view:
            return  # stale view: ignore, never execute
        key = self._key(c)
        slot_map = self.prepares.setdefault(key, {})
        existing = slot_map.get(p.signer)
        if existing is not None and existing.commitment.hash != c.hash:
            # Same signer, same slot, different hash -> self-authenticating equivocation.
            self.conflicts.add(key)
            raise EquivocationDetected(
                f"signer {p.signer} signed {existing.commitment.hash} and {c.hash} "
                f"for {key} in view {c.view}"
            )
        slot_map[p.signer] = p

    def certificate_signers(self, c: Commitment) -> Set[str]:
        key = self._key(c)
        if key in self.conflicts:
            raise EquivocationDetected(f"slot {key} is conflicted; refusing certificate")
        return {
            signer
            for signer, p in self.prepares.get(key, {}).items()
            if p.commitment.hash == c.hash and p.commitment.view == c.view
        }

    def try_commit(self, c: Commitment) -> bool:
        if self._key(c) in self.conflicts:
            raise EquivocationDetected(f"cannot commit conflicted slot {self._key(c)}")
        signers = self.certificate_signers(c)
        if len(signers) < 2 * self.f + 1:
            raise InsufficientCertificate(
                f"hash {c.hash} for {self._key(c)} has {len(signers)} distinct "
                f"signers, need {2 * self.f + 1}"
            )
        return True  # caller may now execute the tool call exactly once
