# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-quorum-certificate-whose-signer-set-crosses-an-epoch-boundary-it-never-observed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-quorum-certificate-whose-signer-set-crosses-an-epoch-boundary-it-never-observed.warrant.json
# Markdown SHA-256:   1f17b4c91aeb5944f023ff62809bde4be6c521b709a8bfde7a7912361249aa56
# Code AST SHA-256:   0c626fee8ee4847189a1f4323130b09ba55dbedd269c069d7c0ed17de1192dca
# Verified Classes:   UndecidableAttestationError, QuorumCertificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UndecidableAttestationError(RuntimeError):
    """Raised when a QC's epoch context cannot be reconstructed locally.

    This is not a verification failure: signatures may well verify. It means
    the receiver cannot prove which signer set was authorized at the QC's
    epoch, so attestation must suspend rather than guess.
    """


@dataclass(frozen=True)
class QuorumCertificate:
    epoch: int
    signer_ids: frozenset
    signatures_valid: bool
    membership_proof: Optional[bytes]  # signed epoch -> signer-set binding


def attest(
    qc: QuorumCertificate,
    current_epoch: int,
    current_signer_set: frozenset,
    quorum_threshold,
    verify_membership_proof,
) -> bool:
    # Crypto check is necessary but never sufficient.
    if not qc.signatures_valid:
        return False

    if qc.epoch == current_epoch:
        # Local set IS the authorized set; mapping is trivially available.
        authorized = current_signer_set
    elif qc.membership_proof is not None:
        # Reconstruct the epoch's authorized set from a signed proof.
        authorized = verify_membership_proof(qc.membership_proof)
        if authorized is None:
            raise UndecidableAttestationError(
                f"membership proof for epoch {qc.epoch} failed to verify"
            )
    else:
        # Past epoch, no proof. Signatures may verify against a stale keyring,
        # which is exactly the silent-success trap. Suspend, do not guess.
        raise UndecidableAttestationError(
            f"QC at epoch {qc.epoch} arrives at epoch {current_epoch} "
            f"without membership proof; authority is unprovable"
        )

    threshold = quorum_threshold(len(authorized))
    if not qc.signer_ids.issubset(authorized):
        return False
    if len(qc.signer_ids) < threshold:
        return False
    return True
