# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-collapse-in-multi-agent-task-commitment-the-equivocation-liveness-trap-in-signed-shared-state-reco.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-collapse-in-multi-agent-task-commitment-the-equivocation-liveness-trap-in-signed-shared-state-reco.warrant.json
# Markdown SHA-256:   a852fe51a0fd398810b107fd56d778be304eeaab6be01123df1861d913c48c22
# Code AST SHA-256:   2277ec96ebb59d4d9ae641a6730bc1ee8cd9e53c0fe6621a5b0254de8aec204c
# Verified Classes:   QuorumEquivocationError, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet


class QuorumEquivocationError(RuntimeError):
    """Raised when two quorum certificates for one slot intersect at <= f peers,
    indicating canonicalization divergence rather than attributable double-signing."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    slot: str
    canonical_digest: str
    signers: FrozenSet[str]


def reconcile_slot(
    slot: str,
    certificates: list[QuorumCertificate],
    n: int,
    f: int,
) -> QuorumCertificate:
    """Return the unique committed QC for a slot, or raise if equivocation is unsafe."""
    if len(certificates) == 1:
        return certificates[0]

    qc_a, qc_b = certificates[0], certificates[1]
    intersection = qc_a.signers & qc_b.signers

    if len(intersection) > f:
        # At least one honest peer double-signed: attributable, recoverable.
        raise QuorumEquivocationError(
            f"slot {slot}: attributable double-sign by {sorted(intersection)}; "
            f"intersection={len(intersection)} > f={f}; reject both, slash, re-propose."
        )

    # intersection <= f: no honest double-sign. The two QCs are independently
    # valid under different canonicalizations. Protocol cannot adjudicate locally.
    raise QuorumEquivocationError(
        f"slot {slot}: UNSAFE equivocation — dual QC with intersection="
        f"{len(intersection)} <= f={f}. Canonicalization divergence suspected "
        f"(digests {qc_a.canonical_digest[:12]} vs {qc_b.canonical_digest[:12]}). "
        f"Escalate to deterministic re-serialization under a single canonicalizer; "
        f"do not resolve via LLM reconciliation."
    )


def verify_signer_used_proposer_bytes(
    received_envelope: bytes,
    proposer_canonical: bytes,
    signer_recanonicalized: bytes,
) -> None:
    """Enforce proposer-canonical signing: signer must NOT re-canonicalize."""
    if hashlib.sha256(signer_recanonicalized).digest() != hashlib.sha256(
        proposer_canonical
    ).digest():
        raise QuorumEquivocationError(
            "signer re-canonicalized the commitment; signature is over a "
            "signer-local digest and cannot participate in a safe quorum. "
            "Reject signature and require signing over proposer_canonical bytes."
        )
