# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-commit-certificate-it-cannot-independently-verify.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-commit-certificate-it-cannot-independently-verify.warrant.json
# Markdown SHA-256:   11ee8662ee0b28cb37dbb0a6aeb51615ee0b761b47b694af6b8760f18cfadc8f
# Code AST SHA-256:   2ba58ce56f9eae18291ca3d5d559a4fa40afff8eb1cc13f2c9b6887644e1dfc7
# Verified Classes:   UnverifiableCommitmentError, SignedEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnverifiableCommitmentError(RuntimeError):
    """Raised when a commit certificate cannot be bound to the exact signed bytes."""


@dataclass(frozen=True)
class SignedEnvelope:
    view: int
    payload_bytes: bytes
    digest: bytes
    signatures: tuple[bytes, ...]


def verify_and_apply(
    envelope: SignedEnvelope,
    receiver_canonical_bytes: bytes | None,
    quorum: int,
) -> bytes:
    """
    Apply a commit only if the receiver can exhibit the exact bytes the quorum signed.

    receiver_canonical_bytes is what the receiver would act on. It MUST be
    byte-identical to envelope.payload_bytes; any reconstruction, truncation,
    or re-serialization is a rejection, not a repair.
    """
    if len(envelope.signatures) < quorum:
        raise UnverifiableCommitmentError(
            f"only {len(envelope.signatures)} signatures, need {quorum}"
        )

    recomputed = hashlib.sha256(envelope.payload_bytes).digest()
    if recomputed != envelope.digest:
        raise UnverifiableCommitmentError(
            "signed envelope payload does not match its own digest"
        )

    if receiver_canonical_bytes is None:
        raise UnverifiableCommitmentError(
            "receiver cannot materialize full signed bytes; "
            "refusing to act on a reconstructed payload"
        )

    if receiver_canonical_bytes != envelope.payload_bytes:
        raise UnverifiableCommitmentError(
            "receiver canonical form differs from signed bytes; "
            "certificate is cryptographically valid but semantically unbound"
        )

    return envelope.payload_bytes
