# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-commit-when-a-byzantine-peer-equivocates-across-the-attestation-threshold.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-commit-when-a-byzantine-peer-equivocates-across-the-attestation-threshold.warrant.json
# Markdown SHA-256:   05a889f4ef1ca121b099c773ecac63c77652a965a00e12e4d3321e293fb6b485
# Code AST SHA-256:   51f7ab7c82a942a6b97f16411c0929a28d23a73432522735017e7aef8240f333
# Verified Classes:   EquivocationDetected, InsufficientQuorum, AttestationView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when a local quorum is satisfied but view-exchange reveals a peer
    signing two different result hashes for the same round."""
    pass


class InsufficientQuorum(RuntimeError):
    """Raised when attestations are below threshold with no conflicting view
    (a liveness/retry condition, NOT a safety violation)."""
    pass


@dataclass
class AttestationView:
    """An instance's local view of one consensus round."""
    round_id: int
    own_hash: str
    # peer_id -> result_hash that peer attested to us for this round
    received: Dict[str, str] = field(default_factory=dict)

    def attestations_for(self, h: str) -> Set[str]:
        return {p for p, hh in self.received.items() if hh == h}


def commit_or_refuse(
    view: AttestationView,
    peer_views: Dict[str, Dict[str, str]],
    n: int,
    f: int,
) -> str:
    """
    Decide whether to commit the round's result.

    peer_views: peer_id -> {round_hash_peer_reports: set_of_signers}
    Enforces the safe threshold m >= (n + f + 1) // 2 and the view-exchange
    handshake. Returns the committed hash or raises.
    """
    m = (n + f + 1) // 2  # safe quorum; for n=4,f=1 this is 3, not 2

    local_for_own = view.attestations_for(view.own_hash) | {view.own_hash and "self"}
    local_count = len(view.attestations_for(view.own_hash))

    # Detect equivocation: any peer that signed BOTH our hash and a different
    # hash for the same round, as evidenced by cross-peer views.
    for peer_id, peer_map in peer_views.items():
        for h, signers in peer_map.items():
            if h != view.own_hash and peer_id in signers and peer_id in view.received:
                # peer_id signed our hash (in view.received) AND another hash
                raise EquivocationDetected(
                    f"round {view.round_id}: peer {peer_id} signed both "
                    f"{view.own_hash!r} and {h!r}; refusing commit"
                )

    if local_count < m:
        raise InsufficientQuorum(
            f"round {view.round_id}: only {local_count}/{m} attestations for "
            f"{view.own_hash!r}; retry (no equivocation evidence)"
        )

    # View-exchange handshake: require >= m peers to independently report our hash.
    corroborating = sum(
        1 for peer_map in peer_views.values()
        if view.own_hash in peer_map
    )
    if corroborating < m:
        raise EquivocationDetected(
            f"round {view.round_id}: local quorum met but only {corroborating}/{m} "
            f"peers corroborate {view.own_hash!r}; possible split attestation"
        )

    return view.own_hash
