# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-delegation-chain-attenuation-loss-when-an-aaif-verifiable-credential-is-re-signed-across-a-scope-reduci.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-delegation-chain-attenuation-loss-when-an-aaif-verifiable-credential-is-re-signed-across-a-scope-reduci.warrant.json
# Markdown SHA-256:   e8575c5c250bc575b513575fda37e4575a8f192c0b33b0984829a168a8dd1675
# Code AST SHA-256:   ee3defb8eb254006cdeab09da03bde23f90a27d483fd4fd8f5ca1a02ddbd76b8
# Verified Classes:   DelegationChainAttenuationError
# Defensive Guards:   8 fail-closed invariants (zero external deps)

class DelegationChainAttenuationError(RuntimeError):
    """Raised when a delegated AAIF credential's provenance is severed or reused."""
    pass


def verify_delegation_chain(chain, pinned_root_pubkey, seen_parent_hashes):
    """
    chain: list of credential dicts ordered root -> leaf.
    Each cred must have: issuer, scope (set), exp, parentCredential (hash or None),
    signature (bytes), canonical_bytes (bytes over which signature is computed,
    including parentCredential and issuer).
    """
    if not chain:
        raise DelegationChainAttenuationError("empty chain")

    root = chain[0]
    if root.get("parentCredential") is not None:
        raise DelegationChainAttenuationError("root credential declares a parent")

    if not verify_sig(root["canonical_bytes"], root["signature"], pinned_root_pubkey):
        raise DelegationChainAttenuationError("root signature does not verify against pinned key")

    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]

        # (1) parent link must be covered by the child's signature
        if child.get("parentCredential") != hash_cred(parent["canonical_bytes"]):
            raise DelegationChainAttenuationError(
                f"hop {i}: parentCredential does not bind to presented parent"
            )

        # (2) monotonic attenuation
        if not child["scope"].issubset(parent["scope"]):
            raise DelegationChainAttenuationError(
                f"hop {i}: scope re-expansion {child['scope']} !<= {parent['scope']}"
            )
        if child["exp"] > parent["exp"]:
            raise DelegationChainAttenuationError(
                f"hop {i}: expiry extended beyond parent"
            )

        # (3) issuer continuity or explicit delegation warrant
        if child["issuer"] != parent["issuer"]:
            warrant = child.get("delegationWarrant")
            if warrant is None or not verify_sig(
                warrant["canonical_bytes"], warrant["signature"], parent["issuer_pubkey"]
            ):
                raise DelegationChainAttenuationError(
                    f"hop {i}: issuer changed {parent['issuer']} -> {child['issuer']} "
                    "without a valid delegation warrant"
                )

        # (4) parent-hash uniqueness across the session
        ph = child["parentCredential"]
        if ph in seen_parent_hashes and seen_parent_hashes[ph] != child["scope"]:
            raise DelegationChainAttenuationError(
                f"hop {i}: parent hash {ph.hex()[:12]} reused with incompatible child scope"
            )
        seen_parent_hashes[ph] = child["scope"]

    return True
