# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-in-byzantine-tolerant-multi-agent-task-commitment-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-in-byzantine-tolerant-multi-agent-task-commitment-quorums.warrant.json
# Markdown SHA-256:   7d17f46892ee76a2321b60d95945eaae4654f6217552e5d6c9be0c36e2082fce
# Code AST SHA-256:   f95b396b9f2ea67491e99317413b3b0587b3b38de952920bcbb9ef5ca240efac
# Verified Classes:   EquivocationCollapseError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json


class EquivocationCollapseError(RuntimeError):
    """Raised when a quorum certificate's payload digest does not bind to a
    locally verifiable payload, indicating payload-blind attestation."""
    pass


def canonical_digest(payload: dict) -> str:
    # Deterministic, out-of-model serializer. Never delegate this to an LLM.
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def verify_quorum_certificate(qc: dict, local_payload: dict, quorum_size: int) -> bool:
    """Validate a quorum certificate against a locally held payload.

    A QC is valid iff:
      1. Its embedded digest matches the local payload's canonical digest.
      2. At least `quorum_size` distinct voters attested to that exact digest.
    """
    embedded_digest = qc.get("payload_digest")
    if embedded_digest is None:
        # A QC without a content digest is unverifiable; treat as absent.
        raise EquivocationCollapseError(
            "QC missing payload_digest; cannot bind certificate to content"
        )

    local_digest = canonical_digest(local_payload)
    if embedded_digest != local_digest:
        raise EquivocationCollapseError(
            f"Digest mismatch: QC binds {embedded_digest[:12]} but local payload "
            f"hashes to {local_digest[:12]}; possible equivocation collapse"
        )

    voters = {v["voter_id"] for v in qc.get("votes", []) if v.get("digest") == embedded_digest}
    if len(voters) < quorum_size:
        raise EquivocationCollapseError(
            f"Only {len(voters)} distinct voters bound to digest; need {quorum_size}"
        )
    return True
