# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-in-a-byzantine-quorum-signs-a-decision-it-never-executed-equivocation-via-recomputed-digests-in-bft-agent-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-in-a-byzantine-quorum-signs-a-decision-it-never-executed-equivocation-via-recomputed-digests-in-bft-agent-quorums.warrant.json
# Markdown SHA-256:   b9008b017ef69b48a14c222f1fb6b48d10a823a98d0d4349a7a161ca228dd61f
# Code AST SHA-256:   fc6f4ba9ed39fe691e046113b5a0ccb282d95090a9f61e78e30f97dbe4a36fe4
# Verified Classes:   DigestEquivocationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any, Callable


class DigestEquivocationError(RuntimeError):
    """Raised when two voters sign the same digest but commit to divergent execution traces."""
    pass


def canonicalize(payload: dict[str, Any]) -> bytes:
    # Lossy by design: strips nulls and false-y optionals. This is the fault surface.
    def strip(obj: Any) -> Any:
        if isinstance(obj, dict):
            return {k: strip(v) for k, v in sorted(obj.items())
                    if v is not None and v is not False}
        if isinstance(obj, list):
            return [strip(v) for v in obj]
        return obj
    return json.dumps(strip(payload), separators=(",", ":")).encode()


def payload_digest(payload: dict[str, Any]) -> str:
    return hashlib.sha256(canonicalize(payload)).hexdigest()


def execution_trace_digest(payload: dict[str, Any],
                           execute: Callable[[dict[str, Any]], list[str]]) -> str:
    # Hash the actual tool-call sequence, not the bytes that produced it.
    trace = execute(payload)
    return hashlib.sha256(json.dumps(trace).encode()).hexdigest()


def verify_quorum_vote(envelope: dict[str, Any],
                       execute: Callable[[dict[str, Any]], list[str]],
                       quorum_trace_digests: list[str]) -> None:
    recomputed = payload_digest(envelope["plan"])
    if recomputed != envelope["digest"]:
        raise DigestEquivocationError(
            f"payload digest mismatch: envelope={envelope['digest']} recomputed={recomputed}"
        )
    trace_digest = execution_trace_digest(envelope["plan"], execute)
    if trace_digest not in quorum_trace_digests:
        raise DigestEquivocationError(
            "digest matched but execution trace diverged from quorum: "
            f"trace={trace_digest} quorum={quorum_trace_digests}. "
            "Signature commits to bytes, not action; refusing to execute."
        )
