# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-bft-agent-quorum-when-the-commit-warrant-is-self-signed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-bft-agent-quorum-when-the-commit-warrant-is-self-signed.warrant.json
# Markdown SHA-256:   881f466a2a4702c4d7aad7555905f89b3a40e1b82d4807110b3cf59a95c1a7ed
# Code AST SHA-256:   d9b17612b9e23fb0721225180e2d422a3d6567e2d791579c69a449fb85de9a3c
# Verified Classes:   EquivocationDetected, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationDetected(RuntimeError):
    """Raised when two distinct payload hashes are observed for one (task_id, round)."""


@dataclass(frozen=True)
class Vote:
    task_id: str
    round: int
    payload_hash: str
    voter_id: str


def payload_hash(task_id: str, round_no: int, payload: bytes) -> str:
    # Bind task_id and round into the hash so votes cannot be replayed across rounds.
    h = hashlib.sha256()
    h.update(task_id.encode())
    h.update(b"|")
    h.update(str(round_no).encode())
    h.update(b"|")
    h.update(payload)
    return h.hexdigest()


def register_and_vote(nullifier, task_id: str, round_no: int, payload: bytes, voter_id: str) -> Vote:
    """Honest voter path: register intent, then sign. Aborts on conflicting hash."""
    ph = payload_hash(task_id, round_no, payload)
    key = (task_id, round_no)

    # Read-quorum-verified view: nullifier.get must return the max-round consensus,
    # not a stale local value. Here we model it as returning the set of hashes seen.
    seen = nullifier.get_verified(key)

    if seen and ph not in seen:
        raise EquivocationDetected(
            f"task {task_id} round {round_no}: voter {voter_id} saw payload {ph[:12]} "
            f"but nullifier already holds {sorted(h[:12] for h in seen)}"
        )

    nullifier.put(key, ph)
    return Vote(task_id=task_id, round=round_no, payload_hash=ph, voter_id=voter_id)


def commit(cert, nullifier) -> str:
    """Commit path: refuse any certificate whose hash conflicts with the nullifier."""
    key = (cert.task_id, cert.round)
    seen = nullifier.get_verified(key)
    if seen and cert.payload_hash not in seen:
        raise EquivocationDetected(
            f"certificate for {cert.task_id}/{cert.round} certifies {cert.payload_hash[:12]} "
            f"but nullifier consensus is {sorted(h[:12] for h in seen)}"
        )
    if len(seen) > 1:
        raise EquivocationDetected(
            f"nullifier split for {cert.task_id}/{cert.round}: {sorted(h[:12] for h in seen)}"
        )
    return cert.payload_hash
