# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-equivocation-boundary-when-byzantine-quorum-voting-agents-sign-divergent-proposals-to-different-peers.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-equivocation-boundary-when-byzantine-quorum-voting-agents-sign-divergent-proposals-to-different-peers.warrant.json
# Markdown SHA-256:   0cb8924922c406be12c054d25ec272a2324e728aa59efc7a7c613833f5bce529
# Code AST SHA-256:   22d90265094640802b3d329d8a8a264ca8ed313fcb0206091d69464dd7fb0a73
# Verified Classes:   EquivocationBoundaryError, StaleHeightError, SignedVote, EquivocationGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass
from typing import Optional


class EquivocationBoundaryError(RuntimeError):
    """Raised when a signing request would produce a second vote at an already-signed height."""


class StaleHeightError(RuntimeError):
    """Raised when a signing request targets a height below the committed counter."""


@dataclass(frozen=True)
class SignedVote:
    height: int
    proposal_hash: str
    signature: str
    already_broadcast: bool


class EquivocationGuard:
    """
    Signer-side guard enforcing the invariant:
      for every height, at most one proposal_hash is ever signed.
    The private key never leaves this object; callers cannot bypass the check.
    """

    def __init__(self, agent_id: str, secret: bytes):
        self._agent_id = agent_id
        self._secret = secret
        self._last_height: int = -1
        self._last_hash: Optional[str] = None
        self._last_sig: Optional[str] = None

    def _sign(self, height: int, proposal_hash: str) -> str:
        msg = f"{self._agent_id}|{height}|{proposal_hash}".encode()
        return hmac.new(self._secret, msg, hashlib.sha256).hexdigest()

    def sign_vote(self, height: int, proposal_hash: str) -> SignedVote:
        if height < self._last_height:
            raise StaleHeightError(
                f"height {height} is below committed height {self._last_height}"
            )

        if height == self._last_height:
            if proposal_hash == self._last_hash:
                # Legitimate retry of an already-signed vote: return cache, mark broadcast.
                return SignedVote(
                    height=height,
                    proposal_hash=proposal_hash,
                    signature=self._last_sig,
                    already_broadcast=True,
                )
            # Equivocation boundary: caller's view shifted under retry pressure.
            raise EquivocationBoundaryError(
                f"agent {self._agent_id} already signed height {height} for "
                f"{self._last_hash!r}; refusing conflicting {proposal_hash!r}. "
                f"Caller view has diverged from signer history."
            )

        # height > last_height: commit atomically before returning.
        sig = self._sign(height, proposal_hash)
        self._last_height = height
        self._last_hash = proposal_hash
        self._last_sig = sig
        return SignedVote(
            height=height,
            proposal_hash=proposal_hash,
            signature=sig,
            already_broadcast=False,
        )


def handle_vote_retry(guard: EquivocationGuard, height: int, proposal_hash: str,
                      transport_timed_out: bool) -> SignedVote:
    """
    Retry path. Distinguishes transport timeout (signature may exist) from
    signer rejection (no signature). Conflating these is the original bug.
    """
    if transport_timed_out:
        # Query the signer for the cached signature rather than re-deriving.
        try:
            return guard.sign_vote(height, proposal_hash)
        except EquivocationBoundaryError:
            # View shifted between attempts; halt and escalate, do not broadcast.
            raise EquivocationBoundaryError(
                f"retry at height {height} hit equivocation boundary; "
                f"halting vote path and escalating to view-change"
            )
    raise EquivocationBoundaryError(
        "retry invoked without a transport-timeout condition; "
        "this path must not re-sign under view uncertainty"
    )
