# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-attestation-chain-after-a-revocation-and-why-the-trust-on-first-handoff-cache-breaks-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-attestation-chain-after-a-revocation-and-why-the-trust-on-first-handoff-cache-breaks-it.warrant.json
# Markdown SHA-256:   b5f03a556295405040a7b6c6310c9d7fef2a44eae3937692dc01c0080eae069a
# Code AST SHA-256:   e4fed7d36a6bcb48c09e88d1bdcd79ed0a881045221efbcd09391073cfbfdc40
# Verified Classes:   RevocationEpochViolation, RevocationEpochCache
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RevocationEpochViolation(RuntimeError):
    """Raised when a cached peer attestation is reused past its revocation-epoch deadline."""
    pass


class RevocationEpochCache:
    def __init__(self, delta_max_seconds: float, revocation_fetch):
        self.delta_max = delta_max_seconds
        self.fetch_revocation = revocation_fetch
        self._entries = {}  # peer_did -> {warrant_id, last_check, not_after, epoch}

    def accept_message(self, peer_did: str, warrant_id: str, msg_epoch: int, now: float) -> bool:
        entry = self._entries.get(peer_did)
        if entry is None or entry["warrant_id"] != warrant_id:
            # First contact: verify chain, record epoch, accept.
            self._entries[peer_did] = {
                "warrant_id": warrant_id,
                "last_check": now,
                "not_after": now + self.delta_max,
                "epoch": msg_epoch,
            }
            return True

        deadline = min(entry["not_after"], entry["last_check"] + self.delta_max)
        if now >= deadline:
            # Epoch expired: must re-verify before accepting authorization-bearing claims.
            status = self.fetch_revocation(peer_did, warrant_id)
            if status is None or status.get("revoked"):
                # Fail closed: peer degraded to informational-only.
                raise RevocationEpochViolation(
                    f"Peer {peer_did} warrant {warrant_id} revoked or unverifiable "
                    f"at epoch boundary (now={now:.1f}, deadline={deadline:.1f}); "
                    f"refusing authorization-bearing message."
                )
            entry["last_check"] = now
            entry["not_after"] = now + self.delta_max
            entry["epoch"] = status["epoch"]

        if msg_epoch < entry["epoch"]:
            # Peer is replaying a pre-revocation epoch: stale authorization.
            raise RevocationEpochViolation(
                f"Peer {peer_did} echoed epoch {msg_epoch} < current {entry['epoch']}; "
                f"message predates known revocation state."
            )
        return True
