# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-equivocation-before-byzantine-quorum-consensus-the-signed-vote-equivocation-window-in-multi-agent-decision-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-equivocation-before-byzantine-quorum-consensus-the-signed-vote-equivocation-window-in-multi-agent-decision-quorums.warrant.json
# Markdown SHA-256:   4631f0bd21bd6c01d9850243e3abae6bc28055f2536502b8cd39d65abb4dcd29
# Code AST SHA-256:   d509d75f1c9a402281f254afc4608bdd877da0fe3568cd6517cd97e251e0735c
# Verified Classes:   EquivocationWindowError, SignerState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EquivocationWindowError(RuntimeError):
    """Raised when a signing instance or quorum collector detects that the
    durable high-water mark was not preserved across a restart, opening an
    equivocation window that invalidates the BFT intersection argument."""


@dataclass
class SignerState:
    identity: str
    epoch: int
    high_water_round: int = -1
    durable: bool = False  # set True only after fsync of high_water_round


def sign_vote(state: SignerState, round_no: int, proposal_hash: str) -> dict:
    # Boundary: the high-water mark must be durable BEFORE the signature is emitted.
    if round_no <= state.high_water_round:
        raise EquivocationWindowError(
            f"identity {state.identity} epoch {state.epoch} already signed "
            f"round {state.high_water_round} >= {round_no}; refusing to double-sign"
        )
    if not state.durable:
        raise EquivocationWindowError(
            f"identity {state.identity} attempted to sign round {round_no} "
            f"with non-durable high-water mark; restart would reopen the window"
        )
    state.high_water_round = round_no
    # In production: fsync state.high_water_round here, then set state.durable = True.
    return {
        "identity": state.identity,
        "epoch": state.epoch,
        "round": round_no,
        "proposal": proposal_hash,
        "sig": hashlib.sha256(f"{state.identity}:{state.epoch}:{round_no}:{proposal_hash}".encode()).hexdigest(),
    }


def validate_certificate(
    cert: dict,
    prior_certs: list[dict],
    n: int,
) -> bool:
    # Condition 3: union-consistency across conflicting certificates at the same round.
    signers = {v["identity"] for v in cert["votes"]}
    if len(signers) != len(cert["votes"]):
        raise EquivocationWindowError("certificate contains duplicate signer identities")
    for prior in prior_certs:
        if prior["round"] != cert["round"]:
            continue
        if prior["proposal"] == cert["proposal"]:
            continue
        prior_signers = {v["identity"] for v in prior["votes"]}
        union = signers | prior_signers
        if len(union) > n:
            raise EquivocationWindowError(
                f"conflicting certificates at round {cert['round']} have union "
                f"{len(union)} > n={n}; intersection argument void"
            )
    return True
