# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-by-receipt-in-bft-agent-consensus-before-a-quorum-certificate-is-forged-from-divergent-proposal-hashes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-by-receipt-in-bft-agent-consensus-before-a-quorum-certificate-is-forged-from-divergent-proposal-hashes.warrant.json
# Markdown SHA-256:   54033c06402f5777254bcfad95925e05decc962d204580807bf460eadf46d3dd
# Code AST SHA-256:   6824a6d0a99a590c29d8c92ea7e234319ea431e6cb9d7b3b88621fc0491a1abb
# Verified Classes:   EquivocationByReceiptError, QuorumCertificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EquivocationByReceiptError(RuntimeError):
    """Raised when two QCs at the same height share a signer with conflicting receipt hashes."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    height: int
    view: int
    proposal_hash: str
    signers: Set[str]
    # receipt_hash[signer] = the proposal hash that signer actually endorsed
    receipt_hash: Dict[str, str] = field(default_factory=dict)


def check_cross_qc_equivocation(
    incoming: QuorumCertificate,
    history: Dict[Tuple[int, int], QuorumCertificate],
    quorum_threshold: int,
) -> None:
    if len(incoming.signers) < quorum_threshold:
        raise EquivocationByReceiptError(
            f"QC at ({incoming.height},{incoming.view}) has {len(incoming.signers)} "
            f"signers, below quorum {quorum_threshold}"
        )

    for (h, v), prior in history.items():
        if h != incoming.height:
            continue
        if prior.proposal_hash == incoming.proposal_hash:
            continue  # idempotent re-delivery
        overlap = incoming.signers & prior.signers
        if not overlap:
            # partition, not equivocation: halt, do not commit either
            raise EquivocationByReceiptError(
                f"disjoint quorums at height {h}: ({v}) vs ({incoming.view}); "
                f"halt for view-sync, do not commit"
            )
        for signer in overlap:
            a = incoming.receipt_hash.get(signer, incoming.proposal_hash)
            b = prior.receipt_hash.get(signer, prior.proposal_hash)
            if a != b:
                raise EquivocationByReceiptError(
                    f"equivocation-by-receipt at height {h}: signer {signer} "
                    f"endorsed {a} in view {incoming.view} and {b} in view {v}"
                )
        # all intersecting signers agree on the same hash in both QCs:
        # this is leader equivocation, escalate to view change, do not commit
        raise EquivocationByReceiptError(
            f"leader equivocation at height {h}: proposal hashes "
            f"{prior.proposal_hash} vs {incoming.proposal_hash} with consistent signers"
        )


def commit_block(
    qc: QuorumCertificate,
    history: Dict[Tuple[int, int], QuorumCertificate],
    shared_state: Dict[str, str],
    quorum_threshold: int,
) -> None:
    # invariant: no commit may proceed until cross-QC equivocation is ruled out
    check_cross_qc_equivocation(qc, history, quorum_threshold)
    shared_state[qc.proposal_hash] = "committed"
    history[(qc.height, qc.view)] = qc
