# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-provenance-chain-contains-a-re-signed-hop-rather-than-a-forwarded-signature.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-provenance-chain-contains-a-re-signed-hop-rather-than-a-forwarded-signature.warrant.json
# Markdown SHA-256:   57dbcc4e3dab9b57142718132f5ef62de55cdd621ce367aa1f11698b52966f35
# Code AST SHA-256:   03bd3482aa208456a7fc6b0df5f3a885fe7da2d675a42068638132c7ea67d5fa
# Verified Classes:   ProvenanceReconstructionError, Hop
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceReconstructionError(RuntimeError):
    """Raised when a delegation hop binds to a reconstruction, not raw prior bytes."""


@dataclass(frozen=True)
class Hop:
    signer: str
    raw_token: bytes          # exact bytes this instance signed
    parent_commit: bytes      # H(raw parent token) embedded in signed payload
    is_minting_authority: bool = False


def verify_chain(hops: list[Hop], trusted_forwarders: set[str],
                 trusted_minters: set[str]) -> None:
    if not hops:
        raise ProvenanceReconstructionError("empty delegation chain")

    for i, hop in enumerate(hops):
        if hop.is_minting_authority:
            if hop.signer not in trusted_minters:
                raise ProvenanceReconstructionError(
                    f"hop {i}: {hop.signer} claims minting authority but is not trusted to mint")
            # A minting hop severs byte-exact provenance; record and continue only
            # if the caller has opted into reconstruction-tolerant mode.
            continue
        if hop.signer not in trusted_forwarders:
            raise ProvenanceReconstructionError(
                f"hop {i}: {hop.signer} is not a trusted forwarding signer")
        if i == 0:
            continue
        prior_raw = hops[i - 1].raw_token
        expected = hashlib.sha256(prior_raw).digest()
        if hop.parent_commit != expected:
            raise ProvenanceReconstructionError(
                f"hop {i}: parent_commit does not match H(raw prior token); "
                f"chain binds to a reconstruction, not the original emission")


def audit_refund(hops: list[Hop], forwarders: set[str], minters: set[str]) -> None:
    # Irreversible side effect: reconstruction chains are not admissible.
    if any(h.is_minting_authority for h in hops):
        raise ProvenanceReconstructionError(
            "audit-grade action refused: chain contains a re-signing hop")
    verify_chain(hops, forwarders, minters)
