# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-quorum-certificate-has-silently-lost-byzantine-safety-across-trust-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-quorum-certificate-has-silently-lost-byzantine-safety-across-trust-domains.warrant.json
# Markdown SHA-256:   1098003b30a4ea827d747ab751b71d8bed967aaa3a53f29922d3fb44a6b7581d
# Code AST SHA-256:   5d3e5cb9f886edcd5016c59f84ab0509240c20013e258cf9cf508ac13590fbb8
# Verified Classes:   QuorumSafetyViolation, QuorumCertificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumSafetyViolation(RuntimeError):
    """Raised when a quorum certificate is cryptographically valid but
    violates the weighted-intersection invariant across trust domains."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    epoch_id: int
    validator_set_hash: str
    signers: frozenset[str]
    action_digest: str
    height: int


def canonical_set_hash(members: frozenset[str]) -> str:
    joined = "|".join(sorted(members)).encode()
    return hashlib.sha256(joined).hexdigest()


def verify_qc(
    qc: QuorumCertificate,
    canonical_members: frozenset[str],
    f: int,
    prior_qc_at_height: QuorumCertificate | None,
) -> None:
    # 1. Set binding: the certificate must name the canonical set, not a local view.
    expected = canonical_set_hash(canonical_members)
    if qc.validator_set_hash != expected:
        raise QuorumSafetyViolation(
            f"QC epoch {qc.epoch_id} bound to set {qc.validator_set_hash[:12]} "
            f"but canonical is {expected[:12]}: membership-view split"
        )

    # 2. Signers must be a subset of the canonical set; union overflow is the tell.
    if not qc.signers <= canonical_members:
        rogue = qc.signers - canonical_members
        raise QuorumSafetyViolation(
            f"QC signers include non-members {sorted(rogue)}: "
            f"signer union exceeds canonical validator set"
        )

    # 3. Absolute threshold over the canonical denominator.
    threshold = 2 * f + 1
    if len(qc.signers) < threshold:
        raise QuorumSafetyViolation(
            f"QC weight {len(qc.signers)} < threshold {threshold} "
            f"under canonical set of {len(canonical_members)}"
        )

    # 4. Weighted-intersection invariant against any competing QC at same height.
    if prior_qc_at_height is not None and prior_qc_at_height.height == qc.height:
        if prior_qc_at_height.action_digest != qc.action_digest:
            intersection = qc.signers & prior_qc_at_height.signers
            if len(intersection) <= f:
                raise QuorumSafetyViolation(
                    f"Conflicting QCs at height {qc.height}: intersection weight "
                    f"{len(intersection)} <= f={f}; Byzantine safety broken"
                )
