# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-from-a-byzantine-coordinator-before-commitment-finalization-in-bft-multi-agent-task-protocols.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-from-a-byzantine-coordinator-before-commitment-finalization-in-bft-multi-agent-task-protocols.warrant.json
# Markdown SHA-256:   0dfc06db0ec6c2e48d239914f8b73c1de8225d6d6cb6b665e9708509f89d619e
# Code AST SHA-256:   ec3a362b61f974a8ccc1ab7a9304059f268dae486d4dc465e3b4779e660d64d8
# Verified Classes:   EquivocationDetected, VoteWithoutProposal, ProposalRecord, ProposalLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Tuple, Optional


class EquivocationDetected(RuntimeError):
    """Raised when a replica observes two distinct proposal digests for the same (view, seq)."""
    pass


class VoteWithoutProposal(RuntimeError):
    """Raised when asked to vote on a digest never logged as a proposal for that (view, seq)."""
    pass


@dataclass(frozen=True)
class ProposalRecord:
    view: int
    seq: int
    digest: bytes
    coordinator_sig: bytes


class ProposalLog:
    """Durable log of every PRE-PREPARE seen, including non-quorum proposals."""

    def __init__(self) -> None:
        self._log: Dict[Tuple[int, int], ProposalRecord] = {}

    def record(self, rec: ProposalRecord) -> None:
        key = (rec.view, rec.seq)
        prior = self._log.get(key)
        if prior is not None and prior.digest != rec.digest:
            # Two distinct digests for the same slot: equivocation.
            raise EquivocationDetected(
                f"coordinator equivocated at view={rec.view} seq={rec.seq}: "
                f"digest {prior.digest.hex()[:8]} vs {rec.digest.hex()[:8]}"
            )
        self._log[key] = rec

    def lookup(self, view: int, seq: int) -> Optional[ProposalRecord]:
        return self._log.get((view, seq))


def cast_prepare_vote(
    log: ProposalLog, view: int, seq: int, digest: bytes
) -> bytes:
    """A replica may only vote on a digest it has itself logged for that slot."""
    rec = log.lookup(view, seq)
    if rec is None:
        raise VoteWithoutProposal(
            f"refusing vote for view={view} seq={seq}: no logged proposal"
        )
    if rec.digest != digest:
        # This is the vote-forwarding trap: the digest differs from our log.
        raise EquivocationDetected(
            f"vote requested for digest {digest.hex()[:8]} but log holds "
            f"{rec.digest.hex()[:8]} at view={view} seq={seq}"
        )
    return b"vote:" + digest  # placeholder for signed vote
