# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-bootstrap-trust-from-a-federation-introducer-it-has-not-itself-pinned-and-why-the-refusal-must-happen-before-capabili.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-bootstrap-trust-from-a-federation-introducer-it-has-not-itself-pinned-and-why-the-refusal-must-happen-before-capabili.warrant.json
# Markdown SHA-256:   d96cff96f8275631fdd103e5c6acab74e0259d602e86187c82b774a5b6f83ac9
# Code AST SHA-256:   f786b15dcbb1013fcbda57fdca75b4a19c76c3ba00b8f980927751a879b8b3bb
# Verified Classes:   UnpinnedIntroducerError, CapabilityAttestationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnpinnedIntroducerError(RuntimeError):
    """Raised when a federation referral originates from an introducer
    that is not present in the local pin set at the signing generation."""


class CapabilityAttestationError(RuntimeError):
    """Raised when an attestation is malformed or fails signature checks."""


def admit_federated_peer(
    referral: dict,
    attestation: dict,
    pin_set: dict,
) -> str:
    """Admit a federated peer only after identity admission against local pins.

    Ordering is load-bearing: the pin check MUST run before the attestation
    is parsed or any network call to the referred peer is made.
    """
    introducer_id = referral.get("introducer_id")
    signing_generation = referral.get("signing_generation")

    pinned = pin_set.get(introducer_id)
    if pinned is None:
        raise UnpinnedIntroducerError(
            f"introducer {introducer_id!r} is not pinned locally; "
            f"refusing to bootstrap peer {referral.get('peer_id')!r}"
        )
    if pinned["current_generation"] != signing_generation:
        raise UnpinnedIntroducerError(
            f"referral for {referral.get('peer_id')!r} signed by retired "
            f"generation {signing_generation!r} of {introducer_id!r}; "
            f"current is {pinned['current_generation']!r}. "
            f"Reconcile pin set before admitting."
        )

    # Only now, with identity admitted against a current pin, evaluate capability.
    if not attestation.get("signature_valid"):
        raise CapabilityAttestationError(
            f"attestation for {referral.get('peer_id')!r} failed signature check"
        )

    return referral["peer_id"]
