# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-an-equivocating-peer-and-a-merely-slow-one-in-byzantine-task-commitment-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-an-equivocating-peer-and-a-merely-slow-one-in-byzantine-task-commitment-consensus.warrant.json
# Markdown SHA-256:   1b05673903e5cf6dff79dc7b35644c9ea0b9f12f7f7fac15950728b6224c028a
# Code AST SHA-256:   5c5c34bf694dad03f5aad1a4fa6d4710093f6416ed10e16ef9281b701449fa05
# Verified Classes:   EquivocationDetected, Commitment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationDetected(RuntimeError):
    """Raised when a peer has signed two conflicting commitments for one slot."""
    pass


@dataclass(frozen=True)
class Commitment:
    proposer: str
    task: str
    epoch: int
    slot: int          # the exclusive resource being assigned
    owner: str
    signature: str     # opaque; assumed verified upstream


def _slot_key(c: Commitment) -> tuple:
    return (c.proposer, c.task, c.epoch, c.slot)


def verify_certificate(a: Commitment, b: Commitment) -> bool:
    """A certificate is valid iff both messages bind the same slot but
    assign different owners, and both signatures verify against the proposer."""
    if _slot_key(a) != _slot_key(b):
        return False
    if a.owner == b.owner:
        return False
    # Signature check is delegated; here we require distinct, well-formed sigs.
    return bool(a.signature) and bool(b.signature) and a.signature != b.signature


def accept_commitment(
    incoming: Commitment,
    local_log: dict,
    finalized: set,
) -> str:
    """Return 'accepted' | 'duplicate'. Raise EquivocationDetected on conflict.

    The invariant: a second conflicting signed message for the same slot is
    a protocol fault, never a benign duplicate -- even if it arrives after
    the liveness deadline and even if the first was already finalized.
    """
    key = _slot_key(incoming)
    prior = local_log.get(key)

    if prior is None:
        local_log[key] = incoming
        return "accepted"

    if prior.owner == incoming.owner:
        return "duplicate"

    # Two conflicting, individually-valid commitments for one slot: equivocation.
    if verify_certificate(prior, incoming):
        # Late evidence must retroactively invalidate a finalized commitment
        # within the reconciliation window; otherwise double-execution survives.
        if key in finalized:
            finalized.discard(key)
        raise EquivocationDetected(
            f"proposer {incoming.proposer} equivocated on {key}: "
            f"owner={prior.owner} vs owner={incoming.owner}"
        )

    raise EquivocationDetected(
        f"malformed conflict on {key}: certificate failed verification"
    )
