# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-resolve-stake-slashing-authority-when-a-federated-registry-s-reputation-oracle-disagrees-with-the-sla-verdict-it-consumes.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-resolve-stake-slashing-authority-when-a-federated-registry-s-reputation-oracle-disagrees-with-the-sla-verdict-it-consumes.warrant.json
# Markdown SHA-256:   31f83dfb74ba661e06b4a971819a80db13105e74f18a25c4bc8351f1e1897201
# Code AST SHA-256:   34d86c973e821d98b4ba756ef367e4f8905a8f98fd0746469bde6dd385bee8b5
# Verified Classes:   UnauthorizedSlashWarrantError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnauthorizedSlashWarrantError(RuntimeError):
    """Raised when a signed SLA verdict is presented as a slash warrant
    but does not bind to the contract terms actually agreed at handshake."""
    pass


def authorize_slash(verdict: dict, handshake: dict, delegations: list[dict]) -> bool:
    # Signature and contract identity are necessary but NOT sufficient.
    if not verdict.get("signature_valid"):
        raise UnauthorizedSlashWarrantError("verdict signature invalid")
    if verdict["contract_hash"] != handshake["contract_hash"]:
        raise UnauthorizedSlashWarrantError(
            f"contract hash mismatch: verdict={verdict['contract_hash']} "
            f"handshake={handshake['contract_hash']}"
        )

    # The binding that actually matters: exact schema semantics and evaluator.
    schema_ok = verdict["sla_schema"] == handshake["sla_schema"]
    semantics_ok = (
        verdict["schema_semantics_hash"] == handshake["schema_semantics_hash"]
    )
    evaluator_ok = verdict["evaluator_id"] == handshake["evaluator_id"]

    if not (schema_ok and semantics_ok and evaluator_ok):
        # Fallback evaluator is only admissible via a pre-signed,
        # contract-bound delegation accepted by both parties at handshake.
        authorized = any(
            d["contract_hash"] == handshake["contract_hash"]
            and d["substitute_evaluator"] == verdict["evaluator_id"]
            and d["substitute_schema_semantics_hash"]
            == verdict["schema_semantics_hash"]
            and d["accepted_by_both_parties"]
            for d in delegations
        )
        if not authorized:
            raise UnauthorizedSlashWarrantError(
                "verdict schema/evaluator not bound to handshake and no "
                "contract-bound delegation authorizes substitution; "
                "quarantine as dispute evidence, do not slash or propagate"
            )

    if not (handshake["window_start"] <= verdict["window_start"]
            and verdict["window_end"] <= handshake["window_end"]):
        raise UnauthorizedSlashWarrantError("verdict window outside contract window")

    return True
