# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-credential-whose-revocation-proof-is-stale-by-one-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-credential-whose-revocation-proof-is-stale-by-one-epoch.warrant.json
# Markdown SHA-256:   c474ed52e95085795ce1528ae0290db1cd2f381970b1bfa1d1d8c4187007b950
# Code AST SHA-256:   5e2d646d8082892231b130fb791770a681240784d999924fe0ae1e26cc4f4794
# Verified Classes:   StaleRevocationProofError, RevocationProof, DelegatedToken
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationProofError(RuntimeError):
    """Raised when a delegated credential's revocation proof cannot be
    ordered against the verifier's clock within the issuer's bound."""
    pass


@dataclass(frozen=True)
class RevocationProof:
    credential_id: str
    status: str          # "valid" | "revoked"
    status_epoch: int
    issuer_sig: bytes


@dataclass(frozen=True)
class DelegatedToken:
    credential_id: str
    parent_hash: bytes
    issued_epoch: int
    expiry_epoch: int
    max_proof_staleness: int   # signed by issuer; 0 == synchronous-only


def verify_delegation(
    token: DelegatedToken,
    proof: RevocationProof,
    now_epoch: int,
    epoch_reference_synchronized: bool,
) -> None:
    # 1. Ordering precondition: without a shared clock we cannot assert
    #    non-revocation. Fail closed rather than warn.
    if not epoch_reference_synchronized:
        raise StaleRevocationProofError(
            f"cannot order proof for {token.credential_id}: "
            f"no synchronized epoch reference"
        )

    # 2. Staleness gate runs BEFORE any status check. A stale proof's
    #    "valid" status is meaningless.
    proof_age = now_epoch - proof.status_epoch
    if proof_age < 0:
        raise StaleRevocationProofError(
            f"proof for {token.credential_id} is from the future "
            f"(status_epoch={proof.status_epoch}, now={now_epoch})"
        )
    if proof_age > token.max_proof_staleness:
        raise StaleRevocationProofError(
            f"proof for {token.credential_id} stale by {proof_age} epochs "
            f"(bound={token.max_proof_staleness}); force synchronous refetch"
        )

    # 3. Only now is the status field trustworthy.
    if proof.status != "valid":
        raise StaleRevocationProofError(
            f"credential {token.credential_id} is revoked"
        )
    if now_epoch >= token.expiry_epoch:
        raise StaleRevocationProofError(
            f"credential {token.credential_id} expired at {token.expiry_epoch}"
        )


def verify_chain(
    tokens: list[DelegatedToken],
    proofs: list[RevocationProof],
    now_epoch: int,
    epoch_reference_synchronized: bool,
) -> None:
    # Every link must independently pass; chain is as fresh as its stalest link.
    if len(tokens) != len(proofs):
        raise StaleRevocationProofError("token/proof cardinality mismatch")
    for tok, prf in zip(tokens, proofs):
        if tok.credential_id != prf.credential_id:
            raise StaleRevocationProofError(
                f"proof {prf.credential_id} does not match token "
                f"{tok.credential_id}"
            )
        verify_delegation(tok, prf, now_epoch, epoch_reference_synchronized)
