# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-evidence-of-task-commitment-rather-than-of-result-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-evidence-of-task-commitment-rather-than-of-result-attestation.warrant.json
# Markdown SHA-256:   ed1a39b0460a57a5bad4027012b897096f08bcbf35d29414fb58111a4f30248f
# Code AST SHA-256:   3f136700359ce92cc355cc0adae35e9b5b31d703951d66ee828855b00dcc0b41
# Verified Classes:   Phase, CertificateConflationError, QuorumCertificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class Phase(Enum):
    COMMIT = "COMMIT"
    ATTEST = "ATTEST"


class CertificateConflationError(RuntimeError):
    """Raised when a QC's signed preimage does not bind phase, epoch, and payload
    to the verifier's current context — i.e. the certificate is valid but its
    meaning cannot be established."""


@dataclass(frozen=True)
class QuorumCertificate:
    phase: Phase
    epoch: int
    task_id: int
    payload_hash: bytes
    signers: frozenset
    signatures: tuple

    def signed_preimage(self) -> bytes:
        # Domain-separated: phase and epoch are inside the hash.
        return hashlib.sha256(
            self.phase.value.encode()
            + self.epoch.to_bytes(8, "big")
            + self.task_id.to_bytes(8, "big")
            + self.payload_hash
        ).digest()


def verify_certificate_for_context(
    qc: QuorumCertificate,
    *,
    expected_phase: Phase,
    current_epoch: int,
    expected_task_id: int,
    expected_payload_hash: bytes,
    quorum_size: int,
    verify_sig,
) -> bool:
    # Signature validity is necessary but not sufficient.
    if len(qc.signers) < quorum_size:
        return False
    if not all(verify_sig(s, qc.signed_preimage()) for s in qc.signers):
        return False

    # Context binding: the certificate must mean what the verifier thinks it means.
    if qc.phase is not expected_phase:
        raise CertificateConflationError(
            f"QC phase {qc.phase} != expected {expected_phase}; "
            f"valid certificate replayed across phase boundary"
        )
    if qc.epoch != current_epoch:
        raise CertificateConflationError(
            f"QC epoch {qc.epoch} != current {current_epoch}; stale certificate"
        )
    if qc.task_id != expected_task_id:
        raise CertificateConflationError(
            f"QC task {qc.task_id} != expected {expected_task_id}"
        )
    if qc.payload_hash != expected_payload_hash:
        raise CertificateConflationError(
            "QC payload hash does not match locally reconstructed payload; "
            "cannot treat as evidence for this phase"
        )
    return True


def admit_for_execution(qc, local_spec, epoch, quorum_size, verify_sig):
    spec_hash = hashlib.sha256(local_spec.encode()).digest()
    try:
        ok = verify_certificate_for_context(
            qc,
            expected_phase=Phase.COMMIT,
            current_epoch=epoch,
            expected_task_id=qc.task_id,
            expected_payload_hash=spec_hash,
            quorum_size=quorum_size,
            verify_sig=verify_sig,
        )
    except CertificateConflationError:
        # Fail closed: do not execute on an ambiguous certificate.
        return False
    return ok
