# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-planners-in-byzantine-consensus-when-the-vote-tally-is-still-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-planners-in-byzantine-consensus-when-the-vote-tally-is-still-valid.warrant.json
# Markdown SHA-256:   ebfa1df5aeb975749aef60ae4409148df31dfd804de3cd5b7c73822f3df3f5e7
# Code AST SHA-256:   29d42bebefad89d84052ed868bbf2ab0e3af2764401daa0a4cb14de018f92743
# Verified Classes:   EquivocationDetected, CertificateInvalid, QuorumCertificate
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class EquivocationDetected(RuntimeError):
    """Raised when two valid, epoch-matched quorum certificates conflict on one slot."""


class CertificateInvalid(RuntimeError):
    """Raised when a certificate fails signature or threshold verification."""


@dataclass(frozen=True)
class QuorumCertificate:
    slot_id: str
    epoch: int
    content_hash: str
    signers: frozenset[str]
    signatures_valid: bool


def _verify(qc: QuorumCertificate, validator_set: frozenset[str], threshold: int) -> None:
    if not qc.signatures_valid:
        raise CertificateInvalid(f"bad signatures on QC for slot={qc.slot_id}")
    if not qc.signers.issubset(validator_set):
        raise CertificateInvalid(f"QC signer outside validator set: {qc.signers - validator_set}")
    if len(qc.signers) < threshold:
        raise CertificateInvalid(
            f"QC for slot={qc.slot_id} has {len(qc.signers)} signers < threshold {threshold}"
        )


def detect_equivocation(
    certificates: Iterable[QuorumCertificate],
    validator_set: frozenset[str],
    threshold: int,
) -> None:
    """
    Scan forwarded certificates for an equivocation proof pair.

    Detection does NOT require the caller to be a member of either quorum.
    It requires only that both certificates independently verify and share
    (slot_id, epoch) while disagreeing on content_hash.
    """
    by_slot_epoch: dict[tuple[str, int], list[QuorumCertificate]] = {}
    for qc in certificates:
        _verify(qc, validator_set, threshold)
        by_slot_epoch.setdefault((qc.slot_id, qc.epoch), []).append(qc)

    for (slot_id, epoch), group in by_slot_epoch.items():
        hashes = {qc.content_hash for qc in group}
        if len(hashes) < 2:
            continue
        # Proof pair exists. Compute the intersection of signers across the
        # conflicting certificates; those are the quarantine candidates.
        intersection = frozenset.intersection(*(qc.signers for qc in group))
        raise EquivocationDetected(
            f"equivocation at slot={slot_id} epoch={epoch}: "
            f"hashes={sorted(hashes)} quarantine={sorted(intersection)}"
        )


def advance_view(
    certificates: Iterable[QuorumCertificate],
    validator_set: frozenset[str],
    threshold: int,
) -> None:
    """
    Guardrail: a view-change must not silently discard conflicting QCs.
    Any conflict must surface as EquivocationDetected before the view advances.
    """
    try:
        detect_equivocation(certificates, validator_set, threshold)
    except EquivocationDetected:
        # Re-raise: the caller is responsible for freezing the slot and
        # quarantining intersection signers before any new epoch begins.
        raise
    except CertificateInvalid as exc:
        # Invalid certs are a separate fault class: log and drop, do not
        # treat as equivocation evidence.
        raise CertificateInvalid(f"view-change aborted: {exc}") from exc
