# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-peer-s-attestation-chain-despite-a-valid-hardware-signature.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-peer-s-attestation-chain-despite-a-valid-hardware-signature.warrant.json
# Markdown SHA-256:   82e118a0e6462bd506a56c236162191b3638691b10fc2fa6e5cb5dda23377d7e
# Code AST SHA-256:   e899b6d12599bcccdcc355279591ba7919043c60257f91955def912887b730fe
# Verified Classes:   AttestationBindingError, Credential, LiveMeasurement
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationBindingError(RuntimeError):
    """Raised when a peer's hardware signature is valid but the live process
    manifest does not match the manifest hash bound in the signed credential."""


@dataclass(frozen=True)
class Credential:
    issuer: str
    subject_device_key: str
    process_manifest_hash: str          # hex digest of the signed manifest
    granted_tools: frozenset[str]
    expires_at: float


@dataclass(frozen=True)
class LiveMeasurement:
    """Obtained via challenge-response: the peer's attestation agent measures
    the running process and signs the measurement with the hardware key."""
    manifest: dict                      # {model, prompt_hash, tools}
    signature_valid: bool
    chain_trusted: bool
    now: float


def recompute_manifest_hash(manifest: dict) -> str:
    # Canonical serialization; order-stable so the digest is reproducible.
    parts = [
        manifest["model"],
        manifest["prompt_hash"],
        ",".join(sorted(manifest["tools"])),
    ]
    return hashlib.sha256("|".join(parts).encode()).hexdigest()


def validate_peer(cred: Credential, live: LiveMeasurement, requested_tools: set[str]) -> None:
    # Layer 1: cryptography. A failure here is a signature failure, not a binding failure.
    if not live.signature_valid:
        raise AttestationBindingError("signature verification failed")
    if not live.chain_trusted:
        raise AttestationBindingError("issuer chain untrusted")
    if live.now >= cred.expires_at:
        raise AttestationBindingError("credential expired")

    # Layer 2: instance binding. The signature is over the device key, not the process.
    # We must recompute the manifest hash from the measured live process and compare
    # it to the hash bound inside the signed credential.
    live_hash = recompute_manifest_hash(live.manifest)
    if live_hash != cred.process_manifest_hash:
        raise AttestationBindingError(
            f"instance-binding failure: live manifest {live_hash[:12]} != "
            f"signed claim {cred.process_manifest_hash[:12]} "
            f"(device key valid, process is not the attested one)"
        )

    # Layer 3: capability check against the SIGNED grant, never the self-reported set.
    unauthorized = set(requested_tools) - set(cred.granted_tools)
    if unauthorized:
        raise AttestationBindingError(
            f"requested tools {sorted(unauthorized)} not in signed grant"
        )


def accept_handoff(cred: Credential, live: LiveMeasurement, requested_tools: set[str]) -> str:
    validate_peer(cred, live, requested_tools)
    return "accepted"
