# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-quorum-certificate-it-helped-sign-equivocation-induced-fork-persistence-in-bft-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-quorum-certificate-it-helped-sign-equivocation-induced-fork-persistence-in-bft-agent-consensus.warrant.json
# Markdown SHA-256:   e2b4539e5ac3de6ba40fbb741b64d3d41451657dae4dbcc5911b7c8ab44331e8
# Code AST SHA-256:   d85f0e2d96ca5e027e71c5b7851a06cd55d3d3c838a2bae2e68ac4590db9e323
# Verified Classes:   EquivocationForkError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EquivocationForkError(RuntimeError):
    """Raised when a quorum certificate is cryptographically valid but
    violates the one-vote-per-signer-per-view invariant, indicating a
    persistent state fork that survived aggregation."""
    pass


def validate_quorum_certificate(
    certificate: dict,
    view: int,
    decision: str,
    f: int,
    local_vote_log: dict,
) -> None:
    """
    certificate: {"view": int, "decision": str, "signatures": [(signer_id, digest), ...]}
    local_vote_log: {view: [(decision, digest), ...]} for THIS instance's own votes
    Raises EquivocationForkError if the certificate cannot be trusted.
    """
    threshold = 2 * f + 1
    sigs = certificate.get("signatures", [])
    signers = [s for s, _ in sigs]
    distinct_signers = set(signers)

    # Guard 1: signature count vs distinct-signer count.
    if len(distinct_signers) < threshold:
        raise EquivocationForkError(
            f"Certificate for view {view} decision {decision!r} has "
            f"{len(sigs)} signatures but only {len(distinct_signers)} distinct "
            f"signers (need {threshold}); duplicate signers indicate "
            f"probabilistic equivocation, not Byzantine forgery."
        )

    # Guard 2: self-equivocation — did this instance sign a conflicting
    # decision in the same view? If so, it must distrust any certificate
    # that includes its own vote, because it cannot vouch for its own
    # sampling determinism.
    own_votes = local_vote_log.get(view, [])
    conflicting_own = [d for d, _ in own_votes if d != decision]
    if conflicting_own and any(s == "self" for s in signers):
        raise EquivocationForkError(
            f"Self-equivocation detected at view {view}: instance signed "
            f"{decision!r} but also {conflicting_own!r} in the same view. "
            f"Certificate cannot be used as NEW-VIEW justification."
        )

    # Guard 3: cross-certificate signer overlap with a conflicting decision.
    # (Caller supplies conflicting certificates via a shared ledger; here we
    # check the local log for any signer that already appears on a conflict.)
    for other_view, votes in local_vote_log.items():
        if other_view != view:
            continue
        for other_decision, _ in votes:
            if other_decision != decision:
                overlap = distinct_signers.intersection(
                    {s for s, _ in certificate.get("signatures", [])}
                )
                if overlap:
                    raise EquivocationForkError(
                        f"Signer overlap {overlap} between certificate for "
                        f"{decision!r} and conflicting decision "
                        f"{other_decision!r} at view {view}."
                    )

    # Certificate is trustworthy: distinct signers >= threshold, no
    # self-equivocation, no cross-certificate overlap.
    return None
