# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-plan-consensus-forks-when-a-byzantine-peer-replays-a-stale-signed-proposal-into-a-fresh-quorum-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-plan-consensus-forks-when-a-byzantine-peer-replays-a-stale-signed-proposal-into-a-fresh-quorum-epoch.warrant.json
# Markdown SHA-256:   d101741f641738022b7848fd4d39c052210411d893fdf25add891c9cba3fd2e0
# Code AST SHA-256:   1d5f6643e9ca9a202aedef00d2c507cd3b1d5486ab87ff644899a6140e516f20
# Verified Classes:   StaleCertificateError, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleCertificateError(RuntimeError):
    """Raised when a quorum certificate is presented outside its formation epoch."""


@dataclass(frozen=True)
class QuorumCertificate:
    plan_hash: str
    epoch_formed: int
    signatures: tuple[str, ...]  # opaque peer signatures over (epoch_formed, plan_hash)


def signed_preimage(epoch: int, plan_hash: str) -> bytes:
    # The epoch MUST be inside the preimage. Signing plan_hash alone is the bug.
    return f"{epoch}:{plan_hash}".encode()


def admit_proposal(
    qc: QuorumCertificate,
    current_epoch: int,
    quorum_size: int,
) -> str:
    if qc.epoch_formed != current_epoch:
        raise StaleCertificateError(
            f"QC formed in epoch {qc.epoch_formed} presented in epoch {current_epoch}; "
            f"proposer must re-collect votes in current epoch"
        )
    if len(qc.signatures) < quorum_size:
        raise StaleCertificateError(
            f"QC has {len(qc.signatures)} signatures, quorum requires {quorum_size}"
        )
    # Verify each signature over the epoch-bound preimage, not the bare plan hash.
    preimage = signed_preimage(qc.epoch_formed, qc.plan_hash)
    for sig in qc.signatures:
        if not _verify(sig, preimage):
            raise StaleCertificateError(f"signature {sig[:8]}... does not cover epoch-bound preimage")
    return qc.plan_hash


def step_idempotency_key(epoch: int, plan_hash: str, step_index: int) -> str:
    # Epoch-keyed so a replayed plan produces NEW keys and re-execution is detectable.
    return hashlib.sha256(f"{epoch}:{plan_hash}:{step_index}".encode()).hexdigest()


def _verify(sig: str, preimage: bytes) -> bool:
    # Placeholder for real signature verification.
    return bool(sig) and bool(preimage)
