# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-byzantine-quorum-certificate-when-reputation-weighted-stake-and-equivocation-evidence-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-byzantine-quorum-certificate-when-reputation-weighted-stake-and-equivocation-evidence-disagree.warrant.json
# Markdown SHA-256:   95d496c8389bf00b8b1adab56e0bed3d875a90edd96166d332b220a60532068e
# Code AST SHA-256:   260de5d1d6db8f9da786b793be97d7016897ca12977b9ba682934bea46cd40e4
# Verified Classes:   QuorumVerificationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class QuorumVerificationError(RuntimeError):
    """Raised when a quorum certificate is evaluated in violation of the seal-before-weight invariant."""
    pass


def verify_certificate(cert, instance, quorum_threshold):
    # cert: {height, block_hash, signers: list[(validator_id, signature)]}
    h = cert["height"]

    # 1. Identity check (no weight involved).
    for vid, sig in cert["signers"]:
        if not instance.valid_signature(vid, cert["block_hash"], h, sig):
            return "REJECT"  # malformed signature, not a safety issue

    # 2. Hard veto: equivocation checked BEFORE weight, as identity-scoped truth.
    equivocators = {vid for vid, _ in cert["signers"]
                    if instance.is_proven_equivocator(vid, h)}

    # 3. Equivocation-completeness barrier.
    sealed = instance.has_height_seal(h)
    if not sealed:
        # Cannot safely evaluate weight; must NOT accept or relay.
        if equivocators:
            return "PENDING"  # proofs still arriving; hold
        return "PENDING"      # weight unevaluable until seal; hold

    # Sealed: now weight is meaningful.
    if equivocators:
        # A signer is proven Byzantine at this height -> certificate is forged.
        raise QuorumVerificationError(
            f"certificate at height {h} signed by proven equivocator(s) "
            f"{sorted(equivocators)}; post-veto weight evaluation forbidden"
        )

    post_veto_weight = sum(instance.weight(vid) for vid, _ in cert["signers"])
    if post_veto_weight < quorum_threshold:
        return "REJECT"  # sealed and under threshold: final, safe to discard

    return "ACCEPT"


def on_certificate_received(cert, instance, quorum_threshold):
    verdict = verify_certificate(cert, instance, quorum_threshold)
    if verdict == "PENDING":
        # Hold; never relay a pending certificate (fork-propagation vector).
        instance.hold_for_height(cert["height"], cert)
        return
    if verdict == "ACCEPT":
        instance.finalize(cert)
    # REJECT: discard; do not relay.
