# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-certificate-equivocation-when-agents-re-sign-state-roots-after-a-partial-view-change.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-certificate-equivocation-when-agents-re-sign-state-roots-after-a-partial-view-change.warrant.json
# Markdown SHA-256:   ee8c6b6efefe5226ede0ee78d9eb49b5b5e9f346b7a168243da1e4caf6cdf414
# Code AST SHA-256:   3c1dc74592bafba62cb35b03e395b393efa1f61ef7f4453f6593859a60cc7d18
# Verified Classes:   EquivocationRefused, SignerState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EquivocationRefused(RuntimeError):
    """Raised when an agent is asked to sign a state root that would
    contribute to a second quorum certificate at the same height."""
    pass


@dataclass
class SignerState:
    chain_id: str
    local_view: int = 0
    # height -> the single view this agent has committed a signature to
    signed_views: dict = field(default_factory=dict)
    # views for which a 2f+1 view-change certificate has been durably recorded
    warranted_views: set = field(default_factory=set)

    def _preimage(self, view: int, height: int, state_root: str) -> bytes:
        # view is bound into the signed payload: cross-view replay is impossible
        return f"{self.chain_id}|{view}|{height}|{state_root}".encode()

    def record_view_change_certificate(self, new_view: int):
        # only called after verifying 2f+1 distinct view-change signatures
        self.warranted_views.add(new_view)
        if new_view > self.local_view:
            self.local_view = new_view

    def sign_state_root(self, view: int, height: int, state_root: str) -> str:
        # Gate 1: no warrant for this view -> refuse to sign
        if view not in self.warranted_views:
            raise EquivocationRefused(
                f"no 2f+1 view-change certificate for view {view}; "
                f"refusing to sign height {height}"
            )
        # Gate 2: must be exactly the local view (not >=, not stale)
        if view != self.local_view:
            raise EquivocationRefused(
                f"proposal view {view} != local_view {self.local_view} at height {height}"
            )
        # Gate 3: atomic sign-once-per-height fence (compare-and-swap semantics)
        prior = self.signed_views.get(height)
        if prior is not None and prior != view:
            raise EquivocationRefused(
                f"already signed height {height} in view {prior}; "
                f"refusing second signature in view {view}"
            )
        self.signed_views[height] = view  # commit the fence BEFORE emitting
        return hashlib.sha256(self._preimage(view, height, state_root)).hexdigest()


def handle_proposal(state: SignerState, view: int, height: int, state_root: str) -> str:
    return state.sign_state_root(view, height, state_root)
