# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-heterogeneous-llm-agents-sign-conflicting-proposals-under-bft-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-heterogeneous-llm-agents-sign-conflicting-proposals-under-bft-consensus.warrant.json
# Markdown SHA-256:   6106e272cf0261710df4f68f041810256009fbf41c68061030a05dd0b526ee45
# Code AST SHA-256:   00f80bda1bddca8eeca2a9425ceda401362914914a2353a63ae95c0619f4ba5e
# Verified Classes:   EquivocationDetectorError, CanonicalizationError, SignedProposal, EquivocationWitness
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class EquivocationDetectorError(RuntimeError):
    """Raised when the equivocation predicate cannot be evaluated soundly."""


class CanonicalizationError(EquivocationDetectorError):
    """Raised when a payload cannot be mapped to a deterministic canonical form."""


@dataclass(frozen=True)
class SignedProposal:
    identity: str
    height: int
    view: int
    payload: dict
    signature: bytes


@dataclass(frozen=True)
class EquivocationWitness:
    identity: str
    height: int
    view: int
    canon_hash_a: str
    canon_hash_b: str
    sig_a: bytes
    sig_b: bytes


CANON_VERSION = "canon-v3"
_KNOWN_KEYS = {"assign"}


def canon(payload: dict) -> bytes:
    """Deterministic canonical form. Must be total over the schema or fail closed."""
    unknown = set(payload) - _KNOWN_KEYS
    if unknown:
        raise CanonicalizationError(
            f"payload has keys outside pinned schema: {sorted(unknown)}"
        )
    assign = payload.get("assign")
    if not isinstance(assign, list) or not all(isinstance(x, str) for x in assign):
        raise CanonicalizationError("assign must be a list[str]")
    # sorting makes set-order presentation-invariant; rationale is stripped by schema
    normalized = "assign=" + ",".join(sorted(assign))
    return normalized.encode("utf-8")


def canon_hash(payload: dict) -> str:
    return hashlib.sha256(canon(payload)).hexdigest()


def detect_equivocation(
    a: Optional[SignedProposal],
    b: Optional[SignedProposal],
) -> Optional[EquivocationWitness]:
    """
    Pure comparator. Returns a witness iff identity X signed two payloads at the
    same (h, v) whose canonical forms differ. Returns None otherwise.

    Caller MUST treat None as NO_CONFLICT_SEEN, never as NO_FAULT.
    """
    if a is None or b is None:
        # insufficient evidence is a distinct outcome; do not fabricate a verdict
        return None
    if (a.identity, a.height, a.view) != (b.identity, b.height, b.view):
        # different identity or different slot => divergence, not equivocation
        return None
    ha, hb = canon_hash(a.payload), canon_hash(b.payload)
    if ha == hb:
        # byte-different but canonically identical => honest retry, not fault
        return None
    return EquivocationWitness(
        identity=a.identity,
        height=a.height,
        view=a.view,
        canon_hash_a=ha,
        canon_hash_b=hb,
        sig_a=a.signature,
        sig_b=b.signature,
    )


def open_fault_investigation(witness: Optional[EquivocationWitness]) -> str:
    if witness is None:
        return "NO_CONFLICT_SEEN"  # explicitly not an acquittal
    # a witness is only admissible if both canon forms are reproducible locally
    for h in (witness.canon_hash_a, witness.canon_hash_b):
        if len(h) != 64:
            raise EquivocationDetectorError(
                f"malformed canon hash in witness: {h!r}"
            )
    return "EQUIVOCATION_PROVEN"
