# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-equivocation-is-indistinguishable-from-its-sampling-temperature.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-equivocation-is-indistinguishable-from-its-sampling-temperature.warrant.json
# Markdown SHA-256:   9ee32060217ac57eed86218157911365e64929f78c5446fa791f42645358148e
# Code AST SHA-256:   1c953e746b8210351120be4f89c42afab421bd0f0c0980e28ad9c9080a636a51
# Verified Classes:   EquivocationAmbiguityError, Vote, VoteLedger, ByzantineFault
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationAmbiguityError(RuntimeError):
    """Raised when a signed vote conflicts with a prior vote in the same view
    but the signer's sampling was not nonce-committed, so the conflict cannot
    be attributed to Byzantine behavior versus stochastic decoding."""


@dataclass(frozen=True)
class Vote:
    view: int
    block: str
    signer: str
    nonce: str | None  # None => uncommitted sampling, attribution impossible
    signature: str


class VoteLedger:
    """Enforces the per-(view, signer) single-vote invariant at the signing boundary."""

    def __init__(self) -> None:
        self._seen: dict[tuple[int, str], Vote] = {}

    def record(self, vote: Vote) -> None:
        key = (vote.view, vote.signer)
        prior = self._seen.get(key)
        if prior is None:
            self._seen[key] = vote
            return
        if prior.block == vote.block:
            return  # idempotent replay of the same vote, harmless
        # Conflicting vote in the same view.
        if prior.nonce is None or vote.nonce is None:
            raise EquivocationAmbiguityError(
                f"signer={vote.signer} view={vote.view} emitted conflicting votes "
                f"({prior.block!r} vs {vote.block!r}) without a committed nonce; "
                f"cannot distinguish stochastic sampling from Byzantine equivocation. "
                f"Route to view-change, do not quarantine."
            )
        # Both votes are nonce-committed: a genuine Byzantine fault.
        raise ByzantineFault(
            f"signer={vote.signer} view={vote.view} equivocated under committed "
            f"nonce {vote.nonce!r}; safe to attribute and slash."
        )


class ByzantineFault(RuntimeError):
    pass


def quorum_size(f: int, s: int = 0) -> int:
    """n >= 3f + 2s + 1 preserves safety and liveness when s stochastic
    equivocations per view are tolerated."""
    if s < 0 or s > f:
        raise EquivocationAmbiguityError(f"stochastic allowance s={s} outside [0, f={f}]")
    return 3 * f + 2 * s + 1
