# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-quorum-certificates-when-a-speculative-swarm-s-consensus-gate-ratifies-a-task-allocation-that-no-single-hones.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-quorum-certificates-when-a-speculative-swarm-s-consensus-gate-ratifies-a-task-allocation-that-no-single-hones.warrant.json
# Markdown SHA-256:   2c71eb8f69bed94a5390185979ebdeef05bbafa52431980a85000daaa4cf47f4
# Code AST SHA-256:   909d391ac87e0c839f50f5058d9aad4953385b545078cf193c14c59740866ea1
# Verified Classes:   SiblingCertificateConflict, BundleReconstructionFailure
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SiblingCertificateConflict(RuntimeError):
    """Raised when two quorum certificates at the same epoch fail quorum intersection."""
    pass


class BundleReconstructionFailure(RuntimeError):
    """Raised when an instance cannot reproduce a bundle hash from its own member view."""
    pass


def verify_allocation_certificate(
    cert,
    sibling_certs,
    local_member_hashes,
    f,
):
    """
    cert: dict with keys 'epoch', 'bundle_hash', 'signers' (set), 'member_hashes' (set)
    sibling_certs: list of other certs observed at the same epoch
    local_member_hashes: set of proposal hashes this instance independently holds
    f: tolerated Byzantine count
    """
    # Invariant 1: bundle hash must be reproducible from member proposals.
    reconstructed = hash_bundle(sorted(cert["member_hashes"]))
    if reconstructed != cert["bundle_hash"]:
        raise BundleReconstructionFailure(
            f"epoch={cert['epoch']} bundle_hash={cert['bundle_hash']} "
            f"reconstructed={reconstructed} — certificate not auditable"
        )

    # Invariant 2: instance must have witnessed the member set.
    if not cert["member_hashes"].issubset(local_member_hashes):
        missing = cert["member_hashes"] - local_member_hashes
        raise BundleReconstructionFailure(
            f"epoch={cert['epoch']} member proposals not in local view: {missing}"
        )

    # Invariant 3: quorum intersection with every sibling at same epoch.
    for sib in sibling_certs:
        if sib["epoch"] != cert["epoch"]:
            continue
        if sib["bundle_hash"] == cert["bundle_hash"]:
            continue
        shared = cert["signers"] & sib["signers"]
        if len(shared) < f + 1:
            raise SiblingCertificateConflict(
                f"epoch={cert['epoch']} cert={cert['bundle_hash']} "
                f"sibling={sib['bundle_hash']} shared_signers={len(shared)} "
                f"required={f + 1} — equivocation suspected, force re-vote"
            )

    return True


def hash_bundle(sorted_hashes):
    import hashlib
    h = hashlib.sha256()
    for m in sorted_hashes:
        h.update(m.encode())
    return h.hexdigest()
