# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-equivocation-evidence-as-valid-only-when-the-signed-payloads-are-bit-identical-across-quorum-paths.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-equivocation-evidence-as-valid-only-when-the-signed-payloads-are-bit-identical-across-quorum-paths.warrant.json
# Markdown SHA-256:   e8349bac98b67b2c151f48bd3e7e0db15a717e1f97a7caa01bc9513e11bd4e19
# Code AST SHA-256:   7b6d4be0f9a160729bb754e0e00e035a53fff7975c453986f3de5cb18c420c83
# Verified Classes:   EquivocationProofInvalid, SignedProposal
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationProofInvalid(RuntimeError):
    """Raised when an equivocation proof fails canonical replay verification."""
    pass


@dataclass(frozen=True)
class SignedProposal:
    task_id: str
    slot: int
    epoch: int
    nonce: bytes            # agent-chosen; NOT part of commitment semantics
    payload_hash: bytes
    retry_of: bytes | None  # digest of a prior message this re-signs, if any
    signature: bytes


def canonical_commitment_key(p: SignedProposal) -> tuple:
    # Only fields the honest agent cannot vary between honest emissions
    # for the same slot are part of the commitment key.
    return (p.task_id, p.slot, p.epoch)


def verify_equivocation(
    accused_pk: bytes,
    m1: SignedProposal,
    m2: SignedProposal,
    nonces_are_slot_assigned: bool,
    verify_sig,
) -> None:
    """Replay-verify an equivocation proof. Raises on any failure."""
    if not verify_sig(accused_pk, m1) or not verify_sig(accused_pk, m2):
        raise EquivocationProofInvalid("signature verification failed")

    if canonical_commitment_key(m1) != canonical_commitment_key(m2):
        raise EquivocationProofInvalid(
            "messages target different slots; not an equivocation"
        )

    if m1.payload_hash == m2.payload_hash:
        raise EquivocationProofInvalid(
            "identical payloads; duplicate or re-sign, not equivocation"
        )

    # The sharp edge: agent-chosen nonces mean distinct nonces do NOT
    # by themselves prove equivocation.
    if not nonces_are_slot_assigned and m1.nonce != m2.nonce:
        # Ambiguous: require retry-lineage disambiguation upstream.
        raise EquivocationProofInvalid(
            "distinct agent-chosen nonces; evidence is ambiguous, "
            "escalate to witness round rather than slash"
        )

    # Protocol-sanctioned retry lineage must be honored.
    if m1.retry_of == m2.payload_hash or m2.retry_of == m1.payload_hash:
        raise EquivocationProofInvalid(
            "one message is a documented re-sign of the other"
        )

    # Proof is valid; caller may emit slash evidence.
    return None
