# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-policy-digest-before-the-trust-anchor-has-been-pinned.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-policy-digest-before-the-trust-anchor-has-been-pinned.warrant.json
# Markdown SHA-256:   5d3eb60c1f45f9358abad64ae2c9fe6425924155ecc546723fbb78d03a5a7261
# Code AST SHA-256:   2825c6e0574d91beb7e58b8fa9f5b0a90648a6a681c1f1cbe60459f8987d650a
# Verified Classes:   AnchorBindingError, PolicyGrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AnchorBindingError(RuntimeError):
    """Raised when a negotiated policy digest is not bound to the pinned anchor."""


@dataclass(frozen=True)
class PolicyGrant:
    policy: dict
    anchor_fingerprint: str
    digest: str


def compute_digest(policy: dict, anchor_fingerprint: str) -> str:
    # Digest MUST commit to the anchor, not just the policy.
    material = repr(sorted(policy.items())) + "|" + anchor_fingerprint
    return hashlib.sha256(material.encode()).hexdigest()


def negotiate(policy: dict, anchor_fingerprint: str) -> PolicyGrant:
    return PolicyGrant(
        policy=policy,
        anchor_fingerprint=anchor_fingerprint,
        digest=compute_digest(policy, anchor_fingerprint),
    )


def revalidate_on_resume(
    checkpoint_grant: PolicyGrant,
    current_policy: dict,
    current_anchor_fingerprint: str,
) -> PolicyGrant:
    # On checkpoint resume or anchor-cache refresh, the anchor must match.
    if checkpoint_grant.anchor_fingerprint != current_anchor_fingerprint:
        raise AnchorBindingError(
            f"anchor rotated: pinned={checkpoint_grant.anchor_fingerprint} "
            f"current={current_anchor_fingerprint}; re-enrollment required, "
            f"refusing silent re-negotiation"
        )
    recomputed = compute_digest(current_policy, current_anchor_fingerprint)
    if recomputed != checkpoint_grant.digest:
        raise AnchorBindingError(
            "policy digest mismatch under stable anchor; possible tampering"
        )
    return checkpoint_grant


# Failure trace: A1 pinned under K_alpha_v1, resumes after rotation to K_alpha_v2.
pinned = negotiate(
    {"read": ["public", "internal"], "write": ["staging"]},
    anchor_fingerprint="K_alpha_v1",
)
try:
    revalidate_on_resume(
        pinned,
        current_policy={"read": ["public", "internal"], "write": ["*"]},
        current_anchor_fingerprint="K_alpha_v2",
    )
except AnchorBindingError as e:
    # Correct behavior: fail closed, force explicit re-enrollment.
    print(f"halted: {e}")
