# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-quorum-silently-accept-a-forged-abstain-as-a-valid-vote-and-how-does-equivocation-laundering-break-the-2f-1-invari.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-quorum-silently-accept-a-forged-abstain-as-a-valid-vote-and-how-does-equivocation-laundering-break-the-2f-1-invari.warrant.json
# Markdown SHA-256:   e9c2e0067ade938567df3073ff626a3b4e8dbead48416fb2a2f5267385068e73
# Code AST SHA-256:   6dfe8ace59ca21b2d52b4b168c1e74d72de31d76d2274e0731bc2f1da4cee307
# Verified Classes:   QuorumInvariantViolation, Vote, QuorumAggregator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from collections import defaultdict
from dataclasses import dataclass, field


class QuorumInvariantViolation(RuntimeError):
    """Raised when a quorum decision cannot be proven sound under equivocation."""
    pass


@dataclass(frozen=True)
class Vote:
    signer_id: str
    epoch: int
    payload: str          # "approve" | "reject" | "abstain"
    signature: bytes


@dataclass
class QuorumAggregator:
    n: int
    f: int
    epoch: int
    votes: list = field(default_factory=list)

    @property
    def threshold(self) -> int:
        # 2f+1 style supermajority over N=3f+1
        return 2 * self.f + 1

    def _payload_hash(self, payload: str) -> str:
        return hashlib.sha256(payload.encode()).hexdigest()

    def tally(self) -> str:
        # Group by (signer, epoch) and detect equivocation before counting.
        by_signer = defaultdict(set)
        for v in self.votes:
            if v.epoch != self.epoch:
                continue
            by_signer[v.signer_id].add(self._payload_hash(v.payload))

        equivocators = {s for s, hashes in by_signer.items() if len(hashes) > 1}

        # If more than f signers equivocate, the fault model is violated:
        # no decision (commit or abort) is safe to emit.
        if len(equivocators) > self.f:
            raise QuorumInvariantViolation(
                f"{len(equivocators)} equivocators exceed f={self.f}; "
                f"epoch {self.epoch} is compromised, halt and re-vote."
            )

        approve_signers = {
            s for s, hashes in by_signer.items()
            if s not in equivocators
            and next(iter(hashes)) == self._payload_hash("approve")
        }

        # Invariant: commit requires distinct honest approvers >= threshold
        # AND the honest-approver floor f+1.
        if len(approve_signers) < self.threshold:
            return "no-commit"
        if len(approve_signers) < self.f + 1:
            raise QuorumInvariantViolation(
                f"approve_set size {len(approve_signers)} < f+1={self.f + 1}; "
                f"threshold met only via equivocation laundering."
            )
        return "commit"


def decide(aggregator: QuorumAggregator) -> str:
    result = aggregator.tally()
    if result == "commit" and len(aggregator.votes) < aggregator.threshold:
        raise QuorumInvariantViolation("commit emitted without threshold message count")
    return result


if __name__ == "__main__":
    agg = QuorumAggregator(n=7, f=2, epoch=1)
    # A3 and A5 equivocate: approve to some, abstain to others.
    agg.votes = [
        Vote("A1", 1, "approve", b".."),
        Vote("A2", 1, "approve", b".."),
        Vote("A4", 1, "approve", b".."),
        Vote("A3", 1, "approve", b".."),
        Vote("A3", 1, "abstain", b".."),   # equivocation
        Vote("A5", 1, "approve", b".."),
        Vote("A5", 1, "abstain", b".."),   # equivocation
        Vote("A6", 1, "abstain", b".."),
        Vote("A7", 1, "abstain", b".."),
    ]
    print(decide(agg))  # raises QuorumInvariantViolation before any commit
