# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-quorum-silently-accept-a-forged-decision-warrant-when-the-auditor-set-is-co-located-with-the-proposer.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-quorum-silently-accept-a-forged-decision-warrant-when-the-auditor-set-is-co-located-with-the-proposer.warrant.json
# Markdown SHA-256:   080de4a45f4e15c68e886cbad8ed513d28826073c3fa9b57ac84aa5baebd2332
# Code AST SHA-256:   b1613431033aefd6ffe3a658375cb0baa0bab9bba7837dae8ac02bd2b65bc6c7
# Verified Classes:   WarrantBindingError, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WarrantBindingError(RuntimeError):
    """Raised when a quorum warrant does not bind to the execution payload."""
    pass


@dataclass(frozen=True)
class Warrant:
    decision_id: str
    nonce: str
    action_digest: str   # digest the auditor actually evaluated
    auditor_id: str
    signature: str       # over H(decision_id || action_digest || nonce)


def _digest(decision_id: str, action_digest: str, nonce: str) -> str:
    return hashlib.sha256(
        f"{decision_id}|{action_digest}|{nonce}".encode()
    ).hexdigest()


def commit_decision(
    decision_id: str,
    nonce: str,
    execution_payload_digest: str,
    warrants: list[Warrant],
    consumed_nonces: set[str],
    f: int,
) -> str:
    # Guardrail 2: replay / rollback collision.
    if nonce in consumed_nonces:
        raise WarrantBindingError(
            f"nonce {nonce!r} for decision {decision_id!r} already consumed; "
            f"possible checkpoint-replay collision"
        )

    expected = _digest(decision_id, execution_payload_digest, nonce)
    bound = [
        w for w in warrants
        if w.decision_id == decision_id
        and w.nonce == nonce
        and w.action_digest == execution_payload_digest
        and w.signature == expected
    ]

    # Guardrail 1: content binding. A warrant that signs only decision_id
    # (action_digest mismatch) is a splice and must not count.
    if any(w.decision_id == decision_id for w in warrants) and not bound:
        raise WarrantBindingError(
            f"warrants for {decision_id!r} do not bind to execution digest "
            f"{execution_payload_digest!r}; proposer splice suspected"
        )

    # Guardrail 3: cardinality over *bound* warrants only.
    distinct = {w.auditor_id for w in bound}
    if len(distinct) < 2 * f + 1:
        raise WarrantBindingError(
            f"insufficient bound warrants for {decision_id!r}: "
            f"{len(distinct)} < {2 * f + 1}"
        )

    consumed_nonces.add(nonce)
    return execution_payload_digest
