# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-agent-quorum-accept-a-forged-audit-warrant-when-the-signature-chain-is-intact.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-agent-quorum-accept-a-forged-audit-warrant-when-the-signature-chain-is-intact.warrant.json
# Markdown SHA-256:   ee2715fd177f7c12eebcb68aba0fe27a1c91d2b974522be2106e48abdd9f3804
# Code AST SHA-256:   24c4d9bddd242b6b201fccb7383ce4d16f852e5aee3640becbf38e99a0ce8ead
# Verified Classes:   EquivocationError, WarrantSigner
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from typing import Dict, Tuple

class EquivocationError(RuntimeError):
    """Raised when an agent detects a conflicting warrant for an already-signed slot."""
    pass

class WarrantSigner:
    def __init__(self):
        # Persistent map: (sequence_number, decision_slot) -> payload_hash
        self.signed_slots: Dict[Tuple[int, int], str] = {}

    def _hash_payload(self, payload: bytes) -> str:
        return hashlib.sha256(payload).hexdigest()

    def sign_warrant(self, sequence_number: int, decision_slot: int, payload: bytes) -> str:
        key = (sequence_number, decision_slot)
        payload_hash = self._hash_payload(payload)
        if key in self.signed_slots:
            existing = self.signed_slots[key]
            if existing != payload_hash:
                raise EquivocationError(
                    f"Refusing to sign slot {key}: already signed payload {existing[:8]}, "
                    f"new payload {payload_hash[:8]} differs. Byzantine equivocation detected."
                )
            # Idempotent re-sign: return existing signature (simulated)
            return f"sig:{key}:{existing[:8]}"
        # Atomic check-and-set (simulated as single-threaded)
        self.signed_slots[key] = payload_hash
        return f"sig:{key}:{payload_hash[:8]}"

    def accept_warrant(self, sequence_number: int, decision_slot: int, payload: bytes, signature: str) -> bool:
        key = (sequence_number, decision_slot)
        payload_hash = self._hash_payload(payload)
        if key in self.signed_slots and self.signed_slots[key] != payload_hash:
            raise EquivocationError(
                f"Rejecting warrant for slot {key}: local commit hash {self.signed_slots[key][:8]} "
                f"conflicts with warrant hash {payload_hash[:8]}. Sender is Byzantine."
            )
        # Signature verification (simulated)
        expected = f"sig:{key}:{payload_hash[:8]}"
        if signature != expected:
            raise EquivocationError(f"Invalid signature for slot {key}.")
        return True

# Example trace: Byzantine proposer attempts equivocation
signer = WarrantSigner()
signer.sign_warrant(seq=10, slot=0, payload=b"decision_X")
try:
    signer.sign_warrant(seq=10, slot=0, payload=b"decision_Y")  # conflicting payload
except EquivocationError as e:
    print(f"Caught: {e}")
