# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-before-committing-to-a-byzantine-fault-tolerant-shared-state-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-before-committing-to-a-byzantine-fault-tolerant-shared-state-quorum.warrant.json
# Markdown SHA-256:   c594266b21e49a3ab9540a563a32d160cb3e72fd2c88a9b083e2120b7ca87254
# Code AST SHA-256:   33aeeea71927d02b7a1823983bfc0dfed86e55fa14e91aec82d9d767a1767d50
# Verified Classes:   EquivocationDetected, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class EquivocationDetected(RuntimeError):
    """Raised when a commit certificate's signatures do not bind to a single value digest."""
    pass


@dataclass(frozen=True)
class Vote:
    signer: str
    view: int
    digest: str  # hex digest of H(value)


def H(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()


def try_commit(
    local_value: bytes,
    votes: Iterable[Vote],
    n_replicas: int,
    view: int,
) -> str:
    """
    Attempt to commit local_value given a set of COMMIT votes.
    Enforces both the quorum check and the digest-binding check.
    Returns the committed digest on success.
    """
    f = (n_replicas - 1) // 3
    threshold = 2 * f + 1
    local_digest = H(local_value)

    # Filter to votes for this view and deduplicate by signer (a signer voting twice
    # is itself equivocation evidence, but we take the first for quorum counting).
    seen: dict[str, Vote] = {}
    for v in votes:
        if v.view != view:
            continue
        if v.signer in seen and seen[v.signer].digest != v.digest:
            raise EquivocationDetected(
                f"signer {v.signer} cast conflicting votes in view {view}"
            )
        seen.setdefault(v.signer, v)

    # Quorum check: enough distinct signers.
    if len(seen) < threshold:
        raise EquivocationDetected(
            f"insufficient quorum: {len(seen)} < {threshold} in view {view}"
        )

    # Digest-binding check: every vote in the quorum must be over local_digest.
    mismatched = [v for v in seen.values() if v.digest != local_digest]
    if mismatched:
        # We have a quorum, but not over our value. This is the equivocation zone.
        # Do NOT commit. Escalate with the certificate as proof-of-misbehavior.
        raise EquivocationDetected(
            f"quorum exists but not over local digest {local_digest[:12]}; "
            f"{len(mismatched)} votes bound to other digests in view {view}"
        )

    return local_digest
