# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-when-byzantine-quorum-certificates-are-valid-but-mutually-inconsistent-across-agent-task-commitment-l.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-when-byzantine-quorum-certificates-are-valid-but-mutually-inconsistent-across-agent-task-commitment-l.warrant.json
# Markdown SHA-256:   f08f291b186aec5e39e00019a44cda8ed8865b209c7f60869349d496641896f1
# Code AST SHA-256:   56c1886bc0a928b2554f8ffbc8401fd36f34defe0a6d3ea391c4564e7b5ad32c
# Verified Classes:   EquivocationDetected, Commitment, PayloadBoundSigner
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationDetected(RuntimeError):
    """Raised when a QC's payload hash contradicts the hash this agent signed."""


@dataclass(frozen=True)
class Commitment:
    epoch: int
    slot: str
    payload: bytes

    @property
    def payload_hash(self) -> str:
        return hashlib.sha256(self.payload).hexdigest()


class PayloadBoundSigner:
    """Signs at most one payload hash per (epoch, slot); rejects contradictory QCs."""

    def __init__(self, agent_id: str, durable_log: dict):
        self.agent_id = agent_id
        # durable_log: {(epoch, slot): payload_hash} — must be fsync'd before signing.
        self.durable_log = durable_log

    def sign(self, commitment: Commitment) -> str:
        key = (commitment.epoch, commitment.slot)
        prior = self.durable_log.get(key)
        if prior is not None and prior != commitment.payload_hash:
            raise EquivocationDetected(
                f"agent {self.agent_id} already signed {prior} for {key}; "
                f"refusing to double-sign {commitment.payload_hash}"
            )
        self.durable_log[key] = commitment.payload_hash
        return f"sig:{self.agent_id}:{commitment.payload_hash}"

    def accept_qc(self, commitment: Commitment, qc_sigs: list[str], threshold: int) -> None:
        key = (commitment.epoch, commitment.slot)
        signed = self.durable_log.get(key)
        if signed is None:
            raise EquivocationDetected(
                f"agent {self.agent_id} never signed {key}; QC cannot bind"
            )
        if signed != commitment.payload_hash:
            raise EquivocationDetected(
                f"QC payload {commitment.payload_hash} contradicts locally signed "
                f"{signed} at {key} — leader equivocation suspected"
            )
        if len(set(qc_sigs)) < threshold:
            raise EquivocationDetected(
                f"QC under threshold: {len(set(qc_sigs))} < {threshold}"
            )
        # Safe to commit: quorum ∧ payload-binding both hold.
