# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-when-byzantine-quorum-certificates-agree-on-the-wrong-state-root.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-when-byzantine-quorum-certificates-agree-on-the-wrong-state-root.warrant.json
# Markdown SHA-256:   036245683de61c4f3936e94c1ed1284b2f4dd9a65330450bc0e79b5bcc7eb128
# Code AST SHA-256:   d30d074a2ec20d8084eaaba740dc54f42465b37711bf9d9426fbc985772e475d
# Verified Classes:   SignedVote, EquivocationDetected, VoteJournal
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

@dataclass(frozen=True)
class SignedVote:
    agent_id: str
    round_no: int
    root: str
    signature: bytes

class EquivocationDetected(RuntimeError):
    """Raised when a peer has signed two conflicting roots for the same round."""
    pass

class VoteJournal:
    def __init__(self) -> None:
        self._votes: dict[tuple[str, int], SignedVote] = {}

    def record(self, vote: SignedVote) -> None:
        # Durable write MUST happen before the signature is broadcast.
        key = (vote.agent_id, vote.round_no)
        prior = self._votes.get(key)
        if prior is not None and prior.root != vote.root:
            raise EquivocationDetected(
                f"peer {vote.agent_id} signed root {prior.root!r} and "
                f"{vote.root!r} for round {vote.round_no}"
            )
        self._votes[key] = vote

def assemble_quorum_certificate(
    votes: list[SignedVote],
    threshold: int,
    journal: VoteJournal,
    verify_sig,
) -> tuple[str, list[str]]:
    if len(votes) < threshold:
        raise EquivocationDetected(f"quorum short: {len(votes)} < {threshold}")
    roots = {v.root for v in votes}
    if len(roots) != 1:
        # Two roots inside one certificate: some signer equivocated.
        by_agent: dict[str, set[str]] = {}
        for v in votes:
            by_agent.setdefault(v.agent_id, set()).add(v.root)
        for agent_id, seen in by_agent.items():
            if len(seen) > 1:
                raise EquivocationDetected(
                    f"{agent_id} contributed {sorted(seen)} to one QC"
                )
        raise EquivocationDetected(f"QC spans divergent roots {sorted(roots)}")
    root = roots.pop()
    signers = sorted(v.agent_id for v in votes)
    for v in votes:
        if not verify_sig(v.agent_id, v.round_no, v.root, v.signature):
            raise EquivocationDetected(f"bad signature from {v.agent_id}")
        journal.record(v)  # detects cross-QC equivocation, not just intra-QC
    return root, signers
