# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-commit-barrier-in-multi-agent-shared-state-agreement-equivocation-quorum-deadlock-at-the-f-1-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-commit-barrier-in-multi-agent-shared-state-agreement-equivocation-quorum-deadlock-at-the-f-1-boundary.warrant.json
# Markdown SHA-256:   3a3f081c553ea204e54e051e475cc39e241014635837ef25fb8e7ddfc027d60c
# Code AST SHA-256:   84e9b9853a4ee809817efb0866ee96c3ca18fe0e35ad9b137a265596d1254201
# Verified Classes:   ByzantineEquivocationBarrier, CommitCertificate, CertificateReconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ByzantineEquivocationBarrier(RuntimeError):
    """Raised when two distinct valid quorum certificates exist for the
    same (epoch, proposal_id) — the f+1 equivocation boundary was crossed."""
    pass


@dataclass(frozen=True)
class CommitCertificate:
    epoch: int
    proposal_id: str
    view: int
    signers: Tuple[str, ...]
    payload_hash: str  # hash over (epoch, proposal_id, view, signers)

    @staticmethod
    def build(epoch: int, proposal_id: str, view: int, signers: Tuple[str, ...]) -> "CommitCertificate":
        h = hashlib.sha256(
            f"{epoch}|{proposal_id}|{view}|{','.join(sorted(signers))}".encode()
        ).hexdigest()
        return CommitCertificate(epoch, proposal_id, view, tuple(sorted(signers)), h)


class CertificateReconciler:
    """Reconciles commit certificates. Fails closed on equivocation."""

    def __init__(self, n: int, f: int) -> None:
        self.n = n
        self.f = f
        self.threshold = 2 * f + 1
        # key: (epoch, proposal_id) -> set of distinct payload_hashes
        self._seen: Dict[Tuple[int, str], Set[str]] = {}

    def admit(self, cert: CommitCertificate) -> CommitCertificate:
        if len(cert.signers) < self.threshold:
            raise ByzantineEquivocationBarrier(
                f"certificate for epoch={cert.epoch} prop={cert.proposal_id} "
                f"has {len(cert.signers)} signers < threshold {self.threshold}"
            )
        key = (cert.epoch, cert.proposal_id)
        hashes = self._seen.setdefault(key, set())
        hashes.add(cert.payload_hash)
        if len(hashes) > 1:
            # Two distinct valid certificates for the same commitment.
            # Do NOT collapse by proposal_id. Halt.
            raise ByzantineEquivocationBarrier(
                f"equivocation at epoch={cert.epoch} prop={cert.proposal_id}: "
                f"{len(hashes)} distinct certificates {sorted(hashes)}"
            )
        return cert


# --- demonstration of the boundary crossing ---
def simulate_equivocation() -> None:
    rec = CertificateReconciler(n=7, f=2)
    # Honest fork A: 5 signers, view=41
    cert_a = CommitCertificate.build(41, "task-77", view=41,
                                     signers=("A1", "A2", "A3", "A4", "A5"))
    rec.admit(cert_a)  # ok
    # Equivocating fork B: same (epoch, proposal_id), different view binding
    cert_b = CommitCertificate.build(41, "task-77", view=42,
                                     signers=("A4", "A5", "A6", "A7", "A1"))
    rec.admit(cert_b)  # raises ByzantineEquivocationBarrier


if __name__ == "__main__":
    simulate_equivocation()
