# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-forged-quorum-certificate-when-the-auditor-set-is-recomputed-mid-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-forged-quorum-certificate-when-the-auditor-set-is-recomputed-mid-epoch.warrant.json
# Markdown SHA-256:   d2865f23236598ffd8984858d810ef6ac5e8ce2ea6a81fdb42f94ab86b15af89
# Code AST SHA-256:   354266b6217dd2960835b002082f0c570684e72ff4e034f1a6ccd3f806be06f9
# Verified Classes:   EpochSkewError, QuorumCertificate, EpochRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class EpochSkewError(RuntimeError):
    """Raised when a quorum certificate is verified against an auditor set
    that differs from the set that produced it."""


@dataclass(frozen=True)
class QuorumCertificate:
    epoch_id: int
    auditor_set_hash: str
    signers: FrozenSet[str]
    payload: str


@dataclass(frozen=True)
class EpochRecord:
    epoch_id: int
    auditors: FrozenSet[str]
    threshold: int
    set_hash: str


def verify_qc(
    qc: QuorumCertificate,
    epoch_log: dict[int, EpochRecord],
    live_epoch_id: int,
) -> None:
    """Verify a QC by binding to its embedded epoch, not the live registry.

    Raises EpochSkewError if the QC's epoch is unknown, its set hash does not
    match the logged auditor set, or the live epoch disagrees with the QC's
    epoch in a way that would change the threshold arithmetic.
    """
    record = epoch_log.get(qc.epoch_id)
    if record is None:
        raise EpochSkewError(
            f"QC references epoch {qc.epoch_id} not present in epoch log; "
            f"cannot reconstruct auditor set for verification"
        )

    if qc.auditor_set_hash != record.set_hash:
        raise EpochSkewError(
            f"QC auditor_set_hash {qc.auditor_set_hash!r} does not match "
            f"logged set hash {record.set_hash!r} for epoch {qc.epoch_id}"
        )

    # Count only signers that were actually auditors in the QC's epoch.
    valid_signers = qc.signers & record.auditors
    if len(valid_signers) < record.threshold:
        raise EpochSkewError(
            f"QC for epoch {qc.epoch_id} has {len(valid_signers)} valid "
            f"signers against threshold {record.threshold}"
        )

    # Defense in depth: if the live epoch differs, the QC is still valid for
    # its own epoch, but the caller must be told the views diverged so it can
    # decide whether to re-vote or to treat the commit as historical.
    if live_epoch_id != qc.epoch_id:
        raise EpochSkewError(
            f"QC epoch {qc.epoch_id} disagrees with live epoch {live_epoch_id}; "
            f"commit is historical and must not be used to justify new votes"
        )
