# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-auditor-s-attestation-when-the-quorum-certificate-is-cryptographically-valid-but-the-attested-execution-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-auditor-s-attestation-when-the-quorum-certificate-is-cryptographically-valid-but-the-attested-execution-trace.warrant.json
# Markdown SHA-256:   2538cb7318f56377d05886c1c876f19ec5486cf8962928b48ced9322d9be029a
# Code AST SHA-256:   54caa522e6114cc6e45e2bf3f538cc8a8b251e3908d6a56c927cd7b7f5c3e5a9
# Verified Classes:   UnboundAttestationError, AbstainInQuorumError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class UnboundAttestationError(RuntimeError):
    """Raised when a quorum certificate counts a signature not bound to a local re-execution."""
    pass

class AbstainInQuorumError(RuntimeError):
    """Raised when an ABSTAIN sentinel is counted toward quorum arithmetic."""
    pass

ABSTAIN = 0x00

def verify_quorum_certificate(
    cert: dict,
    expected_digest: bytes,
    quorum_size: int,
) -> bool:
    """
    cert = {
        "digest": bytes,
        "signatures": [
            {"auditor": str, "sig": bytes, "reexec_digest": bytes, "nonce": bytes},
            ...
        ],
    }
    A signature is valid only if reexec_digest is present, non-sentinel,
    and matches expected_digest. Signatures are never inherited.
    """
    if cert["digest"] != expected_digest:
        raise UnboundAttestationError(
            f"cert digest {cert['digest']!r} != expected {expected_digest!r}"
        )

    valid = 0
    for s in cert["signatures"]:
        rd = s.get("reexec_digest")
        if rd is None:
            raise UnboundAttestationError(
                f"auditor {s['auditor']} signed without a bound re-execution"
            )
        if rd == ABSTAIN:
            raise AbstainInQuorumError(
                f"auditor {s['auditor']} abstained (sentinel digest) but was counted"
            )
        if rd != expected_digest:
            # honest disagreement: this signature must not count, but is not fatal alone
            continue
        # signature must cover the binding
        if not _sig_covers(s["sig"], expected_digest, rd, s["nonce"]):
            raise UnboundAttestationError(
                f"auditor {s['auditor']} signature does not cover reexec binding"
            )
        valid += 1

    if valid < quorum_size:
        raise UnboundAttestationError(
            f"only {valid} bound signatures; quorum requires {quorum_size}"
        )
    return True


def _sig_covers(sig: bytes, digest: bytes, reexec: bytes, nonce: bytes) -> bool:
    # placeholder for real signature verification over H(digest || reexec || nonce)
    return bool(sig) and sig[:1] != b"\x00"
