# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-drift-when-byzantine-agents-commit-divergent-plan-graphs-across-untrusted-orgs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-drift-when-byzantine-agents-commit-divergent-plan-graphs-across-untrusted-orgs.warrant.json
# Markdown SHA-256:   0aacd77717c8c7df6bd8e010d10c205e39fb2995f356d7e11272436f84863d1d
# Code AST SHA-256:   eef8fe390dbacc850a99089cbb622cb14456aafbdbdedb25a941b3f0700dbddc
# Verified Classes:   EquivocationDriftError, SignedDigest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationDriftError(RuntimeError):
    """Raised when two valid partial quorums exist over divergent relation digests
    for the same (proposer_id, round) key. This is not a network partition and
    cannot be resolved by waiting; it requires auditor-quorum round expiry."""
    pass


@dataclass(frozen=True)
class SignedDigest:
    proposer_id: str
    round: int
    relation_digest: str   # H(nodes || edges || protocol_version || proposer_id || round)
    signer_id: str
    signature: bytes


def verify_commitment(
    local: SignedDigest,
    incoming: SignedDigest,
    quorum_signers: set[str],
    received_signers: set[str],
) -> None:
    """Check whether `incoming` conflicts with `local` for the same round key.

    Raises EquivocationDriftError when the digests diverge but both carry
    signatures from quorum members — the signature layer cannot distinguish
    this from a benign partial-quorum race, so we must refuse to proceed.
    """
    if (local.proposer_id, local.round) != (incoming.proposer_id, incoming.round):
        return  # different round key: not an equivocation, just a new proposal

    if local.relation_digest == incoming.relation_digest:
        return  # benign: same relation, differing signer sets

    # Divergent relation digest for the same round key.
    if incoming.signer_id not in quorum_signers:
        return  # non-quorum signer; ignore, do not halt on noise

    # Both digests now have at least one quorum-member signature. We cannot
    # form a full quorum over either without the other's signer, and that
    # signer is committed to the opposite digest. Halt speculative execution.
    raise EquivocationDriftError(
        f"relation digest divergence for ({local.proposer_id}, round={local.round}): "
        f"local={local.relation_digest[:12]} incoming={incoming.relation_digest[:12]} "
        f"signer={incoming.signer_id}; halt speculative execution and escalate "
        f"to auditor quorum for round expiry"
    )


def relation_digest(nodes: list[str], edges: list[tuple[str, str]],
                    protocol_version: str, proposer_id: str, round_no: int) -> str:
    h = hashlib.sha256()
    h.update(b"|".join(sorted(n.encode() for n in nodes)))
    h.update(b"::")
    h.update(b"|".join(sorted(f"{a}->{b}".encode() for a, b in edges)))
    h.update(f"::v={protocol_version}::p={proposer_id}::r={round_no}".encode())
    return h.hexdigest()
