初始版本:基于 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>
This commit is contained in:
commit
e002ba9f62
19 files changed
+5064
No files matched your search
@@ -0,0 +1,247 @@
|
||||
"""Command line entry point: ``python -m dhtchat``.
|
||||
|
||||
Starts the Tkinter client by default; ``--no-gui`` runs a small console client
|
||||
that is handy for debugging or for a machine without a display.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from .app import DEFAULT_PORT
|
||||
from .chat import ChatService
|
||||
from .identity import DEFAULT_STATE_DIR, Identity
|
||||
from .node import DhtNode
|
||||
from .util import local_ip, parse_host_port
|
||||
|
||||
__all__ = ["main", "build_parser", "state_root", "state_directory"]
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="python -m dhtchat",
|
||||
description="基于 DHT 的去中心化聊天客户端(无需服务器)",
|
||||
)
|
||||
parser.add_argument("--nick", "-n", default="", help="显示昵称(默认沿用上次使用过的昵称)")
|
||||
parser.add_argument(
|
||||
"--port", "-p", type=int, default=DEFAULT_PORT,
|
||||
help=f"UDP 监听端口,0 表示随机端口(默认 {DEFAULT_PORT})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--bootstrap", "-b", action="append", default=[], metavar="HOST:PORT",
|
||||
help="引导节点地址,可重复指定,例如 -b 192.168.1.7:47800",
|
||||
)
|
||||
parser.add_argument("--room", "-r", default="大厅", help="启动后自动加入的公共聊天室")
|
||||
parser.add_argument("--state-dir", default="", help="状态目录(默认 ~/.dhtchat)")
|
||||
parser.add_argument("--profile", default="default", help="身份配置名,可用多个身份同时运行")
|
||||
parser.add_argument("--host", default="0.0.0.0", help="绑定的本地地址")
|
||||
parser.add_argument("--no-gui", action="store_true", help="使用命令行界面而不是图形界面")
|
||||
parser.add_argument(
|
||||
"--no-discovery", action="store_true", help="关闭局域网自动发现(仅使用手动引导地址)"
|
||||
)
|
||||
parser.add_argument("--verbose", "-v", action="store_true", help="输出调试日志")
|
||||
return parser
|
||||
|
||||
|
||||
def state_root(args: argparse.Namespace) -> Path:
|
||||
"""Directory holding every profile of this installation."""
|
||||
return Path(args.state_dir).expanduser() if args.state_dir else DEFAULT_STATE_DIR
|
||||
|
||||
|
||||
def state_directory(args: argparse.Namespace) -> Path:
|
||||
"""Directory of the selected profile (identity + nickname live here)."""
|
||||
return state_root(args) / (args.profile or "default")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG if args.verbose else logging.WARNING,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
if args.port < 0 or args.port > 65535:
|
||||
print("端口不合法", file=sys.stderr)
|
||||
return 2
|
||||
if args.no_gui:
|
||||
try:
|
||||
return asyncio.run(run_console(args))
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
try:
|
||||
import tkinter # noqa: F401
|
||||
except ImportError:
|
||||
print(
|
||||
"当前 Python 没有安装 tkinter,无法启动图形界面。\n"
|
||||
"请改用 --no-gui 运行命令行版本,或安装带 tkinter 的 Python。",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
from .gui import run_gui
|
||||
|
||||
return run_gui(args)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# console client
|
||||
# ----------------------------------------------------------------------
|
||||
HELP_TEXT = """\
|
||||
可用命令:
|
||||
/join <聊天室> 加入或切换公共聊天室
|
||||
/msg <昵称> <内容> 发送私聊消息
|
||||
/who 列出当前聊天室成员
|
||||
/peers 列出已知节点
|
||||
/me 显示本机身份与地址
|
||||
/help 显示本帮助
|
||||
/quit 退出
|
||||
直接输入文字即发送到当前聊天室。
|
||||
"""
|
||||
|
||||
|
||||
async def run_console(args: argparse.Namespace) -> int:
|
||||
state_dir = state_directory(args)
|
||||
state_dir.mkdir(parents=True, exist_ok=True)
|
||||
identity = Identity.load_or_create(state_dir / "identity.json")
|
||||
node = DhtNode(identity, host=args.host, port=args.port)
|
||||
await node.start()
|
||||
|
||||
events: asyncio.Queue = asyncio.Queue()
|
||||
|
||||
def emit(event: dict) -> None:
|
||||
events.put_nowait(event)
|
||||
|
||||
chat = ChatService(node, identity, state_dir, emit, nickname=args.nick or f"用户{identity.fingerprint[:8]}")
|
||||
|
||||
seeds = []
|
||||
for text in args.bootstrap:
|
||||
try:
|
||||
seeds.append(parse_host_port(text, DEFAULT_PORT))
|
||||
except ValueError:
|
||||
print(f"[警告] 无法解析引导地址: {text}")
|
||||
if seeds:
|
||||
known = await node.bootstrap(seeds)
|
||||
print(f"[网络] 引导成功 {known}/{len(seeds)}")
|
||||
|
||||
await chat.start()
|
||||
room = args.room or "大厅"
|
||||
chat.join_room(room)
|
||||
|
||||
print(f"[身份] 昵称: {chat.nickname}")
|
||||
print(f"[身份] 节点: {identity.node_id_hex}")
|
||||
print(f"[身份] 指纹: {identity.fingerprint}")
|
||||
print(f"[网络] 监听: {local_ip()}:{node.bound_port} (把这个地址告诉其它人作为引导地址)")
|
||||
print(f"[提示] 当前聊天室: {room},输入 /help 查看命令")
|
||||
if args.no_discovery:
|
||||
print("[网络] 局域网自动发现已关闭")
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
queue: asyncio.Queue[str] = asyncio.Queue()
|
||||
|
||||
def read_stdin() -> None:
|
||||
while True:
|
||||
try:
|
||||
line = input()
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
line = "/quit"
|
||||
loop.call_soon_threadsafe(queue.put_nowait, line)
|
||||
if line.strip() == "/quit":
|
||||
return
|
||||
|
||||
reader = asyncio.get_running_loop().run_in_executor(None, read_stdin)
|
||||
printer = asyncio.create_task(_print_events(events))
|
||||
handler = asyncio.create_task(_handle_input(chat, room, queue, identity, node))
|
||||
|
||||
try:
|
||||
await asyncio.wait({printer, handler}, return_when=asyncio.FIRST_COMPLETED)
|
||||
finally:
|
||||
for task in (printer, handler):
|
||||
task.cancel()
|
||||
await asyncio.gather(printer, handler, return_exceptions=True)
|
||||
await chat.stop()
|
||||
await node.stop()
|
||||
reader.cancel()
|
||||
return 0
|
||||
|
||||
|
||||
async def _print_events(events: asyncio.Queue) -> None:
|
||||
while True:
|
||||
event = await events.get()
|
||||
kind = event.get("type")
|
||||
if kind == "room_message":
|
||||
tag = "历史" if event.get("history") else "聊天"
|
||||
print(f"[{tag}] {event.get('room')} <{event.get('nick')}> {event.get('text')}")
|
||||
elif kind == "direct_message":
|
||||
arrow = "->" if event.get("own") else "<-"
|
||||
print(f"[私聊] {arrow} {event.get('peer')}: {event.get('text')}")
|
||||
elif kind == "direct_status":
|
||||
state = "已送达" if event.get("delivered") else "已存入 DHT 信箱,等待对方上线"
|
||||
print(f"[私聊] 发送给 {event.get('peer')}: {state}")
|
||||
elif kind == "log":
|
||||
print(f"[{str(event.get('level', 'info')).upper()}] {event.get('text')}")
|
||||
elif kind == "room_members":
|
||||
names = ", ".join(sorted(m.get("nick") or "?" for m in event.get("members", [])))
|
||||
print(f"[成员] {event.get('room')}: {names}")
|
||||
elif kind == "peers":
|
||||
print(f"[网络] 已知节点 {event.get('count')}")
|
||||
elif kind == "contact":
|
||||
print(f"[联系人] {event.get('nick')} ({event.get('node', '')[:12]}…)")
|
||||
elif kind == "profile":
|
||||
print(f"[资料] {event.get('nick')} 节点 {event.get('node')} 地址 {event.get('host')}:{event.get('port')}")
|
||||
|
||||
|
||||
async def _handle_input(chat: ChatService, room: str, queue: asyncio.Queue,
|
||||
identity: Identity, node: DhtNode) -> None:
|
||||
current = room
|
||||
while True:
|
||||
line = await queue.get()
|
||||
text = (line or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
if text.startswith("/"):
|
||||
command, _, rest = text[1:].partition(" ")
|
||||
command = command.lower()
|
||||
rest = rest.strip()
|
||||
if command in ("quit", "exit", "q"):
|
||||
print("[退出] 再见")
|
||||
return
|
||||
if command == "help":
|
||||
print(HELP_TEXT)
|
||||
elif command == "join":
|
||||
if not rest:
|
||||
print("[用法] /join 聊天室名称")
|
||||
continue
|
||||
chat.leave_room(current)
|
||||
chat.join_room(rest)
|
||||
current = rest
|
||||
elif command in ("msg", "pm"):
|
||||
target, _, body = rest.partition(" ")
|
||||
if not target or not body:
|
||||
print("[用法] /msg 昵称 内容")
|
||||
continue
|
||||
result = await chat.send_direct(target.strip(), body.strip())
|
||||
if not result.get("delivered"):
|
||||
print(f"[私聊] 未能直接送达:{result.get('reason', '对方离线')}")
|
||||
elif command == "who":
|
||||
members = chat.rooms[current].member_list() if current in chat.rooms else []
|
||||
print("[成员] " + ", ".join(m.get("nick") or "?" for m in members))
|
||||
elif command == "peers":
|
||||
for row in node.routing.snapshot():
|
||||
print(f" {row['nickname'] or '(未知)'} {row['node_id'][:12]}… {row['address']}")
|
||||
elif command == "me":
|
||||
print(f" 昵称 {chat.nickname}")
|
||||
print(f" 节点 {identity.node_id_hex}")
|
||||
print(f" 指纹 {identity.fingerprint}")
|
||||
print(f" 地址 {local_ip()}:{node.bound_port}")
|
||||
else:
|
||||
print(f"[未知命令] {command},输入 /help 查看帮助")
|
||||
continue
|
||||
if current not in chat.rooms:
|
||||
chat.join_room(current)
|
||||
await chat.send_room_message(current, text)
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user