# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-quorum-arithmetic-as-a-state-continuity-invariant-rather-than-a-per-round-vote-count.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-quorum-arithmetic-as-a-state-continuity-invariant-rather-than-a-per-round-vote-count.warrant.json
# Markdown SHA-256:   499a4b082320580c0e720f5167dfa544a4eb5d428fce1305e09c1f12f3e06b71
# Code AST SHA-256:   e2aabec65ba2a8e9e2c80f563c04d65d628ffd59bce21040f5619e2f9610f8b8
# Verified Classes:   QuorumContinuityError, SignedVote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class QuorumContinuityError(RuntimeError):
    """Raised when a resumed quorum tally violates the Byzantine intersection invariant."""


@dataclass(frozen=True)
class SignedVote:
    voter_id: str
    round: int
    proposal_hash: str
    signature: str  # verified out-of-band against registered key


def validate_resumed_quorum(
    target_hash: str,
    current_round: int,
    carried_ledger: Iterable[SignedVote],
    fresh_votes: Iterable[SignedVote],
    f: int,
    verify_signature,
) -> set[str]:
    """
    Rebuild a quorum only from hash-bound, signature-verified votes.
    Refuses to commit if carried votes do not bind to the target or if the
    honest intersection with prior evidence is below f+1.
    """
    threshold = 2 * f + 1
    verified: set[str] = set()
    prior_hashes: set[str] = set()

    for vote in list(carried_ledger) + list(fresh_votes):
        if not verify_signature(vote):
            raise QuorumContinuityError(
                f"unverifiable signature from {vote.voter_id} at round {vote.round}"
            )
        if vote.round > current_round:
            raise QuorumContinuityError(
                f"future-round vote from {vote.voter_id}: {vote.round} > {current_round}"
            )
        if vote.proposal_hash != target_hash:
            # A carried vote for a different hash is evidence of divergence,
            # not a vote we may silently discard.
            prior_hashes.add(vote.proposal_hash)
            raise QuorumContinuityError(
                f"carried vote from {vote.voter_id} bound to {vote.proposal_hash}, "
                f"not target {target_hash}: possible equivocation"
            )
        verified.add(vote.voter_id)

    if len(verified) < threshold:
        raise QuorumContinuityError(
            f"insufficient hash-bound quorum: {len(verified)} < {threshold}"
        )
    # Intersection with any prior quorum must contain >= f+1 honest members.
    if prior_hashes and len(verified) < f + 1:
        raise QuorumContinuityError("honest intersection below f+1")
    return verified
