# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-zero-knowledge-attestation-of-tool-invocation-whose-merkle-inclusion-path-is-valid-but-whose-leaf-prei.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-zero-knowledge-attestation-of-tool-invocation-whose-merkle-inclusion-path-is-valid-but-whose-leaf-prei.warrant.json
# Markdown SHA-256:   0bcc913e3b9e0ef6a7d5f11f60fcba9b16390a39b61dc75663535e6e46a937b2
# Code AST SHA-256:   c001dc8cea7ef966295abf79f4d1fbace7540a5d7a1fc7b8df81650f75b57dca
# Verified Classes:   MalleableAttestationError, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class MalleableAttestationError(RuntimeError):
    """Raised when a leaf preimage is not bound to the issuer's committed encoding."""
    pass


DOMAIN = b"agent-invocation-v1\x00"


@dataclass(frozen=True)
class Attestation:
    preimage: bytes
    merkle_path: list[bytes]
    root: bytes
    leaf_encoding_pinned: bool
    root_from_independent_channel: bool


def commit(preimage: bytes) -> bytes:
    return hashlib.sha256(DOMAIN + preimage).digest()


def fold_path(leaf: bytes, path: list[bytes]) -> bytes:
    node = leaf
    for sibling in path:
        node = hashlib.sha256(node + sibling).digest()
    return node


def verify_attestation(att: Attestation) -> None:
    leaf = commit(att.preimage)
    derived_root = fold_path(leaf, att.merkle_path)

    if derived_root != att.root:
        raise MalleableAttestationError(
            "inclusion path does not fold to the supplied root"
        )

    if not att.leaf_encoding_pinned:
        raise MalleableAttestationError(
            "leaf encoding not pinned to a canonicalization standard; "
            "preimage may not be the issuer's committed preimage"
        )

    if not att.root_from_independent_channel:
        raise MalleableAttestationError(
            "root obtained from same channel as preimage; "
            "inclusion path is self-consistent but not authentic"
        )
