# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-fault-tolerant-llm-quorum-silently-commit-an-equivocating-proposal-when-the-signature-threshold-is-met-but-the-pay.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-fault-tolerant-llm-quorum-silently-commit-an-equivocating-proposal-when-the-signature-threshold-is-met-but-the-pay.warrant.json
# Markdown SHA-256:   1210bfa65837168d5aac9d0d912bfbceb70ae9c142acf4981a517704be2ad273
# Code AST SHA-256:   f2e5a1bba20e3476a5eaed20c73d5f3f8b5a5f9fe615f42871e349a0ff934a13
# Verified Classes:   EquivocationSafetyError, Proposal
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class EquivocationSafetyError(RuntimeError):
    """Raised when a validator would sign a digest it cannot bind to a payload
    it independently reconstructed. Signing in this state converts a detectable
    Byzantine proposer into an undetectable committed equivocation."""
    pass


@dataclass(frozen=True)
class Proposal:
    seq: int
    digest: str
    payload: dict  # full payload, must come from a content-addressed source


def canonical_digest(payload: dict) -> str:
    # Protocol-pinned canonicalization. Must be identical across all validators
    # and must NOT be defined in an LLM prompt.
    encoded = json.dumps(
        payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True
    ).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()


def validate_and_sign(proposal: Proposal, independently_fetched_payload: dict | None) -> str:
    if independently_fetched_payload is None:
        # Payload unavailable from any source other than the proposer.
        # Abstain; do not sign on proposer authority.
        raise EquivocationSafetyError(
            f"seq={proposal.seq}: payload unavailable from independent source; "
            f"refusing to sign digest {proposal.digest[:12]}"
        )

    reconstructed = canonical_digest(independently_fetched_payload)
    if reconstructed != proposal.digest:
        # Mismatch is FATAL. Do not warn-and-proceed.
        raise EquivocationSafetyError(
            f"seq={proposal.seq}: digest mismatch — proposer claims "
            f"{proposal.digest[:12]}, reconstruction yields {reconstructed[:12]}; "
            f"abstaining (abstention {1} of f+1 before view change)"
        )

    # Signature binds to the reconstructed digest, not the proposer's claim.
    return f"sig(seq={proposal.seq}, digest={reconstructed})"
