Files
AI-Create-Dht-Chat/dhtchat/protocol.py
T
MrhongxingandCopilot e002ba9f62 初始版本:基于 DHT 的去中心化聊天客户端
- 纯标准库实现 Kademlia DHT(UDP + asyncio),报文 Ed25519 签名认证
- 超过 1200 字节的载荷自动分片与重组,上限 1 MiB
- 公共聊天室:成员公告 + DHT 日志回放,迟到入群者也能补到历史
- 一对一私聊:X25519 + HKDF + AEAD 端到端加密,支持离线信箱
- Tkinter 图形界面,asyncio 运行在后台线程,事件经队列回传 UI
- 局域网组播自动发现 + 手动引导地址(-b)两种互联方式
- run.cmd / start.bat 启动脚本,自动寻找 py -3 或 python
- 48 个单元测试覆盖密码学原语、DHT 路由/协议与聊天层

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-09-18 17:38:36 +08:00

120 lines
3.1 KiB
Python

"""Wire protocol definitions.
Every packet is a single UDP datagram holding a UTF-8 JSON object. Field names
are kept short because the same fields travel through the whole overlay.
Common envelope fields
----------------------
``v`` protocol version
``t`` message type (see :data:`REQUESTS` / :data:`RESPONSES`)
``src`` sender node id (hex, 20 bytes) -- must equal SHA1(``pub``)
``pub`` sender Ed25519 public key (hex)
``id`` request id (hex, 8 bytes), echoed back by responses
Fragment fields
---------------
When an encoded message exceeds :data:`MAX_DATAGRAM` it is split into
``chunk`` datagrams carrying ``id`` (group id), ``n`` (index), ``c`` (count)
and ``d`` (base64 payload slice). The receiver reassembles the original bytes
and dispatches them as if they had arrived in one piece.
"""
from __future__ import annotations
import base64
import json
import os
PROTOCOL_VERSION = 1
#: Conservative datagram budget that stays below the smallest practical MTU.
MAX_DATAGRAM = 1200
#: Largest accepted datagram (anything above is dropped as junk/DoS).
MAX_ACCEPT = 60000
PING = "ping"
PONG = "pong"
FIND_NODE = "find_node"
NODES = "nodes"
FIND_VALUE = "find_value"
VALUE = "value"
STORE = "store"
STORE_ACK = "store_ack"
ROUTE = "route"
ROUTE_ACK = "route_ack"
ROUTE_FAIL = "route_fail"
ROOM_MSG = "room_msg"
DIRECT_MSG = "direct_msg"
NOTIFY = "notify"
DISCOVER = "discover"
DISCOVER_REPLY = "discover_reply"
CHUNK = "chunk"
#: Raw payload bytes carried by one ``chunk`` datagram. Chosen so that the
#: base64 form plus the envelope header stays comfortably below MAX_DATAGRAM.
CHUNK_SIZE = 512
#: Upper bound on the fragments making up a single message (~1 MiB).
MAX_CHUNKS = 2048
REQUESTS = {
PING,
FIND_NODE,
FIND_VALUE,
STORE,
ROUTE,
DISCOVER,
}
RESPONSES = {
PONG,
NODES,
VALUE,
STORE_ACK,
ROUTE_ACK,
ROUTE_FAIL,
DISCOVER_REPLY,
}
#: Types that are fire-and-forget chat traffic rather than RPC.
UNSOLICITED = {ROOM_MSG, DIRECT_MSG, NOTIFY}
#: Types that are transported as fragment groups and never reassembled into
#: another fragment group.
FRAGMENTABLE = REQUESTS | RESPONSES | UNSOLICITED
def new_id() -> str:
return os.urandom(8).hex()
def b64encode(data: bytes) -> str:
return base64.b64encode(data).decode("ascii")
def b64decode(data: str) -> bytes:
return base64.b64decode(data.encode("ascii"), validate=True)
def encode(message: dict) -> bytes:
"""Serialise a message, dropping parser-injected internal keys."""
clean = {k: v for k, v in message.items() if not k.startswith("_")}
return json.dumps(clean, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
def decode(data: bytes) -> dict | None:
if not data or len(data) > MAX_ACCEPT:
return None
try:
message = json.loads(data.decode("utf-8"))
except (ValueError, UnicodeDecodeError):
return None
if not isinstance(message, dict):
return None
if message.get("v") != PROTOCOL_VERSION:
return None
if not isinstance(message.get("t"), str):
return None
return message