# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-trust-anchor-substitution-during-cross-org-agent-federation-handshakes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-trust-anchor-substitution-during-cross-org-agent-federation-handshakes.warrant.json
# Markdown SHA-256:   8a3c5e297d0dc04c3fb4340d1a524eae358d4979b95c29ecc45a833429eae68f
# Code AST SHA-256:   fd0f468d13ac4ac5cc183dd6831ec92cdd6392c6c9fa5a693c6cc4d83f6234d8
# Verified Classes:   TrustAnchorSubstitutionError, AnchorPin
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Mapping


class TrustAnchorSubstitutionError(RuntimeError):
    """Raised when a handshake's anchor set changes after initiation,
    or when an attestation chains to an anchor not bound to the peer identity."""
    pass


@dataclass(frozen=True)
class AnchorPin:
    org_id: str
    agent_class: str
    fingerprint: str  # hash over sorted (kid, key) pairs


def fingerprint_anchor_set(anchor_set: Mapping[str, bytes]) -> str:
    h = hashlib.sha256()
    for kid in sorted(anchor_set):
        h.update(kid.encode())
        h.update(anchor_set[kid])
    return h.hexdigest()


def initiate_handshake(
    peer_org_id: str,
    peer_agent_class: str,
    resolved_anchor_set: Mapping[str, bytes],
) -> AnchorPin:
    return AnchorPin(
        org_id=peer_org_id,
        agent_class=peer_agent_class,
        fingerprint=fingerprint_anchor_set(resolved_anchor_set),
    )


def complete_handshake(
    pin: AnchorPin,
    current_anchor_set: Mapping[str, bytes],
    attestation_kid: str,
    bound_anchors: Mapping[tuple[str, str], set[str]],
) -> None:
    current_fp = fingerprint_anchor_set(current_anchor_set)
    if current_fp != pin.fingerprint:
        raise TrustAnchorSubstitutionError(
            f"anchor set for {pin.org_id}/{pin.agent_class} drifted mid-handshake: "
            f"pinned {pin.fingerprint[:12]}, current {current_fp[:12]}"
        )

    allowed = bound_anchors.get((pin.org_id, pin.agent_class))
    if allowed is None or attestation_kid not in allowed:
        raise TrustAnchorSubstitutionError(
            f"attestation kid {attestation_kid!r} is not bound to identity "
            f"{pin.org_id}/{pin.agent_class}; allowlist widening detected"
        )
