# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-federation-when-a-brokered-verifiable-credential-s-delegation-chain-outlives-the-policy-epoch-it-was-minted-under.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-federation-when-a-brokered-verifiable-credential-s-delegation-chain-outlives-the-policy-epoch-it-was-minted-under.warrant.json
# Markdown SHA-256:   693eb9b82b1d5fc12f6cc7d91eaef5193c18029376bc2c4ea56bb644b8f8ca69
# Code AST SHA-256:   bc22c5fd5ff68f604b9116e785fa6d6be22cb7593bd02dff6e3131d7f070ab16
# Verified Classes:   FederationHalt, Constraint, VerifiableCredential, TrustStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class FederationHalt(RuntimeError):
    """Raised when a brokered VC chain cannot be proven non-amplifying under current policy epoch."""
    pass


@dataclass(frozen=True)
class Constraint:
    key: str
    value: object

    def __hash__(self) -> int:
        return hash((self.key, repr(self.value)))


@dataclass
class VerifiableCredential:
    issuer_did: str
    subject_did: str
    capability: str
    policy_epoch: str                      # hash of issuer's effective policy at mint time
    constraints: frozenset[Constraint]     # full set, positive AND negative
    expires_at: int                        # unix ts
    signature_valid: bool
    parent: Optional["VerifiableCredential"] = None


@dataclass
class TrustStore:
    known_epochs: set[str] = field(default_factory=set)
    revocation_freshness_window: int = 300   # seconds
    last_revocation_sync: int = 0
    now: int = 0


def _constraint_hash(cs: frozenset[Constraint]) -> str:
    blob = "|".join(sorted(f"{c.key}={c.value!r}" for c in cs))
    return hashlib.sha256(blob.encode()).hexdigest()[:16]


def verify_brokered_chain(
    leaf: VerifiableCredential,
    trust_store: TrustStore,
) -> str:
    """
    Walk leaf -> root. Accept only if every hop preserves-or-tightens constraints,
    the root policy epoch is known, and revocation is fresh.
    Returns the terminal capability string on success; raises FederationHalt otherwise.
    """
    chain: list[VerifiableCredential] = []
    node: Optional[VerifiableCredential] = leaf
    while node is not None:
        chain.append(node)
        node = node.parent

    # 1. Cryptographic validity of every hop.
    for i, vc in enumerate(chain):
        if not vc.signature_valid:
            raise FederationHalt(f"hop {i}: signature invalid for issuer {vc.issuer_did}")
        if vc.expires_at <= trust_store.now:
            raise FederationHalt(f"hop {i}: credential expired at {vc.expires_at}")

    # 2. Non-amplification: constraints(leaf) must be a superset of constraints(parent)
    #    at every hop. A dropped constraint (strict subset) is the amplification signal.
    for i in range(len(chain) - 1):
        child, parent = chain[i], chain[i + 1]
        if not child.constraints.issuperset(parent.constraints):
            dropped = parent.constraints - child.constraints
            raise FederationHalt(
                f"hop {i}->{i+1}: constraint amplification; broker dropped "
                f"{sorted(c.key for c in dropped)} (child={_constraint_hash(child.constraints)}, "
                f"parent={_constraint_hash(parent.constraints)})"
            )

    # 3. Root policy epoch must be recognized by the relying party.
    root = chain[-1]
    if root.policy_epoch not in trust_store.known_epochs:
        raise FederationHalt(
            f"root policy epoch {root.policy_epoch} unknown to relying party; "
            f"cannot prove terminal capability within accepted policy"
        )

    # 4. Revocation freshness: a stale revocation view is a halt, not a warning.
    age = trust_store.now - trust_store.last_revocation_sync
    if age > trust_store.revocation_freshness_window:
        raise FederationHalt(
            f"revocation view stale by {age}s (window {trust_store.revocation_freshness_window}s)"
        )

    return leaf.capability


# --- demonstration of the observed failure ---
if __name__ == "__main__":
    root = VerifiableCredential(
        issuer_did="did:orgA", subject_did="did:orgB:broker",
        capability="read:dataset/analytics", policy_epoch="P0",
        constraints=frozenset({Constraint("derived_export", False),
                               Constraint("max_rows", 1000)}),
        expires_at=2_000_000_000, signature_valid=True,
    )
    brokered = VerifiableCredential(
        issuer_did="did:orgB:broker", subject_did="did:orgC:runtime",
        capability="read:dataset/analytics", policy_epoch="P1",
        constraints=frozenset({Constraint("max_rows", 1000)}),  # derived_export dropped
        expires_at=2_000_000_000, signature_valid=True, parent=root,
    )
    store = TrustStore(
        known_epochs={"P0", "P2"},
        last_revocation_sync=1_999_999_900,
        now=1_999_999_950,
    )
    try:
        verify_brokered_chain(brokered, store)
    except FederationHalt as e:
        print(f"HALT: {e}")
