# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-quorum-certificate-as-forged-when-a-byzantine-auditor-equivocates-across-verification-replays.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-quorum-certificate-as-forged-when-a-byzantine-auditor-equivocates-across-verification-replays.warrant.json
# Markdown SHA-256:   95fc3021177898f2d9c124e6847627e6765943698355f66cb5084175d79aea5a
# Code AST SHA-256:   ae223ceb1bb1b4f2966c9bdbb5fcd4902d291403fe9e3f996603cc67b033a1ff
# Verified Classes:   QuorumCertificateForged, Attestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class QuorumCertificateForged(RuntimeError):
    """Raised when an attestation set is not a function over auditor_id."""


@dataclass(frozen=True)
class Attestation:
    auditor_id: str
    vote_set_hash: str
    round: int
    epoch: int
    verdict: str  # "valid" | "invalid"
    signature: bytes


def canonical_vote_set_hash(votes: Iterable[tuple[str, str]]) -> str:
    # Canonical serialization: sorted, no whitespace, no locale-dependent formatting.
    payload = "|".join(f"{agent}:{choice}" for agent, choice in sorted(votes))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def verify_certificate(
    attestations: list[Attestation],
    expected_hash: str,
    round_no: int,
    epoch_no: int,
    f: int,
) -> str:
    """
    Returns "commit" only if the attestation set is a function over auditor_id
    AND at least 2f+1 auditors attest "valid". Any equivocation => forged.
    """
    seen: dict[str, str] = {}
    valid_count = 0

    for att in attestations:
        if att.vote_set_hash != expected_hash:
            # Hash drift, not equivocation; ignore for this certificate.
            continue
        if att.round != round_no or att.epoch != epoch_no:
            continue

        prior = seen.get(att.auditor_id)
        if prior is not None and prior != att.verdict:
            # Same auditor, same (hash, round, epoch), two verdicts.
            # This is the equivocation boundary. Reject the whole certificate.
            raise QuorumCertificateForged(
                f"auditor {att.auditor_id} equivocated on "
                f"(hash={expected_hash[:12]}, round={round_no}, epoch={epoch_no}): "
                f"{prior!r} vs {att.verdict!r}"
            )

        if prior is None:
            seen[att.auditor_id] = att.verdict
            if att.verdict == "valid":
                valid_count += 1

    if valid_count < 2 * f + 1:
        raise QuorumCertificateForged(
            f"insufficient valid attestations: {valid_count} < {2 * f + 1}"
        )

    return "commit"


def run_round(
    attestations: list[Attestation],
    expected_hash: str,
    round_no: int,
    epoch_no: int,
    f: int,
) -> str:
    try:
        return verify_certificate(attestations, expected_hash, round_no, epoch_no, f)
    except QuorumCertificateForged:
        # Quarantine the round; do not fall back to majority-of-attestations.
        # Escalate the equivocating auditor to the slashing path.
        return "rejected"
