# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-i-saw-an-equivocating-message-and-i-can-prove-it-to-a-third-party-in-bft-plan-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-i-saw-an-equivocating-message-and-i-can-prove-it-to-a-third-party-in-bft-plan-commitment.warrant.json
# Markdown SHA-256:   bf60dbf820b668b1ccc79e8ac98a4a95d0a83895d7f54dd0e5b7b5323c463e0c
# Code AST SHA-256:   56001f55c5e5dad72da96566fa645198c2764c6276e6f33f292e395640e2259f
# Verified Classes:   UnjustifiedQuorumError, SignedFragment, EquivocationProof, QuorumCertificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import FrozenSet


class UnjustifiedQuorumError(RuntimeError):
    """Raised when a quorum certificate counts a locally-suspected peer
    without an accompanying transferable equivocation proof.

    This is the invariant violation described in the record: the local
    instance knows the peer equivocated, but emits or accepts a certificate
    that includes the peer's signature anyway, and the certificate carries
    no proof that a third-party auditor could use to justify the inclusion.
    """


@dataclass(frozen=True)
class SignedFragment:
    sender: str
    round: int
    plan_hash: str
    pred_qc_hash: str
    signature: bytes


@dataclass(frozen=True)
class EquivocationProof:
    """Two signed fragments from the same (sender, round) with conflicting
    content. Bounded size; verifiable offline by any instance."""
    sender: str
    round: int
    fragment_a: SignedFragment
    fragment_b: SignedFragment


@dataclass
class QuorumCertificate:
    round: int
    plan_hash: str
    signers: FrozenSet[str]
    proofs: dict[str, EquivocationProof] = field(default_factory=dict)


def assemble_quorum(
    round: int,
    plan_hash: str,
    signers: FrozenSet[str],
    local_faulty: FrozenSet[str],
    available_proofs: dict[str, EquivocationProof],
    quorum_size: int,
) -> QuorumCertificate:
    """Assemble a quorum certificate, enforcing the invariant:

    If a signer is in `local_faulty`, the certificate MUST carry a
    transferable equivocation proof for that signer. Otherwise the
    certificate is rejected at assembly time — before it can be emitted
    and before it can be used to advance state.
    """
    if len(signers) < quorum_size:
        raise UnjustifiedQuorumError(
            f"round {round}: only {len(signers)} signers, need {quorum_size}"
        )

    carried: dict[str, EquivocationProof] = {}
    for signer in signers:
        if signer not in local_faulty:
            continue
        proof = available_proofs.get(signer)
        if proof is None:
            raise UnjustifiedQuorumError(
                f"round {round}: signer {signer!r} is locally suspected "
                f"of equivocation but the certificate carries no transferable "
                f"proof; a cold-started auditor could not justify counting "
                f"{signer!r} toward this quorum"
            )
        if proof.sender != signer or proof.round != round:
            raise UnjustifiedQuorumError(
                f"round {round}: proof for {signer!r} does not match "
                f"(sender={proof.sender!r}, round={proof.round}); "
                f"stale or misattributed proof"
            )
        if proof.fragment_a.pred_qc_hash == proof.fragment_b.pred_qc_hash:
            raise UnjustifiedQuorumError(
                f"round {round}: proof for {signer!r} does not demonstrate "
                f"equivocation — both fragments cite the same predecessor QC"
            )
        carried[signer] = proof

    return QuorumCertificate(
        round=round,
        plan_hash=plan_hash,
        signers=signers,
        proofs=carried,
    )
