# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-quorum-silently-accept-a-forged-commit-certificate-when-the-proposer-equivocates-across-epochs.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-quorum-silently-accept-a-forged-commit-certificate-when-the-proposer-equivocates-across-epochs.warrant.json
# Markdown SHA-256:   6881e073b8591eb6cc9baaed5755e0cfabd7c3880dc319ea0869177ad67d3d51
# Code AST SHA-256:   98cb2838e2f17a90d379bc4af45c7de0cb400686a31aea3f3401ae1739a1f335
# Verified Classes:   EquivocationDetected, InsufficientQuorum, Signature, CommitCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class EquivocationDetected(RuntimeError):
    """Raised when a commit certificate's signature set is not homogeneous.

    A non-homogeneous set is evidence that the proposer equivocated across
    the quorum; the certificate must be rejected, never filtered.
    """


class InsufficientQuorum(RuntimeError):
    """Raised when the homogeneous signature count falls below the required threshold."""


@dataclass(frozen=True)
class Signature:
    validator_id: str
    view: int
    block_hash: str
    valid: bool  # result of cryptographic verification against (view, block_hash)


@dataclass(frozen=True)
class CommitCertificate:
    view: int
    block_hash: str
    signatures: tuple[Signature, ...]


def admit_commit(
    cert: CommitCertificate,
    f: int,
    local_lock: Optional[tuple[int, str]],
) -> None:
    """Admit a commit certificate, enforcing the homogeneity invariant.

    `local_lock` is the instance's own (view, block_hash) vote, or None if the
    instance has no lock state (cold start / mid-epoch join / post-restart).
    """
    # Step 1: every signature must verify against the certificate's exact tuple.
    # A signature over a *different* tuple is equivocation evidence -> abort.
    homogeneous: list[Signature] = []
    for sig in cert.signatures:
        if sig.view != cert.view or sig.block_hash != cert.block_hash:
            raise EquivocationDetected(
                f"signature from {sig.validator_id} is over "
                f"({sig.view}, {sig.block_hash}) but certificate declares "
                f"({cert.view}, {cert.block_hash}); proposer equivocated"
            )
        if not sig.valid:
            raise EquivocationDetected(
                f"signature from {sig.validator_id} failed verification against "
                f"the declared tuple; certificate is corrupt or forged"
            )
        homogeneous.append(sig)

    # Step 2: threshold depends on whether we hold a lock.
    if local_lock is None:
        # No lock: fast path is unavailable. Require 2f+1 homogeneous
        # signatures, and (in a full implementation) a view-change proof.
        required = 2 * f + 1
        if len(homogeneous) < required:
            raise InsufficientQuorum(
                f"cold-start instance requires {required} homogeneous signatures, "
                f"got {len(homogeneous)}"
            )
    else:
        lock_view, lock_hash = local_lock
        if lock_view == cert.view and lock_hash != cert.block_hash:
            raise EquivocationDetected(
                f"local lock on ({lock_view}, {lock_hash}) conflicts with "
                f"certificate for ({cert.view}, {cert.block_hash})"
            )
        required = f + 1
        if len(homogeneous) < required:
            raise InsufficientQuorum(
                f"locked instance requires {required} homogeneous signatures, "
                f"got {len(homogeneous)}"
            )


# Reproduction of the observed incident: V3 cold-starts (local_lock=None),
# receives the spliced certificate, and the guardrail fires.
if __name__ == "__main__":
    forged = CommitCertificate(
        view=41,
        block_hash="0x9a",
        signatures=(
            Signature("V1", 41, "0x9a", valid=True),
            Signature("V2", 41, "0x9a", valid=True),
            Signature("V4", 41, "0x7c", valid=True),  # signed the other fork
        ),
    )
    try:
        admit_commit(forged, f=1, local_lock=None)
    except EquivocationDetected as exc:
        print(f"rejected: {exc}")
