# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-leaders-when-quorum-certificates-are-valid-but-disjoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-leaders-when-quorum-certificates-are-valid-but-disjoint.warrant.json
# Markdown SHA-256:   afbdd19a4969d24e86bc487f083b7c047f93fcfd00256708a5ae3860b4815a4e
# Code AST SHA-256:   23f439c57d160d37be740dc0f3d68c4460c9866ace490a2284840465975ec16a
# Verified Classes:   EquivocationWitnessError, QuarantineViolationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EquivocationWitnessError(RuntimeError):
    """Raised when a replica detects conflicting QCs whose intersection
    contains at least one provably honest signer, proving leader equivocation."""
    pass


class QuarantineViolationError(RuntimeError):
    """Raised when a commit is attempted on a QC that is still inside the
    quarantine window and a conflicting QC for the same view is outstanding."""
    pass


def evaluate_qc_pair(qc_a, qc_b, leader_id, known_faulty):
    """
    qc_a, qc_b: objects with .view, .block_hash, .signers (set of replica ids)
    leader_id: id of the leader for that view
    known_faulty: set of replica ids known to be Byzantine
    Returns 'equivocation_witness' if a valid witness exists, else 'insufficient'.
    """
    if qc_a.view != qc_b.view:
        return "insufficient"
    if qc_a.block_hash == qc_b.block_hash:
        return "insufficient"

    intersection = qc_a.signers & qc_b.signers
    honest_intersection = intersection - {leader_id} - set(known_faulty)

    if not honest_intersection:
        # Only the leader (or known-faulty replicas) signed both blocks.
        # The two QCs do NOT prove equivocation; they prove the threshold
        # was met by disjoint honest groups, which is a safety hazard but
        # not a witness. Caller must halt, not commit.
        return "insufficient"

    return "equivocation_witness"


def commit_qc(qc, quarantine_open, conflicting_qc_pending):
    """
    Gate commit on equivocation-witness absence, not merely QC validity.
    """
    if quarantine_open and conflicting_qc_pending:
        raise QuarantineViolationError(
            f"Refusing to commit QC for view {qc.view} hash {qc.block_hash[:8]}: "
            f"a conflicting QC for the same view is outstanding and the "
            f"quarantine window has not elapsed."
        )

    witness = evaluate_qc_pair(qc, conflicting_qc_pending, qc.leader_id, qc.known_faulty) \
        if conflicting_qc_pending is not None else "insufficient"

    if witness == "equivocation_witness":
        raise EquivocationWitnessError(
            f"Equivocation proven at view {qc.view}: conflicting hashes "
            f"{qc.block_hash[:8]} and {conflicting_qc_pending.block_hash[:8]} "
            f"share an honest signer. Halting commit and escalating to view-change."
        )

    # Safe to commit only if no conflicting QC is pending at all.
    if conflicting_qc_pending is not None:
        raise QuarantineViolationError(
            f"Cannot commit: conflicting QC at view {qc.view} present but "
            f"intersection is leader-only; halting pending view-change."
        )

    return True
