# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-equivocation-evidence-in-a-bft-agent-quorum-until-the-slashing-warrant-is-cosigned-by-a-supermajority-of-t.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-equivocation-evidence-in-a-bft-agent-quorum-until-the-slashing-warrant-is-cosigned-by-a-supermajority-of-t.warrant.json
# Markdown SHA-256:   1e80c0cff1463a17c16fc73fc0f794daea55c90e1486c0670f309f5d2e11ce95
# Code AST SHA-256:   4b4d1c3b1395ae56a5064792d430773bb714e29a2d3d74548bc0d15b1f7b3ccf
# Verified Classes:   EvidenceReleaseViolation, EquivocationProof, Warrant, EscrowLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EvidenceReleaseViolation(RuntimeError):
    """Raised when equivocation evidence is disclosed before warrant cosigning."""
    pass


@dataclass(frozen=True)
class EquivocationProof:
    accused: str
    view: int
    vote_a: bytes
    vote_b: bytes

    def commitment(self) -> str:
        h = hashlib.sha256()
        h.update(self.accused.encode())
        h.update(self.view.to_bytes(8, "big"))
        h.update(self.vote_a)
        h.update(self.vote_b)
        return h.hexdigest()


@dataclass
class Warrant:
    proof_commitment: str
    accused: str
    view: int
    cosigners: Set[str] = field(default_factory=set)

    def cosign(self, member: str) -> None:
        self.cosigners.add(member)

    def is_committed(self, f: int) -> bool:
        # f+1 independent cosignatures make the warrant irrevocable
        return len(self.cosigners) >= f + 1


class EscrowLedger:
    """Holds equivocation proofs locally until their warrants are cosigned."""

    def __init__(self, quorum_size: int, f: int):
        self.n = quorum_size
        self.f = f
        self._escrowed: Dict[str, EquivocationProof] = {}
        self._warrants: Dict[str, Warrant] = {}

    def escrow(self, proof: EquivocationProof) -> str:
        c = proof.commitment()
        self._escrowed[c] = proof
        self._warrants[c] = Warrant(c, proof.accused, proof.view)
        return c

    def cosign(self, commitment: str, member: str) -> None:
        if commitment not in self._warrants:
            raise EvidenceReleaseViolation(
                f"no warrant for commitment {commitment[:12]}"
            )
        self._warrants[commitment].cosign(member)

    def release(self, commitment: str) -> EquivocationProof:
        warrant = self._warrants.get(commitment)
        if warrant is None:
            raise EvidenceReleaseViolation("unknown commitment")
        if not warrant.is_committed(self.f):
            # The exact boundary: disclosure before f+1 cosignatures is the bug.
            raise EvidenceReleaseViolation(
                f"warrant against {warrant.accused} at view {warrant.view} "
                f"has only {len(warrant.cosigners)}/{self.f + 1} cosignatures; "
                "releasing now exposes accuser to counter-evidence"
            )
        # Liveness guard: accused + accuser quarantine must not break threshold.
        if self.n - 2 < 2 * self.f + 1:
            raise EvidenceReleaseViolation(
                "releasing this warrant would drop effective membership "
                "below 2f+1; escrow is mandatory for this quorum shape"
            )
        return self._escrowed.pop(commitment)


def handle_accusation(
    ledger: EscrowLedger,
    proof: EquivocationProof,
    cosigners: Set[str],
) -> EquivocationProof:
    c = ledger.escrow(proof)
    for member in cosigners:
        ledger.cosign(c, member)
    return ledger.release(c)
