# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-equivocating-attestation-as-a-first-class-fault-rather-than-a-recoverable-divergence.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-equivocating-attestation-as-a-first-class-fault-rather-than-a-recoverable-divergence.warrant.json
# Markdown SHA-256:   e70eb91c72c75ee20e25d4d97c5c4bef54645fec9521240ea7375549b18421a5
# Code AST SHA-256:   0ed098466ab1768ea9255fa922b1680936e449bd0f16352e0f17ca0ea8b63874
# Verified Classes:   EquivocationFault, QuorumExhausted, Attestation, EquivocationDetector
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationFault(RuntimeError):
    """Raised when a signer has provably attested two conflicting results in one epoch."""
    pass


class QuorumExhausted(RuntimeError):
    """Raised when proven equivocators reach f+1 and no safe quorum remains."""
    pass


@dataclass(frozen=True)
class Attestation:
    signer: str
    task_id: str
    epoch: int
    phase: str
    result_hash: str
    commit: bool
    signature: str


def _verify(att: Attestation) -> bool:
    # Signature binds (signer, task_id, epoch, phase, result_hash, commit).
    payload = f"{att.signer}|{att.task_id}|{att.epoch}|{att.phase}|{att.result_hash}|{att.commit}"
    expected = hashlib.sha256(payload.encode()).hexdigest()
    return att.signature == expected


def _same_slot(a: Attestation, b: Attestation) -> bool:
    return (a.signer, a.task_id, a.epoch, a.phase) == (b.signer, b.task_id, b.epoch, b.phase)


def _conflicts(a: Attestation, b: Attestation) -> bool:
    return a.result_hash != b.result_hash or a.commit != b.commit


class EquivocationDetector:
    def __init__(self, n: int, f: int):
        self.n = n
        self.f = f
        self._first_seen: dict[tuple, Attestation] = {}
        self._proven: set[str] = set()

    def observe(self, att: Attestation) -> None:
        if not _verify(att):
            return  # invalid signature is not evidence
        if att.signer in self._proven:
            return
        key = (att.signer, att.task_id, att.epoch, att.phase)
        prior = self._first_seen.get(key)
        if prior is None:
            self._first_seen[key] = att
            return
        if _same_slot(prior, att) and _conflicts(prior, att):
            self._proven.add(att.signer)
            proof = (prior, att)
            if len(self._proven) >= self.f + 1:
                raise QuorumExhausted(
                    f"proven equivocators={sorted(self._proven)} reached f+1={self.f + 1}; "
                    f"aborting task {att.task_id} epoch {att.epoch}"
                )
            raise EquivocationFault(
                f"signer {att.signer} equivocated on {att.task_id}/{att.epoch}/{att.phase}: "
                f"{proof[0].result_hash} vs {proof[1].result_hash}"
            )

    def counts_toward_quorum(self, signer: str) -> bool:
        return signer not in self._proven
