# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-hardware-attested-warrant-when-the-delegation-chain-spans-an-enclave-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-hardware-attested-warrant-when-the-delegation-chain-spans-an-enclave-boundary.warrant.json
# Markdown SHA-256:   2d00d9276414a89035c6f441f1049665a5b38883e2eba8b9624ca73642f51725
# Code AST SHA-256:   4adcf4d2efd40e8ec0cd7164349d6b943d22f2c90ad12b8dbaf089f3ec9b6bc9
# Verified Classes:   AttestationScopeError, AttestationReport, DelegationHop, WarrantChain
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class AttestationScopeError(RuntimeError):
    """Raised when a delegation hop claims hardware attestation it cannot evidence."""
    pass


@dataclass
class AttestationReport:
    report_data: bytes          # hash bound into the hardware report
    nonce: bytes                # verifier-supplied nonce
    issued_at: float
    measurement: str            # e.g. SEV-SNP launch measurement
    hardware_root: str          # "sev-snp" | "tpm" | "secure-enclave"


@dataclass
class DelegationHop:
    issuer_key: str
    subject_key: str
    scope: frozenset
    delegation_binding: bytes   # signature over (subject_key, scope, nonce, upstream_hash)
    attestation: Optional[AttestationReport] = None
    declared_hardware: bool = False


@dataclass
class WarrantChain:
    hops: list = field(default_factory=list)


FRESHNESS_WINDOW_S = 300.0


def _binding_hash(hop: DelegationHop, upstream_hash: bytes) -> bytes:
    payload = hop.subject_key.encode() + b"|" + b"|".join(sorted(hop.scope)).encode()
    return hashlib.sha256(payload + b"|" + upstream_hash).digest()


def verify_chain(chain: WarrantChain, verifier_nonce: bytes) -> str:
    """
    Returns the trust class of the chain: 'hardware-attested' or
    'software-attested(depth=n)'. Raises AttestationScopeError if a hop
    claims hardware attestation without a live, nonce-bound report covering
    its own delegation binding.
    """
    upstream_hash = b""
    trust_floor = "hardware-attested"
    downgrade_depth = None

    for idx, hop in enumerate(chain.hops):
        expected_binding = _binding_hash(hop, upstream_hash)

        if hop.declared_hardware:
            if hop.attestation is None:
                raise AttestationScopeError(
                    f"hop {idx} ({hop.issuer_key}) declares hardware attestation "
                    f"but presents no live report"
                )
            rep = hop.attestation
            if rep.nonce != verifier_nonce:
                raise AttestationScopeError(
                    f"hop {idx} attestation nonce mismatch: report was issued "
                    f"for a different verifier challenge (replay artifact)"
                )
            if time.time() - rep.issued_at > FRESHNESS_WINDOW_S:
                raise AttestationScopeError(
                    f"hop {idx} attestation is stale by "
                    f"{time.time() - rep.issued_at:.0f}s"
                )
            if rep.report_data != expected_binding:
                raise AttestationScopeError(
                    f"hop {idx} hardware report does not cover this hop's "
                    f"delegation binding; attestation terminates upstream and "
                    f"cannot evidence the delegation act"
                )
        else:
            if trust_floor == "hardware-attested":
                trust_floor = "software-attested"
                downgrade_depth = idx

        upstream_hash = hashlib.sha256(
            upstream_hash + hop.delegation_binding
        ).digest()

    if trust_floor == "hardware-attested":
        return "hardware-attested"
    return f"software-attested(depth={downgrade_depth})"
