# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-attestation-chain-whose-root-anchor-was-revoked-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-attestation-chain-whose-root-anchor-was-revoked-mid-handoff.warrant.json
# Markdown SHA-256:   bf569b99eb5da3c814926f7efec1d7c40acd63f803b792f6835eb8c315c20b2d
# Code AST SHA-256:   9d98714898976c8e23b748396b8e71f70ef6ab697f899f1d9db9b47ac2fe9c18
# Verified Classes:   StaleEpochError, RevokedAnchorError, Attestation, RevocationView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleEpochError(RuntimeError):
    """Raised when an attestation's mint epoch is not dominated by the verifier's revocation epoch."""
    pass


class RevokedAnchorError(RuntimeError):
    """Raised when a root anchor in the chain has a revocation record effective at or before verify time."""
    pass


@dataclass(frozen=True)
class Attestation:
    issuer_root: str
    mint_epoch: int          # issuer's monotonic epoch counter at mint
    claims: dict
    signature: bytes


@dataclass(frozen=True)
class RevocationView:
    epoch: int                        # verifier's monotonic epoch
    revoked_anchors: dict             # anchor_id -> effective_epoch


def verify_attestation(
    att: Attestation,
    view: RevocationView,
    now_epoch: int,
) -> dict:
    # 1. Signature check (omitted: assumes cryptographic verify already passed).
    # 2. Retroactivity check: root anchor must not be revoked at or before now.
    effective = view.revoked_anchors.get(att.issuer_root)
    if effective is not None and effective <= now_epoch:
        raise RevokedAnchorError(
            f"root anchor {att.issuer_root!r} revoked effective epoch {effective}, "
            f"verify epoch {now_epoch}"
        )
    # 3. Freshness/dominance check: verifier's epoch must dominate mint epoch.
    if att.mint_epoch > view.epoch:
        raise StaleEpochError(
            f"attestation mint_epoch {att.mint_epoch} not dominated by "
            f"verifier epoch {view.epoch}; revocation view is stale relative to mint"
        )
    return att.claims


def authorize_delegated_call(
    att: Attestation,
    view: RevocationView,
    now_epoch: int,
    capability: str,
) -> None:
    claims = verify_attestation(att, view, now_epoch)
    if capability not in claims.get("capabilities", ()):
        raise StaleEpochError(
            f"capability {capability!r} not granted under epoch {att.mint_epoch}"
        )
    # Call proceeds only under a dominated epoch and a non-revoked anchor.
