# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-an-auditor-quorum-before-committing-its-result-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-an-auditor-quorum-before-committing-its-result-attestation.warrant.json
# Markdown SHA-256:   a0572ce324eaf0ad50c59dc08a5758cc444a9aa89a8148ed82d38c09589865dd
# Code AST SHA-256:   4029f49bb86b107b2575d2c817db1ab0dfce7f3cc6dcf25fa4f0b4c3b40ff2fc
# Verified Classes:   QuorumEquivocationError, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumEquivocationError(RuntimeError):
    """Raised when a certified quorum cannot be proven intersection-safe."""
    pass


@dataclass(frozen=True)
class Vote:
    task_id: str
    epoch: int
    result_hash: str
    recipient: str
    signer: str
    signature: str  # opaque; assumed to bind all fields above


def _binds(vote: Vote, task_id: str, epoch: int, result_hash: str, recipient: str) -> bool:
    return (
        vote.task_id == task_id
        and vote.epoch == epoch
        and vote.result_hash == result_hash
        and vote.recipient == recipient
    )


def commit_attestation(
    task_id: str,
    epoch: int,
    result_hash: str,
    recipient: str,
    votes: list[Vote],
    auditor_set: frozenset[str],
    f: int,
) -> str:
    # 1. Reject votes from outside the epoch-fixed auditor set.
    for v in votes:
        if v.signer not in auditor_set:
            raise QuorumEquivocationError(
                f"vote from {v.signer!r} not in epoch-{epoch} auditor set"
            )

    # 2. Detect double-signing: one signer over two distinct (epoch, hash).
    seen: dict[str, set[tuple[int, str]]] = {}
    for v in votes:
        seen.setdefault(v.signer, set()).add((v.epoch, v.result_hash))
    for signer, pairs in seen.items():
        if len(pairs) > 1:
            raise QuorumEquivocationError(
                f"auditor {signer!r} equivocated across {sorted(pairs)}"
            )

    # 3. Count only votes that bind (task, epoch, hash, recipient=this committer).
    bound = {v.signer for v in votes if _binds(v, task_id, epoch, result_hash, recipient)}
    if len(bound) < 2 * f + 1:
        # Distinguish "not enough bound" from "enough but unbound".
        if len(votes) >= 2 * f + 1:
            raise QuorumEquivocationError(
                f"{len(votes)} signatures present but only {len(bound)} are "
                f"recipient/epoch-bound; cardinality does not imply intersection"
            )
        raise QuorumEquivocationError(
            f"insufficient bound quorum: {len(bound)} < {2 * f + 1}"
        )

    # 4. Intersection is now guaranteed: any competing 2f+1 quorum must share
    #    >= f+1 signers, of which >= 1 is honest and would have refused a second hash.
    digest = hashlib.sha256(
        f"{task_id}:{epoch}:{result_hash}:{sorted(bound)}".encode()
    ).hexdigest()
    return digest
