# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hardware-attested-agent-identity-from-silently-downgrading-during-continuous-re-verification-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hardware-attested-agent-identity-from-silently-downgrading-during-continuous-re-verification-handoffs.warrant.json
# Markdown SHA-256:   bdbea3b815334097eb179c57acd20b0d5ae8e11be893e08a286f36a8246d1def
# Code AST SHA-256:   7ddd3efbcf5ff251189794c45f8f60a4ca5f2d011184897315a21bff76377a83
# Verified Classes:   AttestationBindingError, Quote, Checkpoint
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationBindingError(RuntimeError):
    """Raised when a re-verification quote does not bind the work-signing key."""


@dataclass(frozen=True)
class Quote:
    epoch: int
    nonce: bytes
    attested_key_pub: bytes          # K_att public half (hardware-bound)
    bound_work_key_pub: bytes | None  # K_soft public half, if supervisor bound it
    signature_valid: bool


@dataclass(frozen=True)
class Checkpoint:
    epoch: int
    digest: bytes
    signer_pub: bytes                # key that actually signed the work
    signature_valid: bool


def expected_nonce(checkpoint: Checkpoint) -> bytes:
    return hashlib.sha256(checkpoint.digest + checkpoint.epoch.to_bytes(8, "big")).digest()


def verify_epoch(
    checkpoint: Checkpoint,
    quote: Quote,
    pinned_att_key_pub: bytes,
) -> None:
    if not checkpoint.signature_valid:
        raise AttestationBindingError("checkpoint signature does not verify")
    if not quote.signature_valid:
        raise AttestationBindingError("hardware quote does not verify")
    if quote.attested_key_pub != pinned_att_key_pub:
        raise AttestationBindingError("quote is from a key not pinned in the warrant")
    if quote.epoch != checkpoint.epoch:
        raise AttestationBindingError("quote epoch does not match checkpoint epoch")
    if quote.nonce != expected_nonce(checkpoint):
        raise AttestationBindingError(
            "quote nonce is not derived from this checkpoint digest; "
            "re-verification is not causally bound to the work"
        )
    if quote.bound_work_key_pub is None:
        raise AttestationBindingError(
            "supervisor did not bind a work-signing key in this epoch; "
            "re-verification would silently downgrade to presence-only trust"
        )
    if quote.bound_work_key_pub != checkpoint.signer_pub:
        raise AttestationBindingError(
            "hardware-attested key does not vouch for the key that signed the work"
        )
    # Only here is continuity actually enforced: the pinned hardware key
    # attests, for this specific epoch and this specific digest, that the
    # work-signing key is the one in the execution path.
