# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-when-byzantine-agent-consensus-fails-at-the-signature-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-peers-when-byzantine-agent-consensus-fails-at-the-signature-boundary.warrant.json
# Markdown SHA-256:   b57301e4bdcf5387cd05174ce5d9ecca0d52b1cc4246599e928ff612d8204263
# Code AST SHA-256:   9a00eadf5a03d79c74626d50cf2551fd16216a878081370b7011d53d80b7928f
# Verified Classes:   EquivocationEvidenceError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class EquivocationEvidenceError(RuntimeError):
    """Raised when a vote or evidence artifact cannot be safely adjudicated."""
    pass


def adjudicate_vote(
    slot_id: str,
    sender_id: str,
    value: str,
    signature: bytes,
    public_keys: dict,
    local_evidence: dict,
    verify_sig,
    gossip_fn,
    broadcast_fn,
) -> str:
    """
    Returns one of: 'accepted', 'idempotent', 'equivocation_detected'.
    Raises EquivocationEvidenceError when the instance cannot safely proceed.
    """
    if slot_id not in signature_payload_binding(signature):
        # Slot ID must be inside the signed bytes; otherwise replay is possible.
        raise EquivocationEvidenceError(
            f"vote for slot {slot_id} from {sender_id} has slot ID outside signature; "
            "cannot distinguish equivocation from replay, refusing to tally"
        )

    pub = public_keys.get(sender_id)
    if pub is None:
        raise EquivocationEvidenceError(
            f"no registered public key for {sender_id}; cannot authenticate vote"
        )

    if not verify_sig(pub, slot_id, value, signature):
        raise EquivocationEvidenceError(
            f"signature verification failed for {sender_id} on slot {slot_id}"
        )

    prior = local_evidence.get((sender_id, slot_id))
    if prior is None:
        local_evidence[(sender_id, slot_id)] = (value, signature)
        gossip_fn((sender_id, slot_id, value, signature), fanout_min=3)
        return "accepted"

    prior_value, prior_sig = prior
    if prior_value == value:
        return "idempotent"

    # Local equivocation observation: construct and broadcast the proof.
    artifact = {
        "sender": sender_id,
        "slot": slot_id,
        "value_a": prior_value,
        "sig_a": prior_sig,
        "value_b": value,
        "sig_b": signature,
    }
    broadcast_fn(artifact)
    return "equivocation_detected"


def verify_equivocation_artifact(artifact: dict, public_keys: dict, verify_sig) -> bool:
    """
    Independently verify a peer-supplied proof-of-equivocation before acting on it.
    A forged artifact is itself an attack.
    """
    sender = artifact["sender"]
    slot = artifact["slot"]
    pub = public_keys.get(sender)
    if pub is None:
        raise EquivocationEvidenceError(
            f"artifact references unknown sender {sender}; cannot verify"
        )
    if artifact["value_a"] == artifact["value_b"]:
        raise EquivocationEvidenceError(
            f"artifact for {sender} on slot {slot} has identical values; not equivocation"
        )
    ok_a = verify_sig(pub, slot, artifact["value_a"], artifact["sig_a"])
    ok_b = verify_sig(pub, slot, artifact["value_b"], artifact["sig_b"])
    if not (ok_a and ok_b):
        raise EquivocationEvidenceError(
            f"artifact for {sender} on slot {slot} failed signature verification; "
            "rejecting and flagging artifact sender"
        )
    return True


def signature_payload_binding(signature: bytes) -> set:
    # Placeholder: real implementation parses the signed payload envelope
    # and returns the set of slot identifiers cryptographically bound inside it.
    return set()
