# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-prove-possession-of-its-delegated-warrant-mid-handoff-and-what-breaks-when-revocation-races-the-transfer.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-prove-possession-of-its-delegated-warrant-mid-handoff-and-what-breaks-when-revocation-races-the-transfer.warrant.json
# Markdown SHA-256:   bea09e01c0bd0f88371af7fbaeea02e70943702d6921541a4ebabdac1fc0b28a
# Code AST SHA-256:   2e0530c1912b12852d4b1e7a31b1b380f3035ea6afe0da06b43cbcb313f17206
# Verified Classes:   RevocationRaceError, StaleRevocationViewError, ChainRevokedError, Warrant, RevocationView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class RevocationRaceError(RuntimeError):
    """Raised when a handoff acceptance would inherit revoked authority."""
    pass


class StaleRevocationViewError(RevocationRaceError):
    """Revocation view too old to trust at the acceptance boundary."""
    pass


class ChainRevokedError(RevocationRaceError):
    """A parent warrant in the delegation chain is revoked."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    parent_id: Optional[str]
    scope: str
    expires_at: float
    holder_key: str


@dataclass
class RevocationView:
    revoked_ids: set
    fetched_at: float

    def age(self, now: float) -> float:
        return now - self.fetched_at


def accept_handoff(
    receiver_warrant: Warrant,
    chain: list,                 # ordered leaf -> root
    sender_signature_valid: bool,
    revocation_view: RevocationView,
    delta_max: float,            # freshness bound, must be < propagation p99
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now

    # 1. Proof-of-possession must be bound into acceptance.
    if not sender_signature_valid:
        raise RevocationRaceError(
            f"handoff for {receiver_warrant.warrant_id} lacks valid "
            f"possession proof from sender key {receiver_warrant.holder_key}"
        )

    # 2. Revocation view must be fresh at the acceptance instant.
    view_age = revocation_view.age(now)
    if view_age > delta_max:
        raise StaleRevocationViewError(
            f"revocation view age {view_age:.2f}s exceeds delta_max "
            f"{delta_max:.2f}s; cannot bound exposure window"
        )

    # 3. Full transitive chain must validate against the fresh view.
    for link in chain:
        if link.warrant_id in revocation_view.revoked_ids:
            raise ChainRevokedError(
                f"warrant {link.warrant_id} in chain for "
                f"{receiver_warrant.warrant_id} is revoked "
                f"(revoked at view fetched {revocation_view.fetched_at:.2f})"
            )
        if link.expires_at <= now:
            raise RevocationRaceError(
                f"warrant {link.warrant_id} expired at {link.expires_at:.2f}"
            )

    return True


if __name__ == "__main__":
    root = Warrant("W", None, "write:ledger", time.time() + 300, "key:P")
    leaf = Warrant("W'", "W", "write:ledger:!audit", time.time() + 300, "key:E")
    view = RevocationView(revoked_ids={"W"}, fetched_at=time.time() - 5)

    try:
        accept_handoff(
            receiver_warrant=leaf,
            chain=[leaf, root],
            sender_signature_valid=True,
            revocation_view=view,
            delta_max=10.0,
        )
    except ChainRevokedError as e:
        print(f"handoff rejected: {e}")
